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
sequence
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
sequence
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
sequence
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
sequence
cell_types
sequence
cell_type_groups
sequence
d02ef2d88b1cc5b241e039dcdf2c4e686b5bdcb8
745,607
ipynb
Jupyter Notebook
notebooks/ssd-object-detection-demo.ipynb
p1x31/TRTorch
f99a6ca763eb08982e8b7172eb948a090bcbf11c
[ "BSD-3-Clause" ]
944
2020-03-13T22:50:32.000Z
2021-11-09T05:39:28.000Z
notebooks/ssd-object-detection-demo.ipynb
guoruoqian/TRTorch
f006ba2888ec710fe071ff9dde46f411a1d461df
[ "BSD-3-Clause" ]
434
2020-03-18T03:00:29.000Z
2021-11-09T00:26:36.000Z
notebooks/ssd-object-detection-demo.ipynb
guoruoqian/TRTorch
f006ba2888ec710fe071ff9dde46f411a1d461df
[ "BSD-3-Clause" ]
106
2020-03-18T02:20:21.000Z
2021-11-08T18:58:58.000Z
979.772668
136,832
0.954929
[ [ [ "# Copyright 2020 NVIDIA Corporation. All Rights Reserved.\n#\n# 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# http://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.\n# ==============================================================================", "_____no_output_____" ] ], [ [ "<img src=\"http://developer.download.nvidia.com/compute/machine-learning/frameworks/nvidia_logo.png\" style=\"width: 90px; float: right;\">\n\n# Object Detection with TRTorch (SSD)", "_____no_output_____" ], [ "---\n## Overview\n\n\nIn PyTorch 1.0, TorchScript was introduced as a method to separate your PyTorch model from Python, make it portable and optimizable.\n\nTRTorch is a compiler that uses TensorRT (NVIDIA's Deep Learning Optimization SDK and Runtime) to optimize TorchScript code. It compiles standard TorchScript modules into ones that internally run with TensorRT optimizations.\n\nTensorRT can take models from any major framework and specifically tune them to perform better on specific target hardware in the NVIDIA family, and TRTorch enables us to continue to remain in the PyTorch ecosystem whilst doing so. This allows us to leverage the great features in PyTorch, including module composability, its flexible tensor implementation, data loaders and more. TRTorch is available to use with both PyTorch and LibTorch. \n\nTo get more background information on this, we suggest the **lenet-getting-started** notebook as a primer for getting started with TRTorch.", "_____no_output_____" ], [ "### Learning objectives\n\nThis notebook demonstrates the steps for compiling a TorchScript module with TRTorch on a pretrained SSD network, and running it to test the speedup obtained.\n\n## Contents\n1. [Requirements](#1)\n2. [SSD Overview](#2)\n3. [Creating TorchScript modules](#3)\n4. [Compiling with TRTorch](#4)\n5. [Running Inference](#5)\n6. [Measuring Speedup](#6)\n7. [Conclusion](#7)", "_____no_output_____" ], [ "---\n<a id=\"1\"></a>\n## 1. Requirements\n\nFollow the steps in `notebooks/README` to prepare a Docker container, within which you can run this demo notebook.\n\nIn addition to that, run the following cell to obtain additional libraries specific to this demo.", "_____no_output_____" ] ], [ [ "# Known working versions\n!pip install numpy==1.21.2 scipy==1.5.2 Pillow==6.2.0 scikit-image==0.17.2 matplotlib==3.3.0", "_____no_output_____" ] ], [ [ "---\n<a id=\"2\"></a>\n## 2. SSD\n\n### Single Shot MultiBox Detector model for object detection\n\n_ | _\n- | -\n![alt](https://pytorch.org/assets/images/ssd_diagram.png) | ![alt](https://pytorch.org/assets/images/ssd.png)", "_____no_output_____" ], [ "PyTorch has a model repository called the PyTorch Hub, which is a source for high quality implementations of common models. We can get our SSD model pretrained on [COCO](https://cocodataset.org/#home) from there.\n\n### Model Description\n\nThis SSD300 model is based on the\n[SSD: Single Shot MultiBox Detector](https://arxiv.org/abs/1512.02325) paper, which\ndescribes SSD as “a method for detecting objects in images using a single deep neural network\".\nThe input size is fixed to 300x300.\n\nThe main difference between this model and the one described in the paper is in the backbone.\nSpecifically, the VGG model is obsolete and is replaced by the ResNet-50 model.\n\nFrom the\n[Speed/accuracy trade-offs for modern convolutional object detectors](https://arxiv.org/abs/1611.10012)\npaper, the following enhancements were made to the backbone:\n* The conv5_x, avgpool, fc and softmax layers were removed from the original classification model.\n* All strides in conv4_x are set to 1x1.\n\nThe backbone is followed by 5 additional convolutional layers.\nIn addition to the convolutional layers, we attached 6 detection heads:\n* The first detection head is attached to the last conv4_x layer.\n* The other five detection heads are attached to the corresponding 5 additional layers.\n\nDetector heads are similar to the ones referenced in the paper, however,\nthey are enhanced by additional BatchNorm layers after each convolution.\n\nMore information about this SSD model is available at Nvidia's \"DeepLearningExamples\" Github [here](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/Detection/SSD).", "_____no_output_____" ] ], [ [ "import torch\ntorch.hub._validate_not_a_forked_repo=lambda a,b,c: True", "_____no_output_____" ], [ "# List of available models in PyTorch Hub from Nvidia/DeepLearningExamples\ntorch.hub.list('NVIDIA/DeepLearningExamples:torchhub')", "Downloading: \"https://github.com/NVIDIA/DeepLearningExamples/archive/torchhub.zip\" to /root/.cache/torch/hub/torchhub.zip\n" ], [ "# load SSD model pretrained on COCO from Torch Hub\nprecision = 'fp32'\nssd300 = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_ssd', model_math=precision);", "Using cache found in /root/.cache/torch/hub/NVIDIA_DeepLearningExamples_torchhub\nDownloading checkpoint from https://api.ngc.nvidia.com/v2/models/nvidia/ssd_pyt_ckpt_amp/versions/20.06.0/files/nvidia_ssdpyt_amp_200703.pt\n" ] ], [ [ "Setting `precision=\"fp16\"` will load a checkpoint trained with mixed precision \ninto architecture enabling execution on Tensor Cores. Handling mixed precision data requires the Apex library.", "_____no_output_____" ], [ "### Sample Inference", "_____no_output_____" ], [ "We can now run inference on the model. This is demonstrated below using sample images from the COCO 2017 Validation set.", "_____no_output_____" ] ], [ [ "# Sample images from the COCO validation set\nuris = [\n 'http://images.cocodataset.org/val2017/000000397133.jpg',\n 'http://images.cocodataset.org/val2017/000000037777.jpg',\n 'http://images.cocodataset.org/val2017/000000252219.jpg'\n]\n\n# For convenient and comprehensive formatting of input and output of the model, load a set of utility methods.\nutils = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_ssd_processing_utils')\n\n# Format images to comply with the network input\ninputs = [utils.prepare_input(uri) for uri in uris]\ntensor = utils.prepare_tensor(inputs, False)\n\n# The model was trained on COCO dataset, which we need to access in order to\n# translate class IDs into object names. \nclasses_to_labels = utils.get_coco_object_dictionary()", "Using cache found in /root/.cache/torch/hub/NVIDIA_DeepLearningExamples_torchhub\n" ], [ "# Next, we run object detection\nmodel = ssd300.eval().to(\"cuda\")\ndetections_batch = model(tensor)\n\n# By default, raw output from SSD network per input image contains 8732 boxes with \n# localization and class probability distribution. \n# Let’s filter this output to only get reasonable detections (confidence>40%) in a more comprehensive format.\nresults_per_input = utils.decode_results(detections_batch)\nbest_results_per_input = [utils.pick_best(results, 0.40) for results in results_per_input]", "/opt/conda/lib/python3.8/site-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at ../c10/core/TensorImpl.h:1153.)\n return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)\n" ] ], [ [ "### Visualize results", "_____no_output_____" ] ], [ [ "from matplotlib import pyplot as plt\nimport matplotlib.patches as patches\n\n# The utility plots the images and predicted bounding boxes (with confidence scores).\ndef plot_results(best_results):\n for image_idx in range(len(best_results)):\n fig, ax = plt.subplots(1)\n # Show original, denormalized image...\n image = inputs[image_idx] / 2 + 0.5\n ax.imshow(image)\n # ...with detections\n bboxes, classes, confidences = best_results[image_idx]\n for idx in range(len(bboxes)):\n left, bot, right, top = bboxes[idx]\n x, y, w, h = [val * 300 for val in [left, bot, right - left, top - bot]]\n rect = patches.Rectangle((x, y), w, h, linewidth=1, edgecolor='r', facecolor='none')\n ax.add_patch(rect)\n ax.text(x, y, \"{} {:.0f}%\".format(classes_to_labels[classes[idx] - 1], confidences[idx]*100), bbox=dict(facecolor='white', alpha=0.5))\n plt.show()\n", "_____no_output_____" ], [ "# Visualize results without TRTorch/TensorRT\nplot_results(best_results_per_input)", "_____no_output_____" ] ], [ [ "### Benchmark utility", "_____no_output_____" ] ], [ [ "import time\nimport numpy as np\n\nimport torch.backends.cudnn as cudnn\ncudnn.benchmark = True\n\n# Helper function to benchmark the model\ndef benchmark(model, input_shape=(1024, 1, 32, 32), dtype='fp32', nwarmup=50, nruns=1000):\n input_data = torch.randn(input_shape)\n input_data = input_data.to(\"cuda\")\n if dtype=='fp16':\n input_data = input_data.half()\n \n print(\"Warm up ...\")\n with torch.no_grad():\n for _ in range(nwarmup):\n features = model(input_data)\n torch.cuda.synchronize()\n print(\"Start timing ...\")\n timings = []\n with torch.no_grad():\n for i in range(1, nruns+1):\n start_time = time.time()\n pred_loc, pred_label = model(input_data)\n torch.cuda.synchronize()\n end_time = time.time()\n timings.append(end_time - start_time)\n if i%10==0:\n print('Iteration %d/%d, avg batch time %.2f ms'%(i, nruns, np.mean(timings)*1000))\n\n print(\"Input shape:\", input_data.size())\n print(\"Output location prediction size:\", pred_loc.size())\n print(\"Output label prediction size:\", pred_label.size())\n print('Average batch time: %.2f ms'%(np.mean(timings)*1000))\n", "_____no_output_____" ] ], [ [ "We check how well the model performs **before** we use TRTorch/TensorRT", "_____no_output_____" ] ], [ [ "# Model benchmark without TRTorch/TensorRT\nmodel = ssd300.eval().to(\"cuda\")\nbenchmark(model, input_shape=(128, 3, 300, 300), nruns=100)", "Warm up ...\nStart timing ...\nIteration 10/100, avg batch time 382.30 ms\nIteration 20/100, avg batch time 382.72 ms\nIteration 30/100, avg batch time 382.63 ms\nIteration 40/100, avg batch time 382.83 ms\nIteration 50/100, avg batch time 382.90 ms\nIteration 60/100, avg batch time 382.86 ms\nIteration 70/100, avg batch time 382.88 ms\nIteration 80/100, avg batch time 382.86 ms\nIteration 90/100, avg batch time 382.95 ms\nIteration 100/100, avg batch time 382.97 ms\nInput shape: torch.Size([128, 3, 300, 300])\nOutput location prediction size: torch.Size([128, 4, 8732])\nOutput label prediction size: torch.Size([128, 81, 8732])\nAverage batch time: 382.97 ms\n" ] ], [ [ "---\n<a id=\"3\"></a>\n## 3. Creating TorchScript modules ", "_____no_output_____" ], [ "To compile with TRTorch, the model must first be in **TorchScript**. TorchScript is a programming language included in PyTorch which removes the Python dependency normal PyTorch models have. This conversion is done via a JIT compiler which given a PyTorch Module will generate an equivalent TorchScript Module. There are two paths that can be used to generate TorchScript: **Tracing** and **Scripting**. <br>\n- Tracing follows execution of PyTorch generating ops in TorchScript corresponding to what it sees. <br>\n- Scripting does an analysis of the Python code and generates TorchScript, this allows the resulting graph to include control flow which tracing cannot do. \n\nTracing however due to its simplicity is more likely to compile successfully with TRTorch (though both systems are supported).", "_____no_output_____" ] ], [ [ "model = ssd300.eval().to(\"cuda\")\ntraced_model = torch.jit.trace(model, [torch.randn((1,3,300,300)).to(\"cuda\")])", "_____no_output_____" ] ], [ [ "If required, we can also save this model and use it independently of Python.", "_____no_output_____" ] ], [ [ "# This is just an example, and not required for the purposes of this demo\ntorch.jit.save(traced_model, \"ssd_300_traced.jit.pt\")", "_____no_output_____" ], [ "# Obtain the average time taken by a batch of input with Torchscript compiled modules\nbenchmark(traced_model, input_shape=(128, 3, 300, 300), nruns=100)", "Warm up ...\nStart timing ...\nIteration 10/100, avg batch time 382.67 ms\nIteration 20/100, avg batch time 382.54 ms\nIteration 30/100, avg batch time 382.73 ms\nIteration 40/100, avg batch time 382.53 ms\nIteration 50/100, avg batch time 382.56 ms\nIteration 60/100, avg batch time 382.50 ms\nIteration 70/100, avg batch time 382.54 ms\nIteration 80/100, avg batch time 382.54 ms\nIteration 90/100, avg batch time 382.57 ms\nIteration 100/100, avg batch time 382.62 ms\nInput shape: torch.Size([128, 3, 300, 300])\nOutput location prediction size: torch.Size([128, 4, 8732])\nOutput label prediction size: torch.Size([128, 81, 8732])\nAverage batch time: 382.62 ms\n" ] ], [ [ "---\n<a id=\"4\"></a>\n## 4. Compiling with TRTorch\nTorchScript modules behave just like normal PyTorch modules and are intercompatible. From TorchScript we can now compile a TensorRT based module. This module will still be implemented in TorchScript but all the computation will be done in TensorRT.", "_____no_output_____" ] ], [ [ "import trtorch\n\n# The compiled module will have precision as specified by \"op_precision\".\n# Here, it will have FP16 precision.\ntrt_model = trtorch.compile(traced_model, {\n \"inputs\": [trtorch.Input((3, 3, 300, 300))],\n \"enabled_precisions\": {torch.float, torch.half}, # Run with FP16\n \"workspace_size\": 1 << 20\n})", "_____no_output_____" ] ], [ [ "---\n<a id=\"5\"></a>\n## 5. Running Inference", "_____no_output_____" ], [ "Next, we run object detection", "_____no_output_____" ] ], [ [ "# using a TRTorch module is exactly the same as how we usually do inference in PyTorch i.e. model(inputs)\ndetections_batch = trt_model(tensor.to(torch.half)) # convert the input to half precision\n\n# By default, raw output from SSD network per input image contains 8732 boxes with \n# localization and class probability distribution. \n# Let’s filter this output to only get reasonable detections (confidence>40%) in a more comprehensive format.\nresults_per_input = utils.decode_results(detections_batch)\nbest_results_per_input_trt = [utils.pick_best(results, 0.40) for results in results_per_input]", "_____no_output_____" ] ], [ [ "Now, let's visualize our predictions!\n", "_____no_output_____" ] ], [ [ "# Visualize results with TRTorch/TensorRT\nplot_results(best_results_per_input_trt)", "_____no_output_____" ] ], [ [ "We get similar results as before!", "_____no_output_____" ], [ "---\n## 6. Measuring Speedup\nWe can run the benchmark function again to see the speedup gained! Compare this result with the same batch-size of input in the case without TRTorch/TensorRT above.", "_____no_output_____" ] ], [ [ "batch_size = 128\n\n# Recompiling with batch_size we use for evaluating performance\ntrt_model = trtorch.compile(traced_model, {\n \"inputs\": [trtorch.Input((batch_size, 3, 300, 300))],\n \"enabled_precisions\": {torch.float, torch.half}, # Run with FP16\n \"workspace_size\": 1 << 20\n})\n\nbenchmark(trt_model, input_shape=(batch_size, 3, 300, 300), nruns=100, dtype=\"fp16\")", "Warm up ...\nStart timing ...\nIteration 10/100, avg batch time 72.90 ms\nIteration 20/100, avg batch time 72.95 ms\nIteration 30/100, avg batch time 72.92 ms\nIteration 40/100, avg batch time 72.94 ms\nIteration 50/100, avg batch time 72.99 ms\nIteration 60/100, avg batch time 73.01 ms\nIteration 70/100, avg batch time 73.04 ms\nIteration 80/100, avg batch time 73.04 ms\nIteration 90/100, avg batch time 73.04 ms\nIteration 100/100, avg batch time 73.06 ms\nInput shape: torch.Size([128, 3, 300, 300])\nOutput location prediction size: torch.Size([128, 4, 8732])\nOutput label prediction size: torch.Size([128, 81, 8732])\nAverage batch time: 73.06 ms\n" ] ], [ [ "---\n## 7. Conclusion\n\nIn this notebook, we have walked through the complete process of compiling a TorchScript SSD300 model with TRTorch, and tested the performance impact of the optimization. We find that using the TRTorch compiled model, we gain significant speedup in inference without any noticeable drop in performance!", "_____no_output_____" ], [ "### Details\nFor detailed information on model input and output,\ntraining recipies, inference and performance visit:\n[github](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/Detection/SSD)\nand/or [NGC](https://ngc.nvidia.com/catalog/model-scripts/nvidia:ssd_for_pytorch)\n\n### References\n\n - [SSD: Single Shot MultiBox Detector](https://arxiv.org/abs/1512.02325) paper\n - [Speed/accuracy trade-offs for modern convolutional object detectors](https://arxiv.org/abs/1611.10012) paper\n - [SSD on NGC](https://ngc.nvidia.com/catalog/model-scripts/nvidia:ssd_for_pytorch)\n - [SSD on github](https://github.com/NVIDIA/DeepLearningExamples/tree/master/PyTorch/Detection/SSD)", "_____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", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d02ef61d47c6e5e5630fc3c447eb2d0fb27cb564
26,751
ipynb
Jupyter Notebook
Machine_Learning/05-Hidden_Markov_Models-03-Markov-Models-Example-Problems-and-Applications.ipynb
NathanielDake/NathanielDake.github.io
82b7013afa66328e06e51304b6af10e1ed648eb8
[ "MIT" ]
3
2018-03-30T06:28:21.000Z
2018-04-25T15:43:24.000Z
Machine_Learning/05-Hidden_Markov_Models-03-Markov-Models-Example-Problems-and-Applications.ipynb
NathanielDake/NathanielDake.github.io
82b7013afa66328e06e51304b6af10e1ed648eb8
[ "MIT" ]
null
null
null
Machine_Learning/05-Hidden_Markov_Models-03-Markov-Models-Example-Problems-and-Applications.ipynb
NathanielDake/NathanielDake.github.io
82b7013afa66328e06e51304b6af10e1ed648eb8
[ "MIT" ]
3
2018-02-07T22:21:33.000Z
2018-05-04T20:16:43.000Z
52.350294
738
0.602594
[ [ [ "# 3. Markov Models Example Problems\nWe will now look at a model that examines our state of healthiness vs. being sick. Keep in mind that this is very much like something you could do in real life. If you wanted to model a certain situation or environment, we could take some data that we have gathered, build a maximum likelihood model on it, and do things like study the properties that emerge from the model, or make predictions from the model, or generate the next most likely state. \n\nLet's say we have 2 states: **sick** and **healthy**. We know that we spend most of our time in a healthy state, so the probability of transitioning from healthy to sick is very low:\n\n$$p(sick \\; | \\; healthy) = 0.005$$\n\nHence, the probability of going from healthy to healthy is:\n\n$$p(healthy \\; | \\; healthy) = 0.995$$\n\nNow, on the other hand the probability of going from sick to sick is also very high. This is because if you just got sick yesterday then you are very likely to be sick tomorrow.\n\n$$p(sick \\; | \\; sick) = 0.8$$\n\nHowever, the probability of transitioning from sick to healthy should be higher than the reverse, because you probably won't stay sick for as long as you would stay healthy:\n\n$$p(healthy \\; | \\; sick) = 0.02$$\n\nWe have now fully defined our state transition matrix, and we can now do some calculations. \n\n## 1.1 Example Calculations\n### 1.1.1 \nWhat is the probability of being healthy for 10 days in a row, given that we already start out as healthy? Well that is:\n\n$$p(healthy \\; 10 \\; days \\; in \\; a \\; row \\; | \\; healthy \\; at \\; t=0) = 0.995^9 = 95.6 \\%$$\n\nHow about the probability of being healthy for 100 days in a row? \n\n$$p(healthy \\; 100 \\; days \\; in \\; a \\; row \\; | \\; healthy \\; at \\; t=0) = 0.995^{99} = 60.9 \\%$$", "_____no_output_____" ], [ "## 2. Expected Number of Continuously Sick Days\nWe can now look at the expected number of days that you would remain in the same state (e.g. how many days would you expect to stay sick given the model?). This is a bit more difficult than the last problem, but completely doable, only involving the mathematics of <a href=\"https://en.wikipedia.org/wiki/Geometric_series\">infinite sums</a>.\n\nFirst, we can look at the probability of being in state $i$, and going to state $i$ in the next state. That is just $A(i,i)$:\n\n$$p \\big(s(t)=i \\; | \\; s(t-1)=i \\big) = A(i, i)$$\n\nNow, what is the probability distribution that we actually want to calculate? How about we calculate the probability that we stay in state $i$ for $n$ transitions, at which point we move to another state:\n\n$$p \\big(s(t) \\;!=i \\; | \\; s(t-1)=i \\big) = 1 - A(i, i)$$\n\nSo, the joint probability that we are trying to model is:\n\n$$p\\big(s(1)=i, s(2)=i,...,s(n)=i, s(n+1) \\;!= i\\big) = A(i,i)^{n-1}\\big(1-A(i,i)\\big)$$\n\nIn english this means that we are multiplying the transition probability of staying in the same state, $A(i,i)$, times the number of times we stayed in the same state, $n$, (note it is $n-1$ because we are given that we start in that state, hence there is no transition associated with it) times $1 - A(i,i)$, the probability of transitioning from that state. This leaves us with an expected value for $n$ of:\n\n$$E(n) = \\sum np(n) = \\sum_{n=1..\\infty} nA(i,i)^{n-1}(1-A(i,i))$$\n\nNote, in the above equation $p(n)$ is the probability that we will see state $i$ $n-1$ times after starting from $i$ and then see a state that is not $i$. Also, we know that the expected value of $n$ should be the sum of all possible values of $n$ times $p(n)$. \n\n\n### 2.1 Expected $n$\nSo, we can now expand this function and calculate the two sums separately. \n\n$$E(n) = \\sum_{n=1..\\infty}nA(i,i)^{n-1}(1 - A(i,i)) = \\sum nA(i, i)^{n-1} - \\sum nA(i,i)^n$$\n\n**First Sum**<br>\nWith our first sum, we can say that:\n\n$$S = \\sum na(i, i)^{n-1}$$\n\n$$S = 1 + 2a + 3a^2 + 4a^3+ ...$$\n\nAnd we can then multiply that sum, $S$, by $a$, to get:\n\n$$aS = a + 2a^2 + 3a^3 + 4a^4+...$$\n\nAnd then we can subtract $aS$ from $S$:\n\n$$S - aS = S'= 1 + a + a^2 + a^3+...$$\n\nThis $S'$ is another infinite sum, but it is one that is much easier to solve! \n\n$$S'= 1 + a + a^2 + a^3+...$$\n\nAnd then $aS'$ is:\n\n$$aS' = a + a^2 + a^3+ + a^4 + ...$$\n\nWhich, when we then do $S' - aS'$, we end up with:\n\n$$S' - aS' = 1$$\n\n$$S' = \\frac{1}{1 - a}$$\n\nAnd if we then substitute that value in for $S'$ above:\n\n$$S - aS = S'= 1 + a + a^2 + a^3+... = \\frac{1}{1 - a}$$\n\n$$S - aS = \\frac{1}{1 - a}$$\n\n$$S = \\frac{1}{(1 - a)^2}$$\n\n\n**Second Sum**<br>\nWe can now look at our second sum:\n\n$$S = \\sum na(i,i)^n$$\n\n$$S = 1a + 2a^2 + 3a^3 +...$$\n\n\n$$Sa = 1a^2 + 2a^3 +...$$\n\n$$S - aS = S' = a + a^2 + a^3 + ...$$\n\n$$aS' = a^2 + a^3 + a^4 +...$$\n\n$$S' - aS' = a$$\n\n$$S' = \\frac{a}{1 - a}$$\n\nAnd we can plug back in $S'$ to get:\n\n$$S - aS = \\frac{a}{1 - a}$$\n\n$$S = \\frac{a}{(1 - a)^2}$$\n\n**Combine** <br>\nWe can now combine these two sums as follows:\n\n$$E(n) = \\frac{1}{(1 - a)^2} - \\frac{a}{(1-a)^2}$$\n\n$$E(n) = \\frac{1}{1-a}$$\n\n**Calculate Number of Sick Days**<br>\nSo, how do we calculate the correct number of sick days? That is just:\n\n$$\\frac{1}{1 - 0.8} = 5$$", "_____no_output_____" ], [ "## 3. SEO and Bounce Rate Optimization \nWe are now going to look at SEO and Bounch Rate Optimization. This is a problem that every developer and website owner can relate to. You have a website and obviously you would like to increase traffic, increase conversions, and avoid a high bounce rate (which could lead to google assigning your page a low ranking). What would a good way of modeling this data be? Without even looking at any code we can look at some examples of things that we want to know, and how they relate to markov models. \n\n### 3.1 Arrival\nFirst and foremost, how do people arrive on your page? Is it your home page? Your landing page? Well, this is just the very first page of what is hopefully a sequence of pages. So, the markov analogy here is that this is just the initial state distribution or $\\pi$. So, once we have our markov model, the $\\pi$ vector will tell us which of our pages a user is most likely to start on. \n\n### 3.2 Sequences of Pages \nWhat about sequences of pages? Well, if you think people are getting to your landing page, hitting the buy button, checking out, and then closing the browser window, you can test the validity of that assumption by calculating the probability of that sequence. Of course, the probability of any sequence is probability going to be much less than 1. This is because for a longer sequence, we have more multiplication, and hence smaller final numbers. We do have two alternatives however:\n\n> * 1) You can compare the probability of two different sequences. So, are people going through the entire checkout process? Or is it more probable that they are just bouncing? \n* 2) Another option is to just find the transition probabilities themselves. These are conditional probabilities instead of joint probabilities. You want to know, once they have made it to the landing page, what is the probability of hitting buy. Then, once they have hit buy, what is the probability of them completing the checkout. \n\n### 3.3 Bounce Rate\nThis is hard to measure, unless you are google and hence have analytics on nearly every page on the web. This is because once a user has left your site, you can no longer run code on their computer or track what they are doing. However, let's pretend that we can determine this information. Once we have done this, we can measure which page has the highest bounce rate. At this point we can manually analyze that page and ask our marketing people \"what is different about this page that people don't find it useful/want to leave?\" We can then address that problem, and the hopefully later analysis shows that the fixed page no longer has a high bounce right. In the markov model, we can just represents this as the null state. \n\n### 3.4 Data\nSo, the data we are going to be working with has two columns: `last_page_id` and `next_page_id`. This can be interpreted as the current page and the next page. The site has 10 pages with the id's 0-9. We can represent start pages by making the current page -1, and the next page the actual page. We can represent the end of the page with two different codes, `B`(bounce) or `C` (close). In the case of bounce, the user saw the page and then immediately bounced. In the case of close, the user saw the page stayed and potentially saw some useful information, and then closed the window. So, you can imagine that our engineer may use time as a factor in determining if it is a bounce or a close. ", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "\"\"\"Goal here is to store start page and end page, and the count how many times that happens. After that \nwe are going to turn it into a probability distribution. We can divide all transitions that start with specific\nstart state, by row_sum\"\"\"\ntransitions = {} # getting all specific transitions from start pg to end pg, tallying up # of times each occurs\nrow_sums = {} # start date as key -> getting number of times each starting pg occurs\n\n# Collect our counts\nfor line in open('../../../data/site/site_data.csv'):\n s, e = line.rstrip().split(',') # get start and end page \n transitions[(s, e)] = transitions.get((s, e), 0.) + 1\n row_sums[s] = row_sums.get(s, 0.) + 1 \n \n# Normalize the counts so they become real probability distributions \nfor k, v in transitions.items():\n s, e = k\n transitions[k] = v / row_sums[s]\n \n# Calculate initial state distribution\nprint('Initial state distribution')\nfor k, v in transitions.items():\n s, e = k\n if s == '-1': # this means it is the start of the sequence. \n print (e, v)\n \n# Which page has the highest bounce rate?\nfor k, v in transitions.items():\n s, e = k\n if e == 'B':\n print(f'Bounce rate for {s}: {v}')", "Initial state distribution\n8 0.10152591025834719\n2 0.09507982071813466\n5 0.09779926474291183\n9 0.10384247368686106\n0 0.10298635241980159\n6 0.09800070504104345\n7 0.09971294757516241\n1 0.10348995316513068\n4 0.10243239159993957\n3 0.09513018079266758\nBounce rate for 1: 0.125939617991374\nBounce rate for 2: 0.12649551345962112\nBounce rate for 8: 0.12529550827423167\nBounce rate for 6: 0.1208153180975911\nBounce rate for 7: 0.12371650388179314\nBounce rate for 3: 0.12743384922616077\nBounce rate for 4: 0.1255756067205974\nBounce rate for 5: 0.12369559684398065\nBounce rate for 0: 0.1279673590504451\nBounce rate for 9: 0.13176232104396302\n" ] ], [ [ "We can see that page with `id` 9 has the highest value in the initial state distribution, so we are most likely to start on that page. We can then see that the page with highest bounce rate is also at page `id` 9. ", "_____no_output_____" ], [ "## 4. Build a 2nd-order language model and generate phrases\nSo, we are now going to work with non first order markov chains for a little bit. In this example we are going to try and create a language model. So we are going to first train a model on some data to determine the distribution of a word given the previous two words. We can then use this model to generate new phrases. Note that another step of this model would be to calculate the probability of a phrase.\n\nSo the data that we are going to look at is just a collection of Robert Frost Poems. It is just a text file with all of the poems concatenated together. So, the first thing we are going to want to do is tokenize each sentence, and remove punctuation. It will look similar to this:\n\n```\ndef remove_punctuation(s):\n return s.translate(None, string.punctuation)\n \ntokens = [t for t in remove_puncuation(line.rstrip().lower()).split()]\n```\n\nOnce we have tokenized each line, we want to perform various counts in addition to the second order model counts. We need to measure the initial distribution of words, or stated another way the distribution of the first word of a sentence. We also want to know the distribution of the second word of a sentence. Both of these do not have two previous words, so they are not second order. We could technically include them in the second order measurement by using `None` in place of the previous words, but we won't do that here. We also want to keep track of how to end the sentence (end of sentence distribution, will look similar to (w(t-2), w(t-1) -> END)), so we will include a special token for that too. \n\nWhen we do this counting, what we first want to do is create an array of all possibilities. So, for example if we had two sentences:\n\n```\nI love dogs\nI love cats\n```\n\nThen we could have a dictionary where the key was `(I, love)` and the value was an array `[dogs, cats]`. If \"I love\" was also a stand alone sentence, then the value would be `[dogs, cats, END]`. The function below can help us with this, since we first need to check if there is any value for the key, create an array if not, otherwise just append to the array. \n\n```\ndef add2dict(d, k, v):\n if k not in d:\n d[k] = []\n else:\n d[k].append(v)\n```\n\nOne we have collected all of these arrays of possible next words, we need to turn them into **probability distributions**. For example, the array `[cat, cat, dog]` would become the dictionary `{\"cat\": 2/3, \"dog\": 1/3}`. Here is a function that can do this:\n\n```\ndef list2pdict(ts):\n d = {}\n n = len(ts)\n for t in ts:\n d[t] = d.get(t, 0.) + 1 \n for t, c in d.items():\n d[t] = c / n\n return d\n```\n\nNext, we will need a function that can sample from this dictionary. To do this we will need to generate a random number between 0 and 1, and then use the distribution of the words to sample a word given a random number. Here is a function that can do that:\n\n```\ndef sample_word(d):\n p0 = np.random.random()\n cumulative = 0\n for t, p in d.items():\n cumulative += p\n if p0 < cumulative:\n return t\n assert(False) # should never get here\n```\n\nBecause all of our distributions are structured as dictionaries, we can use the same function for all of them.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport string", "_____no_output_____" ], [ "\"\"\"3 dicts. 1st store pdist for the start of a phrase, then a second word dict which stores the distributions\nfor the 2nd word of a sentence, and then we are going to have a dict for all second order transitions\"\"\"\ninitial = {}\nsecond_word = {}\ntransitions = {}\n\ndef remove_punctuation(s):\n return s.translate(str.maketrans('', '', string.punctuation))\n\ndef add2dict(d, k, v): \n \"\"\"Parameters: Dictionary, Key, Value\"\"\"\n if k not in d:\n d[k] = []\n d[k].append(v)\n \n# Loop through file of poems\nfor line in open('../../../data/poems/robert_frost.txt'):\n tokens = remove_punctuation(line.rstrip().lower()).split() # Get all tokens for specific line we are looping over\n \n T = len(tokens) # Length of sequence\n for i in range(T): # Loop through every token in sequence\n t = tokens[i] \n if i == 0: # We are looking at first word\n initial[t] = initial.get(t, 0.) + 1 \n else:\n t_1 = tokens[i - 1]\n if i == T - 1: # Looking at last word\n add2dict(transitions, (t_1, t), 'END')\n if i == 1: # second word of sentence, hence only 1 previous word\n add2dict(second_word, t_1, t)\n else: \n t_2 = tokens[i - 2] # Get second previous word\n add2dict(transitions, (t_2, t_1), t) # add previous and 2nd previous word as key, and current word as val\n \n# Normalize the distributions\ninitial_total = sum(initial.values())\nfor t, c in initial.items():\n initial[t] = c / initial_total\n\n# Take our list and turn it into a dictionary of probabilities\ndef list2pdict(ts):\n d = {}\n n = len(ts) # get total number of values\n for t in ts: # look at each token\n d[t] = d.get(t, 0.) + 1\n for t, c in d.items(): # go through dictionary, divide frequency by sum\n d[t] = c / n\n return d\n\nfor t_1, ts in second_word.items():\n second_word[t_1] = list2pdict(ts)\n\nfor k, ts in transitions.items():\n transitions[k] = list2pdict(ts)\n \ndef sample_word(d):\n p0 = np.random.random() # Generate random number from 0 to 1 \n cumulative = 0 # cumulative count for all probabilities seen so far\n for t, p in d.items():\n cumulative += p\n if p0 < cumulative:\n return t\n assert(False) # should never hit this\n \n\"\"\"Function to generate a poem\"\"\"\ndef generate():\n for i in range(4):\n sentence = []\n \n # initial word\n w0 = sample_word(initial)\n sentence.append(w0)\n \n # sample second word\n w1 = sample_word(second_word[w0])\n sentence.append(w1)\n \n # second-order transitions until END -> enter infinite loop\n while True:\n w2 = sample_word(transitions[(w0, w1)]) # sample next word given previous two words\n if w2 == 'END': \n break\n sentence.append(w2)\n w0 = w1\n w1 = w2\n print(' '.join(sentence))\n \ngenerate()", "another from the childrens house of makebelieve\nthey dont go with the dead race of the lettered\ni never heard of clara robinson\nwhere he can eat off a barrel from the sense of our having been together\n" ] ], [ [ "## 5. Google's PageRank Algorithm\nMarkov models were even used in Google's PageRank algorithm. The basic problem we face is:\n> * We have $M$ webpages that link to eachother, and we would like to assign importance scores $x(1),...,x(M)$\n* All of these scores are greater than or equal to 0\n* So, we want to assign a page rank to all of these pages \n\nHow can we go about doing this? Well, we can think of a webpage as a sequence, and the page you are on as the state. Where does the ranking come from? Well, the ranking actually comes from the limiting distribution. That is, in the long run, the proportion of visits that will be spent on this page. Now, if you think \"great that is all I need to know\", slow down. How can we actually do this in practice? How do we train the markov model, and what are the values we assign to the state transition matrix? And how can we ensure that the limiting distribution exists and is unique? The key insight was that **we can use the linked structure of the web to determine the ranking**. \n\nThe main idea is that a *link to a page* is like a *vote for its importance*. So, as a first attempt we could just use a frequency count to measure the votes. Of course, that wouldn't be a valid probability distribution, so we could just divide each row by its sum to make it sum to 1. So we set:\n\n$$A(i, j) = \\frac{1}{n(i)} \\; if \\; i \\; links \\; to \\; j$$\n$$A(i, j) = 0 \\; otherwise$$\n\nHere $n(i)$ stands for the total number of links on a page, and you can confirm that the sum of a row is $\\frac{n(i)}{n(i)} = 1$, so this is a valid markov matrix. Now, we still aren't sure if the limiting distribution is unique. \n\n### 5.1 This is already a good start\nLet's keep in mind that the above solution already solves a few problems. For instance, let's say you are a spammer and you want to sell 1000 links on your webpage. Well, because the transition matrix must remain a valid probability matrix, the rows must sum to 1, which means that each of your links now only has a strength of $\\frac{1}{1000}$. For example the frequency matrix would look like:\n\n| |abc.com|amazon.com|facebook.com|github.com|\n|--- |--- |--- | --- |--- |\n|thespammer.com|1 |1 |1 |1 |\n\nAnd then if we transformed that into a probability matrix it would just be each value divided by the total number of links, 4:\n\n| |abc.com|amazon.com|facebook.com|github.com|\n|--- |--- |--- | --- |--- |\n|thespammer.com|0.25 |0.25 |0.25 |0.25 |\n\nYou may then think, I will just create 1000 pages and each of them will only have 1 link. Unfortunately, since nobody knows about those 1000 pages you just created nobody is going to link to them, which means they are impossible to get to. So, in the limiting distribution, those states will have 0 probability because you can't even get to them, so there outgoing links are worthless. Remember, the markov chains limiting distribution will model the long running proportion of visits to a state. So, if you never visit that state, its probability will be 0. \n\nWe still have not ensure that the limiting distribution exists and is unique. \n\n### 5.2 Perron-Frobenius Theorem\nHow can we ensure that our model has a unique stationary distribution. In 1910, this was actually determined. It is known as the **Perron-Frobenius Theorem**, and it states that:\n> *If our transition matrix is a markov matrix -meaning that all of the rows sum to 1, and all of the values are strictly positive, i.e. no values that are 0- then the stationary distribution exists and is unique*. \n\nIn fact, we can start in any initial state and as time approaches infinity we will always end up with the same stationary distribution, therefore this is also the limiting distribution. \n\nSo, how can we satisfy the PF criterion? Let's return to this idea of **smoothing**, which we first talked about when discussing how to train a markov model. The basic idea was that we can make things that were 0, non-zero, so there is still a small possibility that we can get to that state. This might be good news for the spammer. So, we can create a uniform probability distribution $U = \\frac{1}{M}$, which is an $M x M$ matrix ($M$ is the number of states). PageRanks solution was to take the matrix we had before and multiply it by 0.85, and to take the uniform distribution and multiply it by 0.15, and add them together to get the final pagerank matrix. \n\n$$G = 0.85A + 0.15U$$\n\nNow all of the elements are strictly positive, and we can convince ourselves that G is still a valid markov matrix. ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d02efe61c24850b217c75327e86a70753787779e
42,392
ipynb
Jupyter Notebook
quantization/noise_shaping.ipynb
davidjustin1974/digital-signal-processing-lecture
3959b6c929828b0e2b5ae440523d9adc43ea928c
[ "MIT" ]
1
2020-11-04T03:40:49.000Z
2020-11-04T03:40:49.000Z
quantization/noise_shaping.ipynb
davidjustin1974/digital-signal-processing-lecture
3959b6c929828b0e2b5ae440523d9adc43ea928c
[ "MIT" ]
null
null
null
quantization/noise_shaping.ipynb
davidjustin1974/digital-signal-processing-lecture
3959b6c929828b0e2b5ae440523d9adc43ea928c
[ "MIT" ]
null
null
null
223.115789
34,608
0.900335
[ [ [ "# Quantization of Signals\n\n*This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).*", "_____no_output_____" ], [ "## Spectral Shaping of the Quantization Noise\n\nThe quantized signal $x_Q[k]$ can be expressed by the continuous amplitude signal $x[k]$ and the quantization error $e[k]$ as\n\n\\begin{equation}\nx_Q[k] = \\mathcal{Q} \\{ x[k] \\} = x[k] + e[k]\n\\end{equation}\n\nAccording to the [introduced model](linear_uniform_quantization_error.ipynb#Model-for-the-Quantization-Error), the quantization noise can be modeled as uniformly distributed white noise. Hence, the noise is distributed over the entire frequency range. The basic concept of [noise shaping](https://en.wikipedia.org/wiki/Noise_shaping) is a feedback of the quantization error to the input of the quantizer. This way the spectral characteristics of the quantization noise can be modified, i.e. spectrally shaped. Introducing a generic filter $h[k]$ into the feedback loop yields the following structure\n\n![Feedback structure for noise shaping](noise_shaping.png)\n\nThe quantized signal can be deduced from the block diagram above as\n\n\\begin{equation}\nx_Q[k] = \\mathcal{Q} \\{ x[k] - e[k] * h[k] \\} = x[k] + e[k] - e[k] * h[k]\n\\end{equation}\n\nwhere the additive noise model from above has been introduced and it has been assumed that the impulse response $h[k]$ is normalized such that the magnitude of $e[k] * h[k]$ is below the quantization step $Q$. The overall quantization error is then\n\n\\begin{equation}\ne_H[k] = x_Q[k] - x[k] = e[k] * (\\delta[k] - h[k])\n\\end{equation}\n\nThe power spectral density (PSD) of the quantization error with noise shaping is calculated to\n\n\\begin{equation}\n\\Phi_{e_H e_H}(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega}) = \\Phi_{ee}(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega}) \\cdot \\left| 1 - H(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega}) \\right|^2\n\\end{equation}\n\nHence the PSD $\\Phi_{ee}(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega})$ of the quantizer without noise shaping is weighted by $| 1 - H(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega}) |^2$. Noise shaping allows a spectral modification of the quantization error. The desired shaping depends on the application scenario. For some applications, high-frequency noise is less disturbing as low-frequency noise.", "_____no_output_____" ], [ "### Example - First-Order Noise Shaping\n\nIf the feedback of the error signal is delayed by one sample we get with $h[k] = \\delta[k-1]$\n\n\\begin{equation}\n\\Phi_{e_H e_H}(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega}) = \\Phi_{ee}(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega}) \\cdot \\left| 1 - \\mathrm{e}^{\\,-\\mathrm{j}\\,\\Omega} \\right|^2\n\\end{equation}\n\nFor linear uniform quantization $\\Phi_{ee}(\\mathrm{e}^{\\,\\mathrm{j}\\,\\Omega}) = \\sigma_e^2$ is constant. Hence, the spectral shaping constitutes a high-pass characteristic of first order. The following simulation evaluates the noise shaping quantizer of first order.", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as sig\n\nw = 8 # wordlength of the quantized signal\nxmin = -1 # minimum of input signal\nN = 32768 # number of samples\n\n\ndef uniform_midtread_quantizer_w_ns(x, Q):\n # limiter\n x = np.copy(x)\n idx = np.where(x <= -1)\n x[idx] = -1\n idx = np.where(x > 1 - Q)\n x[idx] = 1 - Q\n # linear uniform quantization with noise shaping\n xQ = Q * np.floor(x/Q + 1/2)\n e = xQ - x\n xQ = xQ - np.concatenate(([0], e[0:-1]))\n \n return xQ[1:]\n\n\n# quantization step\nQ = 1/(2**(w-1))\n# compute input signal\nnp.random.seed(5)\nx = np.random.uniform(size=N, low=xmin, high=(-xmin-Q))\n# quantize signal\nxQ = uniform_midtread_quantizer_w_ns(x, Q)\ne = xQ - x[1:]\n# estimate PSD of error signal\nnf, Pee = sig.welch(e, nperseg=64)\n# estimate SNR\nSNR = 10*np.log10((np.var(x)/np.var(e)))\nprint('SNR = {:2.1f} dB'.format(SNR))\n\n\nplt.figure(figsize=(10,5))\nOm = nf*2*np.pi\nplt.plot(Om, Pee*6/Q**2, label='estimated PSD')\nplt.plot(Om, np.abs(1 - np.exp(-1j*Om))**2, label='theoretic PSD')\nplt.plot(Om, np.ones(Om.shape), label='PSD w/o noise shaping')\nplt.title('PSD of quantization error')\nplt.xlabel(r'$\\Omega$')\nplt.ylabel(r'$\\hat{\\Phi}_{e_H e_H}(e^{j \\Omega}) / \\sigma_e^2$')\nplt.axis([0, np.pi, 0, 4.5]);\nplt.legend(loc='upper left')\nplt.grid()", "SNR = 45.2 dB\n" ] ], [ [ "**Exercise**\n\n* The overall average SNR is lower than for the quantizer without noise shaping. Why?\n\nSolution: The average power per frequency is lower that without noise shaping for frequencies below $\\Omega \\approx \\pi$. However, this comes at the cost of a larger average power per frequency for frequencies above $\\Omega \\approx \\pi$. The average power of the quantization noise is given as the integral over the PSD of the quantization noise. It is larger for noise shaping and the resulting SNR is consequently lower. Noise shaping is nevertheless beneficial in applications where a lower quantization error in a limited frequency region is desired.", "_____no_output_____" ], [ "**Copyright**\n\nThis notebook is provided as [Open Educational Resource](https://en.wikipedia.org/wiki/Open_educational_resources). Feel free to use the notebook for your own purposes. The text is licensed under [Creative Commons Attribution 4.0](https://creativecommons.org/licenses/by/4.0/), the code of the IPython examples under the [MIT license](https://opensource.org/licenses/MIT). Please attribute the work as follows: *Sascha Spors, Digital Signal Processing - Lecture notes featuring computational examples, 2016-2018*.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d02f009e9f7f16d92c36c0b27c3a0f693cb27864
74,564
ipynb
Jupyter Notebook
intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb
jr7/deep-learning-v2-pytorch
73ba4caea6b132e21643710c9623f25b09b5fca1
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb
jr7/deep-learning-v2-pytorch
73ba4caea6b132e21643710c9623f25b09b5fca1
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 2 - Neural Networks in PyTorch (Exercises).ipynb
jr7/deep-learning-v2-pytorch
73ba4caea6b132e21643710c9623f25b09b5fca1
[ "MIT" ]
null
null
null
89.405276
16,616
0.793372
[ [ [ "# Neural networks with PyTorch\n\nDeep learning networks tend to be massive with dozens or hundreds of layers, that's where the term \"deep\" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. PyTorch has a nice module `nn` that provides a nice way to efficiently build large neural networks.", "_____no_output_____" ] ], [ [ "# Import necessary packages\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport torch\n\nimport helper\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "\nNow we're going to build a larger network that can solve a (formerly) difficult problem, identifying text in an image. Here we'll use the MNIST dataset which consists of greyscale handwritten digits. Each image is 28x28 pixels, you can see a sample below\n\n<img src='assets/mnist.png'>\n\nOur goal is to build a neural network that can take one of these images and predict the digit in the image.\n\nFirst up, we need to get our dataset. This is provided through the `torchvision` package. The code below will download the MNIST dataset, then create training and test datasets for us. Don't worry too much about the details here, you'll learn more about this later.", "_____no_output_____" ] ], [ [ "### Run this cell\n\nfrom torchvision import datasets, transforms\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,)),\n ])\n\n# Download and load the training data\ntrainset = datasets.MNIST('~/.pytorch/MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)", "_____no_output_____" ] ], [ [ "We have the training data loaded into `trainloader` and we make that an iterator with `iter(trainloader)`. Later, we'll use this to loop through the dataset for training, like\n\n```python\nfor image, label in trainloader:\n ## do things with images and labels\n```\n\nYou'll notice I created the `trainloader` with a batch size of 64, and `shuffle=True`. The batch size is the number of images we get in one iteration from the data loader and pass through our network, often called a *batch*. And `shuffle=True` tells it to shuffle the dataset every time we start going through the data loader again. But here I'm just grabbing the first batch so we can check out the data. We can see below that `images` is just a tensor with size `(64, 1, 28, 28)`. So, 64 images per batch, 1 color channel, and 28x28 images.", "_____no_output_____" ] ], [ [ "dataiter = iter(trainloader)\nimages, labels = dataiter.next()\nprint(type(images))\nprint(images.shape)\nprint(labels.shape)", "<class 'torch.Tensor'>\ntorch.Size([64, 1, 28, 28])\ntorch.Size([64])\n" ] ], [ [ "This is what one of the images looks like. ", "_____no_output_____" ] ], [ [ "plt.imshow(images[1].numpy().squeeze(), cmap='Greys_r');", "_____no_output_____" ] ], [ [ "First, let's try to build a simple network for this dataset using weight matrices and matrix multiplications. Then, we'll see how to do it using PyTorch's `nn` module which provides a much more convenient and powerful method for defining network architectures.\n\nThe networks you've seen so far are called *fully-connected* or *dense* networks. Each unit in one layer is connected to each unit in the next layer. In fully-connected networks, the input to each layer must be a one-dimensional vector (which can be stacked into a 2D tensor as a batch of multiple examples). However, our images are 28x28 2D tensors, so we need to convert them into 1D vectors. Thinking about sizes, we need to convert the batch of images with shape `(64, 1, 28, 28)` to a have a shape of `(64, 784)`, 784 is 28 times 28. This is typically called *flattening*, we flattened the 2D images into 1D vectors.\n\nPreviously you built a network with one output unit. Here we need 10 output units, one for each digit. We want our network to predict the digit shown in an image, so what we'll do is calculate probabilities that the image is of any one digit or class. This ends up being a discrete probability distribution over the classes (digits) that tells us the most likely class for the image. That means we need 10 output units for the 10 classes (digits). We'll see how to convert the network output into a probability distribution next.\n\n> **Exercise:** Flatten the batch of images `images`. Then build a multi-layer network with 784 input units, 256 hidden units, and 10 output units using random tensors for the weights and biases. For now, use a sigmoid activation for the hidden layer. Leave the output layer without an activation, we'll add one that gives us a probability distribution next.", "_____no_output_____" ] ], [ [ "## Your solution\nimages_flat = images.view(64, 784)\n\ndef act(x):\n return 1/(1+torch.exp(-x))\n\ntorch.manual_seed(42)\n\nn_input = 784\nn_hidden = 256\nn_output = 10\n\nW1 = torch.randn((n_input, n_hidden))\nW2 = torch.randn((n_hidden, n_output))\n\nB1 = torch.randn((1, 1))\nB2 = torch.randn((1, 1))\n\ndef network(features):\n return act(torch.mm(act(torch.mm(features, W1) + B1) ,W2) + B2)\n\nout = network(images_flat)\nout.shape\n\n\n\n\n#out = # output of your network, should have shape (64,10)", "_____no_output_____" ] ], [ [ "Now we have 10 outputs for our network. We want to pass in an image to our network and get out a probability distribution over the classes that tells us the likely class(es) the image belongs to. Something that looks like this:\n<img src='assets/image_distribution.png' width=500px>\n\nHere we see that the probability for each class is roughly the same. This is representing an untrained network, it hasn't seen any data yet so it just returns a uniform distribution with equal probabilities for each class.\n\nTo calculate this probability distribution, we often use the [**softmax** function](https://en.wikipedia.org/wiki/Softmax_function). Mathematically this looks like\n\n$$\n\\Large \\sigma(x_i) = \\cfrac{e^{x_i}}{\\sum_k^K{e^{x_k}}}\n$$\n\nWhat this does is squish each input $x_i$ between 0 and 1 and normalizes the values to give you a proper probability distribution where the probabilites sum up to one.\n\n> **Exercise:** Implement a function `softmax` that performs the softmax calculation and returns probability distributions for each example in the batch. Note that you'll need to pay attention to the shapes when doing this. If you have a tensor `a` with shape `(64, 10)` and a tensor `b` with shape `(64,)`, doing `a/b` will give you an error because PyTorch will try to do the division across the columns (called broadcasting) but you'll get a size mismatch. The way to think about this is for each of the 64 examples, you only want to divide by one value, the sum in the denominator. So you need `b` to have a shape of `(64, 1)`. This way PyTorch will divide the 10 values in each row of `a` by the one value in each row of `b`. Pay attention to how you take the sum as well. You'll need to define the `dim` keyword in `torch.sum`. Setting `dim=0` takes the sum across the rows while `dim=1` takes the sum across the columns.", "_____no_output_____" ] ], [ [ "def softmax(x):\n return torch.exp(x)/torch.sum(torch.exp(x), dim=1).reshape(64, 1)\n \n \n \n ## TODO: Implement the softmax function here\n\n# Here, out should be the output of the network in the previous excercise with shape (64,10)\nprobabilities = softmax(out)\n\n# Does it have the right shape? Should be (64, 10)\nprint(probabilities.shape)\n# Does it sum to 1?\nprint(probabilities.sum(dim=1))", "torch.Size([64, 10])\ntensor([1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,\n 1.0000])\n" ] ], [ [ "## Building networks with PyTorch\n\nPyTorch provides a module `nn` that makes building networks much simpler. Here I'll show you how to build the same one as above with 784 inputs, 256 hidden units, 10 output units and a softmax output.", "_____no_output_____" ] ], [ [ "from torch import nn", "_____no_output_____" ], [ "class Network(nn.Module):\n def __init__(self):\n super().__init__()\n \n # Inputs to hidden layer linear transformation\n self.hidden = nn.Linear(784, 256)\n # Output layer, 10 units - one for each digit\n self.output = nn.Linear(256, 10)\n \n # Define sigmoid activation and softmax output \n self.sigmoid = nn.Sigmoid()\n self.softmax = nn.Softmax(dim=1)\n \n def forward(self, x):\n # Pass the input tensor through each of our operations\n x = self.hidden(x)\n x = self.sigmoid(x)\n x = self.output(x)\n x = self.softmax(x)\n \n return x", "_____no_output_____" ] ], [ [ "Let's go through this bit by bit.\n\n```python\nclass Network(nn.Module):\n```\n\nHere we're inheriting from `nn.Module`. Combined with `super().__init__()` this creates a class that tracks the architecture and provides a lot of useful methods and attributes. It is mandatory to inherit from `nn.Module` when you're creating a class for your network. The name of the class itself can be anything.\n\n```python\nself.hidden = nn.Linear(784, 256)\n```\n\nThis line creates a module for a linear transformation, $x\\mathbf{W} + b$, with 784 inputs and 256 outputs and assigns it to `self.hidden`. The module automatically creates the weight and bias tensors which we'll use in the `forward` method. You can access the weight and bias tensors once the network (`net`) is created with `net.hidden.weight` and `net.hidden.bias`.\n\n```python\nself.output = nn.Linear(256, 10)\n```\n\nSimilarly, this creates another linear transformation with 256 inputs and 10 outputs.\n\n```python\nself.sigmoid = nn.Sigmoid()\nself.softmax = nn.Softmax(dim=1)\n```\n\nHere I defined operations for the sigmoid activation and softmax output. Setting `dim=1` in `nn.Softmax(dim=1)` calculates softmax across the columns.\n\n```python\ndef forward(self, x):\n```\n\nPyTorch networks created with `nn.Module` must have a `forward` method defined. It takes in a tensor `x` and passes it through the operations you defined in the `__init__` method.\n\n```python\nx = self.hidden(x)\nx = self.sigmoid(x)\nx = self.output(x)\nx = self.softmax(x)\n```\n\nHere the input tensor `x` is passed through each operation and reassigned to `x`. We can see that the input tensor goes through the hidden layer, then a sigmoid function, then the output layer, and finally the softmax function. It doesn't matter what you name the variables here, as long as the inputs and outputs of the operations match the network architecture you want to build. The order in which you define things in the `__init__` method doesn't matter, but you'll need to sequence the operations correctly in the `forward` method.\n\nNow we can create a `Network` object.", "_____no_output_____" ] ], [ [ "# Create the network and look at it's text representation\nmodel = Network()\nmodel", "_____no_output_____" ] ], [ [ "You can define the network somewhat more concisely and clearly using the `torch.nn.functional` module. This is the most common way you'll see networks defined as many operations are simple element-wise functions. We normally import this module as `F`, `import torch.nn.functional as F`.", "_____no_output_____" ] ], [ [ "import torch.nn.functional as F\n\nclass Network(nn.Module):\n def __init__(self):\n super().__init__()\n # Inputs to hidden layer linear transformation\n self.hidden = nn.Linear(784, 256)\n # Output layer, 10 units - one for each digit\n self.output = nn.Linear(256, 10)\n \n def forward(self, x):\n # Hidden layer with sigmoid activation\n x = F.sigmoid(self.hidden(x))\n # Output layer with softmax activation\n x = F.softmax(self.output(x), dim=1)\n \n return x", "_____no_output_____" ] ], [ [ "### Activation functions\n\nSo far we've only been looking at the sigmoid activation function, but in general any function can be used as an activation function. The only requirement is that for a network to approximate a non-linear function, the activation functions must be non-linear. Here are a few more examples of common activation functions: Tanh (hyperbolic tangent), and ReLU (rectified linear unit).\n\n<img src=\"assets/activation.png\" width=700px>\n\nIn practice, the ReLU function is used almost exclusively as the activation function for hidden layers.", "_____no_output_____" ], [ "### Your Turn to Build a Network\n\n<img src=\"assets/mlp_mnist.png\" width=600px>\n\n> **Exercise:** Create a network with 784 input units, a hidden layer with 128 units and a ReLU activation, then a hidden layer with 64 units and a ReLU activation, and finally an output layer with a softmax activation as shown above. You can use a ReLU activation with the `nn.ReLU` module or `F.relu` function.\n\nIt's good practice to name your layers by their type of network, for instance 'fc' to represent a fully-connected layer. As you code your solution, use `fc1`, `fc2`, and `fc3` as your layer names.", "_____no_output_____" ] ], [ [ "## Your solution here\nclass FirstNet(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 128)\n self.fc2 = nn.Linear(128, 64)\n self.fc3 = nn.Linear(64, 10)\n \n \n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.softmax(self.fc3(x), dim=1)\n return x\n \nmodel = FirstNet()\n ", "_____no_output_____" ] ], [ [ "### Initializing weights and biases\n\nThe weights and such are automatically initialized for you, but it's possible to customize how they are initialized. The weights and biases are tensors attached to the layer you defined, you can get them with `model.fc1.weight` for instance.", "_____no_output_____" ] ], [ [ "print(model.fc1.weight)\nprint(model.fc1.bias)", "Parameter containing:\ntensor([[-0.0324, 0.0352, -0.0258, ..., 0.0276, -0.0145, -0.0265],\n [ 0.0058, 0.0206, -0.0277, ..., 0.0027, -0.0107, -0.0135],\n [-0.0175, -0.0071, 0.0020, ..., -0.0303, 0.0014, -0.0020],\n ...,\n [-0.0153, -0.0351, -0.0131, ..., -0.0250, 0.0067, -0.0284],\n [ 0.0173, -0.0294, 0.0263, ..., -0.0160, 0.0226, -0.0053],\n [ 0.0124, -0.0154, 0.0274, ..., 0.0156, 0.0218, -0.0344]],\n requires_grad=True)\nParameter containing:\ntensor([ 0.0177, -0.0303, -0.0252, -0.0185, -0.0159, 0.0209, -0.0233, 0.0078,\n -0.0006, 0.0265, 0.0153, 0.0204, -0.0302, -0.0021, -0.0076, -0.0075,\n 0.0357, 0.0261, -0.0172, 0.0036, 0.0261, -0.0217, 0.0093, -0.0073,\n 0.0035, 0.0165, 0.0037, -0.0039, 0.0139, -0.0182, 0.0091, -0.0335,\n 0.0334, 0.0294, 0.0281, 0.0304, -0.0251, -0.0110, 0.0209, 0.0265,\n 0.0242, -0.0241, 0.0032, -0.0322, 0.0065, -0.0212, -0.0006, 0.0007,\n 0.0006, 0.0322, -0.0046, -0.0328, 0.0060, 0.0189, -0.0153, 0.0214,\n -0.0122, 0.0064, 0.0167, 0.0233, 0.0340, 0.0207, -0.0257, 0.0185,\n -0.0009, -0.0320, 0.0239, -0.0226, 0.0093, 0.0098, -0.0124, 0.0063,\n -0.0062, 0.0022, -0.0144, 0.0011, 0.0053, 0.0161, -0.0220, 0.0323,\n -0.0197, 0.0168, 0.0340, 0.0330, -0.0035, 0.0030, -0.0253, 0.0044,\n -0.0017, -0.0034, -0.0259, 0.0183, -0.0257, 0.0126, 0.0293, -0.0269,\n 0.0178, 0.0098, 0.0264, 0.0125, 0.0160, 0.0170, 0.0312, 0.0148,\n 0.0223, -0.0148, -0.0042, 0.0080, -0.0098, 0.0243, -0.0257, 0.0050,\n 0.0167, -0.0194, 0.0257, -0.0018, 0.0061, -0.0322, -0.0059, -0.0114,\n 0.0315, -0.0073, 0.0253, -0.0096, 0.0028, 0.0145, 0.0022, -0.0301],\n requires_grad=True)\n" ] ], [ [ "For custom initialization, we want to modify these tensors in place. These are actually autograd *Variables*, so we need to get back the actual tensors with `model.fc1.weight.data`. Once we have the tensors, we can fill them with zeros (for biases) or random normal values.", "_____no_output_____" ] ], [ [ "# Set biases to all zeros\nmodel.fc1.bias.data.fill_(0)", "_____no_output_____" ], [ "# sample from random normal with standard dev = 0.01\nmodel.fc1.weight.data.normal_(std=0.01)", "_____no_output_____" ] ], [ [ "### Forward pass\n\nNow that we have a network, let's see what happens when we pass in an image.", "_____no_output_____" ] ], [ [ "# Grab some data \ndataiter = iter(trainloader)\nimages, labels = dataiter.next()\n\n# Resize images into a 1D vector, new shape is (batch size, color channels, image pixels) \nimages.resize_(64, 1, 784)\n# or images.resize_(images.shape[0], 1, 784) to automatically get batch size\n\n# Forward pass through the network\nimg_idx = 0\nps = model.forward(images[img_idx,:])\n\nimg = images[img_idx]\nhelper.view_classify(img.view(1, 28, 28), ps)", "_____no_output_____" ] ], [ [ "As you can see above, our network has basically no idea what this digit is. It's because we haven't trained it yet, all the weights are random!\n\n### Using `nn.Sequential`\n\nPyTorch provides a convenient way to build networks like this where a tensor is passed sequentially through operations, `nn.Sequential` ([documentation](https://pytorch.org/docs/master/nn.html#torch.nn.Sequential)). Using this to build the equivalent network:", "_____no_output_____" ] ], [ [ "# Hyperparameters for our network\ninput_size = 784\nhidden_sizes = [128, 64]\noutput_size = 10\n\n# Build a feed-forward network\nmodel = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),\n nn.ReLU(),\n nn.Linear(hidden_sizes[0], hidden_sizes[1]),\n nn.ReLU(),\n nn.Linear(hidden_sizes[1], output_size),\n nn.Softmax(dim=1))\nprint(model)\n\n# Forward pass through the network and display output\nimages, labels = next(iter(trainloader))\nimages.resize_(images.shape[0], 1, 784)\nps = model.forward(images[0,:])\nhelper.view_classify(images[0].view(1, 28, 28), ps)", "Sequential(\n (0): Linear(in_features=784, out_features=128, bias=True)\n (1): ReLU()\n (2): Linear(in_features=128, out_features=64, bias=True)\n (3): ReLU()\n (4): Linear(in_features=64, out_features=10, bias=True)\n (5): Softmax()\n)\n" ] ], [ [ "Here our model is the same as before: 784 input units, a hidden layer with 128 units, ReLU activation, 64 unit hidden layer, another ReLU, then the output layer with 10 units, and the softmax output.\n\nThe operations are available by passing in the appropriate index. For example, if you want to get first Linear operation and look at the weights, you'd use `model[0]`.", "_____no_output_____" ] ], [ [ "print(model[0])\nmodel[0].weight", "Linear(in_features=784, out_features=128, bias=True)\n" ] ], [ [ "You can also pass in an `OrderedDict` to name the individual layers and operations, instead of using incremental integers. Note that dictionary keys must be unique, so _each operation must have a different name_.", "_____no_output_____" ] ], [ [ "from collections import OrderedDict\nmodel = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(input_size, hidden_sizes[0])),\n ('relu1', nn.ReLU()),\n ('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])),\n ('relu2', nn.ReLU()),\n ('output', nn.Linear(hidden_sizes[1], output_size)),\n ('softmax', nn.Softmax(dim=1))]))\nmodel", "_____no_output_____" ] ], [ [ "Now you can access layers either by integer or the name", "_____no_output_____" ] ], [ [ "print(model[0])\nprint(model.fc1)", "Linear(in_features=784, out_features=128, bias=True)\nLinear(in_features=784, out_features=128, bias=True)\n" ] ], [ [ "In the next notebook, we'll see how we can train a neural network to accuractly predict the numbers appearing in the MNIST images.", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d02f1a1130e30fbca5de1984b3830be7233f1877
183,189
ipynb
Jupyter Notebook
drafts/exercises/ibovespa.ipynb
ItamarRocha/introduction-to-AI
134e4e39f7034657472d7996ce70f37ff7a6e74b
[ "MIT" ]
2
2020-06-23T16:28:26.000Z
2020-07-11T11:39:18.000Z
drafts/exercises/ibovespa.ipynb
ItamarRocha/Data-Analysis-and-Manipulation
134e4e39f7034657472d7996ce70f37ff7a6e74b
[ "MIT" ]
12
2021-09-08T02:38:57.000Z
2022-03-12T01:00:12.000Z
drafts/exercises/ibovespa.ipynb
ItamarRocha/Data-Analysis-and-Manipulation
134e4e39f7034657472d7996ce70f37ff7a6e74b
[ "MIT" ]
1
2021-05-07T15:22:50.000Z
2021-05-07T15:22:50.000Z
210.804373
134,100
0.887291
[ [ [ "# ------------ First A.I. activity ------------ ", "_____no_output_____" ], [ "## 1. IBOVESPA volume prediction ", "_____no_output_____" ], [ "-> Importing libraries that are going to be used in the code", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "-> Importing the datasets", "_____no_output_____" ] ], [ [ "dataset = pd.read_csv(\"datasets/ibovespa.csv\",delimiter = \";\")", "_____no_output_____" ] ], [ [ "-> Converting time to datetime in order to make it easy to manipulate", "_____no_output_____" ] ], [ [ "dataset['Data/Hora'] = dataset['Data/Hora'].str.replace(\"/\",\"-\")\n\ndataset['Data/Hora'] = pd.to_datetime(dataset['Data/Hora'])", "_____no_output_____" ] ], [ [ "-> Visualizing the data", "_____no_output_____" ] ], [ [ "dataset.head()", "_____no_output_____" ] ], [ [ "-> creating date dataframe and splitting its features", "_____no_output_____" ], [ "date = dataset.iloc[:,0:1]\n\ndate['day'] = date['Data/Hora'].dt.day\ndate['month'] = date['Data/Hora'].dt.month\ndate['year'] = date['Data/Hora'].dt.year\n\ndate = date.drop(columns = ['Data/Hora'])\n", "_____no_output_____" ], [ "-> removing useless columns", "_____no_output_____" ] ], [ [ "dataset = dataset.drop(columns = ['Data/Hora','Unnamed: 7','Unnamed: 8','Unnamed: 9'])", "_____no_output_____" ] ], [ [ "-> transforming atributes to the correct format ", "_____no_output_____" ] ], [ [ "for key, value in dataset.head().iteritems():\n dataset[key] = dataset[key].str.replace(\".\",\"\").str.replace(\",\",\".\").astype(float)\n\"\"\"\nfor key, value in date.head().iteritems():\n dataset[key] = date[key]\n\"\"\"", "_____no_output_____" ] ], [ [ "-> Means", "_____no_output_____" ] ], [ [ "dataset.mean()", "_____no_output_____" ] ], [ [ "-> plotting graphics", "_____no_output_____" ] ], [ [ "plt.boxplot(dataset['Volume'])\nplt.title('boxplot')\nplt.xlabel('volume')\nplt.ylabel('valores')\nplt.ticklabel_format(style='sci', axis='y', useMathText = True)", "_____no_output_____" ], [ "dataset['Maxima'].median()", "_____no_output_____" ], [ "dataset['Minima'].mean()", "_____no_output_____" ] ], [ [ "-> Média truncada", "_____no_output_____" ] ], [ [ "from scipy import stats\nm = stats.trim_mean(dataset['Minima'], 0.1)\nprint(m)", "99109.76692307692\n" ] ], [ [ "-> variancia e standard deviation", "_____no_output_____" ] ], [ [ "v = dataset['Cotacao'].var()\nprint(v)", "15895285.259223964\n" ], [ "d = dataset['Cotacao'].std()\nprint(v)", "15895285.259223964\n" ], [ "m = dataset['Cotacao'].mean()\nprint(m)", "99674.05773437498\n" ] ], [ [ "-> covariancia dos atributos, mas antes fazer uma standard scaler pra facilitar a visão e depois transforma de volta pra dataframe pandas", "_____no_output_____" ], [ "#### correlation shows us the relationship between the two variables and how are they related while covariance shows us how the two variables vary from each other.", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\ndataset_cov = sc.fit_transform(dataset)\ndataset_cov = pd.DataFrame(dataset_cov)\ndataset_cov.cov()", "_____no_output_____" ] ], [ [ "-> plotting the graph may be easier to observe the correlation", "_____no_output_____" ] ], [ [ "corr = dataset.corr()\ncorr.style.background_gradient(cmap = 'coolwarm')", "_____no_output_____" ], [ "pd.plotting.scatter_matrix(dataset, figsize=(6, 6))\nplt.show()", "_____no_output_____" ], [ "plt.matshow(dataset.corr())\nplt.xticks(range(len(dataset.columns)), dataset.columns)\nplt.yticks(range(len(dataset.columns)), dataset.columns)\nplt.colorbar()\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d02f244dd64e4fa08d31f070ecb802bca45eef36
12,130
ipynb
Jupyter Notebook
python-for-data/Ex02 - Functions and Getting Help.ipynb
hoaintp/atom-assignments
f72389ff0648f1cf66ab84007b260d2e6b4ac6f3
[ "MIT" ]
null
null
null
python-for-data/Ex02 - Functions and Getting Help.ipynb
hoaintp/atom-assignments
f72389ff0648f1cf66ab84007b260d2e6b4ac6f3
[ "MIT" ]
null
null
null
python-for-data/Ex02 - Functions and Getting Help.ipynb
hoaintp/atom-assignments
f72389ff0648f1cf66ab84007b260d2e6b4ac6f3
[ "MIT" ]
null
null
null
27.31982
271
0.579802
[ [ [ "# Exercise 02 - Functions and Getting Help !", "_____no_output_____" ], [ "## 1. Complete Your Very First Function \n\nComplete the body of the following function according to its docstring.\n\n*HINT*: Python has a builtin function `round`", "_____no_output_____" ] ], [ [ "def round_to_two_places(num):\n \"\"\"Return the given number rounded to two decimal places. \n \n >>> round_to_two_places(3.14159)\n 3.14\n \"\"\"\n # Replace this body with your own code.\n # (\"pass\" is a keyword that does literally nothing. We used it as a placeholder,\n # so that it will not raise any errors,\n # because after we begin a code block, Python requires at least one line of code)\n pass", "_____no_output_____" ], [ "def round_to_two_places(num):\n num = round(num,2)\n print('The number after rounded to two decimal places is: ', num)\nround_to_two_places(3.4455)", "The number after rounded to two decimal places is: 3.45\n" ] ], [ [ "## 2. Explore the Built-in Function\nThe help for `round` says that `ndigits` (the second argument) may be negative.\nWhat do you think will happen when it is? Try some examples in the following cell?\n\nCan you think of a case where this would be useful?", "_____no_output_____" ] ], [ [ "print(round(122.3444,-3))\nprint(round(122.3456,-2))\nprint(round(122.5454,-1))\nprint(round(122.13432,0))\n\n#round with ndigits <=0 - the rounding will begin from the decimal point to the left", "0.0\n100.0\n120.0\n122.0\n" ] ], [ [ "## 3. More Function\n\nGiving the problem of candy-sharing friends Alice, Bob and Carol tried to split candies evenly. For the sake of their friendship, any candies left over would be smashed. For example, if they collectively bring home 91 candies, they will take 30 each and smash 1.\n\nBelow is a simple function that will calculate the number of candies to smash for *any* number of total candies.\n\n**Your task**: \n- Modify it so that it optionally takes a second argument representing the number of friends the candies are being split between. If no second argument is provided, it should assume 3 friends, as before.\n- Update the docstring to reflect this new behaviour.", "_____no_output_____" ] ], [ [ "def to_smash(total_candies,n = 3):\n \"\"\"Return the number of leftover candies that must be smashed after distributing\n the given number of candies evenly between 3 friends.\n \n >>> to_smash(91)\n 1\n \"\"\"\n return total_candies % n", "_____no_output_____" ], [ "print('#no. of candies to smash = ', to_smash(31))\nprint('#no. of candies to smash = ', to_smash(32,5))", "#no. of candies to smash = 1\n#no. of candies to smash = 2\n" ] ], [ [ "## 4. Taste some Errors\n\nIt may not be fun, but reading and understanding **error messages** will help you improve solving problem skills.\n\nEach code cell below contains some commented-out buggy code. For each cell...\n\n1. Read the code and predict what you think will happen when it's run.\n2. Then uncomment the code and run it to see what happens. *(**Tips**: In the kernel editor, you can highlight several lines and press `ctrl`+`/` to toggle commenting.)*\n3. Fix the code (so that it accomplishes its intended purpose without throwing an exception)\n\n<!-- TODO: should this be autochecked? Delta is probably pretty small. -->", "_____no_output_____" ] ], [ [ "round_to_two_places(9.9999)", "The number after rounded to two decimal places is: 10.0\n" ], [ "x = -10\ny = 5\n# Which of the two variables above has the smallest absolute value?\nsmallest_abs = min(abs(x),abs(y))\nprint(smallest_abs)", "5\n" ], [ "def f(x):\n y = abs(x)\n return y\n\nprint(f(5))", "5\n" ] ], [ [ "## 5. More and more Functions\n\nFor this question, we'll be using two functions imported from Python's `time` module.\n\n### Time Function\nThe [time](https://docs.python.org/3/library/time.html#time.time) function returns the number of seconds that have passed since the Epoch (aka [Unix time](https://en.wikipedia.org/wiki/Unix_time)). \n\n<!-- We've provided a function called `seconds_since_epoch` which returns the number of seconds that have passed since the Epoch (aka [Unix time](https://en.wikipedia.org/wiki/Unix_time)). -->\n\nTry it out below. Each time you run it, you should get a slightly larger number.", "_____no_output_____" ] ], [ [ "# Importing the function 'time' from the module of the same name. \n# (We'll discuss imports in more depth later)\nfrom time import time\nt = time()\nprint(t, \"seconds since the Epoch\")", "1621529220.6860213 seconds since the Epoch\n" ] ], [ [ "### Sleep Function\nWe'll also be using a function called [sleep](https://docs.python.org/3/library/time.html#time.sleep), which makes us wait some number of seconds while it does nothing particular. (Sounds useful, right?)\n\nYou can see it in action by running the cell below:", "_____no_output_____" ] ], [ [ "from time import sleep\nduration = 5\nprint(\"Getting sleepy. See you in\", duration, \"seconds\")\nsleep(duration)\nprint(\"I'm back. What did I miss?\")", "Getting sleepy. See you in 5 seconds\nI'm back. What did I miss?\n" ] ], [ [ "### Your Own Function\nWith the help of these functions, complete the function **`time_call`** below according to its docstring.\n\n<!-- (The sleep function will be useful for testing here since we have a pretty good idea of what something like `time_call(sleep, 1)` should return.) -->", "_____no_output_____" ] ], [ [ "def time_call(fn, arg):\n \"\"\"Return the amount of time the given function takes (in seconds) when called with the given argument.\n \"\"\"\n from time import time\n start_time = time()\n fn(arg)\n end_time = time()\n duration = end_time - start_time\n return duration", "_____no_output_____" ] ], [ [ "How would you verify that `time_call` is working correctly? Think about it...", "_____no_output_____" ] ], [ [ "#solution? use sleep function?", "_____no_output_____" ] ], [ [ "## 6. 🌶️ Reuse your Function\n\n*Note: this question depends on a working solution to the previous question.*\n\nComplete the function below according to its docstring.", "_____no_output_____" ] ], [ [ "def slowest_call(fn, arg1, arg2, arg3):\n \"\"\"Return the amount of time taken by the slowest of the following function\n calls: fn(arg1), fn(arg2), fn(arg3)\n \n \"\"\"\n slowest = min(time_call(fn, arg1), time_call(fn, arg2), time_call(fn,arg3))\n return slowest\nprint(slowest_call(sleep,1,2,3))\n", "1.012155294418335\n" ] ], [ [ "# Keep Going", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d02f35e9eeecbd701187c6fba53490d2bd398334
5,707
ipynb
Jupyter Notebook
00_core.ipynb
mgfrantz/dessiccate
52004d393cd0cc4ffb9f0d361b150ee5087f6bf7
[ "Apache-2.0" ]
null
null
null
00_core.ipynb
mgfrantz/dessiccate
52004d393cd0cc4ffb9f0d361b150ee5087f6bf7
[ "Apache-2.0" ]
null
null
null
00_core.ipynb
mgfrantz/dessiccate
52004d393cd0cc4ffb9f0d361b150ee5087f6bf7
[ "Apache-2.0" ]
null
null
null
21.454887
113
0.493604
[ [ [ "# default_exp core", "_____no_output_____" ] ], [ [ "# Core\n\n> API details.", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.showdoc import *", "_____no_output_____" ], [ "# export\nfrom attrdict import AttrDict\nfrom fastcore.basics import Path\nimport subprocess", "_____no_output_____" ] ], [ [ "## Running bash commands in Python", "_____no_output_____" ] ], [ [ "# export\ndef run_bash(cmd, return_output=True):\n process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n if not error:\n print(output.decode('utf-8'))\n if return_output:\n return output.decode('utf-8')\n else:\n print(error.decode('utf-8'))\n if return_output:\n return error.decoe('utf-8')", "_____no_output_____" ], [ "out = run_bash('ls')", "00_core.ipynb\n01_plotting.ipynb\n02_pandas.ipynb\nCONTRIBUTING.md\nLICENSE\nMANIFEST.in\nMakefile\nREADME.md\nbuild\nconda\ndessiccate\ndessiccate.egg-info\ndist\ndocker-compose.yml\ndocs\nindex.ipynb\nsettings.ini\nsetup.py\n\n" ] ], [ [ "## Setting up in colab\n\nIf you're in colab, you may not have the proper packages installed.\nRunning this function will set you up to work in colab.", "_____no_output_____" ] ], [ [ "# export\ndef colab_setup():\n \"\"\"\n Sets up for development in Google Colab.\n Repo must be cloned in drive/colab/ directory.\n \"\"\"\n try:\n from google.colab import drive\n print('Running in colab')\n drive.mount('/content/drive', force_remount=True)\n _ = run_bash(\"pip install -Uqq nbdev\")\n import os\n os.chdir('/content/drive/MyDrive/colab/dessiccate/')\n print(\"Working in\", os.getcwd())\n _ = run_bash('pip install -e . --quiet')\n except:\n import os\n print(\"Working in\", os.getcwd())\n print('Running locally')", "_____no_output_____" ], [ "colab_setup()", "Working in /Users/michaelfrantz/Google Drive/colab/dessiccate\nRunning locally\n" ] ], [ [ "## Path\n\nOften, you want to create a new directory.\nEven if all you have is a file path, you can now call `mkdir_if_not_exists` to create the parent directory.", "_____no_output_____" ] ], [ [ "# export\ndef mkdir_if_not_exists(self, parents=True):\n \"\"\"\n Creates the directory of the path if ot doesn't exist.\n If the path is a file, will not make the file itself,\n but will create the parent directory.\n \"\"\"\n if path.is_dir():\n p = path\n else:\n p = path.parent\n if not p.exists():\n p.mkdir(parents=parents)\n\nPath.mkdir_if_not_exists = mkdir_if_not_exists", "_____no_output_____" ], [ "path = Path('testdir/test.txt')", "_____no_output_____" ], [ "assert not path.exists()", "_____no_output_____" ], [ "path.mkdir_if_not_exists()", "_____no_output_____" ], [ "assert not path.exists()\nassert path.parent.exists()", "_____no_output_____" ], [ "path.parent.rmdir()", "_____no_output_____" ], [ "assert not path.parent.exists()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
d02f3a07db9c679afcfa08ef91183357d631ecbd
212,108
ipynb
Jupyter Notebook
notebooks/Tidal Station Locations.ipynb
SalishSeaCast/analysis-susan
52633f4fe82af6d7c69dff58f69f0da4f7933f48
[ "Apache-2.0" ]
null
null
null
notebooks/Tidal Station Locations.ipynb
SalishSeaCast/analysis-susan
52633f4fe82af6d7c69dff58f69f0da4f7933f48
[ "Apache-2.0" ]
null
null
null
notebooks/Tidal Station Locations.ipynb
SalishSeaCast/analysis-susan
52633f4fe82af6d7c69dff58f69f0da4f7933f48
[ "Apache-2.0" ]
null
null
null
301.289773
17,318
0.92039
[ [ [ "import matplotlib.pyplot as plt\nimport netCDF4 as nc\nimport numpy as np\nfrom salishsea_tools import geo_tools\n\n%matplotlib inline", "_____no_output_____" ], [ "bathyfile = '/home/sallen/MEOPAR/grid/bathymetry_201702.nc'\nmeshfile = '/home/sallen/MEOPAR/grid/mesh_mask201702.nc'\nmesh = nc.Dataset(meshfile)\nmodel_lats = nc.Dataset(bathyfile).variables['nav_lat'][:]\nmodel_lons = nc.Dataset(bathyfile).variables['nav_lon'][:]\nt_mask = mesh.variables['tmask'][0, 0]", "_____no_output_____" ], [ "windfile = './ubcSSaAtmosphereGridV1_0f03_6268_df4b.nc'\nwind_lats = nc.Dataset(windfile).variables['latitude'][:]\nwind_lons = nc.Dataset(windfile).variables['longitude'][:] -360", "_____no_output_____" ], [ "wavefile = '/results/SalishSea/wwatch3-forecast/SoG_ww3_fields_20170515_20170517.nc'\nwave_lats = nc.Dataset(wavefile).variables['latitude'][:]\nwave_lons = nc.Dataset(wavefile).variables['longitude'][:] -360.\nwave_lons, wave_lats = np.meshgrid(wave_lons, wave_lats)\nhs = nc.Dataset(wavefile).variables['hs'][0]\nwave_mask = np.where(hs !=0, 1, 0)", "_____no_output_____" ], [ "def get_tidal_stations(lon, lat, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=20):\n y, x = geo_tools.find_closest_model_point(lon, lat, model_lons, model_lats, grid='NEMO', land_mask=1-t_mask)\n ywind, xwind = geo_tools.find_closest_model_point(lon, lat, wind_lons, wind_lats, grid='GEM2.5')\n ywave, xwave = geo_tools.find_closest_model_point(lon, lat, wave_lons, wave_lats, grid='NEMO', land_mask=1-wave_mask)\n\n fig, ax = plt.subplots(1, 1, figsize=(7, 7))\n bigx = min(x+size, model_lons.shape[1]-1)\n imin, imax = model_lats[y-size, x-size], model_lats[y+size, bigx]\n jmin, jmax = model_lons[y+size, x-size], model_lons[y-size, bigx]\n dlon = model_lons[y+1, x+1] - model_lons[y, x]\n dlat = model_lats[y+1, x+1] - model_lats[y, x]\n ax.pcolormesh(model_lons - dlon/2., model_lats-dlat/2., t_mask, cmap='Greys_r')\n ax.set_xlim(jmin, jmax)\n ax.set_ylim(imin, imax)\n ax.plot(model_lons[y, x], model_lats[y, x], 'ro', label='NEMO')\n ax.plot(wind_lons[ywind, xwind], wind_lats[ywind, xwind], 'ys', label='GEM2.5')\n ax.plot(wave_lons[ywave, xwave], wave_lats[ywave, xwave], 'bo', label='WW3')\n ax.legend()\n return \"NEMO y, x: {0}, Wind y, x: {1}, Wave y, x: {2}\".format([y, x], [ywind, xwind], [ywave, xwave])", "_____no_output_____" ] ], [ [ "### Patricia Bay\n\n7277\tPatricia Bay\t48.6536 \t123.4515 ", "_____no_output_____" ] ], [ [ "get_tidal_stations(-123.4515, 48.6536, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ] ], [ [ "### Woodwards\n7610\tWoodwards's Landing\t49.1251 \t123.0754 ", "_____no_output_____" ] ], [ [ "get_tidal_stations(-123.0754, 49.1251, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ] ], [ [ "### New Westminster\n7654\tNew Westminster\t49.203683 \t122.90535 ", "_____no_output_____" ] ], [ [ "get_tidal_stations(-122.90535, 49.203683, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ] ], [ [ "### Sandy Cove\n7786\tSandy Cove\t49.34 \t123.23 ", "_____no_output_____" ] ], [ [ "get_tidal_stations(-123.23, 49.34, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ] ], [ [ "### Port Renfrew \ncheck\n8525\tPort Renfrew\t48.555\t124.421", "_____no_output_____" ] ], [ [ "get_tidal_stations(-124.421, 48.555, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ] ], [ [ "### Victoria\n7120\tVictoria\t48.424666 \t123.3707 ", "_____no_output_____" ] ], [ [ "get_tidal_stations(-123.3707, 48.424666, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ] ], [ [ "### Sand Heads\n7594\tSand Heads\t49.125\t123.195  \nFrom Marlene's email \n49º 06’ 21.1857’’, -123º 18’ 12.4789’’\nwe are using 426, 292 \nend of jetty is 429, 295 ", "_____no_output_____" ] ], [ [ "lat_sh = 49+6/60.+21.1857/3600.\nlon_sh = -(123+18/60.+12.4789/3600.)\nprint(lon_sh, lat_sh)\nget_tidal_stations(lon_sh, lat_sh, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=20)", "-123.3034663611111 49.10588491666667\n" ] ], [ [ "### Nanaimo\n7917\tNanaimo\t49.17 \t123.93 ", "_____no_output_____" ] ], [ [ "get_tidal_stations(-123.93, 49.17, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ] ], [ [ "In our code its at 484, 208 with lon,lat at -123.93 and 49.16: leave as is for now", "_____no_output_____" ], [ "### Boundary Bay\n\nGuesstimated from Map\n-122.925 49.0", "_____no_output_____" ] ], [ [ "get_tidal_stations(-122.925, 49.0, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=15)\n", "_____no_output_____" ] ], [ [ "### Squamish\n49 41.675 N 123 09.299 W", "_____no_output_____" ] ], [ [ "print (49+41.675/60, -(123+9.299/60.))\nprint (model_lons.shape)\nget_tidal_stations(-(123+9.299/60.), 49.+41.675/60., model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)\n", "49.694583333333334 -123.15498333333333\n(898, 398)\n" ] ], [ [ "### Half Moon Bay\n49 30.687 N 123 54.726 W", "_____no_output_____" ] ], [ [ "print (49+30.687/60, -(123+54.726/60.))\nget_tidal_stations(-(123+54.726/60.), 49.+30.687/60., model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)\n", "49.51145 -123.9121\n" ] ], [ [ "### Friday Harbour\n-123.016667, 48.55", "_____no_output_____" ] ], [ [ "get_tidal_stations(-123.016667, 48.55, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)\n", "_____no_output_____" ] ], [ [ "### Neah Bay\n-124.6, 48.4", "_____no_output_____" ] ], [ [ "get_tidal_stations(-124.6, 48.4, model_lons, model_lats, wind_lons, wind_lats, \n wave_lons, wave_lats, t_mask, wave_mask, size=10)", "_____no_output_____" ], [ "from salishsea_tools import places", "_____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" ]
[ [ "code", "code", "code", "code", "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", "code" ] ]
d02f41e3173ec8c075669fab17bdd104931772c0
4,524
ipynb
Jupyter Notebook
bindings/pydeck/examples/04 - Plotting massive data sets.ipynb
jcready/deck.gl
bcabe14d942a3e50a64e50497f9da7c20d9e069d
[ "MIT" ]
7,702
2016-04-19T15:56:09.000Z
2020-04-14T19:03:13.000Z
bindings/pydeck/examples/04 - Plotting massive data sets.ipynb
jcready/deck.gl
bcabe14d942a3e50a64e50497f9da7c20d9e069d
[ "MIT" ]
3,126
2016-04-20T23:04:42.000Z
2020-04-14T22:46:02.000Z
bindings/pydeck/examples/04 - Plotting massive data sets.ipynb
jcready/deck.gl
bcabe14d942a3e50a64e50497f9da7c20d9e069d
[ "MIT" ]
1,526
2016-05-07T06:55:07.000Z
2020-04-14T18:52:19.000Z
33.021898
365
0.588417
[ [ [ "# Plotting massive data sets\n\nThis notebook plots about half a million LIDAR points around Toronto from the KITTI data set. ([Source](http://www.cvlibs.net/datasets/kitti/raw_data.php)) The data is meant to be played over time. With pydeck, we can render these points and interact with them.", "_____no_output_____" ], [ "### Cleaning the data\n\nFirst we need to import the data. Each row of data represents one x/y/z coordinate for a point in space at a point in time, with each frame representing about 115,000 points.\n\nWe also need to scale the points to plot closely on a map. These point coordinates are not given in latitude and longitude, so as a workaround we'll plot them very close to (0, 0) on the earth.\n\nIn future versions of pydeck other viewports, like a flat plane, will be supported out-of-the-box. For now, we'll make do with scaling the points.", "_____no_output_____" ] ], [ [ "import pandas as pd\nall_lidar = pd.concat([\n pd.read_csv('https://raw.githubusercontent.com/ajduberstein/kitti_subset/master/kitti_1.csv'),\n pd.read_csv('https://raw.githubusercontent.com/ajduberstein/kitti_subset/master/kitti_2.csv'),\n pd.read_csv('https://raw.githubusercontent.com/ajduberstein/kitti_subset/master/kitti_3.csv'),\n pd.read_csv('https://raw.githubusercontent.com/ajduberstein/kitti_subset/master/kitti_4.csv'),\n])\n\n# Filter to one frame of data\nlidar = all_lidar[all_lidar['source'] == 136]\nlidar.loc[: , ['x', 'y']] = lidar[['x', 'y']] / 10000", "_____no_output_____" ] ], [ [ "### Plotting the data\n\nWe'll define a single `PointCloudLayer` and plot it.\n\nPydeck by default expects the input of `get_position` to be a string name indicating a single position value. For convenience, you can pass in a string indicating the X/Y/Z coordinate, here `get_position='[x, y, z]'`. You also have access to a small expression parser--in our `get_position` function here, we increase the size of the z coordinate times 10.\n\nUsing `pydeck.data_utils.compute_view`, we'll zoom to the approximate center of the data.", "_____no_output_____" ] ], [ [ "import pydeck as pdk\n\n\npoint_cloud = pdk.Layer(\n 'PointCloudLayer',\n lidar[['x', 'y', 'z']],\n get_position=['x', 'y', 'z * 10'],\n get_normal=[0, 0, 1],\n get_color=[255, 0, 100, 200],\n pickable=True, \n auto_highlight=True,\n point_size=1)\n\n\nview_state = pdk.data_utils.compute_view(lidar[['x', 'y']], 0.9)\nview_state.max_pitch = 360\nview_state.pitch = 80\nview_state.bearing = 120\n\nr = pdk.Deck(\n point_cloud,\n initial_view_state=view_state,\n map_provider=None,\n)\nr.show()", "_____no_output_____" ], [ "import time\nfrom collections import deque\n\n# Choose a handful of frames to loop through\nframe_buffer = deque([42, 56, 81, 95])\nprint('Press the stop icon to exit')\nwhile True:\n current_frame = frame_buffer[0]\n lidar = all_lidar[all_lidar['source'] == current_frame]\n r.layers[0].get_position = '@@=[x / 10000, y / 10000, z * 10]'\n r.layers[0].data = lidar.to_dict(orient='records')\n frame_buffer.rotate()\n r.update()\n time.sleep(0.5)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d02f4b395b1623da8d59d678df13154bfe040b2d
102,900
ipynb
Jupyter Notebook
colab/NMT-Seq2SeqWithAttention.ipynb
drlego9/NMT-pytorch
eeb5beed5eb092b3250dc7615d4570dba9fdce48
[ "MIT" ]
1
2021-12-05T07:27:36.000Z
2021-12-05T07:27:36.000Z
colab/NMT-Seq2SeqWithAttention.ipynb
drlego9/NMT-pytorch
eeb5beed5eb092b3250dc7615d4570dba9fdce48
[ "MIT" ]
null
null
null
colab/NMT-Seq2SeqWithAttention.ipynb
drlego9/NMT-pytorch
eeb5beed5eb092b3250dc7615d4570dba9fdce48
[ "MIT" ]
null
null
null
102,900
102,900
0.619854
[ [ [ "# Seq2Seq with Attention for Korean-English Neural Machine Translation\n- Network architecture based on this [paper](https://arxiv.org/abs/1409.0473)\n- Fit to run on Google Colaboratory", "_____no_output_____" ] ], [ [ "import os\nimport io\nimport tarfile\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchtext\n\nfrom torchtext.data import Dataset\nfrom torchtext.data import Example\nfrom torchtext.data import Field\nfrom torchtext.data import BucketIterator", "_____no_output_____" ] ], [ [ "# 1. Upload Data to Colab Workspace\n\n로컬에 존재하는 다음 3개의 데이터를 가상 머신에 업로드. 파일의 원본은 [여기](https://github.com/jungyeul/korean-parallel-corpora/tree/master/korean-english-news-v1/)에서도 확인\n\n- korean-english-park.train.tar.gz\n- korean-english-park.dev.tar.gz\n- korean.english-park.test.tar.gz\n\n", "_____no_output_____" ] ], [ [ "# 현재 작업경로를 확인 & 'data' 폴더 생성\n!echo 'Current working directory:' ${PWD}\n!mkdir -p data/\n!ls -al", "Current working directory: /content\ntotal 20\ndrwxr-xr-x 1 root root 4096 Aug 1 00:22 .\ndrwxr-xr-x 1 root root 4096 Aug 1 00:21 ..\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 .config\ndrwxr-xr-x 2 root root 4096 Aug 1 00:22 data\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 sample_data\n" ], [ "# 로컬의 데이터 업로드\nfrom google.colab import files\nuploaded = files.upload()", "_____no_output_____" ], [ "# 'data' 폴더 하위로 이동, 잘 옮겨졌는지 확인\n!mv *.tar.gz data/\n!ls -al data/", "total 8864\ndrwxr-xr-x 2 root root 4096 Aug 1 00:25 .\ndrwxr-xr-x 1 root root 4096 Aug 1 00:25 ..\n-rw-r--r-- 1 root root 113461 Aug 1 00:23 korean-english-park.dev.tar.gz\n-rw-r--r-- 1 root root 229831 Aug 1 00:23 korean-english-park.test.tar.gz\n-rw-r--r-- 1 root root 8718893 Aug 1 00:24 korean-english-park.train.tar.gz\n" ] ], [ [ "# 2. Check Packages", "_____no_output_____" ], [ "## KoNLPy (설치 필요)", "_____no_output_____" ] ], [ [ "# Java 1.8 & KoNLPy 설치\n!apt-get update\n!apt-get install g++ openjdk-8-jdk python-dev python3-dev\n!pip3 install JPype1-py3\n!pip3 install konlpy", "\r0% [Working]\r \rIgn:1 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 InRelease\n\r0% [Connecting to archive.ubuntu.com (91.189.88.24)] [Waiting for headers] [Wai\r \rGet:2 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ InRelease [3,626 B]\n\r0% [Connecting to archive.ubuntu.com (91.189.88.24)] [Waiting for headers] [2 I\r0% [Connecting to archive.ubuntu.com (91.189.88.24)] [Waiting for headers] [Wai\r \rGet:3 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]\n\r0% [Connecting to archive.ubuntu.com (91.189.88.24)] [3 InRelease 2,586 B/88.7 \r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 2,586 B/88.7 k\r \rGet:4 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic InRelease [21.3 kB]\n\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 5,482 B/88.7 k\r \rIgn:5 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 InRelease\n\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 14.2 kB/88.7 k\r \rHit:6 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 Release\n\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 14.2 kB/88.7 k\r \rGet:7 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 Release [564 B]\n\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 17.1 kB/88.7 k\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 17.1 kB/88.7 k\r \rHit:8 http://archive.ubuntu.com/ubuntu bionic InRelease\n\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 17.1 kB/88.7 k\r \rGet:9 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 Release.gpg [833 B]\n\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 22.9 kB/88.7 k\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 22.9 kB/88.7 k\r0% [2 InRelease gpgv 3,626 B] [Waiting for headers] [3 InRelease 22.9 kB/88.7 k\r \rGet:10 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]\n\r0% [2 InRelease gpgv 3,626 B] [10 InRelease 2,604 B/88.7 kB 3%] [3 InRelease 46\r0% [10 InRelease 15.6 kB/88.7 kB 18%] [3 InRelease 86.6 kB/88.7 kB 98%] [Waitin\r0% [Release.gpg gpgv 564 B] [10 InRelease 15.6 kB/88.7 kB 18%] [3 InRelease 86.\r0% [Release.gpg gpgv 564 B] [10 InRelease 15.6 kB/88.7 kB 18%] [Waiting for hea\r \rGet:11 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages [65.5 kB]\n\r0% [Release.gpg gpgv 564 B] [10 InRelease 17.1 kB/88.7 kB 19%] [11 Packages 0 B\r \rGet:12 http://ppa.launchpad.net/marutter/c2d4u3.5/ubuntu bionic InRelease [15.4 kB]\nGet:14 http://archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]\nGet:15 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 Packages [11.5 kB]\nGet:16 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic/main amd64 Packages [29.0 kB]\nGet:17 http://security.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [727 kB]\nGet:18 http://ppa.launchpad.net/marutter/c2d4u3.5/ubuntu bionic/main Sources [1,672 kB]\nGet:19 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [594 kB]\nGet:20 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 Packages [1,250 kB]\nGet:21 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages [905 kB]\nGet:22 http://archive.ubuntu.com/ubuntu bionic-backports/universe amd64 Packages [3,930 B]\nGet:23 http://ppa.launchpad.net/marutter/c2d4u3.5/ubuntu bionic/main amd64 Packages [802 kB]\nFetched 6,354 kB in 3s (1,974 kB/s)\nReading package lists... Done\nReading package lists... Done\nBuilding dependency tree \nReading state information... Done\npython-dev is already the newest version (2.7.15~rc1-1).\ng++ is already the newest version (4:7.4.0-1ubuntu2.3).\ng++ set to manually installed.\npython3-dev is already the newest version (3.6.7-1~18.04).\nThe following package was automatically installed and is no longer required:\n libnvidia-common-410\nUse 'apt autoremove' to remove it.\nThe following additional packages will be installed:\n fonts-dejavu-core fonts-dejavu-extra libatk-wrapper-java\n libatk-wrapper-java-jni libgail-common libgail18 libgtk2.0-0 libgtk2.0-bin\n libgtk2.0-common libxxf86dga1 openjdk-8-jdk-headless openjdk-8-jre\n openjdk-8-jre-headless x11-utils\nSuggested packages:\n gvfs openjdk-8-demo openjdk-8-source visualvm icedtea-8-plugin libnss-mdns\n fonts-ipafont-gothic fonts-ipafont-mincho fonts-wqy-microhei\n fonts-wqy-zenhei fonts-indic mesa-utils\nThe following NEW packages will be installed:\n fonts-dejavu-core fonts-dejavu-extra libatk-wrapper-java\n libatk-wrapper-java-jni libgail-common libgail18 libgtk2.0-0 libgtk2.0-bin\n libgtk2.0-common libxxf86dga1 openjdk-8-jdk openjdk-8-jre x11-utils\nThe following packages will be upgraded:\n openjdk-8-jdk-headless openjdk-8-jre-headless\n2 upgraded, 13 newly installed, 0 to remove and 57 not upgraded.\nNeed to get 42.8 MB of archives.\nAfter this operation, 20.3 MB of additional disk space will be used.\nGet:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 libxxf86dga1 amd64 2:1.1.4-1 [13.7 kB]\nGet:2 http://archive.ubuntu.com/ubuntu bionic/main amd64 fonts-dejavu-core all 2.37-1 [1,041 kB]\nGet:3 http://archive.ubuntu.com/ubuntu bionic/main amd64 fonts-dejavu-extra all 2.37-1 [1,953 kB]\nGet:4 http://archive.ubuntu.com/ubuntu bionic/main amd64 x11-utils amd64 7.7+3build1 [196 kB]\nGet:5 http://archive.ubuntu.com/ubuntu bionic/main amd64 libatk-wrapper-java all 0.33.3-20ubuntu0.1 [34.7 kB]\nGet:6 http://archive.ubuntu.com/ubuntu bionic/main amd64 libatk-wrapper-java-jni amd64 0.33.3-20ubuntu0.1 [28.3 kB]\nGet:7 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgtk2.0-common all 2.24.32-1ubuntu1 [125 kB]\nGet:8 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgtk2.0-0 amd64 2.24.32-1ubuntu1 [1,769 kB]\nGet:9 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgail18 amd64 2.24.32-1ubuntu1 [14.2 kB]\nGet:10 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgail-common amd64 2.24.32-1ubuntu1 [112 kB]\nGet:11 http://archive.ubuntu.com/ubuntu bionic/main amd64 libgtk2.0-bin amd64 2.24.32-1ubuntu1 [7,536 B]\nGet:12 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 openjdk-8-jdk-headless amd64 8u222-b10-1ubuntu1~18.04.1 [8,267 kB]\nGet:13 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 openjdk-8-jre-headless amd64 8u222-b10-1ubuntu1~18.04.1 [27.4 MB]\nGet:14 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 openjdk-8-jre amd64 8u222-b10-1ubuntu1~18.04.1 [69.3 kB]\nGet:15 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 openjdk-8-jdk amd64 8u222-b10-1ubuntu1~18.04.1 [1,756 kB]\nFetched 42.8 MB in 2s (20.2 MB/s)\nSelecting previously unselected package libxxf86dga1:amd64.\n(Reading database ... 131331 files and directories currently installed.)\nPreparing to unpack .../00-libxxf86dga1_2%3a1.1.4-1_amd64.deb ...\nUnpacking libxxf86dga1:amd64 (2:1.1.4-1) ...\nSelecting previously unselected package fonts-dejavu-core.\nPreparing to unpack .../01-fonts-dejavu-core_2.37-1_all.deb ...\nUnpacking fonts-dejavu-core (2.37-1) ...\nSelecting previously unselected package fonts-dejavu-extra.\nPreparing to unpack .../02-fonts-dejavu-extra_2.37-1_all.deb ...\nUnpacking fonts-dejavu-extra (2.37-1) ...\nSelecting previously unselected package x11-utils.\nPreparing to unpack .../03-x11-utils_7.7+3build1_amd64.deb ...\nUnpacking x11-utils (7.7+3build1) ...\nSelecting previously unselected package libatk-wrapper-java.\nPreparing to unpack .../04-libatk-wrapper-java_0.33.3-20ubuntu0.1_all.deb ...\nUnpacking libatk-wrapper-java (0.33.3-20ubuntu0.1) ...\nSelecting previously unselected package libatk-wrapper-java-jni:amd64.\nPreparing to unpack .../05-libatk-wrapper-java-jni_0.33.3-20ubuntu0.1_amd64.deb ...\nUnpacking libatk-wrapper-java-jni:amd64 (0.33.3-20ubuntu0.1) ...\nSelecting previously unselected package libgtk2.0-common.\nPreparing to unpack .../06-libgtk2.0-common_2.24.32-1ubuntu1_all.deb ...\nUnpacking libgtk2.0-common (2.24.32-1ubuntu1) ...\nSelecting previously unselected package libgtk2.0-0:amd64.\nPreparing to unpack .../07-libgtk2.0-0_2.24.32-1ubuntu1_amd64.deb ...\nUnpacking libgtk2.0-0:amd64 (2.24.32-1ubuntu1) ...\nSelecting previously unselected package libgail18:amd64.\nPreparing to unpack .../08-libgail18_2.24.32-1ubuntu1_amd64.deb ...\nUnpacking libgail18:amd64 (2.24.32-1ubuntu1) ...\nSelecting previously unselected package libgail-common:amd64.\nPreparing to unpack .../09-libgail-common_2.24.32-1ubuntu1_amd64.deb ...\nUnpacking libgail-common:amd64 (2.24.32-1ubuntu1) ...\nSelecting previously unselected package libgtk2.0-bin.\nPreparing to unpack .../10-libgtk2.0-bin_2.24.32-1ubuntu1_amd64.deb ...\nUnpacking libgtk2.0-bin (2.24.32-1ubuntu1) ...\nPreparing to unpack .../11-openjdk-8-jdk-headless_8u222-b10-1ubuntu1~18.04.1_amd64.deb ...\nUnpacking openjdk-8-jdk-headless:amd64 (8u222-b10-1ubuntu1~18.04.1) over (8u212-b03-0ubuntu1.18.04.1) ...\nPreparing to unpack .../12-openjdk-8-jre-headless_8u222-b10-1ubuntu1~18.04.1_amd64.deb ...\nUnpacking openjdk-8-jre-headless:amd64 (8u222-b10-1ubuntu1~18.04.1) over (8u212-b03-0ubuntu1.18.04.1) ...\nSelecting previously unselected package openjdk-8-jre:amd64.\nPreparing to unpack .../13-openjdk-8-jre_8u222-b10-1ubuntu1~18.04.1_amd64.deb ...\nUnpacking openjdk-8-jre:amd64 (8u222-b10-1ubuntu1~18.04.1) ...\nSelecting previously unselected package openjdk-8-jdk:amd64.\nPreparing to unpack .../14-openjdk-8-jdk_8u222-b10-1ubuntu1~18.04.1_amd64.deb ...\nUnpacking openjdk-8-jdk:amd64 (8u222-b10-1ubuntu1~18.04.1) ...\nSetting up libgtk2.0-common (2.24.32-1ubuntu1) ...\nProcessing triggers for mime-support (3.60ubuntu1) ...\nSetting up fonts-dejavu-core (2.37-1) ...\nSetting up libxxf86dga1:amd64 (2:1.1.4-1) ...\nProcessing triggers for libc-bin (2.27-3ubuntu1) ...\nProcessing triggers for man-db (2.8.3-2ubuntu0.1) ...\nSetting up fonts-dejavu-extra (2.37-1) ...\nProcessing triggers for hicolor-icon-theme (0.17-2) ...\nProcessing triggers for fontconfig (2.12.6-0ubuntu2) ...\nSetting up openjdk-8-jre-headless:amd64 (8u222-b10-1ubuntu1~18.04.1) ...\nSetting up libgtk2.0-0:amd64 (2.24.32-1ubuntu1) ...\nSetting up libgail18:amd64 (2.24.32-1ubuntu1) ...\nSetting up openjdk-8-jdk-headless:amd64 (8u222-b10-1ubuntu1~18.04.1) ...\nSetting up x11-utils (7.7+3build1) ...\nSetting up libgail-common:amd64 (2.24.32-1ubuntu1) ...\nSetting up libatk-wrapper-java (0.33.3-20ubuntu0.1) ...\nSetting up libgtk2.0-bin (2.24.32-1ubuntu1) ...\nSetting up libatk-wrapper-java-jni:amd64 (0.33.3-20ubuntu0.1) ...\nSetting up openjdk-8-jre:amd64 (8u222-b10-1ubuntu1~18.04.1) ...\nupdate-alternatives: using /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/policytool to provide /usr/bin/policytool (policytool) in auto mode\nSetting up openjdk-8-jdk:amd64 (8u222-b10-1ubuntu1~18.04.1) ...\nupdate-alternatives: using /usr/lib/jvm/java-8-openjdk-amd64/bin/appletviewer to provide /usr/bin/appletviewer (appletviewer) in auto mode\nupdate-alternatives: using /usr/lib/jvm/java-8-openjdk-amd64/bin/jconsole to provide /usr/bin/jconsole (jconsole) in auto mode\nProcessing triggers for libc-bin (2.27-3ubuntu1) ...\nCollecting JPype1-py3\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/9b/81/63f5e4202c598f362ee4684b41890f993d6e58309c5d90703f570ab85f62/JPype1-py3-0.5.5.4.tar.gz (88kB)\n\u001b[K |████████████████████████████████| 92kB 3.4MB/s \n\u001b[?25hBuilding wheels for collected packages: JPype1-py3\n Building wheel for JPype1-py3 (setup.py) ... \u001b[?25l\u001b[?25hdone\n Stored in directory: /root/.cache/pip/wheels/52/37/1f/1015d908d12a0e9b239543d031fda0cded9823aa1306939541\nSuccessfully built JPype1-py3\nInstalling collected packages: JPype1-py3\nSuccessfully installed JPype1-py3-0.5.5.4\nCollecting konlpy\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/e5/3d/4e983cd98d87b50b2ab0387d73fa946f745aa8164e8888a714d5129f9765/konlpy-0.5.1-py2.py3-none-any.whl (19.4MB)\n\u001b[K |████████████████████████████████| 19.4MB 979kB/s \n\u001b[?25hCollecting JPype1>=0.5.7 (from konlpy)\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/07/09/e19ce27d41d4f66d73ac5b6c6a188c51b506f56c7bfbe6c1491db2d15995/JPype1-0.7.0-cp36-cp36m-manylinux2010_x86_64.whl (2.7MB)\n\u001b[K |████████████████████████████████| 2.7MB 25.9MB/s \n\u001b[?25hInstalling collected packages: JPype1, konlpy\nSuccessfully installed JPype1-0.7.0 konlpy-0.5.1\n" ], [ "from konlpy.tag import Okt\nko_tokens = Okt().pos('트위터 데이터로 학습한 형태소 분석기가 잘 실행이 되는지 확인해볼까요?') # list of (word, POS TAG) tuples\nko_tokens = [t[0] for t in ko_tokens] # Only get words\nprint(ko_tokens)\n\ndel ko_tokens # 필요 없으니까 삭제", "/usr/local/lib/python3.6/dist-packages/jpype/_core.py:210: UserWarning: \n-------------------------------------------------------------------------------\nDeprecated: convertStrings was not specified when starting the JVM. The default\nbehavior in JPype will be False starting in JPype 0.8. The recommended setting\nfor new code is convertStrings=False. The legacy value of True was assumed for\nthis session. If you are a user of an application that reported this warning,\nplease file a ticket with the developer.\n-------------------------------------------------------------------------------\n\n \"\"\")\n" ] ], [ [ "## Spacy (이미 설치되어 있음)", "_____no_output_____" ] ], [ [ "# 설치가 되어있는지 확인\n!pip show spacy", "Name: spacy\nVersion: 2.1.6\nSummary: Industrial-strength Natural Language Processing (NLP) with Python and Cython\nHome-page: https://spacy.io\nAuthor: Explosion AI\nAuthor-email: contact@explosion.ai\nLicense: MIT\nLocation: /usr/local/lib/python3.6/dist-packages\nRequires: preshed, thinc, requests, plac, wasabi, blis, murmurhash, numpy, srsly, cymem\nRequired-by: fastai, en-core-web-sm\n" ], [ "# 설치가 되어있는지 확인 (없다면 자동설치됨)\n!python -m spacy download en_core_web_sm", "Requirement already satisfied: en_core_web_sm==2.1.0 from https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.1.0/en_core_web_sm-2.1.0.tar.gz#egg=en_core_web_sm==2.1.0 in /usr/local/lib/python3.6/dist-packages (2.1.0)\n\u001b[38;5;2m✔ Download and installation successful\u001b[0m\nYou can now load the model via spacy.load('en_core_web_sm')\n" ], [ "import spacy\nspacy_en = spacy.load('en_core_web_sm')\nen_tokens = [t.text for t in spacy_en.tokenizer('Check that spacy tokenizer works.')]\nprint(en_tokens)\n\ndel en_tokens # 필요 없으니까 삭제", "['Check', 'that', 'spacy', 'tokenizer', 'works', '.']\n" ] ], [ [ "# 3. Define Tokenizing Functions\n문장을 받아 그보다 작은 어절 혹은 형태소 단위의 리스트로 반환해주는 함수를 각 언어에 대해 작성\n- Korean: konlpy.tag.Okt() <- Twitter()에서 명칭변경\n- English: spacy.tokenizer", "_____no_output_____" ], [ "## Korean Tokenizer", "_____no_output_____" ] ], [ [ "#from konlpy.tag import Okt\n\nclass KoTokenizer(object):\n \"\"\"For Korean.\"\"\"\n def __init__(self):\n self.tokenizer = Okt()\n \n def tokenize(self, text):\n tokens = self.tokenizer.pos(text)\n tokens = [t[0] for t in tokens]\n return tokens", "_____no_output_____" ], [ "# Usage example\nprint(KoTokenizer().tokenize('전처리는 언제나 지겨워요.'))", "['전', '처리', '는', '언제나', '지겨워요', '.']\n" ] ], [ [ "## English Tokenizer", "_____no_output_____" ] ], [ [ "#import spacy\n\nclass EnTokenizer(object):\n \"\"\"For English.\"\"\"\n def __init__(self):\n self.spacy_en = spacy.load('en_core_web_sm')\n \n def tokenize(self, text):\n tokens = [t.text for t in self.spacy_en.tokenizer(text)]\n return tokens", "_____no_output_____" ], [ "# Usage example\nprint(EnTokenizer().tokenize(\"What I cannot create, I don't understand.\"))", "['What', 'I', 'can', 'not', 'create', ',', 'I', 'do', \"n't\", 'understand', '.']\n" ] ], [ [ "# 4. Data Preprocessing", "_____no_output_____" ], [ "## Load data", "_____no_output_____" ] ], [ [ "# Current working directory & list of files\n!echo 'Current working directory:' ${PWD}\n!ls -al", "Current working directory: /content\ntotal 20\ndrwxr-xr-x 1 root root 4096 Aug 1 00:25 .\ndrwxr-xr-x 1 root root 4096 Aug 1 00:21 ..\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 .config\ndrwxr-xr-x 2 root root 4096 Aug 1 00:25 data\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 sample_data\n" ], [ "DATA_DIR = './data/'\nprint('Data directory exists:', os.path.isdir(DATA_DIR))\nprint('List of files:')\nprint(*os.listdir(DATA_DIR), sep='\\n')", "Data directory exists: True\nList of files:\nkorean-english-park.test.tar.gz\nkorean-english-park.train.tar.gz\nkorean-english-park.dev.tar.gz\n" ], [ "def get_data_from_tar_gz(filename):\n \"\"\"\n Retrieve contents from a `tar.gz` file without extraction.\n Arguments:\n filename: path to `tar.gz` file.\n Returns:\n dict, (name, content) pairs\n \"\"\"\n \n assert os.path.exists(filename)\n \n out = {}\n with tarfile.open(filename, 'r:gz') as tar:\n for member in tar.getmembers():\n lang = member.name.split('.')[-1] # ex) korean-english-park.train.ko -> ko\n f = tar.extractfile(member)\n if f is not None:\n content = f.read().decode('utf-8')\n content = content.splitlines()\n out[lang] = content\n \n assert isinstance(out, dict)\n \n return out", "_____no_output_____" ], [ "# Each 'xxx_data' is a dictionary with keys; 'ko', 'en'\ntrain_dict= get_data_from_tar_gz(os.path.join(DATA_DIR, 'korean-english-park.train.tar.gz')) # train\ndev_dict = get_data_from_tar_gz(os.path.join(DATA_DIR, 'korean-english-park.dev.tar.gz')) # dev\ntest_dict = get_data_from_tar_gz(os.path.join(DATA_DIR, 'korean-english-park.test.tar.gz')) # test", "_____no_output_____" ], [ "# Some samples (ko)\ntrain_dict['ko'][100:105]", "_____no_output_____" ], [ "# Some samples (en)\ntrain_dict['en'][100:105]", "_____no_output_____" ] ], [ [ "## Define Datasets", "_____no_output_____" ] ], [ [ "#from torchtext.data import Dataset\n#from torchtext.data import Example\n\nclass KoEnTranslationDataset(Dataset):\n \"\"\"A dataset for Korean-English Neural Machine Translation.\"\"\"\n \n @staticmethod\n def sort_key(ex):\n return torchtext.data.interleave_keys(len(ex.src), len(ex.trg))\n \n def __init__(self, data_dict, field_dict, source_lang='ko', max_samples=None, **kwargs):\n \"\"\"\n Only 'ko' and 'en' supported for `language`\n Arguments: \n data_dict: dict of (`language`, text) pairs.\n field_dict: dict of (`language`, Field instance) pairs.\n source_lang: str, default 'ko'.\n Other kwargs are passed to the constructor of `torchtext.data.Dataset`.\n \"\"\"\n \n if not all(k in ['ko', 'en'] for k in data_dict.keys()):\n raise KeyError(\"Check data keys.\")\n \n if not all(k in ['ko', 'en'] for k in field_dict.keys()):\n raise KeyError(\"Check field keys.\")\n \n if source_lang == 'ko':\n fields = [('src', field_dict['ko']), ('trg', field_dict['en'])]\n src_data = data_dict['ko']\n trg_data = data_dict['en']\n elif source_lang == 'en':\n fields = [('src', field_dict['en']), ('trg', field_dict['ko'])]\n src_data = data_dict['en']\n trg_data = data_dict['ko']\n else:\n raise NotImplementedError\n \n\n if not len(src_data) == len(trg_data):\n raise ValueError('Inconsistent number of instances between two languages.')\n \n examples = []\n for i, (src_line, trg_line) in enumerate(zip(src_data, trg_data)):\n src_line = src_line.strip()\n trg_line = trg_line.strip()\n if src_line != '' and trg_line != '':\n \n examples.append(\n torchtext.data.Example.fromlist(\n [src_line, trg_line], fields\n )\n )\n \n i += 1\n if max_samples is not None:\n if i >= max_samples:\n break\n \n super(KoEnTranslationDataset, self).__init__(examples, fields, **kwargs)\n ", "_____no_output_____" ] ], [ [ "## Define Fields\n- Instantiate tokenizers; one for each language.\n- The 'tokenize' argument of `Field` requires a tokenizing function.", "_____no_output_____" ] ], [ [ "#from torchtext.data import Field\n\nko_tokenizer = KoTokenizer() # korean tokenizer\nen_tokenizer = EnTokenizer() # english tokenizer\n\n# Field instance for korean\nKOREAN = Field(\n init_token='<sos>',\n eos_token='<eos>',\n tokenize=ko_tokenizer.tokenize,\n batch_first=True,\n lower=False\n)\n\n# Field instance for english\nENGLISH = Field(\n init_token='<sos>',\n eos_token='<eos>',\n tokenize=en_tokenizer.tokenize,\n batch_first=True,\n lower=True\n)\n\n# Store Field instances in a dictionary\nfield_dict = {\n 'ko': KOREAN,\n 'en': ENGLISH,\n}", "_____no_output_____" ] ], [ [ "## Instantiate datasets\n- one for each set (train, dev, test)", "_____no_output_____" ] ], [ [ "# 학습시간 단축을 위해 학습 데이터 줄이기\nMAX_TRAIN_SAMPLES = 10000", "_____no_output_____" ], [ "# Instantiate with data\ntrain_set = KoEnTranslationDataset(train_dict, field_dict, max_samples=MAX_TRAIN_SAMPLES)\nprint('Train set ready.')\nprint('#. examples:', len(train_set.examples)) \n\ndev_set = KoEnTranslationDataset(dev_dict, field_dict)\nprint('Dev set ready...')\nprint('#. examples:', len(dev_set.examples))\n\ntest_set = KoEnTranslationDataset(test_dict, field_dict)\nprint('Test set ready...')\nprint('#. examples:', len(test_set.examples))", "Train set ready.\n#. examples: 10000\nDev set ready...\n#. examples: 1000\nTest set ready...\n#. examples: 2000\n" ], [ "# Training example (KO, source language)\ntrain_set.examples[50].src", "_____no_output_____" ], [ "# Training example (EN, target language)\ntrain_set.examples[50].trg", "_____no_output_____" ] ], [ [ "## Build Vocabulary\n- 각 언어별 생성: `Field`의 인스턴스를 활용\n- 최소 빈도수(`MIN_FREQ`) 값을 작게 하면 vocabulary의 크기가 커짐.\n- 최소 빈도수(`MIN_FREQ`) 값을 크게 하면 vocabulary의 크기가 작아짐.\n", "_____no_output_____" ] ], [ [ "MIN_FREQ = 2 # TODO: try different values", "_____no_output_____" ], [ "# Build vocab for Korean\nKOREAN.build_vocab(train_set, dev_set, test_set, min_freq=MIN_FREQ) # ko\nprint('Size of source vocab (ko):', len(KOREAN.vocab))", "Size of source vocab (ko): 14308\n" ], [ "# Check indices of some important tokens\ntokens = ['<unk>', '<pad>', '<sos>', '<eos>']\nfor token in tokens:\n print(f\"{token} -> {KOREAN.vocab.stoi[token]}\")", "<unk> -> 0\n<pad> -> 1\n<sos> -> 2\n<eos> -> 3\n" ], [ "# Build vocab for English\nENGLISH.build_vocab(train_set, dev_set, test_set, min_freq=MIN_FREQ) # en\nprint('Size of target vocab (en):', len(ENGLISH.vocab))", "Size of target vocab (en): 12430\n" ], [ "# Check indices of some important tokens\ntokens = ['<unk>', '<pad>', '<sos>', '<eos>']\nfor token in tokens:\n print(f\"{token} -> {KOREAN.vocab.stoi[token]}\")", "<unk> -> 0\n<pad> -> 1\n<sos> -> 2\n<eos> -> 3\n" ] ], [ [ "## Configure Device\n- *'런타임' -> '런타임 유형변경'* 에서 하드웨어 가속기로 **GPU** 선택", "_____no_output_____" ] ], [ [ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint('Device to use:', device)", "Device to use: cuda\n" ] ], [ [ "## Create Data Iterators\n- 데이터를 미니배치(mini-batch) 단위로 반환해주는 역할\n- `train_set`, `dev_set`, `test_set`에 대해 개별적으로 정의해야 함\n- `BATCH_SIZE`를 정의해주어야 함\n- `torchtext.data.BucketIterator`는 하나의 미니배치를 서로 비슷한 길이의 관측치들로 구성함\n- [Bucketing](https://medium.com/@rashmi.margani/how-to-speed-up-the-training-of-the-sequence-model-using-bucketing-techniques-9e302b0fd976)의 효과: 하나의 미니배치 내 padding을 최소화하여 연산의 낭비를 줄여줌\n", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 128", "_____no_output_____" ], [ "#from torchtext.data import BucketIterator\n\n# Train iterator\ntrain_iterator = BucketIterator(\n train_set,\n batch_size=BATCH_SIZE,\n train=True,\n shuffle=True,\n device=device\n)\n\nprint(f'Number of minibatches per epoch: {len(train_iterator)}')", "Number of minibatches per epoch: 79\n" ], [ "#from torchtext.data import BucketIterator\n\n# Dev iterator\ndev_iterator = BucketIterator(\n dev_set,\n batch_size=100,\n train=False,\n shuffle=False,\n device=device\n)\n\nprint(f'Number of minibatches per epoch: {len(dev_iterator)}')", "Number of minibatches per epoch: 10\n" ], [ "#from torchtext.data import BucketIterator\n\n# Test iterator\ntest_iterator = BucketIterator(\n test_set,\n batch_size=200,\n train=False,\n shuffle=False,\n device=device\n)\n\nprint(f'Number of minibatches per epoch: {len(test_iterator)}')", "Number of minibatches per epoch: 10\n" ], [ "train_batch = next(iter(train_iterator))\nprint('a batch of source examples has shape:', train_batch.src.size()) # (b, s)\nprint('a batch of target examples has shape:', train_batch.trg.size()) # (b, s)", "a batch of source examples has shape: torch.Size([128, 71])\na batch of target examples has shape: torch.Size([128, 51])\n" ], [ "# Checking first sample in mini-batch (KO, source lang)\nko_indices = train_batch.src[0]\nko_tokens = [KOREAN.vocab.itos[i] for i in ko_indices]\nfor t, i in zip(ko_tokens, ko_indices):\n print(f\"{t} ({i})\")\n \ndel ko_indices, ko_tokens", "<sos> (2)\n창기 (1486)\n라이 (1211)\n는 (12)\n“ (33)\n지금 (299)\n필요한 (579)\n것 (16)\n은 (9)\n새로운 (155)\n선거 (278)\n” (34)\n라며 (465)\n“ (33)\n선거 (278)\n를 (11)\n다시 (272)\n치러야 (13744)\n폭력 (643)\n사태 (432)\n와 (35)\n혼란 (1865)\n을 (6)\n막 (2294)\n을 (6)\n수 (36)\n있다 (26)\n” (34)\n고 (32)\n지적 (641)\n했다 (15)\n. (4)\n<eos> (3)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n" ], [ "# Checking first sample in mini-batch (EN, target lang)\nen_indices = train_batch.trg[0]\nen_tokens = [ENGLISH.vocab.itos[i] for i in en_indices]\nfor t, i in zip(en_tokens, en_indices):\n print(f\"{t} ({i})\")\n \ndel en_indices, en_tokens", "<sos> (2)\n\" (12)\nthe (4)\nreality (3089)\nis (18)\nthat (14)\na (9)\nnew (53)\nelection (372)\n, (5)\n<unk> (0)\nof (7)\nviolence (563)\nand (10)\nintimidation (3272)\n, (5)\nis (18)\nthe (4)\nonly (113)\nway (180)\nto (8)\nput (392)\nzimbabwe (737)\nright (297)\n. (6)\n<eos> (3)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n<pad> (1)\n" ], [ "del train_batch # 더 이상 필요 없으니까 삭제", "_____no_output_____" ] ], [ [ "# 5. Building Seq2Seq Model", "_____no_output_____" ], [ "## Hyperparameters", "_____no_output_____" ] ], [ [ "# Hyperparameters\nINPUT_DIM = len(KOREAN.vocab)\nOUTPUT_DIM = len(ENGLISH.vocab)\nENC_EMB_DIM = DEC_EMB_DIM = 100\nENC_HID_DIM = DEC_HID_DIM = 60\nUSE_BIDIRECTIONAL = False", "_____no_output_____" ] ], [ [ "## Encoder", "_____no_output_____" ] ], [ [ "class Encoder(nn.Module):\n \"\"\"\n Learns an embedding for the source text.\n Arguments:\n input_dim: int, size of input language vocabulary.\n emb_dim: int, size of embedding layer output.\n enc_hid_dim: int, size of encoder hidden state.\n dec_hid_dim: int, size of decoder hidden state.\n bidirectional: uses bidirectional RNNs if True. default is False.\n \"\"\"\n def __init__(self, input_dim, emb_dim, enc_hid_dim, dec_hid_dim, bidirectional=False):\n \n super(Encoder, self).__init__()\n \n self.input_dim = input_dim\n self.emb_dim = emb_dim\n self.enc_hid_dim = enc_hid_dim\n self.dec_hid_dim = dec_hid_dim\n self.bidirectional = bidirectional\n \n self.embedding = nn.Embedding(\n num_embeddings=self.input_dim,\n embedding_dim=self.emb_dim\n )\n \n self.rnn = nn.GRU(\n input_size=self.emb_dim,\n hidden_size=self.enc_hid_dim,\n bidirectional=self.bidirectional,\n batch_first=True\n )\n \n self.rnn_output_dim = self.enc_hid_dim\n if self.bidirectional:\n self.rnn_output_dim *= 2\n \n self.fc = nn.Linear(self.rnn_output_dim, self.dec_hid_dim)\n self.dropout = nn.Dropout(.2)\n \n def forward(self, src):\n \"\"\"\n Arguments:\n src: 2d tensor of shape (batch_size, input_seq_len)\n Returns:\n outputs: 3d tensor of shape (batch_size, input_seq_len, num_directions * enc_h)\n hidden: 2d tensor of shape (b, dec_h). This tensor will be used as the initial\n hidden state value of the decoder (h0 of decoder).\n \"\"\"\n \n assert len(src.size()) == 2, 'Input requires dimension (batch_size, seq_len).'\n \n # Shape: (b, s, h)\n embedded = self.embedding(src)\n embedded = self.dropout(embedded)\n \n outputs, hidden = self.rnn(embedded)\n \n if self.bidirectional:\n # (2, b, enc_h) -> (b, 2 * enc_h)\n hidden = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1)\n else:\n # (1, b, enc_h) -> (b, enc_h)\n hidden = hidden.squeeze(0)\n \n # (b, num_directions * enc_h) -> (b, dec_h)\n hidden = self.fc(hidden)\n hidden = torch.tanh(hidden)\n \n return outputs, hidden\n ", "_____no_output_____" ] ], [ [ "## Attention", "_____no_output_____" ] ], [ [ "class Attention(nn.Module):\n def __init__(self, enc_hid_dim, dec_hid_dim, encoder_is_bidirectional=False):\n super(Attention, self).__init__()\n \n self.enc_hid_dim = enc_hid_dim\n self.dec_hid_dim = dec_hid_dim\n self.encoder_is_bidirectional = encoder_is_bidirectional\n \n self.attention_input_dim = enc_hid_dim + dec_hid_dim\n if self.encoder_is_bidirectional:\n self.attention_input_dim += enc_hid_dim # 2 * h_enc + h_dec\n \n self.linear = nn.Linear(self.attention_input_dim, dec_hid_dim)\n self.v = nn.Parameter(torch.rand(dec_hid_dim))\n \n def forward(self, hidden, encoder_outputs):\n \"\"\"\n Arguments:\n hidden: 2d tensor with shape (batch_size, dec_hid_dim).\n encoder_outputs: 3d tensor with shape (batch_size, input_seq_len, enc_hid_dim).\n if encoder is bidirectional, expects (batch_size, input_seq_len, 2 * enc_hid_dim).\n \"\"\"\n \n # Shape check\n assert hidden.dim() == 2\n assert encoder_outputs.dim() == 3\n \n batch_size, seq_len, _ = encoder_outputs.size()\n \n # (b, dec_h) -> (b, s, dec_h)\n hidden = hidden.unsqueeze(1).expand(-1, seq_len, -1)\n \n # concat; shape results in (b, s, enc_h + dec_h).\n # if encoder is bidirectional, (b, s, 2 * h_enc + h_dec).\n concat = torch.cat((hidden, encoder_outputs), dim=2)\n \n # concat; shape is (b, s, dec_h)\n concat = self.linear(concat)\n concat = torch.tanh(concat)\n \n # tile v; (dec_h, ) -> (b, dec_h, 1)\n v = self.v.repeat(batch_size, 1).unsqueeze(2)\n \n # attn; (b, s, dec_h) @ (b, dec_h, 1) -> (b, s, 1) -> (b, s)\n attn_scores = torch.bmm(concat, v).squeeze(-1)\n \n assert attn_scores.dim() == 2 # Final shape check: (b, s)\n \n return F.softmax(attn_scores, dim=1)\n ", "_____no_output_____" ] ], [ [ "## Decoder", "_____no_output_____" ] ], [ [ "class Decoder(nn.Module):\n \"\"\"\n Unlike the encoder, a single forward pass of\n a `Decoder` instance is defined for only a single timestep.\n Arguments:\n output_dim: int,\n emb_dim: int,\n enc_hid_dim: int,\n dec_hid_dim: int,\n attention_module: torch.nn.Module,\n encoder_is_bidirectional: False\n \"\"\"\n def __init__(self, output_dim, emb_dim, enc_hid_dim, dec_hid_dim, attention_module, encoder_is_bidirectional=False):\n super(Decoder, self).__init__()\n \n self.emb_dim = emb_dim\n self.enc_hid_dim = enc_hid_dim\n self.dec_hid_dim = dec_hid_dim\n self.output_dim = output_dim\n self.encoder_is_bidirectional = encoder_is_bidirectional\n \n if isinstance(attention_module, nn.Module):\n self.attention_module = attention_module\n else:\n raise ValueError\n \n self.rnn_input_dim = enc_hid_dim + emb_dim # enc_h + dec_emb_dim\n if self.encoder_is_bidirectional:\n self.rnn_input_dim += enc_hid_dim # 2 * enc_h + dec_emb_dim\n \n self.embedding = nn.Embedding(output_dim, emb_dim)\n \n self.rnn = nn.GRU(\n input_size=self.rnn_input_dim,\n hidden_size=dec_hid_dim,\n bidirectional=False,\n batch_first=True,\n )\n \n out_input_dim = 2 * dec_hid_dim + emb_dim # hidden + dec_hidden_dim + dec_emb_dim\n self.out = nn.Linear(out_input_dim, output_dim)\n \n self.dropout = nn.Dropout(.2)\n \n def forward(self, inp, hidden, encoder_outputs):\n \"\"\"\n Arguments:\n inp: 1d tensor with shape (batch_size, )\n hidden: 2d tensor with shape (batch_size, dec_hid_dim).\n This `hidden` tensor is the hidden state vector from the previous timestep.\n encoder_outputs: 3d tensor with shape (batch_size, seq_len, enc_hid_dim).\n If encoder_is_bidirectional is True, expects shape (batch_size, seq_len, 2 * enc_hid_dim).\n \"\"\"\n \n assert inp.dim() == 1\n assert hidden.dim() == 2\n assert encoder_outputs.dim() == 3\n \n # (batch_size, ) -> (batch_size, 1)\n inp = inp.unsqueeze(1)\n \n # (batch_size, 1) -> (batch_size, 1, emb_dim)\n embedded = self.embedding(inp)\n embedded = self.dropout(embedded)\n \n # attention probabilities; (batch_size, seq_len)\n attn_probs = self.attention_module(hidden, encoder_outputs)\n \n # (batch_size, 1, seq_len)\n attn_probs = attn_probs.unsqueeze(1)\n \n # (b, 1, s) @ (b, s, enc_hid_dim) -> (b, 1, enc_hid_dim)\n weighted = torch.bmm(attn_probs, encoder_outputs)\n \n # (batch_size, 1, emb_dim + enc_hid_dim)\n rnn_input = torch.cat((embedded, weighted), dim=2)\n \n # output; (batch_size, 1, dec_hid_dim)\n # new_hidden; (1, batch_size, dec_hid_dim)\n output, new_hidden = self.rnn(rnn_input, hidden.unsqueeze(0))\n \n embedded = embedded.squeeze(1) # (b, 1, emb) -> (b, emb)\n output = output.squeeze(1) # (b, 1, dec_h) -> (b, dec_h)\n weighted = weighted.squeeze(1) # (b, 1, dec_h) -> (b, dec_h)\n \n # output; (batch_size, emb + 2 * dec_h) -> (batch_size, output_dim)\n output = self.out(torch.cat((output, weighted, embedded), dim=1))\n \n return output, new_hidden.squeeze(0)", "_____no_output_____" ] ], [ [ "## Seq2Seq", "_____no_output_____" ] ], [ [ "class Seq2Seq(nn.Module):\n def __init__(self, encoder, decoder, device):\n super(Seq2Seq, self).__init__()\n \n self.encoder = encoder\n self.decoder = decoder\n self.device = device\n \n def forward(self, src, trg, teacher_forcing_ratio=.5):\n \n batch_size, max_seq_len = trg.size()\n trg_vocab_size = self.decoder.output_dim\n \n # An empty tesnor to store decoder outputs (time index first for indexing)\n outputs_shape = (max_seq_len, batch_size, trg_vocab_size)\n outputs = torch.zeros(outputs_shape).to(self.device)\n \n encoder_outputs, hidden = self.encoder(src)\n \n # first input to the decoder is '<sos>'\n # trg; shape (batch_size, seq_len)\n initial_dec_input = output = trg[:, 0] # get first timestep token\n \n for t in range(1, max_seq_len):\n \n output, hidden = self.decoder(output, hidden, encoder_outputs)\n outputs[t] = output # Save output for timestep t, for 1 <= t <= max_len\n \n top1_val, top1_idx = output.max(dim=1)\n teacher_force = torch.rand(1).item() >= teacher_forcing_ratio\n \n output = trg[:, t] if teacher_force else top1_idx\n \n # Switch batch and time dimensions for consistency (batch_first=True)\n outputs = outputs.permute(1, 0, 2) # (s, b, trg_vocab) -> (b, s, trg_vocab)\n \n return outputs", "_____no_output_____" ] ], [ [ "## Build Model", "_____no_output_____" ] ], [ [ "# Define encoder\nenc = Encoder(\n input_dim=INPUT_DIM,\n emb_dim=ENC_EMB_DIM,\n enc_hid_dim=ENC_HID_DIM,\n dec_hid_dim=DEC_HID_DIM,\n bidirectional=USE_BIDIRECTIONAL\n)\n\nprint(enc)", "Encoder(\n (embedding): Embedding(14308, 100)\n (rnn): GRU(100, 60, batch_first=True)\n (fc): Linear(in_features=60, out_features=60, bias=True)\n (dropout): Dropout(p=0.2)\n)\n" ], [ "# Define attention layer\nattn = Attention(\n enc_hid_dim=ENC_HID_DIM,\n dec_hid_dim=DEC_HID_DIM,\n encoder_is_bidirectional=USE_BIDIRECTIONAL\n)\n\nprint(attn)", "Attention(\n (linear): Linear(in_features=120, out_features=60, bias=True)\n)\n" ], [ "# Define decoder\ndec = Decoder(\n output_dim=OUTPUT_DIM,\n emb_dim=DEC_EMB_DIM,\n enc_hid_dim=ENC_HID_DIM,\n dec_hid_dim=DEC_HID_DIM,\n attention_module=attn,\n encoder_is_bidirectional=USE_BIDIRECTIONAL\n)\n\nprint(dec)", "Decoder(\n (attention_module): Attention(\n (linear): Linear(in_features=120, out_features=60, bias=True)\n )\n (embedding): Embedding(12430, 100)\n (rnn): GRU(160, 60, batch_first=True)\n (out): Linear(in_features=220, out_features=12430, bias=True)\n (dropout): Dropout(p=0.2)\n)\n" ], [ "model = Seq2Seq(enc, dec, device).to(device)\nprint(model)", "Seq2Seq(\n (encoder): Encoder(\n (embedding): Embedding(14308, 100)\n (rnn): GRU(100, 60, batch_first=True)\n (fc): Linear(in_features=60, out_features=60, bias=True)\n (dropout): Dropout(p=0.2)\n )\n (decoder): Decoder(\n (attention_module): Attention(\n (linear): Linear(in_features=120, out_features=60, bias=True)\n )\n (embedding): Embedding(12430, 100)\n (rnn): GRU(160, 60, batch_first=True)\n (out): Linear(in_features=220, out_features=12430, bias=True)\n (dropout): Dropout(p=0.2)\n )\n)\n" ], [ "def count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\nprint(f'The model has {count_parameters(model):,} trainable parameters.')", "The model has 5,500,930 trainable parameters.\n" ] ], [ [ "# 6. Train", "_____no_output_____" ], [ "## Optimizer\n- Use `optim.Adam` or `optim.RMSprop`.", "_____no_output_____" ] ], [ [ "optimizer = optim.Adam(model.parameters(), lr=0.001)\n#optimizer = optim.RMSprop(model.parameters(), lr=0.01)", "_____no_output_____" ] ], [ [ "## Loss function", "_____no_output_____" ] ], [ [ "# Padding indices should not be considered when loss is calculated.\nPAD_IDX = ENGLISH.vocab.stoi['<pad>']\ncriterion = nn.CrossEntropyLoss(ignore_index=PAD_IDX)", "_____no_output_____" ] ], [ [ "## Train function", "_____no_output_____" ] ], [ [ "def train(seq2seq_model, iterator, optimizer, criterion, grad_clip=1.0):\n \n seq2seq_model.train()\n \n epoch_loss = .0\n \n for i, batch in enumerate(iterator):\n \n print('.', end='')\n \n src = batch.src\n trg = batch.trg\n \n optimizer.zero_grad()\n \n decoder_outputs = seq2seq_model(src, trg, teacher_forcing_ratio=.5)\n seq_len, batch_size, trg_vocab_size = decoder_outputs.size() # (b, s, trg_vocab)\n \n # (b-1, s, trg_vocab)\n decoder_outputs = decoder_outputs[:, 1:, :] \n \n # ((b-1) * s, trg_vocab)\n decoder_outputs = decoder_outputs.contiguous().view(-1, trg_vocab_size)\n \n # ((b-1) * s, )\n trg = trg[:, 1:].contiguous().view(-1) \n \n loss = criterion(decoder_outputs, trg)\n loss.backward()\n \n # Gradient clipping; remedy for exploding gradients\n torch.nn.utils.clip_grad_norm_(seq2seq_model.parameters(), grad_clip)\n optimizer.step()\n \n epoch_loss += loss.item()\n \n return epoch_loss / len(iterator)", "_____no_output_____" ] ], [ [ "## Evaluate function", "_____no_output_____" ] ], [ [ "def evaluate(seq2seq_model, iterator, criterion):\n \n seq2seq_model.eval()\n \n epoch_loss = 0.\n \n with torch.no_grad():\n \n for i, batch in enumerate(iterator):\n \n print('.', end='')\n \n src = batch.src\n trg = batch.trg\n \n decoder_outputs = seq2seq_model(src, trg, teacher_forcing_ratio=0.)\n seq_len, batch_size, trg_vocab_size = decoder_outputs.size() # (b, s, trg_vocab)\n \n # (b-1, s, trg_vocab)\n decoder_outputs = decoder_outputs[:, 1:, :] \n \n # ((b-1) * s, trg_vocab)\n decoder_outputs = decoder_outputs.contiguous().view(-1, trg_vocab_size)\n \n # ((b-1) * s, )\n trg = trg[:, 1:].contiguous().view(-1)\n \n loss = criterion(decoder_outputs, trg)\n \n epoch_loss += loss.item()\n \n return epoch_loss / len(iterator)", "_____no_output_____" ] ], [ [ "## Epoch time measure function", "_____no_output_____" ] ], [ [ "def epoch_time(start_time, end_time):\n \"\"\"Returns elapsed time in mins & secs.\"\"\"\n elapsed_time = end_time - start_time\n elapsed_mins = int(elapsed_time / 60)\n elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\n return elapsed_mins, elapsed_secs", "_____no_output_____" ] ], [ [ "## Train for multiple epochs", "_____no_output_____" ] ], [ [ "NUM_EPOCHS = 50", "_____no_output_____" ], [ "import time\nimport math\n\nbest_dev_loss = float('inf')\n\nfor epoch in range(NUM_EPOCHS):\n \n start_time = time.time()\n \n train_loss = train(model, train_iterator, optimizer, criterion)\n dev_loss = evaluate(model, dev_iterator, criterion)\n \n end_time = time.time()\n \n epoch_mins, epoch_secs = epoch_time(start_time, end_time)\n \n if dev_loss < best_dev_loss:\n best_dev_loss = dev_loss\n torch.save(model.state_dict(), './best_model.pt')\n \n print(\"\\n\")\n print(f\"Epoch: {epoch + 1:>02d} | Time: {epoch_mins}m {epoch_secs}s\")\n print(f\"Train Loss: {train_loss:>.4f} | Train Perplexity: {math.exp(train_loss):7.3f}\")\n print(f\"Dev Loss: {dev_loss:>.4f} | Dev Perplexity: {math.exp(dev_loss):7.3f}\")\n ", ".........................................................................................\n\nEpoch: 01 | Time: 1m 19s\nTrain Loss: 7.2537 | Train Perplexity: 1413.394\nDev Loss: 6.5596 | Dev Perplexity: 705.983\n.........................................................................................\n\nEpoch: 02 | Time: 1m 18s\nTrain Loss: 6.5319 | Train Perplexity: 686.695\nDev Loss: 6.4354 | Dev Perplexity: 623.532\n.........................................................................................\n\nEpoch: 03 | Time: 1m 18s\nTrain Loss: 6.4319 | Train Perplexity: 621.383\nDev Loss: 6.3587 | Dev Perplexity: 577.470\n.........................................................................................\n\nEpoch: 04 | Time: 1m 18s\nTrain Loss: 6.3550 | Train Perplexity: 575.378\nDev Loss: 6.2845 | Dev Perplexity: 536.183\n.........................................................................................\n\nEpoch: 05 | Time: 1m 19s\nTrain Loss: 6.2784 | Train Perplexity: 532.939\nDev Loss: 6.2367 | Dev Perplexity: 511.187\n.........................................................................................\n\nEpoch: 06 | Time: 1m 20s\nTrain Loss: 6.2436 | Train Perplexity: 514.711\nDev Loss: 6.2160 | Dev Perplexity: 500.680\n.........................................................................................\n\nEpoch: 07 | Time: 1m 19s\nTrain Loss: 6.1707 | Train Perplexity: 478.508\nDev Loss: 6.1750 | Dev Perplexity: 480.602\n.........................................................................................\n\nEpoch: 08 | Time: 1m 19s\nTrain Loss: 6.1252 | Train Perplexity: 457.256\nDev Loss: 6.1175 | Dev Perplexity: 453.724\n.........................................................................................\n\nEpoch: 09 | Time: 1m 18s\nTrain Loss: 6.0602 | Train Perplexity: 428.447\nDev Loss: 6.0776 | Dev Perplexity: 435.961\n.........................................................................................\n\nEpoch: 10 | Time: 1m 17s\nTrain Loss: 6.0100 | Train Perplexity: 407.500\nDev Loss: 6.0515 | Dev Perplexity: 424.754\n.........................................................................................\n\nEpoch: 11 | Time: 1m 18s\nTrain Loss: 5.9789 | Train Perplexity: 395.025\nDev Loss: 6.0203 | Dev Perplexity: 411.700\n.........................................................................................\n\nEpoch: 12 | Time: 1m 17s\nTrain Loss: 5.9032 | Train Perplexity: 366.219\nDev Loss: 5.9970 | Dev Perplexity: 402.239\n.........................................................................................\n\nEpoch: 13 | Time: 1m 18s\nTrain Loss: 5.8394 | Train Perplexity: 343.577\nDev Loss: 5.9690 | Dev Perplexity: 391.100\n.........................................................................................\n\nEpoch: 14 | Time: 1m 18s\nTrain Loss: 5.7811 | Train Perplexity: 324.115\nDev Loss: 5.9306 | Dev Perplexity: 376.392\n.........................................................................................\n\nEpoch: 15 | Time: 1m 18s\nTrain Loss: 5.7331 | Train Perplexity: 308.923\nDev Loss: 5.9141 | Dev Perplexity: 370.223\n.........................................................................................\n\nEpoch: 16 | Time: 1m 17s\nTrain Loss: 5.7038 | Train Perplexity: 300.002\nDev Loss: 5.8974 | Dev Perplexity: 364.074\n.........................................................................................\n\nEpoch: 17 | Time: 1m 17s\nTrain Loss: 5.6431 | Train Perplexity: 282.331\nDev Loss: 5.8884 | Dev Perplexity: 360.836\n.........................................................................................\n\nEpoch: 18 | Time: 1m 18s\nTrain Loss: 5.5801 | Train Perplexity: 265.111\nDev Loss: 5.8606 | Dev Perplexity: 350.934\n.........................................................................................\n\nEpoch: 19 | Time: 1m 18s\nTrain Loss: 5.5536 | Train Perplexity: 258.167\nDev Loss: 5.8534 | Dev Perplexity: 348.428\n.........................................................................................\n\nEpoch: 20 | Time: 1m 18s\nTrain Loss: 5.4865 | Train Perplexity: 241.412\nDev Loss: 5.8389 | Dev Perplexity: 343.409\n.........................................................................................\n\nEpoch: 21 | Time: 1m 18s\nTrain Loss: 5.4370 | Train Perplexity: 229.756\nDev Loss: 5.8224 | Dev Perplexity: 337.769\n.........................................................................................\n\nEpoch: 22 | Time: 1m 18s\nTrain Loss: 5.4458 | Train Perplexity: 231.791\nDev Loss: 5.8218 | Dev Perplexity: 337.593\n.........................................................................................\n\nEpoch: 23 | Time: 1m 18s\nTrain Loss: 5.3683 | Train Perplexity: 214.504\nDev Loss: 5.8152 | Dev Perplexity: 335.373\n.........................................................................................\n\nEpoch: 24 | Time: 1m 18s\nTrain Loss: 5.3330 | Train Perplexity: 207.066\nDev Loss: 5.8054 | Dev Perplexity: 332.090\n.........................................................................................\n\nEpoch: 25 | Time: 1m 18s\nTrain Loss: 5.2826 | Train Perplexity: 196.878\nDev Loss: 5.8117 | Dev Perplexity: 334.199\n.........................................................................................\n\nEpoch: 26 | Time: 1m 18s\nTrain Loss: 5.2420 | Train Perplexity: 189.039\nDev Loss: 5.7976 | Dev Perplexity: 329.503\n.........................................................................................\n\nEpoch: 27 | Time: 1m 19s\nTrain Loss: 5.2041 | Train Perplexity: 182.024\nDev Loss: 5.8016 | Dev Perplexity: 330.841\n.........................................................................................\n\nEpoch: 28 | Time: 1m 17s\nTrain Loss: 5.1639 | Train Perplexity: 174.838\nDev Loss: 5.7970 | Dev Perplexity: 329.298\n.........................................................................................\n\nEpoch: 29 | Time: 1m 17s\nTrain Loss: 5.1491 | Train Perplexity: 172.281\nDev Loss: 5.8014 | Dev Perplexity: 330.763\n.........................................................................................\n\nEpoch: 30 | Time: 1m 19s\nTrain Loss: 5.0821 | Train Perplexity: 161.110\nDev Loss: 5.7841 | Dev Perplexity: 325.084\n.........................................................................................\n\nEpoch: 31 | Time: 1m 17s\nTrain Loss: 5.1006 | Train Perplexity: 164.126\nDev Loss: 5.7953 | Dev Perplexity: 328.739\n.........................................................................................\n\nEpoch: 32 | Time: 1m 19s\nTrain Loss: 5.0535 | Train Perplexity: 156.566\nDev Loss: 5.7965 | Dev Perplexity: 329.147\n.........................................................................................\n\nEpoch: 33 | Time: 1m 18s\nTrain Loss: 4.9971 | Train Perplexity: 147.984\nDev Loss: 5.7983 | Dev Perplexity: 329.726\n.........................................................................................\n\nEpoch: 34 | Time: 1m 17s\nTrain Loss: 4.9565 | Train Perplexity: 142.093\nDev Loss: 5.7988 | Dev Perplexity: 329.910\n.........................................................................................\n\nEpoch: 35 | Time: 1m 18s\nTrain Loss: 4.9383 | Train Perplexity: 139.528\nDev Loss: 5.8000 | Dev Perplexity: 330.293\n.........................................................................................\n\nEpoch: 36 | Time: 1m 19s\nTrain Loss: 4.8999 | Train Perplexity: 134.283\nDev Loss: 5.8093 | Dev Perplexity: 333.389\n.........................................................................................\n\nEpoch: 37 | Time: 1m 18s\nTrain Loss: 4.8997 | Train Perplexity: 134.245\nDev Loss: 5.8123 | Dev Perplexity: 334.372\n.........................................................................................\n\nEpoch: 38 | Time: 1m 17s\nTrain Loss: 4.8393 | Train Perplexity: 126.383\nDev Loss: 5.8158 | Dev Perplexity: 335.573\n.........................................................................................\n\nEpoch: 39 | Time: 1m 19s\nTrain Loss: 4.8277 | Train Perplexity: 124.927\nDev Loss: 5.8190 | Dev Perplexity: 336.649\n.........................................................................................\n\nEpoch: 40 | Time: 1m 18s\nTrain Loss: 4.8214 | Train Perplexity: 124.136\nDev Loss: 5.8254 | Dev Perplexity: 338.790\n.........................................................................................\n\nEpoch: 41 | Time: 1m 17s\nTrain Loss: 4.7666 | Train Perplexity: 117.515\nDev Loss: 5.8272 | Dev Perplexity: 339.422\n.........................................................................................\n\nEpoch: 42 | Time: 1m 17s\nTrain Loss: 4.7465 | Train Perplexity: 115.185\nDev Loss: 5.8347 | Dev Perplexity: 341.961\n.........................................................................................\n\nEpoch: 43 | Time: 1m 18s\nTrain Loss: 4.7185 | Train Perplexity: 112.002\nDev Loss: 5.8403 | Dev Perplexity: 343.890\n.........................................................................................\n\nEpoch: 44 | Time: 1m 18s\nTrain Loss: 4.6992 | Train Perplexity: 109.863\nDev Loss: 5.8445 | Dev Perplexity: 345.327\n.........................................................................................\n\nEpoch: 45 | Time: 1m 18s\nTrain Loss: 4.6552 | Train Perplexity: 105.133\nDev Loss: 5.8490 | Dev Perplexity: 346.876\n.........................................................................................\n\nEpoch: 46 | Time: 1m 17s\nTrain Loss: 4.6396 | Train Perplexity: 103.507\nDev Loss: 5.8575 | Dev Perplexity: 349.859\n.........................................................................................\n\nEpoch: 47 | Time: 1m 17s\nTrain Loss: 4.6115 | Train Perplexity: 100.631\nDev Loss: 5.8613 | Dev Perplexity: 351.196\n.........................................................................................\n\nEpoch: 48 | Time: 1m 18s\nTrain Loss: 4.5860 | Train Perplexity: 98.106\nDev Loss: 5.8655 | Dev Perplexity: 352.655\n.........................................................................................\n\nEpoch: 49 | Time: 1m 19s\nTrain Loss: 4.5769 | Train Perplexity: 97.214\nDev Loss: 5.8753 | Dev Perplexity: 356.114\n.........................................................................................\n\nEpoch: 50 | Time: 1m 19s\nTrain Loss: 4.5624 | Train Perplexity: 95.810\nDev Loss: 5.8867 | Dev Perplexity: 360.214\n" ] ], [ [ "## Save last model (overfitted)", "_____no_output_____" ] ], [ [ "torch.save(model.state_dict(), './last_model.pt')", "_____no_output_____" ] ], [ [ "# 7. Test", "_____no_output_____" ], [ "## Function to convert indices to original text strings", "_____no_output_____" ] ], [ [ "def indices_to_text(src_or_trg, lang_field):\n \n assert src_or_trg.dim() == 1, f'{src_or_trg.dim()}' #(seq_len, )\n assert isinstance(lang_field, torchtext.data.Field)\n assert hasattr(lang_field, 'vocab')\n \n return [lang_field.vocab.itos[t] for t in src_or_trg]", "_____no_output_____" ] ], [ [ "## Function to make predictions\n- Returns a list of examples, where each example is a (src, trg, prediction) tuple.", "_____no_output_____" ] ], [ [ "def predict(seq2seq_model, iterator):\n \n seq2seq_model.eval()\n \n out = []\n \n with torch.no_grad():\n for i, batch in enumerate(iterator):\n \n src = batch.src\n trg = batch.trg\n \n decoder_outputs = seq2seq_model(src, trg, teacher_forcing_ratio=0.)\n seq_len, batch_size, trg_vocab_size = decoder_outputs.size() # (b, s, trg_vocab)\n \n # Discard initial decoder input (index = 0)\n #decoder_outputs = decoder_outputs[:, 1:, :]\n \n decoder_predictions = decoder_outputs.argmax(dim=-1) # (b, s)\n \n for i, pred in enumerate(decoder_predictions):\n out.append((src[i], trg[i], pred))\n \n return out", "_____no_output_____" ] ], [ [ "## Load best model", "_____no_output_____" ] ], [ [ "!ls -al", "total 43004\ndrwxr-xr-x 1 root root 4096 Aug 1 04:40 .\ndrwxr-xr-x 1 root root 4096 Aug 1 00:21 ..\n-rw-r--r-- 1 root root 22006424 Aug 1 04:10 best_model.pt\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 .config\ndrwxr-xr-x 2 root root 4096 Aug 1 00:25 data\n-rw-r--r-- 1 root root 22006424 Aug 1 04:40 last_model.pt\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 sample_data\n" ], [ "# Load model\nmodel.load_state_dict(torch.load('./best_model.pt'))", "_____no_output_____" ] ], [ [ "## Make predictions", "_____no_output_____" ] ], [ [ "# Make prediction\ntest_predictions = predict(model, dev_iterator)", "_____no_output_____" ], [ "for i, prediction in enumerate(test_predictions):\n \n src, trg, pred = prediction\n \n src_text = indices_to_text(src, lang_field=KOREAN)\n trg_text = indices_to_text(trg, lang_field=ENGLISH)\n pred_text = indices_to_text(pred, lang_field=ENGLISH)\n \n print('source:\\n', src_text)\n print('target:\\n', trg_text)\n print('prediction:\\n', pred_text)\n print('-' * 160)\n \n if i > 5:\n break", "source:\n ['<sos>', '오랫동안', '이탈리아', '전역', '이', '곤혹', '스러웠다', '.', '<eos>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>']\ntarget:\n ['<sos>', 'naples', ',', 'italy', '(', 'cnn', ')', 'for', 'years', ',', 'it', \"'s\", 'been', 'a', 'national', 'embarrassment', '.', '<eos>', '<pad>']\nprediction:\n ['<unk>', 'the', 'was', 'the', '.', 'cnn', ')', '.', 'the', '.', '<eos>', '.', '.', '.', '.', '.', '.', '<eos>', '<eos>']\n----------------------------------------------------------------------------------------------------------------------------------------------------------------\nsource:\n ['<sos>', 'bank', '-', '<unk>', 'company', '은행', '지주회사', '<eos>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>']\ntarget:\n ['<sos>', '“', 'gm', \"'s\", 'financing', 'arm', ',', 'gmac', ',', 'has', 'been', 'declared', 'a', 'bank', '-', 'holding', 'company', '.', '<eos>']\nprediction:\n ['<unk>', 'the', 'the', 'to', '<unk>', 'to', '<unk>', '<unk>', '<unk>', '<unk>', 'been', '<unk>', '.', '<unk>', '.', '<unk>', '<unk>', '.', '<eos>']\n----------------------------------------------------------------------------------------------------------------------------------------------------------------\nsource:\n ['<sos>', '미', '연', '방법', '원', '이', '로비스트', '박동선', '씨', '의', '보석', '신청', '을', '기각', '했다', '.', '<eos>']\ntarget:\n ['<sos>', 'u.s.', 'government', 'prosecutors', 'are', 'against', 'bail', 'being', 'set', 'for', 'south', 'korean', 'lobbyist', 'tongsun', 'park', '.', '<eos>', '<pad>', '<pad>']\nprediction:\n ['<unk>', 'the', 'officials', 'has', ',', '<unk>', 'the', ',', 'recounted', 'up', 'the', 'korea', 'peninsula', '.', '.', '.', '<eos>', '<eos>', '.']\n----------------------------------------------------------------------------------------------------------------------------------------------------------------\nsource:\n ['<sos>', 'GM', '의', '자회사', '가', '연방', '준비', '제도로', '부터', '재정', '적', '지원', '을', '받게', '되었습니다', '.', '<eos>']\ntarget:\n ['<sos>', 'a', 'division', 'of', 'general', 'motors', 'is', 'getting', 'some', 'financial', 'help', 'from', 'the', 'federal', 'reserve', ':', '<eos>', '<pad>', '<pad>']\nprediction:\n ['<unk>', 'the', 'few', 'of', 'the', 'motors', 'to', 'a', 'to', 'of', 'crisis', '.', 'the', '.', '.', '.', '<eos>', '.', '.']\n----------------------------------------------------------------------------------------------------------------------------------------------------------------\nsource:\n ['<sos>', '검찰', '은', '명단', '의', '모든', '사람', '이', '공모자', '로', '여겨지고', '있지는', '않다고', '전', '했다', '.', '<eos>']\ntarget:\n ['<sos>', 'a', 'prosecutor', 'said', 'not', 'everyone', 'on', 'the', 'list', 'was', 'considered', 'a', 'co', '-', '<unk>', '.', '<eos>', '<pad>', '<pad>']\nprediction:\n ['<unk>', 'the', 'statement', 'said', 'that', 'the', ',', 'the', ',', 'of', 'a', 'to', '<unk>', '-', 'old', '.', '<eos>', '<eos>', '.']\n----------------------------------------------------------------------------------------------------------------------------------------------------------------\nsource:\n ['<sos>', '이', '날', '테러', '현장', '인근', '에', '주차', '한', '차량', '에서', '폭탄', '이', '발견', '됐다', '.', '<eos>']\ntarget:\n ['<sos>', 'a', 'bomb', 'was', 'discovered', 'in', 'a', 'parked', 'car', 'near', 'the', 'site', 'of', 'the', 'attack', '.', '<eos>', '<pad>', '<pad>']\nprediction:\n ['<unk>', 'the', 'police', 'exploded', 'a', 'in', 'the', '<unk>', ',', 'bomb', 'the', ',', ',', 'the', ',', ',', '<eos>', '<eos>', 'police']\n----------------------------------------------------------------------------------------------------------------------------------------------------------------\nsource:\n ['<sos>', '그러나', '합성', '테스토스테론', '제', '는', '남성', '을', '위', '해서만', '승인', '을', '받은', '의약품', '이다', '.', '<eos>']\ntarget:\n ['<sos>', '<unk>', 'testosterone', ',', 'however', ',', 'has', 'been', 'approved', 'only', 'for', 'use', 'with', 'men', '.', '<eos>', '<pad>', '<pad>', '<pad>']\nprediction:\n ['<unk>', 'but', ',', ',', 'the', ',', 'the', 'been', 'to', 'to', 'condemn', 'the', '.', 'the', '.', '<eos>', '<eos>', '.', '.']\n----------------------------------------------------------------------------------------------------------------------------------------------------------------\n" ] ], [ [ "# 8. Download Model", "_____no_output_____" ] ], [ [ "!ls -al", "total 43004\ndrwxr-xr-x 1 root root 4096 Aug 1 04:40 .\ndrwxr-xr-x 1 root root 4096 Aug 1 00:21 ..\n-rw-r--r-- 1 root root 22006424 Aug 1 04:10 best_model.pt\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 .config\ndrwxr-xr-x 2 root root 4096 Aug 1 00:25 data\n-rw-r--r-- 1 root root 22006424 Aug 1 04:40 last_model.pt\ndrwxr-xr-x 1 root root 4096 Jul 19 16:14 sample_data\n" ], [ "from google.colab import files\nprint('Downloading models...') # Known bug; if using Firefox, a print statement in the same cell is necessary.\nfiles.download('./best_model.pt')\nfiles.download('./last_model.pt')", "Downloading models...\n" ] ], [ [ "# 9. Discussions", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "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", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d02f50ae12822714d252c4b968c0375c756bb8cf
476,942
ipynb
Jupyter Notebook
Machine_Learning/Conv_neu_network/Conv_network.ipynb
ozkanuysal/Un-vers-tySecondClass
0330fe3576e5febb517f1a3e6b7ec90be0ff759f
[ "Unlicense" ]
2
2020-12-10T16:05:32.000Z
2020-12-14T22:20:58.000Z
Machine_Learning/Conv_neu_network/Conv_network.ipynb
ozkanuysal/UniversitySecondClass
0330fe3576e5febb517f1a3e6b7ec90be0ff759f
[ "Unlicense" ]
null
null
null
Machine_Learning/Conv_neu_network/Conv_network.ipynb
ozkanuysal/UniversitySecondClass
0330fe3576e5febb517f1a3e6b7ec90be0ff759f
[ "Unlicense" ]
null
null
null
1,595.123746
451,460
0.957064
[ [ [ "import tensorflow as tf\n", "_____no_output_____" ], [ "from tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()", "Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n170500096/170498071 [==============================] - 423s 2us/step\n" ], [ "#piksel 0-1 arası değer alıyor\ntrain_images, test_images = train_images / 255.0, test_images / 255.0", "_____no_output_____" ], [ "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck']\n", "_____no_output_____" ], [ "#çizdirelim bakalım\nplt.figure(figsize=(10,10))\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(train_images[i], cmap=plt.cm.binary)\n plt.xlabel(class_names[train_labels[i][0]])\nplt.show()", "_____no_output_____" ], [ "#modeli oluşturalım\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation='relu'))", "_____no_output_____" ], [ "#Yapısına bakalım nasıl olmuş\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 30, 30, 32) 896 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 15, 15, 32) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 13, 13, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 6, 6, 64) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 4, 4, 64) 36928 \n=================================================================\nTotal params: 56,320\nTrainable params: 56,320\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "#maxpooling için katman ekleyelim\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(64, activation='relu'))\nmodel.add(layers.Dense(10))\n", "_____no_output_____" ], [ "#Yapısına bakalım\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 30, 30, 32) 896 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 15, 15, 32) 0 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 13, 13, 64) 18496 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 6, 6, 64) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 4, 4, 64) 36928 \n_________________________________________________________________\nflatten (Flatten) (None, 1024) 0 \n_________________________________________________________________\ndense (Dense) (None, 64) 65600 \n_________________________________________________________________\ndense_1 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 122,570\nTrainable params: 122,570\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "#modeli egitmeye başlayalım\nmodel.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\nhistory = model.fit(train_images, train_labels, epochs=10, \n validation_data=(test_images, test_labels))", "Epoch 1/10\n1563/1563 [==============================] - 26s 17ms/step - loss: 1.5640 - accuracy: 0.4290 - val_loss: 1.2695 - val_accuracy: 0.5456\nEpoch 2/10\n1563/1563 [==============================] - 27s 17ms/step - loss: 1.1755 - accuracy: 0.5853 - val_loss: 1.0673 - val_accuracy: 0.6229\nEpoch 3/10\n1563/1563 [==============================] - 27s 17ms/step - loss: 1.0205 - accuracy: 0.6406 - val_loss: 1.0022 - val_accuracy: 0.6531\nEpoch 4/10\n1563/1563 [==============================] - 27s 18ms/step - loss: 0.9256 - accuracy: 0.6743 - val_loss: 0.9387 - val_accuracy: 0.6714\nEpoch 5/10\n1563/1563 [==============================] - 29s 19ms/step - loss: 0.8566 - accuracy: 0.7008 - val_loss: 0.9098 - val_accuracy: 0.6803\nEpoch 6/10\n1563/1563 [==============================] - 29s 19ms/step - loss: 0.8003 - accuracy: 0.7190 - val_loss: 0.9274 - val_accuracy: 0.6771\nEpoch 7/10\n1563/1563 [==============================] - 29s 19ms/step - loss: 0.7550 - accuracy: 0.7349 - val_loss: 0.8979 - val_accuracy: 0.6865\nEpoch 8/10\n1563/1563 [==============================] - 32s 20ms/step - loss: 0.7107 - accuracy: 0.7523 - val_loss: 0.8901 - val_accuracy: 0.6954\nEpoch 9/10\n1563/1563 [==============================] - 30s 19ms/step - loss: 0.6771 - accuracy: 0.7618 - val_loss: 0.8738 - val_accuracy: 0.7036\nEpoch 10/10\n1563/1563 [==============================] - 27s 17ms/step - loss: 0.6394 - accuracy: 0.7759 - val_loss: 0.8651 - val_accuracy: 0.7115\n" ], [ "#Doğruluk oranını çizdirip bakalım\nplt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label = 'val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0.5, 1])\nplt.legend(loc='lower right')\ntest_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)", "313/313 - 1s - loss: 0.8651 - accuracy: 0.7115\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d02f7834600d18b520f6fa46786f8f2b031a2a7f
129
ipynb
Jupyter Notebook
otherTeam/get_citation.ipynb
zeroknowledgediscovery/unitcov
abeb5208f47610ed154bf0d45cab96c61c936cf0
[ "MIT" ]
null
null
null
otherTeam/get_citation.ipynb
zeroknowledgediscovery/unitcov
abeb5208f47610ed154bf0d45cab96c61c936cf0
[ "MIT" ]
1
2020-11-09T22:59:14.000Z
2020-11-09T22:59:14.000Z
otherTeam/get_citation.ipynb
zeroknowledgediscovery/unitcov
abeb5208f47610ed154bf0d45cab96c61c936cf0
[ "MIT" ]
null
null
null
32.25
75
0.883721
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
d02f7c003a50435d2116dbc18e8185d589099a03
60,694
ipynb
Jupyter Notebook
notebooks/bgg_weekly_crawler.ipynb
MichoelSnow/BGG
d100c0c15c3b57cb2e4d0ba89df6f3c4b4b5b10f
[ "MIT" ]
null
null
null
notebooks/bgg_weekly_crawler.ipynb
MichoelSnow/BGG
d100c0c15c3b57cb2e4d0ba89df6f3c4b4b5b10f
[ "MIT" ]
4
2020-03-24T16:18:40.000Z
2021-12-13T19:50:55.000Z
notebooks/bgg_weekly_crawler.ipynb
MichoelSnow/BGG
d100c0c15c3b57cb2e4d0ba89df6f3c4b4b5b10f
[ "MIT" ]
null
null
null
36.278542
462
0.378192
[ [ [ "# Imports and Paths", "_____no_output_____" ] ], [ [ "import urllib3\nhttp = urllib3.PoolManager()", "_____no_output_____" ], [ "from urllib import request\nfrom bs4 import BeautifulSoup, Comment\nimport pandas as pd\nfrom datetime import datetime\n# from shutil import copyfile\n# import time\nimport json", "_____no_output_____" ] ], [ [ "# Load in previous list of games", "_____no_output_____" ] ], [ [ "df_gms_lst = pd.read_csv('../data/bgg_top2000_2018-10-06.csv')", "_____no_output_____" ], [ "df_gms_lst.columns", "_____no_output_____" ], [ "metadata_dict = {\"title\": \"BGG Top 2000\",\n \"subtitle\": \"Board Game Geek top 2000 games rankings\",\n \"description\": \"Board Game Geek top 2000 games rankings and other info\",\n \"id\": \"mseinstein/bgg_top2000\",\n \"licenses\": [{\"name\": \"CC-BY-SA-4.0\"}],\n \"resources\":[\n {\"path\": \"bgg_top2000_2018-10-06.csv\",\n \"description\": \"Board Game Geek top 2000 games on 2018-10-06\"\n }\n ] }", "_____no_output_____" ], [ "with open('../data/kaggle/dataset-metadata.json', 'w') as fp:\n json.dump(metadata_dict, fp)", "_____no_output_____" ] ], [ [ "# Get the id's of the top 2000 board games", "_____no_output_____" ] ], [ [ "pg_gm_rnks = 'https://boardgamegeek.com/browse/boardgame/page/'", "_____no_output_____" ], [ "def extract_gm_id(soup):\n rows = soup.find('div', {'id': 'collection'}).find_all('tr')[1:]\n id_list = []\n for row in rows:\n id_list.append(int(row.find_all('a')[1]['href'].split('/')[2]))\n return id_list", "_____no_output_____" ], [ "def top_2k_gms(pg_gm_rnks):\n gm_ids = []\n for pg_num in range(1,21):\n pg = request.urlopen(f'{pg_gm_rnks}{str(pg_num)}')\n soup = BeautifulSoup(pg, 'html.parser')\n gm_ids += extract_gm_id(soup)\n return gm_ids", "_____no_output_____" ], [ "gm_ids = top_2k_gms(pg_gm_rnks)\nlen(gm_ids)", "_____no_output_____" ] ], [ [ "# Extract the info for each game in the top 2k using the extracted game id's", "_____no_output_____" ] ], [ [ "bs_pg = 'https://www.boardgamegeek.com/xmlapi2/'\nbs_pg_gm = f'{bs_pg}thing?type=boardgame&stats=1&ratingcomments=1&page=1&pagesize=10&id='", "_____no_output_____" ], [ "def extract_game_item(item):\n gm_dict = {}\n field_int = ['yearpublished', 'minplayers', 'maxplayers', 'playingtime', 'minplaytime', 'maxplaytime', 'minage']\n field_categ = ['boardgamecategory', 'boardgamemechanic', 'boardgamefamily','boardgamedesigner', 'boardgameartist', 'boardgamepublisher']\n field_rank = [x['friendlyname'] for x in item.find_all('rank')]\n field_stats = ['usersrated', 'average', 'bayesaverage', 'stddev', 'median', 'owned', 'trading', 'wanting', 'wishing', 'numcomments', 'numweights', 'averageweight']\n gm_dict['name'] = item.find('name')['value']\n gm_dict['id'] = item['id']\n gm_dict['num_of_rankings'] = int(item.find('comments')['totalitems'])\n for i in field_int:\n field_val = item.find(i)\n if field_val is None:\n gm_dict[i] = -1\n else:\n gm_dict[i] = int(field_val['value'])\n for i in field_categ:\n gm_dict[i] = [x['value'] for x in item.find_all('link',{'type':i})]\n for i in field_rank:\n field_val = item.find('rank',{'friendlyname':i})\n if field_val is None or field_val['value'] == 'Not Ranked':\n gm_dict[i.replace(' ','')] = -1\n else:\n gm_dict[i.replace(' ','')] = int(field_val['value'])\n for i in field_stats:\n field_val = item.find(i)\n if field_val is None:\n gm_dict[i] = -1\n else:\n gm_dict[i] = float(field_val['value'])\n return gm_dict", "_____no_output_____" ], [ "len(gm_ids)", "_____no_output_____" ], [ "gm_list = []\nidx_split = 4\nidx_size = int(len(gm_ids)/idx_split)\nfor i in range(idx_split):\n idx = str(gm_ids[i*idx_size:(i+1)*idx_size]).replace(' ','')[1:-1] \n pg = request.urlopen(f'{bs_pg_gm}{str(idx)}')\n item_ct = 0\n xsoup = BeautifulSoup(pg, 'xml')\n# while item_ct < 500:\n# xsoup = BeautifulSoup(pg, 'xml')\n# item_ct = len(xsoup.find_all('item'))\n gm_list += [extract_game_item(x) for x in xsoup.find_all('item')]\n# break\ndf2 = pd.DataFrame(gm_list)\ndf2.shape", "_____no_output_____" ], [ "df2.head()", "_____no_output_____" ], [ "df2.loc[df2[\"Children'sGameRank\"].notnull(),:].head().T", "_____no_output_____" ], [ "df2.isnull().sum()", "_____no_output_____" ], [ "gm_list = []\nidx_split = 200\nidx_size = int(len(gm_ids)/idx_split)\nfor i in range(idx_split):\n idx = str(gm_ids[i*idx_size:(i+1)*idx_size]).replace(' ','')[1:-1] \n break\n# pg = request.urlopen(f'{bs_pg_gm}{str(idx)}')\n# item_ct = 0\n# xsoup = BeautifulSoup(pg, 'xml')\n# # while item_ct < 500:\n# # xsoup = BeautifulSoup(pg, 'xml')\n# # item_ct = len(xsoup.find_all('item'))\n# gm_list += [extract_game_item(x) for x in xsoup.find_all('item')]\n# # break\n# df2 = pd.DataFrame(gm_list)\n# df2.shape", "_____no_output_____" ], [ "idx", "_____no_output_____" ], [ "def create_df_gm_ranks(gm_ids, bs_pg_gm):\n gm_list = []\n idx_split = 4\n idx_size = int(len(gm_ids)/idx_split)\n for i in range(idx_split):\n idx = str(gm_ids[i*idx_size:(i+1)*idx_size]).replace(' ','')[1:-1] \n pg = request.urlopen(f'{bs_pg_gm}{str(idx)}')\n xsoup = BeautifulSoup(pg, 'xml')\n gm_list += [extract_game_item(x) for x in xsoup.find_all('item')]\n df = pd.DataFrame(gm_list)\n return df", "_____no_output_____" ], [ "df = create_df_gm_ranks(gm_ids, bs_pg_gm)", "_____no_output_____" ], [ "df2.to_csv(f'../data/kaggle/{str(datetime.now().date())}_bgg_top{len(gm_ids)}.csv', index=False)", "_____no_output_____" ], [ "with open('../data/kaggle/dataset-metadata.json', 'rb') as f:\n meta_dict = json.load(f)", "_____no_output_____" ], [ "meta_dict['resources'].append({\n 'path': f'{str(datetime.now().date())}_bgg_top{len(gm_ids)}.csv',\n 'description': f'Board Game Geek top 2000 games on {str(datetime.now().date())}'\n})", "_____no_output_____" ], [ "meta_dict", "_____no_output_____" ], [ "meta_dict['title'] = 'Board Game Geek (BGG) Top 2000'", "_____no_output_____" ], [ "meta_dict['resources'][-1]['path'] = '2018-12-15_bgg_top2000.csv'\nmeta_dict['resources'][-1]['description']= 'Board Game Geek top 2000 games on 2018-12-15'", "_____no_output_____" ], [ "with open('../data/kaggle/dataset-metadata.json', 'w') as fp:\n json.dump(meta_dict, fp)", "_____no_output_____" ] ], [ [ "Code for kaggle\n\nkaggle datasets version -m \"week of 2018-10-20\" -p .\\ -d", "_____no_output_____" ] ], [ [ "meta_dict", "_____no_output_____" ], [ "gm_list = []\nidx_split = 4\nidx_size = int(len(gm_ids)/idx_split)\nfor i in range(idx_split):\n idx = str(gm_ids[i*idx_size:(i+1)*idx_size]).replace(' ','')[1:-1] \n break", "_____no_output_____" ], [ "idx2 = '174430,161936,182028,167791,12333,187645,169786,220308,120677,193738,84876,173346,180263,115746,3076,102794,205637'", "_____no_output_____" ], [ "pg = request.urlopen(f'{bs_pg_gm}{str(idx)}')", "_____no_output_____" ], [ "xsoup = BeautifulSoup(pg, 'xml')", "_____no_output_____" ], [ "aa = xsoup.find_all('item')\nlen(aa)", "_____no_output_____" ], [ "http.urlopen()", "_____no_output_____" ], [ "r = http.request('GET', f'{bs_pg_gm}{str(idx)}')", "/home/msnow/miniconda3/envs/bgg/lib/python3.7/site-packages/urllib3/connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n" ], [ "xsoup2 = BeautifulSoup(r.data, 'xml')", "_____no_output_____" ], [ "bb = xsoup.find_all('item')\nlen(bb)", "_____no_output_____" ] ], [ [ "# XML2 API", "_____no_output_____" ], [ "Base URI: /xmlapi2/thing?parameters\n- id=NNN\t\n - Specifies the id of the thing(s) to retrieve. To request multiple things with a single query, NNN can specify a comma-delimited list of ids.\n- type=THINGTYPE\t\n - Specifies that, regardless of the type of thing asked for by id, the results are filtered by the THINGTYPE(s) specified. Multiple THINGTYPEs can be specified in a comma-delimited list.\n- versions=1\t\n - Returns version info for the item.\n- videos = 1\t\n - Returns videos for the item.\n- stats=1\t\t\n - Returns ranking and rating stats for the item.\n- historical=1\t\t\n - Returns historical data over time. See page parameter.\n- marketplace=1\t\t\n - Returns marketplace data.\n- comments=1\t\t\n - Returns all comments about the item. Also includes ratings when commented. See page parameter.\n- ratingcomments=1\t\t\n - Returns all ratings for the item. Also includes comments when rated. See page parameter. The ratingcomments and comments parameters cannot be used together, as the output always appears in the \\<comments\\> node of the XML; comments parameter takes precedence if both are specified. Ratings are sorted in descending rating value, based on the highest rating they have assigned to that item (each item in the collection can have a different rating).\n- page=NNN\t\t\n - Defaults to 1, controls the page of data to see for historical info, comments, and ratings data.\n- pagesize=NNN\t\t\n - Set the number of records to return in paging. Minimum is 10, maximum is 100.\n- from=YYYY-MM-DD\t\t\n - Not currently supported.\n- to=YYYY-MM-DD\t\t\n - Not currently supported.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
d02f81dfd853205440ba24586c08c47ae26bcb59
16,403
ipynb
Jupyter Notebook
testing/FNSB_Graph_Util_Notebook.ipynb
alanmitchell/fnsb-benchmark
b7b8066d6adadfb13758fa5c77fa0e52175a6211
[ "MIT" ]
null
null
null
testing/FNSB_Graph_Util_Notebook.ipynb
alanmitchell/fnsb-benchmark
b7b8066d6adadfb13758fa5c77fa0e52175a6211
[ "MIT" ]
25
2017-10-19T17:28:43.000Z
2017-10-20T22:36:50.000Z
testing/FNSB_Graph_Util_Notebook.ipynb
alanmitchell/fnsb-benchmark
b7b8066d6adadfb13758fa5c77fa0e52175a6211
[ "MIT" ]
null
null
null
39.241627
131
0.557154
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\nimport matplotlib as mpl\nimport matplotlib.dates as mdates\nimport datetime\n\n# Set the matplotlib settings (eventually this will go at the top of the graph_util)\nmpl.rcParams['axes.labelsize'] = 16\nmpl.rcParams['axes.titlesize'] = 20\nmpl.rcParams['legend.fontsize'] = 16\nmpl.rcParams['font.size'] = 16.0\nmpl.rcParams['figure.figsize'] = [15,10]\nmpl.rcParams['xtick.labelsize'] = 16\nmpl.rcParams['ytick.labelsize'] = 16\n\n# Set the style for the graphs\nplt.style.use('bmh')\n\n# Additional matplotlib formatting settings\nmonths = mdates.MonthLocator()\n\n# This formats the months as three-letter abbreviations\nmonths_format = mdates.DateFormatter('%b')", "_____no_output_____" ], [ "def area_cost_distribution(df, fiscal_year_col, utility_col_list, filename):\n # Inputs include the dataframe, the column name for the fiscal year column, and the list of column names for the \n # different utility bills. The dataframe should already include the summed bills for each fiscal year.\n\n fig, ax = plt.subplots()\n\n \n # Take costs for each utility type and convert to percent of total cost by fiscal year\n df['total_costs'] = df[utility_col_list].sum(axis=1)\n\n percent_columns = []\n\n for col in utility_col_list:\n percent_col = \"Percent \" + col\n percent_columns.append(percent_col)\n df[percent_col] = df[col] / df.total_costs\n\n # Create stacked area plot\n ax.stackplot(df[fiscal_year_col], df[percent_columns].T, labels=percent_columns)\n\n # Format the y axis to be in percent\n ax.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format))\n \n # Format the x-axis to include all fiscal years\n plt.xticks(np.arange(df[fiscal_year_col].min(), df[fiscal_year_col].max()+1, 1.0))\n\n # Add title and axis labels\n plt.title('Annual Utility Cost Distribution')\n plt.ylabel('Utility Cost Distribution')\n plt.xlabel('Fiscal Year')\n \n # Add legend\n plt.legend()\n \n # Make sure file goes in the proper directory\n folder_and_filename = 'output/images/' + filename\n \n # Save and show\n plt.savefig(folder_and_filename)\n plt.show()", "_____no_output_____" ], [ "def area_use_distribution(df, fiscal_year_col, utility_col_list, filename):\n # Inputs include the dataframe, the column name for the fiscal year column, and the list of column names for the \n # different utility bills. The dataframe should already include the summed bills for each fiscal year.\n \n\n fig, ax = plt.subplots()\n\n \n # Take usage for each utility type and convert to percent of total cost by fiscal year\n df['total_use'] = df[utility_col_list].sum(axis=1)\n\n percent_columns = []\n\n for col in utility_col_list:\n percent_col = \"Percent \" + col\n percent_columns.append(percent_col)\n df[percent_col] = df[col] / df.total_use\n\n # Create stacked area plot\n ax.stackplot(df[fiscal_year_col], df[percent_columns].T, labels=percent_columns)\n\n\n # Format the y axis to be in percent\n ax.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format))\n \n # Format the x-axis to include all fiscal years\n plt.xticks(np.arange(df[fiscal_year_col].min(), df[fiscal_year_col].max()+1, 1.0))\n\n # Add title and axis labels\n plt.title('Annual Energy Usage Distribution')\n plt.ylabel('Annual Energy Usage Distribution')\n plt.xlabel('Fiscal Year')\n \n # Add legend \n plt.legend()\n \n # Make sure file goes in the proper directory\n folder_and_filename = 'output/images/' + filename\n \n # Save and show\n plt.savefig(folder_and_filename)\n plt.show()", "_____no_output_____" ], [ "def create_stacked_bar(df, fiscal_year_col, column_name_list, filename):\n \n # Parameters include the dataframe, the name of the column where the fiscal year is listed, a list of the column names\n # with the correct data for the chart, and the filename where the output should be saved.\n \n \n # Create the figure\n plt.figure()\n \n # Set the bar width\n width = 0.50\n \n \n # Create the stacked bars. The \"bottom\" is the sum of all previous bars to set the starting point for the next bar.\n previous_col_name = 0\n \n for col in column_name_list:\n short_col_name = col.split(\" Cost\")[0]\n short_col_name = plt.bar(df[fiscal_year_col], df[col], width, label=short_col_name, bottom=previous_col_name)\n previous_col_name = previous_col_name + df[col]\n \n # label axes\n plt.ylabel('Utility Cost [$]')\n plt.xlabel('Fiscal Year')\n plt.title('Total Annual Utility Costs')\n \n # Make one bar for each fiscal year\n plt.xticks(np.arange(df[fiscal_year_col].min(), df[fiscal_year_col].max()+1, 1.0), \n np.sort(list(df[fiscal_year_col].unique())))\n \n # Set the yticks to go up to the total cost in increments of 100,000\n df['total_cost'] = df[column_name_list].sum(axis=1)\n plt.yticks(np.arange(0, df.total_cost.max(), 100000))\n \n plt.legend()\n \n # Make sure file goes in the proper directory\n folder_and_filename = 'output/images/' + filename\n \n # Save and show\n plt.savefig(filename)\n plt.show()", "_____no_output_____" ], [ "def energy_use_stacked_bar(df, fiscal_year_col, column_name_list, filename):\n \n # Parameters include the dataframe, the name of the column where the fiscal year is listed, a list of the column names\n # with the correct data for the chart, and the filename where the output should be saved.\n \n # Create the figure\n plt.figure()\n \n # Set the bar width\n width = 0.50\n \n \n # Create the stacked bars. The \"bottom\" is the sum of all previous bars to set the starting point for the next bar.\n previous_col_name = 0\n \n for col in column_name_list:\n short_col_name = col.split(\" [MMBTU\")[0]\n short_col_name = plt.bar(df[fiscal_year_col], df[col], width, label=short_col_name, bottom=previous_col_name)\n previous_col_name = previous_col_name + df[col]\n \n # label axes\n plt.ylabel('Annual Energy Usage [MMBTU]')\n plt.xlabel('Fiscal Year')\n plt.title('Total Annual Energy Usage')\n \n \n # Make one bar for each fiscal year\n plt.xticks(np.arange(df[fiscal_year_col].min(), df[fiscal_year_col].max()+1, 1.0), \n np.sort(list(df[fiscal_year_col].unique())))\n \n # Set the yticks to go up to the total usage in increments of 1,000\n df['total_use'] = df[column_name_list].sum(axis=1)\n plt.yticks(np.arange(0, df.total_use.max(), 1000))\n \n plt.legend()\n \n # Make sure file goes in the proper directory\n folder_and_filename = 'output/images/' + filename\n \n # Save and show\n plt.savefig(folder_and_filename)\n plt.show()", "_____no_output_____" ], [ "def usage_pie_charts(df, use_or_cost_cols, chart_type, filename):\n \n # df: A dataframe with the fiscal_year as the index and needs to include the values for the passed in list of columns.\n # use_or_cost_cols: a list of the energy usage or energy cost column names\n # chart_type: 1 for an energy use pie chart, 2 for an energy cost pie chart\n \n \n # Get the three most recent complete years of data\n complete_years = df.query(\"month_count == 12.0\")\n sorted_completes = complete_years.sort_index(ascending=False)\n most_recent_complete_years = sorted_completes[0:3]\n years = list(most_recent_complete_years.index.values)\n \n # Create percentages from usage\n most_recent_complete_years = most_recent_complete_years[use_or_cost_cols]\n most_recent_complete_years['Totals'] = most_recent_complete_years.sum(axis=1)\n for col in use_or_cost_cols:\n most_recent_complete_years[col] = most_recent_complete_years[col] / most_recent_complete_years.Totals\n \n most_recent_complete_years = most_recent_complete_years.drop('Totals', axis=1)\n \n for col in use_or_cost_cols:\n if most_recent_complete_years[col].iloc[0] == 0:\n most_recent_complete_years = most_recent_complete_years.drop(col, axis=1)\n \n \n # Create a pie chart for each of 3 most recent complete years\n for year in years:\n \n year_df = most_recent_complete_years.query(\"fiscal_year == @year\")\n plt.figure()\n fig, ax = plt.subplots()\n \n ax.pie(list(year_df.iloc[0].values), labels=list(year_df.columns.values), autopct='%1.1f%%',\n shadow=True, startangle=90)\n \n # Create the title based on whether it is an energy use or energy cost pie chart. \n if chart_type == 1:\n title = \"FY \" + str(year) + \" Energy Usage [MMBTU]\"\n else:\n titel = \"FY \" + str(year) + \" Energy Cost [$]\"\n \n plt.title(title)\n\n ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\n\n # Make sure file goes in the proper directory\n folder_and_filename = 'output/images/' + filename + str(year)\n\n # Save and show\n plt.savefig(folder_and_filename)\n plt.show()", "_____no_output_____" ], [ "def create_monthly_profile(df, graph_column_name, yaxis_name, color_choice, filename):\n # Parameters: \n # df: A dataframe with the fiscal_year, fiscal_mo, and appropriate graph column name ('kWh', 'kW', etc.)\n # graph_column_name: The name of the column containing the data to be graphed on the y-axis\n # yaxis_name: A string that will be displayed on the y-axis\n # color_choice: 'blue', 'red', or 'green' depending on the desired color palette. \n \n # Additional matplotlib formatting settings\n months = mdates.MonthLocator()\n \n # This formats the months as three-letter abbreviations\n months_format = mdates.DateFormatter('%b')\n\n # Get five most recent years\n recent_years = (sorted(list(df.index.levels[0].values), reverse=True)[0:5])\n \n # Reset the index of the dataframe for more straightforward queries\n df_reset = df.reset_index()\n \n def get_date(row):\n # Converts the fiscal year and fiscal month columns to a datetime object for graphing\n \n # Year is set to 2016-17 so that the charts overlap; otherwise they will be spread out by year.\n # The \"year trick\" allows the graph to start from July so the seasonal energy changes are easier to identify\n if row['fiscal_mo'] > 6:\n year_trick = 2016\n else:\n year_trick = 2017\n\n return datetime.date(year=year_trick, month=row['fiscal_mo'], day=1)\n\n # This creates a new date column with data in the datetime format for graphing\n df_reset['date'] = df_reset[['fiscal_year', 'fiscal_mo']].apply(get_date, axis=1)\n \n # Create a color dictionary of progressively lighter colors of three different shades and convert to dataframe\n color_dict = {'blue': ['#08519c', '#3182bd', '#6baed6', '#bdd7e7', '#eff3ff'],\n 'red': ['#a50f15', '#de2d26', '#fb6a4a', '#fcae91', '#fee5d9'],\n 'green': ['#006d2c', '#31a354', '#74c476', '#bae4b3', '#edf8e9']\n }\n\n color_df = pd.DataFrame.from_dict(color_dict)\n\n \n # i is the counter for the different colors\n i=0\n\n # Create the plots\n fig, ax = plt.subplots()\n\n for year in recent_years:\n\n # Create df for one year only so it's plotted as a single line\n year_df = electric_pivot_monthly_reset.query(\"fiscal_year == @year\")\n year_df = year_df.sort_values(by='date')\n\n # Plot the data\n ax.plot_date(year_df['date'], year_df[graph_column_name], fmt='-', color=color_df.iloc[i][color_choice], \n label=str(year_df.fiscal_year.iloc[0]))\n\n # Increase counter by one to use the next color\n i += 1\n\n\n # Format the dates\n ax.xaxis.set_major_locator(months)\n ax.xaxis.set_major_formatter(months_format)\n fig.autofmt_xdate()\n\n # Add the labels\n plt.xlabel('Month of Year')\n plt.ylabel(yaxis_name)\n plt.legend()\n\n # Make sure file goes in the proper directory\n folder_and_filename = 'output/images/' + filename\n \n # Save and show\n plt.savefig(folder_and_filename)\n plt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d02f87b7d2be7b575b51f66eba55cc588f10dce3
955,869
ipynb
Jupyter Notebook
vui_notebook.ipynb
RomansWorks/AIND-VUI-Capstone
1ecc287cab7197d1a3122d2f3b943db5651053cf
[ "MIT" ]
null
null
null
vui_notebook.ipynb
RomansWorks/AIND-VUI-Capstone
1ecc287cab7197d1a3122d2f3b943db5651053cf
[ "MIT" ]
null
null
null
vui_notebook.ipynb
RomansWorks/AIND-VUI-Capstone
1ecc287cab7197d1a3122d2f3b943db5651053cf
[ "MIT" ]
null
null
null
628.447732
423,247
0.854925
[ [ [ "# Artificial Intelligence Nanodegree\n\n## Voice User Interfaces\n\n## Project: Speech Recognition with Neural Networks\n\n---\n\nIn this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'(IMPLEMENTATION)'** in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully! \n\n> **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \\n\",\n \"**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.\n\nIn addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.\n\n>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.\n\nThe rubric contains _optional_ \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. If you decide to pursue the \"Stand Out Suggestions\", you should include the code in this Jupyter notebook.\n\n---\n\n## Introduction \n\nIn this notebook, you will build a deep neural network that functions as part of an end-to-end automatic speech recognition (ASR) pipeline! Your completed pipeline will accept raw audio as input and return a predicted transcription of the spoken language. The full pipeline is summarized in the figure below.\n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/pipeline.png?raw=1\">\n\n- **STEP 1** is a pre-processing step that converts raw audio to one of two feature representations that are commonly used for ASR. \n- **STEP 2** is an acoustic model which accepts audio features as input and returns a probability distribution over all potential transcriptions. After learning about the basic types of neural networks that are often used for acoustic modeling, you will engage in your own investigations, to design your own acoustic model!\n- **STEP 3** in the pipeline takes the output from the acoustic model and returns a predicted transcription. \n\nFeel free to use the links below to navigate the notebook:\n- [The Data](#thedata)\n- [**STEP 1**](#step1): Acoustic Features for Speech Recognition\n- [**STEP 2**](#step2): Deep Neural Networks for Acoustic Modeling\n - [Model 0](#model0): RNN\n - [Model 1](#model1): RNN + TimeDistributed Dense\n - [Model 2](#model2): CNN + RNN + TimeDistributed Dense\n - [Model 3](#model3): Deeper RNN + TimeDistributed Dense\n - [Model 4](#model4): Bidirectional RNN + TimeDistributed Dense\n - [Models 5+](#model5)\n - [Compare the Models](#compare)\n - [Final Model](#final)\n- [**STEP 3**](#step3): Obtain Predictions\n\n<a id='thedata'></a>\n## The Data\n\nWe begin by investigating the dataset that will be used to train and evaluate your pipeline. [LibriSpeech](http://www.danielpovey.com/files/2015_icassp_librispeech.pdf) is a large corpus of English-read speech, designed for training and evaluating models for ASR. The dataset contains 1000 hours of speech derived from audiobooks. We will work with a small subset in this project, since larger-scale data would take a long while to train. However, after completing this project, if you are interested in exploring further, you are encouraged to work with more of the data that is provided [online](http://www.openslr.org/12/).\n\nIn the code cells below, you will use the `vis_train_features` module to visualize a training example. The supplied argument `index=0` tells the module to extract the first example in the training set. (You are welcome to change `index=0` to point to a different training example, if you like, but please **DO NOT** amend any other code in the cell.) The returned variables are:\n- `vis_text` - transcribed text (label) for the training example.\n- `vis_raw_audio` - raw audio waveform for the training example.\n- `vis_mfcc_feature` - mel-frequency cepstral coefficients (MFCCs) for the training example.\n- `vis_spectrogram_feature` - spectrogram for the training example. \n- `vis_audio_path` - the file path to the training example.", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%autoreload 1\n%pip install python_speech_features\n!rm -rf AIND-VUI-Capstone/\n!git clone https://github.com/RomansWorks/AIND-VUI-Capstone\n!cp -r ./AIND-VUI-Capstone/* .\n!wget https://filebin.net/archive/s14yfd2p3q0sj1r2/zip\n!unzip zip\n!7z x capstone-ds.zip\n!mv aind-vui-capstone-ds-processed/* .\n!rm zip capstone-ds.*", "Collecting python_speech_features\n Downloading python_speech_features-0.6.tar.gz (5.6 kB)\nBuilding wheels for collected packages: python-speech-features\n Building wheel for python-speech-features (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for python-speech-features: filename=python_speech_features-0.6-py3-none-any.whl size=5888 sha256=6ea50726da99e2b10fe3375134965f6d43530490e5c38c0e39041a3591c86000\n Stored in directory: /root/.cache/pip/wheels/b0/0e/94/28cd6afa3cd5998a63eef99fe31777acd7d758f59cf24839eb\nSuccessfully built python-speech-features\nInstalling collected packages: python-speech-features\nSuccessfully installed python-speech-features-0.6\nCloning into 'AIND-VUI-Capstone'...\nremote: Enumerating objects: 172, done.\u001b[K\nremote: Counting objects: 100% (37/37), done.\u001b[K\nremote: Compressing objects: 100% (25/25), done.\u001b[K\nremote: Total 172 (delta 17), reused 24 (delta 10), pack-reused 135\u001b[K\nReceiving objects: 100% (172/172), 2.89 MiB | 15.09 MiB/s, done.\nResolving deltas: 100% (82/82), done.\n--2022-03-20 06:30:03-- https://filebin.net/archive/s14yfd2p3q0sj1r2/zip\nResolving filebin.net (filebin.net)... 185.47.40.36, 2a02:c0:2f0:700:f816:3eff:feac:c605\nConnecting to filebin.net (filebin.net)|185.47.40.36|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: unspecified [application/zip]\nSaving to: ‘zip’\n\nzip [ <=>] 970.54M 22.2MB/s in 45s \n\n2022-03-20 06:30:49 (21.5 MB/s) - ‘zip’ saved [1017683148]\n\nArchive: zip\n extracting: capstone-ds.z01 \n extracting: capstone-ds.z02 \n extracting: capstone-ds.z03 \n extracting: capstone-ds.z04 \n extracting: capstone-ds.z05 \n extracting: capstone-ds.z06 \n extracting: capstone-ds.z07 \n extracting: capstone-ds.z08 \n extracting: capstone-ds.z09 \n extracting: capstone-ds.zip \n\n7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21\np7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,2 CPUs Intel(R) Xeon(R) CPU @ 2.30GHz (306F0),ASM,AES-NI)\n\nScanning the drive for archives:\n 0M Scan\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b1 file, 73963326 bytes (71 MiB)\n\nExtracting archive: capstone-ds.zip\n 70% 4096 Open\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b--\nPath = capstone-ds.zip\nType = zip\nPhysical Size = 73963326\nEmbedded Stub Size = 4\nTotal Physical Size = 1017681726\nMultivolume = +\nVolume Index = 9\nVolumes = 10\n\n 0%\b\b\b\b \b\b\b\b 1% 74 - aind-vui-capstone-ds-processed/Li . /2078/142845/2078-142845-0031.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 2% 141 - aind-vui-capstone-ds-processed/ . ean/3752/4943/3752-4943-0001.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 4% 257 - aind-vui-capstone-ds-processed/L . n/1988/24833/1988-24833-0007.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 5% 330 - aind-vui-capstone-ds-processe . 9/142785/1919-142785-0008.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 6% 389 - aind-vui-capstone-ds-processed/L . n/422/122949/422-122949-0005.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 7% 438 - aind-vui-capstone-ds-processed/L . n/3000/15664/3000-15664-0015.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 9% 494 - aind-vui-capstone-ds-processe . 3/147964/1993-147964-0010.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 10% 560 - aind-vui-capstone-ds-processed/L . n/6313/76958/6313-76958-0019.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 11% 651 - aind-vui-capstone-ds-processed/L . n/251/136532/251-136532-0003.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 12% 737 - aind-vui-capstone-ds-processe . 2/302201/8842-302201-0005.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 14% 802 - aind-vui-capstone-ds-processed/L . n/5536/43358/5536-43358-0013.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 15% 875 - aind-vui-capstone-ds-processe . 0/281318/7850-281318-0023.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 16% 954 - aind-vui-capstone-ds-processed/L . n/174/168635/174-168635-0002.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 18% 1028 - aind-vui-capstone-ds-processed/L . n/6295/64301/6295-64301-0003.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 19% 1119 - aind-vui-capstone-ds-processe . 6/110523/7976-110523-0013.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 20% 1205 - aind-vui-capstone-ds-processe . 3/154328/2803-154328-0000.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 22% 1283 - aind-vui-capstone-ds-processed/L . n/777/126732/777-126732-0007.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 23% 1354 - aind-vui-capstone-ds-processed/L . n/5694/64025/5694-64025-0002.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 24% 1454 - aind-vui-capstone-ds-processe . 2/170145/1462-170145-0007.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 25% 1549 - aind-vui-capstone-ds-processed/L . n/5895/34622/5895-34622-0015.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 26% 1625 - aind-vui-capstone-ds-processe . 6/149220/2086-149220-0012.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 28% 1694 - aind-vui-capstone-ds-processed/L . n/6241/66616/6241-66616-0011.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 29% 1790 - aind-vui-capstone-ds-processe . 7/149897/2277-149897-0015.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 30% 1894 - aind-vui-capstone-ds-processed/L . n/2428/83705/2428-83705-0026.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 32% 1979 - aind-vui-capstone-ds-processed/L . n/3536/23268/3536-23268-0020.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 33% 2026 - aind-vui-capstone-ds-processed/ . ean/2902/9008/2902-9008-0016.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 34% 2112 - aind-vui-capstone-ds-processe . 7/275154/8297-275154-0000.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 35% 2196 - aind-vui-capstone-ds-processe . 1/166546/3081-166546-0067.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 37% 2270 - aind-vui-capstone-ds-processed/L . n/6345/93302/6345-93302-0019.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 38% 2352 - aind-vui-capstone-ds-processed/L . n/652/129742/652-129742-0012.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 39% 2421 - aind-vui-capstone-ds-processe . 3/163249/3853-163249-0028.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 40% 2494 - aind-vui-capstone-ds-processed/L . n/5338/24615/5338-24615-0012.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 42% 2558 - aind-vui-capstone-ds-processe . 9/275224/6319-275224-0003.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 43% 2615 - aind-vui-capstone-ds-processe . 0/137482/3170-137482-0002.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 45% 2710 - aind-vui-capstone-ds-processed/ . ean/84/121123/84-121123-0028.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 46% 2776 - aind-vui-capstone-ds-processe . 6/138058/3576-138058-0017.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 47% 2822 - aind-vui-capstone-ds-processe . 3/143397/1673-143397-0012.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 48% 2878 - aind-vui-capstone-ds-processe . 5/147961/2035-147961-0032.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 50% 2959 - aind-vui-capstone-ds-processed/ . lean/61/70970/61-70970-0035.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 51% 3065 - aind-vui-capstone-ds-process . 639/40744/5639-40744-0034.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 52% 3130 - aind-vui-capstone-ds-process . 829/68769/6829-68769-0051.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 54% 3220 - aind-vui-capstone-ds-process . 08/157963/908-157963-0019.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 55% 3293\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b 56% 3373 - aind-vui-capstone-ds-processe . 55/210777/8455-210777-0045.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 57% 3437 - aind-vui-capstone-ds-processe . 63/294825/8463-294825-0005.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 59% 3515 - aind-vui-capstone-ds-processe . 20/122617/1320-122617-0030.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 60% 3577 - aind-vui-capstone-ds-processe . 00/131720/2300-131720-0018.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 61% 3642 - aind-vui-capstone-ds-process . 930/75918/6930-75918-0017.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 62% 3712 - aind-vui-capstone-ds-process . 60/123288/260-123288-0006.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 64% 3810 - aind-vui-capstone-ds-processed/ . ean/1995/1836/1995-1836-0014.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 65% 3882 - aind-vui-capstone-ds-processe . 75/170457/3575-170457-0025.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 67% 3950 - aind-vui-capstone-ds-process . 507/16021/4507-16021-0025.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 68% 4037 - aind-vui-capstone-ds-process . 683/32866/5683-32866-0019.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 69% 4119 - aind-vui-capstone-ds-process . 127/75947/7127-75947-0000.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 70% 4183 - aind-vui-capstone-ds-processed/ . ean/1284/1180/1284-1180-0013.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 72% 4266 - aind-vui-capstone-ds-process . 21/123859/121-123859-0003.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 73% 4334 - aind-vui-capstone-ds-processe . 89/134686/1089-134686-0000.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 74% 4404 - aind-vui-capstone-ds-process . 992/41806/4992-41806-0006.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 76% 4475 - aind-vui-capstone-ds-process . 970/29095/4970-29095-0021.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 77% 4560 - aind-vui-capstone-ds-processe . 80/141083/1580-141083-0040.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 78% 4669 - aind-vui-capstone-ds-processe . 88/133604/1188-133604-0005.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 80% 4718 - aind-vui-capstone-ds-processe . 30/279154/8230-279154-0008.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 81% 4789 - aind-vui-capstone-ds-process . 142/33396/5142-33396-0059.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 82% 4882 - aind-vui-capstone-ds-processed/ . lean/2961/961/2961-961-0003.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 83% 4931 - aind-vui-capstone-ds-processed/ . ean/4446/2275/4446-2275-0017.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 85% 5042 - aind-vui-capstone-ds-processe . 24/274384/8224-274384-0006.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 86% 5083 - aind-vui-capstone-ds-process . 37/126133/237-126133-0014.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 87% 5169 - aind-vui-capstone-ds-process . 077/13751/4077-13751-0021.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 88% 5211 - aind-vui-capstone-ds-process . 105/28241/5105-28241-0009.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 90% 5274 - aind-vui-capstone-ds-processe . 29/102255/7729-102255-0016.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 91% 5335 - aind-vui-capstone-ds-processe . 94/142345/2094-142345-0034.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 92% 5404 - aind-vui-capstone-ds-process . 176/88083/7176-88083-0020.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 94% 5478 - aind-vui-capstone-ds-processe . 21/135766/1221-135766-0002.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 95% 5533 - aind-vui-capstone-ds-processed/ . ean/2830/3980/2830-3980-0042.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 96% 5617 - aind-vui-capstone-ds-processed/ . ean/3729/6852/3729-6852-0020.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 97% 5678 - aind-vui-capstone-ds-processe . 55/284447/8555-284447-0014.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 99% 5747 - aind-vui-capstone-ds-processed/ . ean/3570/5694/3570-5694-0003.wav\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bEverything is Ok\n\nFolders: 268\nFiles: 5516\nSize: 1246231437\nCompressed: 1017681726\n" ], [ "from data_generator import vis_train_features\n\n# extract label and audio features for a single training example\nvis_text, vis_raw_audio, vis_mfcc_feature, vis_spectrogram_feature, vis_audio_path = vis_train_features()", "There are 2136 total training examples.\n" ] ], [ [ "The following code cell visualizes the audio waveform for your chosen example, along with the corresponding transcript. You also have the option to play the audio in the notebook!", "_____no_output_____" ] ], [ [ "from IPython.display import Markdown, display\nfrom data_generator import vis_train_features, plot_raw_audio\nfrom IPython.display import Audio\n%matplotlib inline\n\n# plot audio signal\nplot_raw_audio(vis_raw_audio)\n# print length of audio signal\ndisplay(Markdown('**Shape of Audio Signal** : ' + str(vis_raw_audio.shape)))\n# print transcript corresponding to audio clip\ndisplay(Markdown('**Transcript** : ' + str(vis_text)))\n# play the audio file\nAudio(vis_audio_path)", "_____no_output_____" ] ], [ [ "<a id='step1'></a>\n## STEP 1: Acoustic Features for Speech Recognition\n\nFor this project, you won't use the raw audio waveform as input to your model. Instead, we provide code that first performs a pre-processing step to convert the raw audio to a feature representation that has historically proven successful for ASR models. Your acoustic model will accept the feature representation as input.\n\nIn this project, you will explore two possible feature representations. _After completing the project_, if you'd like to read more about deep learning architectures that can accept raw audio input, you are encouraged to explore this [research paper](https://pdfs.semanticscholar.org/a566/cd4a8623d661a4931814d9dffc72ecbf63c4.pdf).\n\n### Spectrograms\n\nThe first option for an audio feature representation is the [spectrogram](https://www.youtube.com/watch?v=_FatxGN3vAM). In order to complete this project, you will **not** need to dig deeply into the details of how a spectrogram is calculated; but, if you are curious, the code for calculating the spectrogram was borrowed from [this repository](https://github.com/baidu-research/ba-dls-deepspeech). The implementation appears in the `utils.py` file in your repository.\n\nThe code that we give you returns the spectrogram as a 2D tensor, where the first (_vertical_) dimension indexes time, and the second (_horizontal_) dimension indexes frequency. To speed the convergence of your algorithm, we have also normalized the spectrogram. (You can see this quickly in the visualization below by noting that the mean value hovers around zero, and most entries in the tensor assume values close to zero.)", "_____no_output_____" ] ], [ [ "from data_generator import plot_spectrogram_feature\n\n# plot normalized spectrogram\nplot_spectrogram_feature(vis_spectrogram_feature)\n# print shape of spectrogram\ndisplay(Markdown('**Shape of Spectrogram** : ' + str(vis_spectrogram_feature.shape)))", "_____no_output_____" ] ], [ [ "### Mel-Frequency Cepstral Coefficients (MFCCs)\n\nThe second option for an audio feature representation is [MFCCs](https://en.wikipedia.org/wiki/Mel-frequency_cepstrum). You do **not** need to dig deeply into the details of how MFCCs are calculated, but if you would like more information, you are welcome to peruse the [documentation](https://github.com/jameslyons/python_speech_features) of the `python_speech_features` Python package. Just as with the spectrogram features, the MFCCs are normalized in the supplied code.\n\nThe main idea behind MFCC features is the same as spectrogram features: at each time window, the MFCC feature yields a feature vector that characterizes the sound within the window. Note that the MFCC feature is much lower-dimensional than the spectrogram feature, which could help an acoustic model to avoid overfitting to the training dataset. ", "_____no_output_____" ] ], [ [ "from data_generator import plot_mfcc_feature\n\n# plot normalized MFCC\nplot_mfcc_feature(vis_mfcc_feature)\n# print shape of MFCC\ndisplay(Markdown('**Shape of MFCC** : ' + str(vis_mfcc_feature.shape)))", "_____no_output_____" ] ], [ [ "When you construct your pipeline, you will be able to choose to use either spectrogram or MFCC features. If you would like to see different implementations that make use of MFCCs and/or spectrograms, please check out the links below:\n- This [repository](https://github.com/baidu-research/ba-dls-deepspeech) uses spectrograms.\n- This [repository](https://github.com/mozilla/DeepSpeech) uses MFCCs.\n- This [repository](https://github.com/buriburisuri/speech-to-text-wavenet) also uses MFCCs.\n- This [repository](https://github.com/pannous/tensorflow-speech-recognition/blob/master/speech_data.py) experiments with raw audio, spectrograms, and MFCCs as features.", "_____no_output_____" ], [ "<a id='step2'></a>\n## STEP 2: Deep Neural Networks for Acoustic Modeling\n\nIn this section, you will experiment with various neural network architectures for acoustic modeling. \n\nYou will begin by training five relatively simple architectures. **Model 0** is provided for you. You will write code to implement **Models 1**, **2**, **3**, and **4**. If you would like to experiment further, you are welcome to create and train more models under the **Models 5+** heading. \n\nAll models will be specified in the `sample_models.py` file. After importing the `sample_models` module, you will train your architectures in the notebook.\n\nAfter experimenting with the five simple architectures, you will have the opportunity to compare their performance. Based on your findings, you will construct a deeper architecture that is designed to outperform all of the shallow models.\n\nFor your convenience, we have designed the notebook so that each model can be specified and trained on separate occasions. That is, say you decide to take a break from the notebook after training **Model 1**. Then, you need not re-execute all prior code cells in the notebook before training **Model 2**. You need only re-execute the code cell below, that is marked with **`RUN THIS CODE CELL IF YOU ARE RESUMING THE NOTEBOOK AFTER A BREAK`**, before transitioning to the code cells corresponding to **Model 2**.", "_____no_output_____" ] ], [ [ "#####################################################################\n# RUN THIS CODE CELL IF YOU ARE RESUMING THE NOTEBOOK AFTER A BREAK #\n#####################################################################\n\n# allocate 50% of GPU memory (if you like, feel free to change this)\n# from keras.backend.tensorflow_backend import set_session\nimport tensorflow as tf \n# config = tf.ConfigProto()\n# config.gpu_options.per_process_gpu_memory_fraction = 0.5\n# set_session(tf.Session(config=config))\n\nfrom tensorflow.keras.optimizers import Adam, SGD\n\n\n\n# watch for any changes in the sample_models module, and reload it automatically\n%load_ext autoreload\n%autoreload 2\n# import NN architectures for speech recognition\nfrom sample_models import *\n# import function for training acoustic model\nfrom train_utils import train_model", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ] ], [ [ "<a id='model0'></a>\n### Model 0: RNN\n\nGiven their effectiveness in modeling sequential data, the first acoustic model you will use is an RNN. As shown in the figure below, the RNN we supply to you will take the time sequence of audio features as input.\n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/simple_rnn.png?raw=1\" width=\"50%\">\n\nAt each time step, the speaker pronounces one of 28 possible characters, including each of the 26 letters in the English alphabet, along with a space character (\" \"), and an apostrophe (').\n\nThe output of the RNN at each time step is a vector of probabilities with 29 entries, where the $i$-th entry encodes the probability that the $i$-th character is spoken in the time sequence. (The extra 29th character is an empty \"character\" used to pad training examples within batches containing uneven lengths.) If you would like to peek under the hood at how characters are mapped to indices in the probability vector, look at the `char_map.py` file in the repository. The figure below shows an equivalent, rolled depiction of the RNN that shows the output layer in greater detail. \n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/simple_rnn_unrolled.png?raw=1\" width=\"60%\">\n\nThe model has already been specified for you in Keras. To import it, you need only run the code cell below. ", "_____no_output_____" ] ], [ [ "model_0 = simple_rnn_model(input_dim=161) # change to 13 if you would like to use MFCC features", "Model: \"model\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n the_input (InputLayer) [(None, None, 161)] 0 \n \n rnn (GRU) (None, None, 29) 16704 \n \n softmax (Activation) (None, None, 29) 0 \n \n=================================================================\nTotal params: 16,704\nTrainable params: 16,704\nNon-trainable params: 0\n_________________________________________________________________\nNone\n" ] ], [ [ "As explored in the lesson, you will train the acoustic model with the [CTC loss](http://www.cs.toronto.edu/~graves/icml_2006.pdf) criterion. Custom loss functions take a bit of hacking in Keras, and so we have implemented the CTC loss function for you, so that you can focus on trying out as many deep learning architectures as possible :). If you'd like to peek at the implementation details, look at the `add_ctc_loss` function within the `train_utils.py` file in the repository.\n\nTo train your architecture, you will use the `train_model` function within the `train_utils` module; it has already been imported in one of the above code cells. The `train_model` function takes three **required** arguments:\n- `input_to_softmax` - a Keras model instance.\n- `pickle_path` - the name of the pickle file where the loss history will be saved.\n- `save_model_path` - the name of the HDF5 file where the model will be saved.\n\nIf we have already supplied values for `input_to_softmax`, `pickle_path`, and `save_model_path`, please **DO NOT** modify these values. \n\nThere are several **optional** arguments that allow you to have more control over the training process. You are welcome to, but not required to, supply your own values for these arguments.\n- `minibatch_size` - the size of the minibatches that are generated while training the model (default: `20`).\n- `spectrogram` - Boolean value dictating whether spectrogram (`True`) or MFCC (`False`) features are used for training (default: `True`).\n- `mfcc_dim` - the size of the feature dimension to use when generating MFCC features (default: `13`).\n- `optimizer` - the Keras optimizer used to train the model (default: `SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)`). \n- `epochs` - the number of epochs to use to train the model (default: `20`). If you choose to modify this parameter, make sure that it is *at least* 20.\n- `verbose` - controls the verbosity of the training output in the `model.fit_generator` method (default: `1`).\n- `sort_by_duration` - Boolean value dictating whether the training and validation sets are sorted by (increasing) duration before the start of the first epoch (default: `False`).\n\nThe `train_model` function defaults to using spectrogram features; if you choose to use these features, note that the acoustic model in `simple_rnn_model` should have `input_dim=161`. Otherwise, if you choose to use MFCC features, the acoustic model should have `input_dim=13`.\n\nWe have chosen to use `GRU` units in the supplied RNN. If you would like to experiment with `LSTM` or `SimpleRNN` cells, feel free to do so here. If you change the `GRU` units to `SimpleRNN` cells in `simple_rnn_model`, you may notice that the loss quickly becomes undefined (`nan`) - you are strongly encouraged to check this for yourself! This is due to the [exploding gradients problem](http://www.wildml.com/2015/10/recurrent-neural-networks-tutorial-part-3-backpropagation-through-time-and-vanishing-gradients/). We have already implemented [gradient clipping](https://arxiv.org/pdf/1211.5063.pdf) in your optimizer to help you avoid this issue.\n\n__IMPORTANT NOTE:__ If you notice that your gradient has exploded in any of the models below, feel free to explore more with gradient clipping (the `clipnorm` argument in your optimizer) or swap out any `SimpleRNN` cells for `LSTM` or `GRU` cells. You can also try restarting the kernel to restart the training process.", "_____no_output_____" ] ], [ [ "from tensorflow.keras.optimizers import Adam\n\ntrain_model(input_to_softmax=model_0, \n pickle_path='model_0.pickle', \n save_model_path='model_0.h5',\n minibatch_size=25,\n optimizer=Adam(learning_rate=0.1, clipnorm=5), #SGD(lr=0.002, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5),\n spectrogram=True) # change to False if you would like to use MFCC features", "/content/train_utils.py:77: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n callbacks=[checkpointer], verbose=verbose)\n" ] ], [ [ "<a id='model1'></a>\n### (IMPLEMENTATION) Model 1: RNN + TimeDistributed Dense\n\nRead about the [TimeDistributed](https://keras.io/layers/wrappers/) wrapper and the [BatchNormalization](https://keras.io/layers/normalization/) layer in the Keras documentation. For your next architecture, you will add [batch normalization](https://arxiv.org/pdf/1510.01378.pdf) to the recurrent layer to reduce training times. The `TimeDistributed` layer will be used to find more complex patterns in the dataset. The unrolled snapshot of the architecture is depicted below.\n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/rnn_model.png?raw=1\" width=\"60%\">\n\nThe next figure shows an equivalent, rolled depiction of the RNN that shows the (`TimeDistrbuted`) dense and output layers in greater detail. \n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/rnn_model_unrolled.png?raw=1\" width=\"60%\">\n\nUse your research to complete the `rnn_model` function within the `sample_models.py` file. The function should specify an architecture that satisfies the following requirements:\n- The first layer of the neural network should be an RNN (`SimpleRNN`, `LSTM`, or `GRU`) that takes the time sequence of audio features as input. We have added `GRU` units for you, but feel free to change `GRU` to `SimpleRNN` or `LSTM`, if you like!\n- Whereas the architecture in `simple_rnn_model` treated the RNN output as the final layer of the model, you will use the output of your RNN as a hidden layer. Use `TimeDistributed` to apply a `Dense` layer to each of the time steps in the RNN output. Ensure that each `Dense` layer has `output_dim` units.\n\nUse the code cell below to load your model into the `model_1` variable. Use a value for `input_dim` that matches your chosen audio features, and feel free to change the values for `units` and `activation` to tweak the behavior of your recurrent layer.", "_____no_output_____" ] ], [ [ "model_1 = rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features\n units=200,\n activation='relu')", "_____no_output_____" ] ], [ [ "Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_1.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_1.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required.", "_____no_output_____" ] ], [ [ "train_model(input_to_softmax=model_1, \n pickle_path='model_1.pickle', \n save_model_path='model_1.h5',\n optimizer=Adam(clipvalue=0.5, clipnorm=1.0),\n spectrogram=True) # change to False if you would like to use MFCC features", "_____no_output_____" ] ], [ [ "<a id='model2'></a>\n### (IMPLEMENTATION) Model 2: CNN + RNN + TimeDistributed Dense\n\nThe architecture in `cnn_rnn_model` adds an additional level of complexity, by introducing a [1D convolution layer](https://keras.io/layers/convolutional/#conv1d). \n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/cnn_rnn_model.png?raw=1\" width=\"100%\">\n\nThis layer incorporates many arguments that can be (optionally) tuned when calling the `cnn_rnn_model` module. We provide sample starting parameters, which you might find useful if you choose to use spectrogram audio features. \n\nIf you instead want to use MFCC features, these arguments will have to be tuned. Note that the current architecture only supports values of `'same'` or `'valid'` for the `conv_border_mode` argument.\n\nWhen tuning the parameters, be careful not to choose settings that make the convolutional layer overly small. If the temporal length of the CNN layer is shorter than the length of the transcribed text label, your code will throw an error.\n\nBefore running the code cell below, you must modify the `cnn_rnn_model` function in `sample_models.py`. Please add batch normalization to the recurrent layer, and provide the same `TimeDistributed` layer as before.", "_____no_output_____" ] ], [ [ "model_2 = cnn_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features\n filters=200,\n kernel_size=11, \n conv_stride=2,\n conv_border_mode='valid',\n units=100)", "_____no_output_____" ] ], [ [ "Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_2.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_2.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required.", "_____no_output_____" ] ], [ [ "train_model(input_to_softmax=model_2, \n pickle_path='model_2.pickle', \n save_model_path='model_2.h5', \n optimizer=Adam(clipvalue=0.5),\n spectrogram=True) # change to False if you would like to use MFCC features", "_____no_output_____" ] ], [ [ "<a id='model3'></a>\n### (IMPLEMENTATION) Model 3: Deeper RNN + TimeDistributed Dense\n\nReview the code in `rnn_model`, which makes use of a single recurrent layer. Now, specify an architecture in `deep_rnn_model` that utilizes a variable number `recur_layers` of recurrent layers. The figure below shows the architecture that should be returned if `recur_layers=2`. In the figure, the output sequence of the first recurrent layer is used as input for the next recurrent layer.\n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/deep_rnn_model.png?raw=1\" width=\"80%\">\n\nFeel free to change the supplied values of `units` to whatever you think performs best. You can change the value of `recur_layers`, as long as your final value is greater than 1. (As a quick check that you have implemented the additional functionality in `deep_rnn_model` correctly, make sure that the architecture that you specify here is identical to `rnn_model` if `recur_layers=1`.)", "_____no_output_____" ] ], [ [ "model_3 = deep_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features\n units=100,\n recur_layers=2) ", "_____no_output_____" ] ], [ [ "Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_3.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_3.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required.", "_____no_output_____" ] ], [ [ "train_model(input_to_softmax=model_3, \n pickle_path='model_3.pickle', \n save_model_path='model_3.h5', \n optimizer=Adam(clipvalue=0.5),\n spectrogram=True) # change to False if you would like to use MFCC features", "_____no_output_____" ] ], [ [ "<a id='model4'></a>\n### (IMPLEMENTATION) Model 4: Bidirectional RNN + TimeDistributed Dense\n\nRead about the [Bidirectional](https://keras.io/layers/wrappers/) wrapper in the Keras documentation. For your next architecture, you will specify an architecture that uses a single bidirectional RNN layer, before a (`TimeDistributed`) dense layer. The added value of a bidirectional RNN is described well in [this paper](http://www.cs.toronto.edu/~hinton/absps/DRNN_speech.pdf).\n> One shortcoming of conventional RNNs is that they are only able to make use of previous context. In speech recognition, where whole utterances are transcribed at once, there is no reason not to exploit future context as well. Bidirectional RNNs (BRNNs) do this by processing the data in both directions with two separate hidden layers which are then fed forwards to the same output layer.\n\n<img src=\"https://github.com/RomansWorks/AIND-VUI-Capstone/blob/master/images/bidirectional_rnn_model.png?raw=1\" width=\"80%\">\n\nBefore running the code cell below, you must complete the `bidirectional_rnn_model` function in `sample_models.py`. Feel free to use `SimpleRNN`, `LSTM`, or `GRU` units. When specifying the `Bidirectional` wrapper, use `merge_mode='concat'`.", "_____no_output_____" ] ], [ [ "model_4 = bidirectional_rnn_model(input_dim=161, # change to 13 if you would like to use MFCC features\n units=100)", "Model: \"model_17\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n the_input (InputLayer) [(None, None, 161)] 0 \n \n bidi (Bidirectional) (None, None, 200) 157800 \n \n batch_normalization_9 (Batc (None, None, 200) 800 \n hNormalization) \n \n time_distributed_9 (TimeDis (None, None, 29) 5829 \n tributed) \n \n softmax (Activation) (None, None, 29) 0 \n \n=================================================================\nTotal params: 164,429\nTrainable params: 164,029\nNon-trainable params: 400\n_________________________________________________________________\nNone\n" ] ], [ [ "Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_4.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_4.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required.", "_____no_output_____" ] ], [ [ "train_model(input_to_softmax=model_4, \n pickle_path='model_4.pickle', \n save_model_path='model_4.h5', \n optimizer=Adam(clipvalue=0.5),\n spectrogram=True) # change to False if you would like to use MFCC features", "/content/train_utils.py:77: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n callbacks=[checkpointer], verbose=verbose)\n" ] ], [ [ "<a id='model5'></a>\n### (OPTIONAL IMPLEMENTATION) Models 5+\n\nIf you would like to try out more architectures than the ones above, please use the code cell below. Please continue to follow the same convention for saving the models; for the $i$-th sample model, please save the loss at **`model_i.pickle`** and saving the trained model at **`model_i.h5`**.", "_____no_output_____" ] ], [ [ "## (Optional) TODO: Try out some more models!\n### Feel free to use as many code cells as needed.\nmodel_5 = dilated_double_cnn_rnn_model(input_dim=161, \n filters=200, \n kernel_size=6, \n conv_border_mode='valid', \n units=200, \n dilation=2)\n\ntrain_model(input_to_softmax=model_5, \n pickle_path='model_5.pickle', \n save_model_path='model_5.h5', \n optimizer=Adam(clipvalue=0.5, amsgrad=True),\n spectrogram=True)", "Model: \"model_11\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n the_input (InputLayer) [(None, None, 161)] 0 \n \n conv_1d_1 (Conv1D) (None, None, 200) 193400 \n \n conv_1d_2 (Conv1D) (None, None, 100) 240100 \n \n rnn (GRU) (None, None, 200) 181200 \n \n batch_normalization_6 (Batc (None, None, 200) 800 \n hNormalization) \n \n time_distributed_6 (TimeDis (None, None, 29) 5829 \n tributed) \n \n softmax (Activation) (None, None, 29) 0 \n \n=================================================================\nTotal params: 621,329\nTrainable params: 620,929\nNon-trainable params: 400\n_________________________________________________________________\nNone\nEpoch 1/20\n" ] ], [ [ "<a id='compare'></a>\n### Compare the Models\n\nExecute the code cell below to evaluate the performance of the drafted deep learning models. The training and validation loss are plotted for each model.", "_____no_output_____" ] ], [ [ "from glob import glob\nimport numpy as np\nimport _pickle as pickle\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\nsns.set_style(style='white')\n\n# obtain the paths for the saved model history\nall_pickles = sorted(glob(\"results/*.pickle\"))\n# extract the name of each model\nmodel_names = [item[8:-7] for item in all_pickles]\n# extract the loss history for each model\nvalid_loss = [pickle.load( open( i, \"rb\" ) )['val_loss'] for i in all_pickles]\ntrain_loss = [pickle.load( open( i, \"rb\" ) )['loss'] for i in all_pickles]\n# save the number of epochs used to train each model\nnum_epochs = [len(valid_loss[i]) for i in range(len(valid_loss))]\n\nfig = plt.figure(figsize=(16,5))\n\n# plot the training loss vs. epoch for each model\nax1 = fig.add_subplot(121)\nfor i in range(len(all_pickles)):\n ax1.plot(np.linspace(1, num_epochs[i], num_epochs[i]), \n train_loss[i], label=model_names[i])\n# clean up the plot\nax1.legend() \nax1.set_xlim([1, max(num_epochs)])\nplt.xlabel('Epoch')\nplt.ylabel('Training Loss')\n\n# plot the validation loss vs. epoch for each model\nax2 = fig.add_subplot(122)\nfor i in range(len(all_pickles)):\n ax2.plot(np.linspace(1, num_epochs[i], num_epochs[i]), \n valid_loss[i], label=model_names[i])\n# clean up the plot\nax2.legend() \nax2.set_xlim([1, max(num_epochs)])\nplt.xlabel('Epoch')\nplt.ylabel('Validation Loss')\nplt.show()", "_____no_output_____" ] ], [ [ "__Question 1:__ Use the plot above to analyze the performance of each of the attempted architectures. Which performs best? Provide an explanation regarding why you think some models perform better than others. \n\n__Answer:__", "_____no_output_____" ], [ "<a id='final'></a>\n### (IMPLEMENTATION) Final Model\n\nNow that you've tried out many sample models, use what you've learned to draft your own architecture! While your final acoustic model should not be identical to any of the architectures explored above, you are welcome to merely combine the explored layers above into a deeper architecture. It is **NOT** necessary to include new layer types that were not explored in the notebook.\n\nHowever, if you would like some ideas for even more layer types, check out these ideas for some additional, optional extensions to your model:\n\n- If you notice your model is overfitting to the training dataset, consider adding **dropout**! To add dropout to [recurrent layers](https://faroit.github.io/keras-docs/1.0.2/layers/recurrent/), pay special attention to the `dropout_W` and `dropout_U` arguments. This [paper](http://arxiv.org/abs/1512.05287) may also provide some interesting theoretical background.\n- If you choose to include a convolutional layer in your model, you may get better results by working with **dilated convolutions**. If you choose to use dilated convolutions, make sure that you are able to accurately calculate the length of the acoustic model's output in the `model.output_length` lambda function. You can read more about dilated convolutions in Google's [WaveNet paper](https://arxiv.org/abs/1609.03499). For an example of a speech-to-text system that makes use of dilated convolutions, check out this GitHub [repository](https://github.com/buriburisuri/speech-to-text-wavenet). You can work with dilated convolutions [in Keras](https://keras.io/layers/convolutional/) by paying special attention to the `padding` argument when you specify a convolutional layer.\n- If your model makes use of convolutional layers, why not also experiment with adding **max pooling**? Check out [this paper](https://arxiv.org/pdf/1701.02720.pdf) for example architecture that makes use of max pooling in an acoustic model.\n- So far, you have experimented with a single bidirectional RNN layer. Consider stacking the bidirectional layers, to produce a [deep bidirectional RNN](https://www.cs.toronto.edu/~graves/asru_2013.pdf)!\n\nAll models that you specify in this repository should have `output_length` defined as an attribute. This attribute is a lambda function that maps the (temporal) length of the input acoustic features to the (temporal) length of the output softmax layer. This function is used in the computation of CTC loss; to see this, look at the `add_ctc_loss` function in `train_utils.py`. To see where the `output_length` attribute is defined for the models in the code, take a look at the `sample_models.py` file. You will notice this line of code within most models:\n```\nmodel.output_length = lambda x: x\n```\nThe acoustic model that incorporates a convolutional layer (`cnn_rnn_model`) has a line that is a bit different:\n```\nmodel.output_length = lambda x: cnn_output_length(\n x, kernel_size, conv_border_mode, conv_stride)\n```\n\nIn the case of models that use purely recurrent layers, the lambda function is the identity function, as the recurrent layers do not modify the (temporal) length of their input tensors. However, convolutional layers are more complicated and require a specialized function (`cnn_output_length` in `sample_models.py`) to determine the temporal length of their output.\n\nYou will have to add the `output_length` attribute to your final model before running the code cell below. Feel free to use the `cnn_output_length` function, if it suits your model. ", "_____no_output_____" ] ], [ [ "# specify the model\nmodel_end = final_model()", "Model: \"model_7\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n the_input (InputLayer) [(None, None, 161)] 0 \n \n conv1d (Conv1D) (None, None, 400) 708800 \n \n batch_normalization_6 (Batc (None, None, 400) 1600 \n hNormalization) \n \n bidi (Bidirectional) (None, None, 400) 722400 \n \n batch_normalization_7 (Batc (None, None, 400) 1600 \n hNormalization) \n \n time_distributed_3 (TimeDis (None, None, 29) 11629 \n tributed) \n \n dropout_3 (Dropout) (None, None, 29) 0 \n \n softmax (Activation) (None, None, 29) 0 \n \n=================================================================\nTotal params: 1,446,029\nTrainable params: 1,444,429\nNon-trainable params: 1,600\n_________________________________________________________________\nNone\n" ] ], [ [ "Please execute the code cell below to train the neural network you specified in `input_to_softmax`. After the model has finished training, the model is [saved](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model) in the HDF5 file `model_end.h5`. The loss history is [saved](https://wiki.python.org/moin/UsingPickle) in `model_end.pickle`. You are welcome to tweak any of the optional parameters while calling the `train_model` function, but this is not required.", "_____no_output_____" ] ], [ [ "train_model(input_to_softmax=model_end, \n pickle_path='model_end.pickle', \n save_model_path='model_end.h5', \n optimizer=Adam(clipvalue=0.5, amsgrad=True),\n spectrogram=True) # change to False if you would like to use MFCC features", "/content/train_utils.py:77: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n callbacks=[checkpointer], verbose=verbose)\n" ] ], [ [ "__Question 2:__ Describe your final model architecture and your reasoning at each step. \n\n__Answer:__", "_____no_output_____" ], [ "<a id='step3'></a>\n## STEP 3: Obtain Predictions\n\nWe have written a function for you to decode the predictions of your acoustic model. To use the function, please execute the code cell below.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom data_generator import AudioGenerator\nfrom keras import backend as K\nfrom utils import int_sequence_to_text\nfrom IPython.display import Audio\n\ndef get_predictions(index, partition, input_to_softmax, model_path):\n \"\"\" Print a model's decoded predictions\n Params:\n index (int): The example you would like to visualize\n partition (str): One of 'train' or 'validation'\n input_to_softmax (Model): The acoustic model\n model_path (str): Path to saved acoustic model's weights\n \"\"\"\n # load the train and test data\n data_gen = AudioGenerator()\n data_gen.load_train_data()\n data_gen.load_validation_data()\n \n # obtain the true transcription and the audio features \n if partition == 'validation':\n transcr = data_gen.valid_texts[index]\n audio_path = data_gen.valid_audio_paths[index]\n data_point = data_gen.normalize(data_gen.featurize(audio_path))\n elif partition == 'train':\n transcr = data_gen.train_texts[index]\n audio_path = data_gen.train_audio_paths[index]\n data_point = data_gen.normalize(data_gen.featurize(audio_path))\n else:\n raise Exception('Invalid partition! Must be \"train\" or \"validation\"')\n \n # obtain and decode the acoustic model's predictions\n input_to_softmax.load_weights(model_path)\n prediction = input_to_softmax.predict(np.expand_dims(data_point, axis=0))\n output_length = [input_to_softmax.output_length(data_point.shape[0])] \n pred_ints = (K.eval(K.ctc_decode(\n prediction, output_length)[0][0])+1).flatten().tolist()\n \n # play the audio file, and display the true and predicted transcriptions\n print('-'*80)\n Audio(audio_path)\n print('True transcription:\\n' + '\\n' + transcr)\n print('-'*80)\n print('Predicted transcription:\\n' + '\\n' + ''.join(int_sequence_to_text(pred_ints)))\n print('-'*80)", "_____no_output_____" ] ], [ [ "Use the code cell below to obtain the transcription predicted by your final model for the first example in the training dataset.", "_____no_output_____" ] ], [ [ "get_predictions(index=0, \n partition='train',\n input_to_softmax=final_model(), \n model_path='model_end.h5')", "_____no_output_____" ] ], [ [ "Use the next code cell to visualize the model's prediction for the first example in the validation dataset.", "_____no_output_____" ] ], [ [ "get_predictions(index=0, \n partition='validation',\n input_to_softmax=final_model(), \n model_path='model_end.h5')", "_____no_output_____" ] ], [ [ "One standard way to improve the results of the decoder is to incorporate a language model. We won't pursue this in the notebook, but you are welcome to do so as an _optional extension_. \n\nIf you are interested in creating models that provide improved transcriptions, you are encouraged to download [more data](http://www.openslr.org/12/) and train bigger, deeper models. But beware - the model will likely take a long while to train. For instance, training this [state-of-the-art](https://arxiv.org/pdf/1512.02595v1.pdf) model would take 3-6 weeks on a single GPU!", "_____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" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d02f8ebf84afb7c678be1593313a8ae19952453b
37,905
ipynb
Jupyter Notebook
Code/LogisticRegression.ipynb
IulianRo3/Predicting-GooglePlayStore-Apps-Succes-Through-Logistic-Regression
e5c23fe03b3946df7b7e4502ab4bf6f7e98ecb55
[ "Apache-2.0" ]
null
null
null
Code/LogisticRegression.ipynb
IulianRo3/Predicting-GooglePlayStore-Apps-Succes-Through-Logistic-Regression
e5c23fe03b3946df7b7e4502ab4bf6f7e98ecb55
[ "Apache-2.0" ]
null
null
null
Code/LogisticRegression.ipynb
IulianRo3/Predicting-GooglePlayStore-Apps-Succes-Through-Logistic-Regression
e5c23fe03b3946df7b7e4502ab4bf6f7e98ecb55
[ "Apache-2.0" ]
null
null
null
228.343373
23,073
0.718111
[ [ [ "<h1> Logistic Regression <h1>\r\n<h2> ROMÂNĂ <h2>\r\n<blockquote><p>În final, o să observăm dacă Google PlayStore a avut destule date pentru a putea prezice popularitatea unei aplicații de trading sau pentru topul jocurilor plătite.\r\nLucrul acesta se va face prin împărțirea descărcărilor în 2 variabile dummy. Cu mai mult de 1.000.000 pentru variabila 1 și cu mai puțin de 1.000.000 pentru variabila 0, pentru \r\naplicațiile de Trading și pentru jocurile plătite cu mai mult de 670.545 de descărcari pentru variabila 1 iar 0 corespunde celorlalte aplicații.</p></blockquote>\r\n<h2>ENGLISH<h2>\r\n\r\n<blockquote><p>Lastly, we shall see if Google PlayStore had enough data in order to predict the popularity of a trading app or for the top paid games of the store . \r\nThis will be done by dividing the downloads into 2 dummy variables. With more than 1,000,000 for variable 1 and less than 1,000,000 for variable 0, for Trading applications and for paid games with more than 670,545 downloads for variable 1 and 0 corresponding to the other applications.</p></blockquote>\r\n", "_____no_output_____" ], [ "<h3>Now we shall create a logistic regression model using a 80/20 ratio between the training sample and the testing sample<h3>", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import cross_val_score\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nfrom sklearn.model_selection import train_test_split\r\nimport matplotlib.pyplot as plt\r\ndef Log_reg(x,y):\r\n model = LogisticRegression(solver='liblinear',C=10, random_state=0).fit(x,y)\r\n print(\"Model accuracy\",model.score(x,y))\r\n cm = confusion_matrix(y, model.predict(x))\r\n fig, ax = plt.subplots(figsize=(8, 8))\r\n ax.imshow(cm)\r\n ax.grid(False)\r\n ax.xaxis.set(ticks=(0, 1), ticklabels=('Predicted 0s', 'Predicted 1s'))\r\n ax.yaxis.set(ticks=(0, 1), ticklabels=('Actual 0s', 'Actual 1s'))\r\n ax.set_ylim(1.5, -0.5)\r\n for i in range(2):\r\n for j in range(2):\r\n ax.text(j, i, cm[i, j], ha='center', va='center', color='black')\r\n plt.title('Confusion Matrix') \r\n plt.show()\r\n print(classification_report(y, model.predict(x)))\r\n scores = cross_val_score(model, x,y, cv=10)\r\n print('Cross-Validation Accuracy Scores', scores)\r\n scores = pd.Series(scores)\r\n print(\"Mean Accuracy: \",scores.mean())", "_____no_output_____" ], [ "import pandas as pd\r\nimport numpy as np\r\n\r\n#path = \"D:\\Java\\VS-CodPitonul\\\\GAME.xlsx\"\r\n#df = pd.read_excel (path, sheet_name='Sheet1')\r\n\r\npath = \"D:\\Java\\VS-CodPitonul\\\\Trading_Apps.xlsx\"\r\ndf = pd.read_excel (path, sheet_name='Results')\r\n'''\r\nRO: Folosește dropna daca ai valori lipsă, altfel îți va da eroare\r\nENG: Use dropna only if you have missing values else you will recive an error message\r\n'''\r\n#df = df.dropna()", "_____no_output_____" ], [ "\r\n#Log_reg(df[['Score','Ratings','Reviews','Months_From_Release','Price']],df['Instalari_Bin']) #For GAME.xlsx\r\nLog_reg(df[['Score','Ratings','Reviews','Months_From_Release']],df['Instalari_Bin']) #For Trading_Apps.xlsx", "Model accuracy 0.847457627118644\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
d02f9026d4b319059ebec66a43ef74790f5e26b6
109,701
ipynb
Jupyter Notebook
notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb
sparsh-ai/reco-tut-asr
d64b6ed02826933e8add8f83a5773c5a0a21896b
[ "MIT" ]
null
null
null
notebooks/reco-tut-asr-99-10-metrics-calculation.ipynb
sparsh-ai/reco-tut-asr
d64b6ed02826933e8add8f83a5773c5a0a21896b
[ "MIT" ]
1
2022-01-12T05:40:57.000Z
2022-01-12T05:40:57.000Z
_docs/nbs/reco-tut-asr-99-10-metrics-calculation.ipynb
RecoHut-Projects/recohut
4121f665761ffe38c9b6337eaa9293b26bee2376
[ "Apache-2.0" ]
null
null
null
50.068918
31,364
0.615318
[ [ [ "# Import libraries and data\n\nDataset was obtained in the capstone project description (direct link [here](https://d3c33hcgiwev3.cloudfront.net/_429455574e396743d399f3093a3cc23b_capstone.zip?Expires=1530403200&Signature=FECzbTVo6TH7aRh7dXXmrASucl~Cy5mlO94P7o0UXygd13S~Afi38FqCD7g9BOLsNExNB0go0aGkYPtodekxCGblpc3I~R8TCtWRrys~2gciwuJLGiRp4CfNtfp08sFvY9NENaRb6WE2H4jFsAo2Z2IbXV~llOJelI3k-9Waj~M_&Key-Pair-Id=APKAJLTNE6QMUY6HBC5A)) and splited manually in separated csv files. They were stored at my personal github account (folder link [here](https://github.com/caiomiyashiro/RecommenderSystemsNotebooks/tree/master/data/capstone)) and you can download and paste inside your working directory in order for this notebook to run.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np", "_____no_output_____" ] ], [ [ "## Preprocess data\n\nFloat data came with ',' in the csv and python works with '.', so it treated the number as text. In order to convert them to numbers, I first replaced all the commas by punct and then converted the columns to float.", "_____no_output_____" ] ], [ [ "items = pd.read_csv('data/capstone/Capstone Data - Office Products - Items.csv', index_col=0) \nactual_ratings = pd.read_csv('data/capstone/Capstone Data - Office Products - Ratings.csv', index_col=0) \n\ncontent_based = pd.read_csv('data/capstone/Capstone Data - Office Products - CBF.csv', index_col=0)\nuser_user = pd.read_csv('data/capstone/Capstone Data - Office Products - User-User.csv', index_col=0)\nitem_item = pd.read_csv('data/capstone/Capstone Data - Office Products - Item-Item.csv', index_col=0)\nmatrix_fact = pd.read_csv('data/capstone/Capstone Data - Office Products - MF.csv', index_col=0)\npers_bias = pd.read_csv('data/capstone/Capstone Data - Office Products - PersBias.csv', index_col=0)\n\nitems[['Availability','Price']] = items[['Availability','Price']].apply(lambda col: col.apply(lambda elem: str(elem).replace(',', '.'))).astype(float)\n\n# preprocess\ncontent_based = content_based.apply(lambda col: col.apply(lambda elem: str(elem).replace(',', '.'))).astype(float)\nuser_user = user_user.apply(lambda col: col.apply(lambda elem: str(elem).replace(',', '.'))).astype(float)\nitem_item = item_item.apply(lambda col: col.apply(lambda elem: str(elem).replace(',', '.'))).astype(float)\nmatrix_fact = matrix_fact.apply(lambda col: col.apply(lambda elem: str(elem).replace(',', '.'))).astype(float)\npers_bias = pers_bias.apply(lambda col: col.apply(lambda elem: str(elem).replace(',', '.'))).astype(float)\n\nprint('items.shape = ' + str(items.shape))\nprint('actual_ratings.shape = ' + str(actual_ratings.shape))\nprint('content_based.shape = ' + str(content_based.shape))\nprint('user_user.shape = ' + str(user_user.shape))\nprint('item_item.shape = ' + str(item_item.shape))\nprint('matrix_fact.shape = ' + str(matrix_fact.shape))\nprint('pers_bias.shape = ' + str(pers_bias.shape))\n\nactual_ratings.head()", "items.shape = (200, 7)\nactual_ratings.shape = (200, 100)\ncontent_based.shape = (200, 100)\nuser_user.shape = (200, 100)\nitem_item.shape = (200, 100)\nmatrix_fact.shape = (200, 100)\npers_bias.shape = (200, 100)\n" ] ], [ [ "# Class RecommenderEvaluator\n\nIn order to become easier to evaluate the metrics, I created a class that receives all the original ratings and predicted ratings for every recommender system and defined functions to extract all the metrics established in section 1 of the capstone report. Lets take a look at a summary of the class before looking at the code:\n- **Constructor (init)**: receive all recommendation algorithms, besides the actual rating list and the list of items. All data is contained in the data downloaded from Coursera. Besides storing all recommendation algorithms, the constructor also calculate the 20 most frequent items, which is used in the popularity metric calculation.\n\n- **get_observed_ratings**: as the ratings matrix is sparse, this method only returns the items a user with id userId has purchased.\n\n- **get_top_n**: by ordering all the predicted ratings for each recommendation algorithm, we can extract what would be their 'top' recommendation for a given user. Given a parameter $n$, we can then return all the top $n$ recommendations for all the recommendation algorithms.\n\n- **rmse**: by comparing the observed ratings a given user has given to an item and the predicted rating an algorithm has defined for a user, we can have an idea of how much error the algorithm is predicting the user's ratings. Here we don't work with lists, as usually each user has rated only a few amount of items. So here we get all the items the user has rated, recover these items from the algorithms' recommendations and them calculate the error.\n\n- **nDCG**: By looking at lists now, we can have an idea of how optimal the ranked lists are. By using the scoring factor defined in the report, we can calculate the overall DCG for the recommenders' lists and then normalise them using the concepts of the nDCG.\n\n- **Price and avalaibility diversity**: Diversity metric which evaluate how the recommended items' prices vary, *i.e.*, how is the standard deviation of the price. The higher, the better in this case. The same is for the availability index, but here, with higher standard deviations, it means the models are recommending items which are present and not present in local stores.\n\n- **Popularity**: A popular recommender tries to recommend items which has a high chance of being purchased. In the formulation of this metric, an item has a high chance of being purchased if lots of people have purchased them. In the class constructor, we take the observed ratings data and the item list and select which were the top $n$ (standard = 20) most purchased data. In a recommendation list, we return the ration of how many items were inside this list of top $n$ ones.", "_____no_output_____" ] ], [ [ "class RecommenderEvaluator:\n \n def __init__(self, items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias):\n \n self.items = items\n self.actual_ratings = actual_ratings\n # static data containing the average score given by each user\n self.average_rating_per_userid = actual_ratings.apply(lambda row: np.average(row[~np.isnan(row)]))\n \n self.content_based = content_based\n self.user_user = user_user\n self.item_item = item_item\n self.matrix_fact = matrix_fact\n self.pers_bias = pers_bias\n \n # aggregate list. Makes for loops among all recommenders' predictions easier\n self.recommenders_list = [self.content_based, self.user_user, self.item_item, self.matrix_fact,self.pers_bias]\n self.recommenders_list_names = ['content_based', 'user_user', 'item_item', 'matrix_fact','pers_bias']\n \n # Used for item popularity metric.\n # Calculate the 20 most popular items (item which most of the customers bought)\n N_LIM = 20\n perc_users_bought_item = self.actual_ratings.apply(lambda item: np.sum(~np.isnan(item)), axis=0)/actual_ratings.shape[1]\n sort_pop_items = np.argsort(perc_users_bought_item)[::-1]\n self.pop_items = perc_users_bought_item.iloc[sort_pop_items][:N_LIM].index.values.astype(np.int)\n \n \n def get_observed_ratings(self, userId):\n \"\"\"\n Returns all the items a given user evaluated and their ratings. Used mainly by all the metrics calculation\n :parameter: userId - user id\n :return: array of rated items. Index is the item id and value is the item rating\n \"\"\"\n userId = str(userId)\n filtered_ratings = self.actual_ratings[userId]\n rated_items = filtered_ratings[~np.isnan(filtered_ratings)]\n return rated_items\n \n def get_top_n(self, userId, n):\n \"\"\"\n Get the top n recommendations for every recommender in the list given a user id\n :parameter: userId - user id\n :parameter: n - max number of recommendations to return\n :return: dictionary where the key is the recommender's name and the value is an array of size n for the top n recommnendations.\n \"\"\"\n userId = str(userId)\n predicted_ratings = dict()\n for recommender, recommender_name in zip(self.recommenders_list,self.recommenders_list_names):\n item_ids = recommender[userId].argsort().sort_values()[:n].index.values\n predicted_ratings[recommender_name] = item_ids\n return predicted_ratings\n \n def rmse(self, userId):\n \"\"\"\n Root Mean Square Error of the predicted and observed values between the recommender's prediction and the actual ratings\n :parameter: userId - user id\n :return: dataframe of containing the rmse from all recommenders given user id\n \"\"\"\n userId = str(userId)\n observed_ratings = self.get_observed_ratings(userId)\n rmse_list = {'rmse': []}\n for recommender in self.recommenders_list:\n predicted_ratings = recommender.loc[observed_ratings.index, userId]\n rmse_list['rmse'].append(np.sqrt(np.average((predicted_ratings - observed_ratings)**2)))\n rmse_list = pd.DataFrame(rmse_list, index = self.recommenders_list_names)\n return rmse_list\n \n def nDCG(self, userId, top_n = 5, individual_recommendation = None):\n \"\"\"\n Normalised Discounted Cumulative Gain for all recommenders given user id\n :parameter: userId - user id\n :return: dataframe of containing the nDCG from all recommenders given user id\n \"\"\"\n ri = self.get_observed_ratings(userId)\n \n if(individual_recommendation is None):\n topn = self.get_top_n(userId,top_n)\n results_pandas_index = self.recommenders_list_names\n else:\n topn = individual_recommendation\n results_pandas_index = list(individual_recommendation.keys())\n\n # 1st step: Given recommendations, transform list into scores (see score transcriptions in the capstone report)\n scores_all = []\n for name, item_list in topn.items():\n scores = np.empty_like(item_list) # initialise 'random' array\n scores[:] = -10 ###########################\n # check which items returned by the recommender\n is_already_rated = np.isin(item_list, ri.index.values) # the user already rated. Items users didn't rate\n scores[~is_already_rated] = 0 # receive score = 0\n for index, score in enumerate(scores):\n if(score != 0): # for each recommended items the user rated\n if(ri[item_list[index]] < self.average_rating_per_userid[userId] - 1): # score accordingly the report \n scores[index] = -1\n elif((ri[item_list[index]] >= self.average_rating_per_userid[userId] - 1) & \n (ri[item_list[index]] < self.average_rating_per_userid[userId] + 0.5)):\n scores[index] = 1\n else:\n scores[index] = 2\n scores_all.append(scores) # append all the transformed scores\n scores_all \n\n # 2nd step: Given scores, calculate the model's DCG, ideal DCG and then nDCG\n nDCG_all = dict()\n \n for index_model, scores_model in enumerate(scores_all): # for each model\n model_DCG = 0 # calculate model's DCG\n for index, score in enumerate(scores_model): #\n index_ = index + 1 #\n model_DCG = model_DCG + score/np.log2(index_ + 1) # \n ideal_rank_items = np.sort(scores_model)[::-1] # calculate model's ideal DCG\n ideal_rank_DCG = 0 #\n for index, ideal_score in enumerate(ideal_rank_items): #\n index_ = index + 1 #\n ideal_rank_DCG = ideal_rank_DCG + ideal_score/np.log2(index_ + 1) #\n if((ideal_rank_DCG == 0) | (np.abs(ideal_rank_DCG) < np.abs(model_DCG))): # if nDCG is 0 or only negative scores came up\n nDCG = 0 \n else: # calculate final nDCG when ideal DCG is != 0\n nDCG = model_DCG/ideal_rank_DCG\n \n nDCG_all[results_pandas_index[index_model]] = nDCG # save each model's nDCG in a dict\n # convert it to dataframe\n result_final = pd.DataFrame(nDCG_all, index=range(1)).transpose()\n result_final.columns = ['nDCG']\n return result_final\n\n def price_diversity(self,userId,top_n = 5,individual_recommendation = None):\n \"\"\"\n Mean and standard deviation of the price of the top n products recommended by each algorithm. \n Intuition for a high price wise diversity recommender is to have a high price standard deviation\n :parameter: userId - user id\n :return: dataframe of containing the price's mean and standard deviation from all recommenders given user id\n \"\"\"\n\n if(individual_recommendation is None):\n topn = self.get_top_n(userId,top_n)\n else:\n topn = individual_recommendation\n\n stats = pd.DataFrame()\n for key, value in topn.items():\n data_filtered = self.items.loc[topn[key]][['Price']].agg(['mean','std']).transpose()\n data_filtered.index = [key]\n stats = stats.append(data_filtered)\n return stats\n \n def availability_diversity(self,userId,top_n = 5,individual_recommendation = None):\n \"\"\"\n Mean and standard deviation of the availabity index of the top n products recommended by each algorithm. \n Intuition for a high availabity diversity is to have a small mean value in the availabity index\n :parameter: userId - user id\n :return: dataframe of containing the availabity index's mean and standard deviation from all recommenders given user id\n \"\"\"\n if(individual_recommendation is None):\n topn = self.get_top_n(userId,top_n)\n else:\n topn = individual_recommendation\n\n stats = pd.DataFrame()\n for key, value in topn.items():\n data_filtered = self.items.loc[topn[key]][['Availability']].agg(['mean','std']).transpose()\n data_filtered.index = [key]\n stats = stats.append(data_filtered)\n return stats\n \n def popularity(self, userId,top_n = 5,individual_recommendation = None):\n \"\"\"\n Return the ratio of how many items of the top n items are among the most popular purchased items. Default is\n the 20 most purchased items.\n :parameter: userId - user id\n :return: dataframe of containing ratio of popular items in the recommended list from all recommenders given user id\n \"\"\"\n if(individual_recommendation is None):\n topn = self.get_top_n(userId,top_n)\n results_pandas_index = self.recommenders_list_names\n else:\n topn = individual_recommendation\n results_pandas_index = list(individual_recommendation.keys())\n\n results = {'popularity': []}\n for recommender, recommendations in topn.items():\n popularity = np.sum(np.isin(recommendations,self.pop_items))\n results['popularity'].append(popularity)\n return pd.DataFrame(results,index = results_pandas_index)\n \n def precision_at_n(self, userId, top_n = 5, individual_recommendation = None):\n \n if(individual_recommendation is None):\n topn = self.get_top_n(userId,top_n)\n results_pandas_index = self.recommenders_list_names\n else:\n topn = individual_recommendation\n results_pandas_index = list(individual_recommendation.keys())\n \n observed_ratings = self.get_observed_ratings(userId).index.values\n precisions = {'precision_at_'+str(top_n): []}\n for recommender, recommendations in topn.items():\n precisions['precision_at_'+str(top_n)].append(np.sum(np.isin(recommendations, observed_ratings))/top_n)\n return pd.DataFrame(precisions,index = results_pandas_index)\n ", "_____no_output_____" ] ], [ [ "# Test methods:\n\nJust to have an idea of the output of each method, lets call all them with a test user. At the next section we will calculate these metrics for all users.", "_____no_output_____" ] ], [ [ "userId = '64'\nre = RecommenderEvaluator(items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias)", "_____no_output_____" ] ], [ [ "## Test RMSE", "_____no_output_____" ] ], [ [ "re.rmse(userId)", "_____no_output_____" ] ], [ [ "## Test nDCG", "_____no_output_____" ] ], [ [ "re.nDCG(userId)", "_____no_output_____" ] ], [ [ "## Test Diversity - Price and Availability", "_____no_output_____" ] ], [ [ "re.price_diversity(userId)", "_____no_output_____" ], [ "re.availability_diversity(userId)", "_____no_output_____" ] ], [ [ "## Test Popularity", "_____no_output_____" ] ], [ [ "re.popularity(userId)", "_____no_output_____" ] ], [ [ "## Test Precision@N", "_____no_output_____" ] ], [ [ "re.precision_at_n(userId)", "_____no_output_____" ] ], [ [ "# Average metrics by all users\n\nEspefically for user 907, the recommendations from the user user came with all nulls (original dataset). This specifically impacted the RMSE calculation, as one Nan damaged the entire average calculation. So specifically for RMSE we did a separate calculation section. All the other metrics are going the be calculated in the next code block.", "_____no_output_____" ] ], [ [ "re = RecommenderEvaluator(items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias)\n\ni = 0\ncount = np.array([0,0,0,0,0])\nfor userId in actual_ratings.columns:\n if(userId == '907'):\n rmse_recommenders = re.rmse(userId).fillna(0)\n else:\n rmse_recommenders = re.rmse(userId)\n count = count + rmse_recommenders['rmse']\n\n# as we didn't use user 907 for user user, divide it by the number of users - 1\ndenominator = [len(actual_ratings.columns)] * 5\ndenominator[1] = len(actual_ratings.columns) - 1\nprint('Average RMSE for all users')\ncount/ denominator", "Average RMSE for all users\n" ], [ "count_nDCG = np.array([0,0,0,0,0])\ncount_diversity_price = np.ndarray([5,2])\ncount_diversity_availability = np.ndarray([5,2])\ncount_popularity = np.array([0,0,0,0,0])\ncount_precision_at_5 = np.array([0,0,0,0,0])\n\nfor userId in actual_ratings.columns:\n nDCG_recommenders = re.nDCG(userId)\n count_nDCG = count_nDCG + nDCG_recommenders['nDCG']\n \n diversity_price_recommenders = re.price_diversity(userId)\n count_diversity_price = count_diversity_price + diversity_price_recommenders[['mean','std']]\n \n diversity_availability_recommenders = re.availability_diversity(userId)\n count_diversity_availability = count_diversity_availability + diversity_availability_recommenders[['mean','std']]\n \n popularity_recommenders = re.popularity(userId)\n count_popularity = count_popularity + popularity_recommenders['popularity'] \n \n precision_recommenders = re.precision_at_n(userId)\n count_precision_at_5 = count_precision_at_5 + precision_recommenders['precision_at_5'] \n\nprint('\\n---')\nprint('Average nDCG')\nprint('---\\n')\nprint(count_nDCG/len(actual_ratings.columns))\nprint('\\n---')\nprint('Average Price - Diversity Measure')\nprint('---\\n')\nprint(count_diversity_price/len(actual_ratings.columns))\nprint('\\n---')\nprint('Average Availability - Diversity Measure')\nprint('---\\n')\nprint(count_diversity_availability/len(actual_ratings.columns))\nprint('\\n---')\nprint('Average Popularity')\nprint('---\\n')\nprint(count_popularity/len(actual_ratings.columns))\nprint('---\\n')\nprint('Average Precision@5')\nprint('---\\n')\nprint(count_precision_at_5/len(actual_ratings.columns))", "\n---\nAverage nDCG\n---\n\ncontent_based 0.136505\nitem_item 0.146798\nmatrix_fact 0.155888\npers_bias 0.125180\nuser_user 0.169080\nName: nDCG, dtype: float64\n\n---\nAverage Price - Diversity Measure\n---\n\n mean std\ncontent_based 19.286627 19.229536\nuser_user 21.961776 25.275120\nitem_item 25.931943 32.224609\nmatrix_fact 21.165554 26.236822\npers_bias 9.938984 5.159261\n\n---\nAverage Availability - Diversity Measure\n---\n\n mean std\ncontent_based 0.623888 0.225789\nuser_user 0.682751 0.230219\nitem_item 0.655725 0.223781\nmatrix_fact 0.601153 0.202596\npers_bias 0.638596 0.202630\n\n---\nAverage Popularity\n---\n\ncontent_based 0.00\nuser_user 0.01\nitem_item 0.00\nmatrix_fact 0.00\npers_bias 0.00\nName: popularity, dtype: float64\n---\n\nAverage Precision@5\n---\n\ncontent_based 0.050\nuser_user 0.066\nitem_item 0.076\nmatrix_fact 0.064\npers_bias 0.052\nName: precision_at_5, dtype: float64\n" ] ], [ [ "# Final Analysis\n\nIn terms of **RMSE**, the user-user collaborative filtering showed to be the most effective, despite it not being significantly better.\n\nFor nDCG rank score, again user user and now item item collaborative filtering were the best.\n\nIn terms of price diversity, the item item algorith was the most diverse, providing products varying ~32 dollars from the mean item price list. Matrix factorisation and user user follow right behind, with price standard deviation around 25 dollars. An interesting factor here was the *pers_bias* algorithm, as it recommended basically cheap products with a low standard deviation.\n\nFor the availabity index, all the algorithms besides the user user managed to recommend items not so present in the local stores **together** with items present in local stores, as we can see they also provided items with availability index high (high standard deviation).\n\nIn terms of popularity, no algorithm actually managed to obtain good scores in the way we defined. So, if the popularity is focused in the future, we can either change the popularity concept or improve mechanics in the recommender so it predict higher scores for the most popular items in the store.\n\nAfter this evaluation, it seemed to us that the item-item recommender system had an overall better performance, highlighted in terms of its diversity scores. Unfortunately, the items that item item recommender has suggested are in overall pricy, and we can check if there is any mixture possibility with the pers_bias algorithm, as it really indicated cheap prices and a low price standard deviation. Matrix factorization performed good as well but it didn't outperform any of the other recommenders.", "_____no_output_____" ], [ "# Hibridization Techniques - Part III\n\nWe are trying four different types of hibridization here.\n\n1. Linear ensemble\n2. Non linear ensemble\n3. Top 1 from each recommender\n4. Recommender switching\n \nThe first two options approach the recommender's performance in terms of how good it predicts the users' ratings, so its only evaluation will be in terms of RMSE.\n \nThe third approach have the intuition that, if we get the top 1 recommendation from each algorithm, the resulting 5 item list will have a better performance in terms of identyfing 'good' items to users. In this case, we defined the good items if the recommender suggested an already bought item for an user. Therefore, the final measurement of this hibridization mechanism is through the precision@5, as we end up with a 5 item list.\n\nThe final mixing algorithm has the underlying theory of how collaborative filtering mechanisms perform with items that had not enough users/items in its calculations. As a well known weakness of these recommenders, the idea was to check how many items we would affect if we established a threshold of enough data in order for us to use a collaborative filtering. Otherwise, if the item doesn't have enough support in form of users' ratings we could have a support of a content based recommendation, or even, in last case, a non personalised one.\n \n \n## Dataset Creation and User Sample Definition\n\n### Dataset\n\nFor the first and second approach, we need another perspective on the data. The dataset contains all the existing ratings from all users and concatenates all the predictions made the 5 traditional recommenders. The idea is to use the observed rating as target variable and all recommenders' predictions as dependent variable, *i.e.* treat this as a regression problems.", "_____no_output_____" ] ], [ [ "obs_ratings_list = []\ncontent_based_list = []\nuser_user_list = []\nitem_item_list = []\nmatrix_fact_list = []\npers_bias_list = []\n\nre = RecommenderEvaluator(items, actual_ratings, content_based, user_user, item_item, matrix_fact, pers_bias)\nfor userId in actual_ratings.columns:\n \n observed_ratings = re.get_observed_ratings(userId)\n obs_ratings_list.extend(observed_ratings.values)\n \n content_based_list.extend(content_based.loc[observed_ratings.index, userId].values)\n user_user_list.extend(user_user.loc[observed_ratings.index, userId].values)\n item_item_list.extend(item_item.loc[observed_ratings.index, userId].values)\n matrix_fact_list.extend(matrix_fact.loc[observed_ratings.index, userId].values)\n pers_bias_list.extend(pers_bias.loc[observed_ratings.index, userId].values)\ndataset = pd.DataFrame({'rating': obs_ratings_list, 'content_based':content_based_list, 'user_user': user_user_list,\n 'item_item':item_item_list, 'matrix_fact':matrix_fact_list,'pers_bias':pers_bias_list})\ndataset = dataset.dropna()\ndataset.head()", "_____no_output_____" ] ], [ [ "### In order to have an idea of the results, let's choose 3 users randomly to show the predictions using the new hybrid models", "_____no_output_____" ] ], [ [ "np.random.seed(42)\nsample_users = np.random.choice(actual_ratings.columns, 3).astype(str)\nprint('sample_users: ' + str(sample_users))", "sample_users: ['1528' '3524' '417']\n" ] ], [ [ "### Get recommenders' predictions for sample users in order to create input for ensemble models (hybridization I and II)", "_____no_output_____" ] ], [ [ "from collections import OrderedDict\n\ndf_sample = pd.DataFrame()\nfor user in sample_users:\n content_based_ = re.content_based[user]\n user_user_ = re.user_user[user]\n item_item_ = re.item_item[user]\n matrix_fact_ = re.matrix_fact[user]\n pers_bias_ = re.pers_bias[user]\n df_sample = df_sample.append(pd.DataFrame(OrderedDict({'user':user,'item':actual_ratings.index.values,'content_based':content_based_, 'user_user':user_user_, 'item_item':item_item_,\n 'matrix_fact':matrix_fact_,'pers_bias':pers_bias_})), ignore_index=True)\n \ndf_sample.head()\n", "_____no_output_____" ] ], [ [ "\n## Focus on Performance (RMSE) I - Linear Model", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import cross_val_score\n\nlinear = LinearRegression()\nprint('RMSE for linear ensemble of recommender systems:')\nnp.mean(cross_val_score(linear, dataset.drop('rating', axis=1), dataset['rating'], cv=5))", "RMSE for linear ensemble of recommender systems:\n" ] ], [ [ "### Predictions for sample users: Creating top 5 recommendations for sample users", "_____no_output_____" ] ], [ [ "pred_cols = ['content_based','user_user','item_item','matrix_fact','pers_bias']\npredictions = linear.fit(dataset.drop('rating', axis=1), dataset['rating']).predict(df_sample[pred_cols])\nrecommendations = pd.DataFrame(OrderedDict({'user':df_sample['user'], 'item':df_sample['item'], 'predictions':predictions}))\nrecommendations.groupby('user').apply(lambda df_user : df_user.loc[df_user['predictions'].sort_values(ascending=False)[:5].index.values])\n", "_____no_output_____" ] ], [ [ "## Focus on Performance (RMSE) II - Emsemble", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestRegressor\n\nrf = RandomForestRegressor(random_state=42)\nprint('RMSE for non linear ensemble of recommender systems:')\nnp.mean(cross_val_score(rf, dataset.drop('rating', axis=1), dataset['rating'], cv=5))", "RMSE for non linear ensemble of recommender systems:\n" ] ], [ [ "### Predictions for sample users:", "_____no_output_____" ] ], [ [ "predictions = rf.fit(dataset.drop('rating', axis=1), dataset['rating']).predict(df_sample[pred_cols])\nrecommendations = pd.DataFrame(OrderedDict({'user':df_sample['user'], 'item':df_sample['item'], 'predictions':predictions}))\nrecommendations.groupby('user').apply(lambda df_user : df_user.loc[df_user['predictions'].sort_values(ascending=False)[:5].index.values])\n", "_____no_output_____" ] ], [ [ "## Focus on Recommendations - Top 1 from each Recommender\n\nWith the all top 1 recommender, we can evaluate its performance not just with RMSE, but all the list metrics we evaluated before. As a business constraint, we will also pay more attention to the *precision@5* metric, as a general information on how good is the recommender on providing suggestions that the user will buy, or already bought in this case.\nThe majority of metrics were in the same scale as the best metrics in the all models comparison. However, it's good to highlight the the top 1 all recommender had the best *precision@5* metric among all recommender, showing to be a **good suitable hibridization mechanism**.", "_____no_output_____" ] ], [ [ "count_nDCG = np.array([0])\ncount_diversity_price = np.ndarray([1,2])\ncount_diversity_availability = np.ndarray([1,2])\ncount_popularity = np.array([0])\ncount_precision = np.array([0])\n\nfor userId in actual_ratings.columns:\n \n top_n_1 = re.get_top_n(userId,1)\n user_items = {}\n user_items['top_1_all'] = [a[0] for a in top_n_1.values()]\n \n nDCG_recommenders = re.nDCG(userId, individual_recommendation = user_items)\n count_nDCG = count_nDCG + nDCG_recommenders['nDCG']\n \n diversity_price_recommenders = re.price_diversity(userId, individual_recommendation = user_items)\n count_diversity_price = count_diversity_price + diversity_price_recommenders[['mean','std']]\n \n diversity_availability_recommenders = re.availability_diversity(userId, individual_recommendation = user_items)\n count_diversity_availability = count_diversity_availability + diversity_availability_recommenders[['mean','std']]\n \n popularity_recommenders = re.popularity(userId, individual_recommendation = user_items)\n count_popularity = count_popularity + popularity_recommenders['popularity'] \n \n precision_recommenders = re.precision_at_n(userId, individual_recommendation = user_items)\n count_precision = count_precision + precision_recommenders['precision_at_5'] \n\nprint('\\n---')\nprint('Average nDCG')\nprint('---\\n')\nprint(count_nDCG/len(actual_ratings.columns))\nprint('\\n---')\nprint('Average Price - Diversity Measure')\nprint('---\\n')\nprint(count_diversity_price/len(actual_ratings.columns))\nprint('\\n---')\nprint('Average Availability - Diversity Measure')\nprint('---\\n')\nprint(count_diversity_availability/len(actual_ratings.columns))\nprint('\\n---')\nprint('Average Popularity')\nprint('---\\n')\nprint(count_popularity/len(actual_ratings.columns))\nprint('\\n---')\nprint('Average Precision@5')\nprint('---\\n')\nprint(count_precision/len(actual_ratings.columns))\n", "\n---\nAverage nDCG\n---\n\ntop_1_all 0.159211\nName: nDCG, dtype: float64\n\n---\nAverage Price - Diversity Measure\n---\n\n mean std\ntop_1_all 16.4625 14.741783\n\n---\nAverage Availability - Diversity Measure\n---\n\n mean std\ntop_1_all 0.575683 0.161168\n\n---\nAverage Popularity\n---\n\ntop_1_all 0.0\nName: popularity, dtype: float64\n\n---\nAverage Precision@5\n---\n\ntop_1_all 0.082\nName: precision_at_5, dtype: float64\n" ] ], [ [ "### Predictions for sample users:", "_____no_output_____" ] ], [ [ "results = {}\nfor user_sample in sample_users:\n results[user_sample] = [a[0] for a in list(re.get_top_n(user_sample, 1).values())]\nresults", "_____no_output_____" ] ], [ [ "## Focus on Recommendations - Switching algorithm\n\n### Can we use a Content Based Recommender for items with less evaluations?\n\nWe can see in the cumulative histogram that only around 20% of the rated items had 10 or more ratings. This signals us that maybe we can prioritize the use of a content based recommender or even a non personalised one for the majority of the items which don't have a sufficient amount of ratings in order to make the collaborative filtering algorithms to be stable.", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\nitem_nbr_ratings = actual_ratings.apply(lambda col: np.sum(~np.isnan(col)), axis=1)\nitem_max_nbr_ratings = item_nbr_ratings.max()\nrange_item_max_nbr_ratings = range(item_max_nbr_ratings+1)\n\nplt.figure(figsize=(15,3))\nplt.subplot(121)\nnbr_ratings_items = []\nfor i in range_item_max_nbr_ratings:\n nbr_ratings_items.append(len(item_nbr_ratings[item_nbr_ratings == i]))\nplt.plot(nbr_ratings_items)\nplt.xlabel('Number of ratings')\nplt.ylabel('Amount of items')\nplt.title('Histogram of amount of ratings')\n\nplt.subplot(122)\ncum_nbr_ratings_items = []\nfor i in range(len(nbr_ratings_items)):\n cum_nbr_ratings_items.append(np.sum(nbr_ratings_items[:i]))\n \ncum_nbr_ratings_items = np.array(cum_nbr_ratings_items)\nplt.plot(cum_nbr_ratings_items/actual_ratings.shape[0])\nplt.xlabel('Number of ratings')\nplt.ylabel('Cumulative distribution')\nplt.title('Cumulative histogram of amount of ratings');", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d02f9f694a1e105f95f6a24f1e555267cfaae7f5
95,134
ipynb
Jupyter Notebook
notebooks/CL.plots.ipynb
sandeepsoni/semantic-progressiveness
824079b388d0eebc92b2197805b27ed320353f8f
[ "MIT" ]
2
2021-04-11T16:28:44.000Z
2021-07-31T03:22:07.000Z
notebooks/CL.plots.ipynb
sandeepsoni/semantic-progressiveness
824079b388d0eebc92b2197805b27ed320353f8f
[ "MIT" ]
null
null
null
notebooks/CL.plots.ipynb
sandeepsoni/semantic-progressiveness
824079b388d0eebc92b2197805b27ed320353f8f
[ "MIT" ]
1
2021-09-01T22:45:25.000Z
2021-09-01T22:45:25.000Z
48.962429
23,588
0.5707
[ [ [ "import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ], [ "STATS_DIR = \"/hg191/corpora/legaldata/data/stats/\"\nSEM_FEATS_FILE = os.path.join (STATS_DIR, \"ops.temp.semfeat\")\nINDEG_FILE = os.path.join (STATS_DIR, \"ops.ind\")", "_____no_output_____" ], [ "ind = pd.read_csv (INDEG_FILE, sep=\",\", header=None, names=[\"opid\", \"indeg\"])", "_____no_output_____" ], [ "semfeat = pd.read_csv (SEM_FEATS_FILE, sep=\",\", header=None, names=[\"opid\", \"semfeat\"])", "_____no_output_____" ], [ "indegs = pd.Series([ind[ind[\"opid\"] == opid][\"indeg\"].values[0] for opid in semfeat.opid.values])", "_____no_output_____" ], [ "semfeat[\"indeg\"] = indegs", "_____no_output_____" ], [ "def labelPercentile (series):\n labels = list ()\n p50 = np.percentile (series, q=50)\n p75 = np.percentile (series, q=75)\n p90 = np.percentile (series, q=90)\n \n for value in series:\n if value <= p50:\n labels.append (\"<=50\")\n elif value <= p90:\n labels.append (\">50\")\n elif value > p90:\n labels.append (\">90\")\n return labels", "_____no_output_____" ], [ "semfeat[\"percentile\"] = pd.Series (labelPercentile(semfeat[\"semfeat\"].values))\ndf = semfeat[semfeat[\"indeg\"] > 0]\ndf[\"log(indeg)\"] = np.log(df[\"indeg\"])", "/nethome/ssoni30/venvs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n This is separate from the ipykernel package so we can avoid doing imports until\n" ], [ "ax = sns.boxplot(x=\"percentile\", y=\"log(indeg)\", data=df, order=[\"<=50\", \">50\", \">90\"])", "_____no_output_____" ], [ "vals = df[df[\"percentile\"] == \">50\"][\"log(indeg)\"].values\nnp.sort(vals)[int(len(vals)/2)]", "_____no_output_____" ], [ "print(len(df[df[\"percentile\"] == \">50\"]))\nprint(len(df[df[\"percentile\"] == \">90\"]))", "11394\n1993\n" ], [ "print (df[df[\"percentile\"] == \"<=50\"][\"log(indeg)\"].median())\nprint (df[df[\"percentile\"] == \">50\"][\"log(indeg)\"].median())\nprint (df[df[\"percentile\"] == \">90\"][\"log(indeg)\"].median())\n#print (semfeat[semfeat[\"percentile\"] == \">P99\"][\"logindeg\"].mean())", "1.6094379124341003\n1.9459101490553132\n1.9459101490553132\n" ], [ "print (semfeat[semfeat[\"percentile\"] == \"<=P50\"][\"logindeg\"].mean())\nprint (semfeat[semfeat[\"percentile\"] == \">P50\"][\"logindeg\"].mean())\nprint (semfeat[semfeat[\"percentile\"] == \">P90\"][\"logindeg\"].mean())", "1.3677560520966618\n1.807529253586165\n1.2936526699313982\n" ], [ "print (semfeat[semfeat[\"percentile\"] == \"<=P50\"][\"indeg\"].median())\nprint (semfeat[semfeat[\"percentile\"] == \">P50\"][\"indeg\"].median())\nprint (semfeat[semfeat[\"percentile\"] == \">P90\"][\"indeg\"].median())", "_____no_output_____" ], [ "print (semfeat[semfeat[\"percentile\"] == \"<=P50\"][\"indeg\"].median())\nprint (semfeat[semfeat[\"percentile\"] == \">P50\"][\"indeg\"].median())\nprint (semfeat[semfeat[\"percentile\"] == \">P90\"][\"indeg\"].median())", "0.0\n2.0\n0.0\n" ], [ "np.percentile(semfeat[\"semfeat\"].values, q=90)", "_____no_output_____" ], [ "[semfeat[\"percentile\"] == \">P90\"][\"indeg\"].mean()", "_____no_output_____" ], [ "semfeat[semfeat[\"percentile\"] == \">P90\"].tail(500)", "_____no_output_____" ], [ "sorted(semfeat[\"indeg\"], reverse=True)[0:10]", "_____no_output_____" ], [ "semfeat[semfeat[\"indeg\"].isin(sorted(semfeat[\"indeg\"], reverse=True)[0:10])]", "_____no_output_____" ], [ "semfeat.loc[48004,][\"semfeat\"] = 1", "_____no_output_____" ], [ "semfeat[semfeat[\"indeg\"].isin(sorted(semfeat[\"indeg\"], reverse=True)[0:10])]", "_____no_output_____" ], [ "print(np.mean((semfeat[semfeat[\"percentile\"] == \"<=P50\"][\"indeg\"] > 0).values))\nprint(np.mean((semfeat[semfeat[\"percentile\"] == \">P50\"][\"indeg\"] > 0).values))\nprint(np.mean((semfeat[semfeat[\"percentile\"] == \">P90\"][\"indeg\"] > 0).values))", "0.49868\n0.5697\n0.3986\n" ], [ "print (len(semfeat[(semfeat[\"percentile\"] == \"<=P50\") & (semfeat[\"indeg\"] > 0)]))\nprint (len(semfeat[(semfeat[\"percentile\"] == \">P50\") & (semfeat[\"indeg\"] > 0)]))\nprint (len(semfeat[(semfeat[\"percentile\"] == \">P90\") & (semfeat[\"indeg\"] > 0)]))", "12467\n11394\n1993\n" ], [ "print (semfeat[(semfeat[\"percentile\"] == \"<=P50\") & (semfeat[\"indeg\"] > 0)][\"indeg\"].mean())\nprint (semfeat[(semfeat[\"percentile\"] == \">P50\") & (semfeat[\"indeg\"] > 0)][\"indeg\"].mean())\nprint (semfeat[(semfeat[\"percentile\"] == \">P90\") & (semfeat[\"indeg\"] > 0)][\"indeg\"].mean())", "10.696558915537018\n17.132964718272774\n30.600602107375817\n" ], [ "print (semfeat[(semfeat[\"percentile\"] == \"<=P50\") & (semfeat[\"indeg\"] > 0)][\"logindeg\"].mean())\nprint (semfeat[(semfeat[\"percentile\"] == \">P50\") & (semfeat[\"indeg\"] > 0)][\"logindeg\"].mean())\nprint (semfeat[(semfeat[\"percentile\"] == \">P90\") & (semfeat[\"indeg\"] > 0)][\"logindeg\"].mean())", "1.9011314895415956\n2.1991992380250522\n2.2496028619839286\n" ], [ "ax = sns.violinplot(x=\"percentile\", y=\"logindeg\", data=df, order=[\"<=P50\", \">P50\", \">P90\"])", "_____no_output_____" ], [ "semfeat[semfeat[\"indeg\"] == 1]", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d02fad5d44a4d62cc745129e811a0145477c2133
126,563
ipynb
Jupyter Notebook
geometric-operations.ipynb
AdrianKriger/Automating-GIS-Processess
ecd31958ac7861e7d70dd1454e74ff43f42dcf32
[ "MIT" ]
null
null
null
geometric-operations.ipynb
AdrianKriger/Automating-GIS-Processess
ecd31958ac7861e7d70dd1454e74ff43f42dcf32
[ "MIT" ]
null
null
null
geometric-operations.ipynb
AdrianKriger/Automating-GIS-Processess
ecd31958ac7861e7d70dd1454e74ff43f42dcf32
[ "MIT" ]
null
null
null
175.781944
31,676
0.884437
[ [ [ "# Geometric operations\n\n## Overlay analysis\n\nIn this tutorial, the aim is to make an overlay analysis where we create a new layer based on geometries from a dataset that `intersect` with geometries of another layer. As our test case, we will select Polygon grid cells from `TravelTimes_to_5975375_RailwayStation_Helsinki.shp` that intersects with municipality borders of Helsinki found in `Helsinki_borders.shp`.\n\nTypical overlay operations are (source: [QGIS docs](https://docs.qgis.org/2.8/en/docs/gentle_gis_introduction/vector_spatial_analysis_buffers.html#more-spatial-analysis-tools)):\n![](img/overlay_operations.png)\n\n## Download data\n\nFor this lesson, you should [download a data package](https://github.com/AutoGIS/data/raw/master/L4_data.zip) that includes 3 files:\n\n 1. Helsinki_borders.shp\n 2. Travel_times_to_5975375_RailwayStation.shp\n 3. Amazon_river.shp\n \n```\n$ cd /home/jovyan/notebooks/L4\n$ wget https://github.com/AutoGIS/data/raw/master/L4_data.zip\n$ unzip L4_data.zip\n```\n\nLet's first read the data and see how they look like.\n\n- Import required packages and read in the input data:", "_____no_output_____" ] ], [ [ "import geopandas as gpd\nimport matplotlib.pyplot as plt\nimport shapely.speedups\n%matplotlib inline\n\n# File paths\nborder_fp = \"data/Helsinki_borders.shp\"\ngrid_fp = \"data/TravelTimes_to_5975375_RailwayStation.shp\"\n\n# Read files\ngrid = gpd.read_file(grid_fp)\nhel = gpd.read_file(border_fp)", "_____no_output_____" ] ], [ [ "- Visualize the layers:", "_____no_output_____" ] ], [ [ "# Plot the layers\nax = grid.plot(facecolor='gray')\nhel.plot(ax=ax, facecolor='None', edgecolor='blue')", "_____no_output_____" ] ], [ [ "Here the grey area is the Travel Time Matrix grid (13231 grid squares) that covers the Helsinki region, and the blue area represents the municipality of Helsinki. Our goal is to conduct an overlay analysis and select the geometries from the grid polygon layer that intersect with the Helsinki municipality polygon.\n\nWhen conducting overlay analysis, it is important to check that the CRS of the layers match!\n\n- Check if Helsinki polygon and the grid polygon are in the same crs:", "_____no_output_____" ] ], [ [ "# Ensure that the CRS matches, if not raise an AssertionError\nassert hel.crs == grid.crs, \"CRS differs between layers!\"", "_____no_output_____" ] ], [ [ "Indeed, they do. Hence, the pre-requisite to conduct spatial operations between the layers is fullfilled (also the map we plotted indicated this).\n\n- Let's do an overlay analysis and create a new layer from polygons of the grid that `intersect` with our Helsinki layer. We can use a function called `overlay()` to conduct the overlay analysis that takes as an input 1) the GeoDataFrame where the selection is taken, 2) the GeoDataFrame used for making the selection, and 3) parameter `how` that can be used to control how the overlay analysis is conducted (possible values are `'intersection'`, `'union'`, `'symmetric_difference'`, `'difference'`, and `'identity'`):", "_____no_output_____" ] ], [ [ "intersection = gpd.overlay(grid, hel, how='intersection')", "_____no_output_____" ] ], [ [ "- Let's plot our data and see what we have:", "_____no_output_____" ] ], [ [ "intersection.plot(color=\"b\")", "_____no_output_____" ] ], [ [ "As a result, we now have only those grid cells that intersect with the Helsinki borders. As we can see **the grid cells are clipped based on the boundary.**\n\n- Whatabout the data attributes? Let's see what we have:\n", "_____no_output_____" ] ], [ [ "print(intersection.head())", " car_m_d car_m_t car_r_d car_r_t from_id pt_m_d pt_m_t pt_m_tt \\\n0 29476 41 29483 46 5876274 29990 76 95 \n1 29456 41 29462 46 5876275 29866 74 95 \n2 36772 50 36778 56 5876278 33541 116 137 \n3 36898 49 36904 56 5876279 33720 119 141 \n4 29411 40 29418 44 5878128 29944 75 95 \n\n pt_r_d pt_r_t pt_r_tt to_id walk_d walk_t GML_ID NAMEFIN \\\n0 24984 77 99 5975375 25532 365 27517366 Helsinki \n1 24860 75 93 5975375 25408 363 27517366 Helsinki \n2 44265 130 146 5975375 31110 444 27517366 Helsinki \n3 44444 132 155 5975375 31289 447 27517366 Helsinki \n4 24938 76 99 5975375 25486 364 27517366 Helsinki \n\n NAMESWE NATCODE geometry \n0 Helsingfors 091 POLYGON ((402250.000 6685750.000, 402024.224 6... \n1 Helsingfors 091 POLYGON ((402367.890 6685750.000, 402250.000 6... \n2 Helsingfors 091 POLYGON ((403250.000 6685750.000, 403148.515 6... \n3 Helsingfors 091 POLYGON ((403456.484 6685750.000, 403250.000 6... \n4 Helsingfors 091 POLYGON ((402000.000 6685500.000, 401900.425 6... \n" ] ], [ [ "As we can see, due to the overlay analysis, the dataset contains the attributes from both input layers.\n\n- Let's save our result grid as a GeoJSON file that is commonly used file format nowadays for storing spatial data.\n", "_____no_output_____" ] ], [ [ "# Output filepath\noutfp = \"data/TravelTimes_to_5975375_RailwayStation_Helsinki.geojson\"\n\n# Use GeoJSON driver\nintersection.to_file(outfp, driver=\"GeoJSON\")", "_____no_output_____" ] ], [ [ "There are many more examples for different types of overlay analysis in [Geopandas documentation](http://geopandas.org/set_operations.html) where you can go and learn more.", "_____no_output_____" ], [ "## Aggregating data\n\nData aggregation refers to a process where we combine data into groups. When doing spatial data aggregation, we merge the geometries together into coarser units (based on some attribute), and can also calculate summary statistics for these combined geometries from the original, more detailed values. For example, suppose that we are interested in studying continents, but we only have country-level data like the country dataset. If we aggregate the data by continent, we would convert the country-level data into a continent-level dataset.\n\nIn this tutorial, we will aggregate our travel time data by car travel times (column `car_r_t`), i.e. the grid cells that have the same travel time to Railway Station will be merged together.\n\n- For doing the aggregation we will use a function called `dissolve()` that takes as input the column that will be used for conducting the aggregation:\n", "_____no_output_____" ] ], [ [ "# Conduct the aggregation\ndissolved = intersection.dissolve(by=\"car_r_t\")\n\n# What did we get\nprint(dissolved.head())", " geometry car_m_d car_m_t \\\ncar_r_t \n-1 MULTIPOLYGON (((388000.000 6668750.000, 387750... -1 -1 \n 0 POLYGON ((386000.000 6672000.000, 385750.000 6... 0 0 \n 7 POLYGON ((386250.000 6671750.000, 386000.000 6... 1051 7 \n 8 MULTIPOLYGON (((386250.000 6671500.000, 386000... 1286 8 \n 9 MULTIPOLYGON (((386500.000 6671250.000, 386250... 1871 9 \n\n car_r_d from_id pt_m_d pt_m_t pt_m_tt pt_r_d pt_r_t pt_r_tt \\\ncar_r_t \n-1 -1 5913094 -1 -1 -1 -1 -1 -1 \n 0 0 5975375 0 0 0 0 0 0 \n 7 1051 5973739 617 5 6 617 5 6 \n 8 1286 5973736 706 10 10 706 10 10 \n 9 1871 5970457 1384 11 13 1394 11 12 \n\n to_id walk_d walk_t GML_ID NAMEFIN NAMESWE NATCODE \ncar_r_t \n-1 -1 -1 -1 27517366 Helsinki Helsingfors 091 \n 0 5975375 0 0 27517366 Helsinki Helsingfors 091 \n 7 5975375 448 6 27517366 Helsinki Helsingfors 091 \n 8 5975375 706 10 27517366 Helsinki Helsingfors 091 \n 9 5975375 1249 18 27517366 Helsinki Helsingfors 091 \n" ] ], [ [ "- Let's compare the number of cells in the layers before and after the aggregation:", "_____no_output_____" ] ], [ [ "print('Rows in original intersection GeoDataFrame:', len(intersection))\nprint('Rows in dissolved layer:', len(dissolved))", "Rows in original intersection GeoDataFrame: 3826\nRows in dissolved layer: 51\n" ] ], [ [ "Indeed the number of rows in our data has decreased and the Polygons were merged together.\n\nWhat actually happened here? Let's take a closer look. \n\n- Let's see what columns we have now in our GeoDataFrame:", "_____no_output_____" ] ], [ [ "print(dissolved.columns)", "Index(['geometry', 'car_m_d', 'car_m_t', 'car_r_d', 'from_id', 'pt_m_d',\n 'pt_m_t', 'pt_m_tt', 'pt_r_d', 'pt_r_t', 'pt_r_tt', 'to_id', 'walk_d',\n 'walk_t', 'GML_ID', 'NAMEFIN', 'NAMESWE', 'NATCODE'],\n dtype='object')\n" ] ], [ [ "As we can see, the column that we used for conducting the aggregation (`car_r_t`) can not be found from the columns list anymore. What happened to it?\n\n- Let's take a look at the indices of our GeoDataFrame:", "_____no_output_____" ] ], [ [ "print(dissolved.index)", "Int64Index([-1, 0, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,\n 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,\n 56],\n dtype='int64', name='car_r_t')\n" ] ], [ [ "Aha! Well now we understand where our column went. It is now used as index in our `dissolved` GeoDataFrame. \n\n- Now, we can for example select only such geometries from the layer that are for example exactly 15 minutes away from the Helsinki Railway Station:", "_____no_output_____" ] ], [ [ "# Select only geometries that are within 15 minutes away\ndissolved.iloc[15]", "_____no_output_____" ], [ "# See the data type\nprint(type(dissolved.iloc[15]))", "<class 'pandas.core.series.Series'>\n" ], [ "# See the data\nprint(dissolved.iloc[15].head())", "geometry (POLYGON ((388250.0001354316 6668750.000042891...\ncar_m_d 12035\ncar_m_t 18\ncar_r_d 11997\nfrom_id 5903886\nName: 20, dtype: object\n" ] ], [ [ "As we can see, as a result, we have now a Pandas `Series` object containing basically one row from our original aggregated GeoDataFrame.\n\nLet's also visualize those 15 minute grid cells.\n\n- First, we need to convert the selected row back to a GeoDataFrame:", "_____no_output_____" ] ], [ [ "# Create a GeoDataFrame\nselection = gpd.GeoDataFrame([dissolved.iloc[15]], crs=dissolved.crs)", "_____no_output_____" ] ], [ [ "- Plot the selection on top of the entire grid:", "_____no_output_____" ] ], [ [ "# Plot all the grid cells, and the grid cells that are 15 minutes a way from the Railway Station\nax = dissolved.plot(facecolor='gray')\nselection.plot(ax=ax, facecolor='red')", "_____no_output_____" ] ], [ [ "## Simplifying geometries", "_____no_output_____" ], [ "Sometimes it might be useful to be able to simplify geometries. This could be something to consider for example when you have very detailed spatial features that cover the whole world. If you make a map that covers the whole world, it is unnecessary to have really detailed geometries because it is simply impossible to see those small details from your map. Furthermore, it takes a long time to actually render a large quantity of features into a map. Here, we will see how it is possible to simplify geometric features in Python.\n\nAs an example we will use data representing the Amazon river in South America, and simplify it's geometries.\n\n- Let's first read the data and see how the river looks like:", "_____no_output_____" ] ], [ [ "import geopandas as gpd\n\n# File path\nfp = \"data/Amazon_river.shp\"\ndata = gpd.read_file(fp)\n\n# Print crs\nprint(data.crs)\n\n# Plot the river\ndata.plot();", "PROJCS[\"Mercator_2SP\",GEOGCS[\"GCS_GRS 1980(IUGG, 1980)\",DATUM[\"D_unknown\",SPHEROID[\"GRS80\",6378137,298.257222101]],PRIMEM[\"Unknown\",0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_2SP\"],PARAMETER[\"standard_parallel_1\",-2],PARAMETER[\"central_meridian\",-43],PARAMETER[\"false_easting\",5000000],PARAMETER[\"false_northing\",10000000],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH]]\n" ] ], [ [ "The LineString that is presented here is quite detailed, so let's see how we can generalize them a bit. As we can see from the coordinate reference system, the data is projected in a metric system using [Mercator projection based on SIRGAS datum](http://spatialreference.org/ref/sr-org/7868/). \n\n- Generalization can be done easily by using a Shapely function called `.simplify()`. The `tolerance` parameter can be used to adjusts how much geometries should be generalized. **The tolerance value is tied to the coordinate system of the geometries**. Hence, the value we pass here is 20 000 **meters** (20 kilometers).\n\n", "_____no_output_____" ] ], [ [ "# Generalize geometry\ndata2 = data.copy()\ndata2['geom_gen'] = data2.simplify(tolerance=20000)\n\n# Set geometry to be our new simlified geometry\ndata2 = data2.set_geometry('geom_gen')\n\n# Plot \ndata2.plot()", "_____no_output_____" ], [ "# plot them side-by-side\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\n#basic config\nfig, (ax1,ax2) = plt.subplots(nrows=1, ncols=2, figsize=(20, 16))\n#ax1, ax2 = axes\n\n#1st plot\nax1 = data.plot(ax=ax1, color='red', alpha=0.5)\nax1.set_title('Original')\n\n#2nd plot\nax2 = data2.plot(ax=ax2, color='orange', alpha=0.5)\nax2.set_title('Generalize')\n\nfig.tight_layout()", "_____no_output_____" ] ], [ [ "Nice! As a result, now we have simplified our LineString quite significantly as we can see from the map.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d02fafdf557ad6475f5f56eb6cc1837bc772bbf9
17,775
ipynb
Jupyter Notebook
Experiments/Ping.ipynb
slastrina/notebooks
733ca2d903971c714ad7f01c745a611e54f2b84c
[ "MIT" ]
null
null
null
Experiments/Ping.ipynb
slastrina/notebooks
733ca2d903971c714ad7f01c745a611e54f2b84c
[ "MIT" ]
null
null
null
Experiments/Ping.ipynb
slastrina/notebooks
733ca2d903971c714ad7f01c745a611e54f2b84c
[ "MIT" ]
null
null
null
39.765101
145
0.524276
[ [ [ "import sys, pexpect, time, datetime\n\n# PingInterval\ninterval = 5\n\nfilenameBase = 'ping_tester'\n\n# LOG TO WRITE TO WHEN PINGS TAKE LONGER THAN THE THRESHOLD SET ABOVE\ni = datetime.datetime.now()\nlog_file = filenameBase + '-' + i.strftime('%Y%m%d_%H%M%S') + '.log'\n\n# SET YOUR PING RESPONSE TIME THRESHOLD HERE, IN MILLISECONDS\nthreshold = 250\n\n# WHO SHOULD WE RUN THE PING TEST AGAINST\nping_destination = 'www.google.com'\n\ndef write_to_file(file_to_write, message):\n fh = open(file_to_write, 'a')\n fh.write(message)\n fh.close()\n\ncount = 0\nline = 'Ping Interval: ' + str(interval) + ', Destination: ' + ping_destination + ', Threshold to Log (msec): ' + str(threshold) + '\\n'\n\nwrite_to_file(log_file, line)\n \nping_command = 'ping -i ' + str(interval) + ' ' + ping_destination\nprint(line)\n\nchild = pexpect.spawn(ping_command)\nchild.timeout=1200\n\nwhile 1:\n line = child.readline()\n if not line:\n break\n\n if line.startswith(b'ping: unknown host'):\n print('Unknown host: ' + ping_destination)\n #write_to_file(log_file, 'Unknown host: ' + ping_destination)\n break\n\n if count > 0:\n ping_time = float(line[line.find(b'time=') + 5:line.find(b' ms')])\n line = time.strftime(\"%m/%d/%Y %H:%M:%S\") + \": \" + str(ping_time)\n print(str(count) + \": \" + line)\n write_to_file(log_file, str(count) + \": \" + line + '\\n')\n\n# if ping_time > threshold:\n# write_to_file(log_file, line + '\\n')\n\n count += 1", "Ping Interval: 5, Destination: www.google.com, Threshold to Log (msec): 250\n\n1: 04/05/2017 23:51:56: 198.723\n2: 04/05/2017 23:52:01: 225.095\n3: 04/05/2017 23:52:06: 218.243\n4: 04/05/2017 23:52:11: 210.674\n5: 04/05/2017 23:52:16: 184.237\n6: 04/05/2017 23:52:21: 234.062\n7: 04/05/2017 23:52:26: 257.998\n8: 04/05/2017 23:52:31: 202.9\n9: 04/05/2017 23:52:36: 211.084\n10: 04/05/2017 23:52:41: 194.787\n11: 04/05/2017 23:52:46: 218.35\n12: 04/05/2017 23:52:51: 219.459\n13: 04/05/2017 23:52:56: 179.099\n14: 04/05/2017 23:53:01: 190.603\n15: 04/05/2017 23:53:06: 203.959\n16: 04/05/2017 23:53:11: 353.801\n17: 04/05/2017 23:53:16: 179.028\n18: 04/05/2017 23:53:21: 179.286\n19: 04/05/2017 23:53:26: 179.052\n20: 04/05/2017 23:53:31: 179.036\n21: 04/05/2017 23:53:36: 334.024\n22: 04/05/2017 23:53:41: 179.015\n23: 04/05/2017 23:53:46: 198.23\n24: 04/05/2017 23:53:51: 179.147\n25: 04/05/2017 23:53:56: 184.939\n26: 04/05/2017 23:54:01: 179.248\n27: 04/05/2017 23:54:06: 185.966\n28: 04/05/2017 23:54:11: 179.131\n29: 04/05/2017 23:54:16: 197.994\n30: 04/05/2017 23:54:21: 183.465\n31: 04/05/2017 23:54:26: 179.148\n32: 04/05/2017 23:54:31: 179.077\n33: 04/05/2017 23:54:36: 219.916\n34: 04/05/2017 23:54:41: 180.647\n35: 04/05/2017 23:54:46: 179.029\n36: 04/05/2017 23:54:51: 179.184\n37: 04/05/2017 23:54:56: 179.223\n38: 04/05/2017 23:55:01: 179.233\n39: 04/05/2017 23:55:06: 179.068\n40: 04/05/2017 23:55:11: 179.029\n41: 04/05/2017 23:55:16: 204.105\n42: 04/05/2017 23:55:21: 179.098\n43: 04/05/2017 23:55:26: 179.062\n44: 04/05/2017 23:55:31: 187.983\n45: 04/05/2017 23:55:36: 178.966\n46: 04/05/2017 23:55:41: 179.01\n47: 04/05/2017 23:55:46: 198.81\n48: 04/05/2017 23:55:51: 179.066\n49: 04/05/2017 23:55:56: 178.951\n50: 04/05/2017 23:56:01: 179.024\n51: 04/05/2017 23:56:06: 181.154\n52: 04/05/2017 23:56:11: 259.187\n53: 04/05/2017 23:56:16: 199.466\n54: 04/05/2017 23:56:21: 179.11\n55: 04/05/2017 23:56:26: 179.103\n56: 04/05/2017 23:56:31: 179.094\n57: 04/05/2017 23:56:36: 180.395\n58: 04/05/2017 23:56:41: 179.762\n59: 04/05/2017 23:56:46: 178.98\n60: 04/05/2017 23:56:51: 179.542\n61: 04/05/2017 23:56:56: 179.0\n62: 04/05/2017 23:57:01: 179.045\n63: 04/05/2017 23:57:06: 190.081\n64: 04/05/2017 23:57:11: 179.164\n65: 04/05/2017 23:57:16: 179.082\n66: 04/05/2017 23:57:21: 178.948\n67: 04/05/2017 23:57:26: 179.056\n68: 04/05/2017 23:57:31: 179.061\n69: 04/05/2017 23:57:36: 179.103\n70: 04/05/2017 23:57:41: 179.239\n71: 04/05/2017 23:57:46: 179.613\n72: 04/05/2017 23:57:51: 179.07\n73: 04/05/2017 23:57:56: 179.072\n74: 04/05/2017 23:58:01: 179.092\n75: 04/05/2017 23:58:06: 179.107\n76: 04/05/2017 23:58:11: 186.93\n77: 04/05/2017 23:58:16: 179.063\n78: 04/05/2017 23:58:21: 178.963\n79: 04/05/2017 23:58:26: 179.09\n80: 04/05/2017 23:58:31: 223.012\n81: 04/05/2017 23:58:36: 178.987\n82: 04/05/2017 23:58:41: 184.495\n83: 04/05/2017 23:58:46: 179.095\n84: 04/05/2017 23:58:51: 179.038\n85: 04/05/2017 23:58:56: 179.304\n86: 04/05/2017 23:59:01: 206.079\n87: 04/05/2017 23:59:06: 179.288\n88: 04/05/2017 23:59:11: 183.811\n89: 04/05/2017 23:59:16: 179.057\n90: 04/05/2017 23:59:21: 179.105\n91: 04/05/2017 23:59:26: 179.254\n92: 04/05/2017 23:59:31: 179.237\n93: 04/05/2017 23:59:36: 194.338\n94: 04/05/2017 23:59:41: 187.935\n95: 04/05/2017 23:59:46: 181.789\n96: 04/05/2017 23:59:51: 179.088\n97: 04/05/2017 23:59:56: 179.138\n98: 04/06/2017 00:00:01: 178.991\n99: 04/06/2017 00:00:06: 179.158\n100: 04/06/2017 00:00:11: 179.78\n101: 04/06/2017 00:00:16: 181.029\n102: 04/06/2017 00:00:21: 188.471\n103: 04/06/2017 00:00:26: 179.066\n104: 04/06/2017 00:00:31: 179.025\n105: 04/06/2017 00:00:36: 179.023\n106: 04/06/2017 00:00:41: 179.108\n107: 04/06/2017 00:00:46: 178.982\n108: 04/06/2017 00:00:51: 214.006\n109: 04/06/2017 00:00:56: 179.003\n110: 04/06/2017 00:01:01: 179.067\n111: 04/06/2017 00:01:06: 182.809\n112: 04/06/2017 00:01:11: 178.991\n113: 04/06/2017 00:01:16: 183.519\n114: 04/06/2017 00:01:21: 179.065\n115: 04/06/2017 00:01:26: 179.409\n116: 04/06/2017 00:01:31: 179.081\n117: 04/06/2017 00:01:36: 179.036\n118: 04/06/2017 00:01:41: 179.165\n119: 04/06/2017 00:01:46: 179.15\n120: 04/06/2017 00:01:51: 179.166\n121: 04/06/2017 00:01:56: 178.968\n122: 04/06/2017 00:02:01: 179.047\n123: 04/06/2017 00:02:06: 179.07\n124: 04/06/2017 00:02:11: 178.982\n125: 04/06/2017 00:02:16: 178.999\n126: 04/06/2017 00:02:21: 179.058\n127: 04/06/2017 00:02:26: 179.01\n128: 04/06/2017 00:02:31: 179.011\n129: 04/06/2017 00:02:36: 179.102\n130: 04/06/2017 00:02:41: 179.06\n131: 04/06/2017 00:02:46: 179.031\n132: 04/06/2017 00:02:51: 178.957\n133: 04/06/2017 00:02:56: 179.048\n134: 04/06/2017 00:03:01: 179.094\n135: 04/06/2017 00:03:06: 178.995\n136: 04/06/2017 00:03:11: 191.198\n137: 04/06/2017 00:03:17: 704.403\n138: 04/06/2017 00:03:21: 192.723\n139: 04/06/2017 00:03:26: 178.985\n140: 04/06/2017 00:03:31: 179.047\n141: 04/06/2017 00:03:36: 178.952\n142: 04/06/2017 00:03:41: 179.088\n143: 04/06/2017 00:03:46: 179.017\n144: 04/06/2017 00:03:51: 189.98\n145: 04/06/2017 00:03:56: 179.025\n146: 04/06/2017 00:04:01: 179.096\n147: 04/06/2017 00:04:06: 178.975\n148: 04/06/2017 00:04:11: 179.036\n149: 04/06/2017 00:04:16: 181.081\n150: 04/06/2017 00:04:21: 179.038\n151: 04/06/2017 00:04:26: 179.093\n152: 04/06/2017 00:04:31: 179.72\n153: 04/06/2017 00:04:36: 179.044\n154: 04/06/2017 00:04:41: 181.69\n155: 04/06/2017 00:04:47: 179.009\n156: 04/06/2017 00:04:52: 179.046\n157: 04/06/2017 00:04:57: 179.185\n158: 04/06/2017 00:05:02: 178.964\n159: 04/06/2017 00:05:07: 189.831\n160: 04/06/2017 00:05:12: 179.078\n161: 04/06/2017 00:05:17: 179.146\n162: 04/06/2017 00:05:22: 179.052\n163: 04/06/2017 00:05:27: 179.078\n164: 04/06/2017 00:05:32: 179.166\n165: 04/06/2017 00:05:37: 179.125\n166: 04/06/2017 00:05:42: 197.553\n167: 04/06/2017 00:05:47: 179.176\n168: 04/06/2017 00:05:52: 179.023\n169: 04/06/2017 00:05:57: 178.999\n170: 04/06/2017 00:06:02: 179.053\n171: 04/06/2017 00:06:07: 179.082\n172: 04/06/2017 00:06:12: 180.644\n173: 04/06/2017 00:06:17: 179.066\n174: 04/06/2017 00:06:22: 179.106\n175: 04/06/2017 00:06:27: 179.079\n176: 04/06/2017 00:06:32: 179.093\n177: 04/06/2017 00:06:37: 179.099\n178: 04/06/2017 00:06:42: 179.079\n179: 04/06/2017 00:06:47: 179.098\n180: 04/06/2017 00:06:52: 184.171\n181: 04/06/2017 00:06:57: 196.305\n182: 04/06/2017 00:07:02: 178.989\n183: 04/06/2017 00:07:07: 716.029\n184: 04/06/2017 00:07:12: 179.046\n185: 04/06/2017 00:07:17: 185.988\n186: 04/06/2017 00:07:22: 183.382\n187: 04/06/2017 00:07:27: 178.95\n188: 04/06/2017 00:07:32: 178.982\n189: 04/06/2017 00:07:37: 179.116\n190: 04/06/2017 00:07:42: 179.072\n191: 04/06/2017 00:07:47: 179.051\n192: 04/06/2017 00:07:52: 179.118\n193: 04/06/2017 00:07:57: 180.089\n194: 04/06/2017 00:08:02: 179.077\n195: 04/06/2017 00:08:07: 179.02\n196: 04/06/2017 00:08:12: 179.178\n197: 04/06/2017 00:08:17: 627.686\n198: 04/06/2017 00:08:22: 188.879\n199: 04/06/2017 00:08:27: 179.071\n200: 04/06/2017 00:08:32: 179.076\n201: 04/06/2017 00:08:37: 179.143\n202: 04/06/2017 00:08:42: 187.486\n203: 04/06/2017 00:08:47: 179.131\n204: 04/06/2017 00:08:52: 179.117\n205: 04/06/2017 00:08:57: 183.852\n206: 04/06/2017 00:09:02: 189.089\n207: 04/06/2017 00:09:07: 179.084\n208: 04/06/2017 00:09:12: 179.11\n209: 04/06/2017 00:09:17: 179.074\n210: 04/06/2017 00:09:22: 203.129\n211: 04/06/2017 00:09:27: 179.517\n212: 04/06/2017 00:09:32: 179.04\n213: 04/06/2017 00:09:37: 179.05\n214: 04/06/2017 00:09:42: 179.142\n215: 04/06/2017 00:09:47: 184.147\n216: 04/06/2017 00:09:52: 186.064\n217: 04/06/2017 00:09:57: 179.076\n218: 04/06/2017 00:10:02: 179.145\n219: 04/06/2017 00:10:07: 180.744\n220: 04/06/2017 00:10:12: 179.125\n221: 04/06/2017 00:10:17: 179.121\n222: 04/06/2017 00:10:22: 178.964\n223: 04/06/2017 00:10:27: 179.09\n224: 04/06/2017 00:10:32: 179.05\n225: 04/06/2017 00:10:37: 179.086\n226: 04/06/2017 00:10:42: 179.062\n227: 04/06/2017 00:10:47: 179.07\n228: 04/06/2017 00:10:52: 179.071\n229: 04/06/2017 00:10:57: 179.079\n230: 04/06/2017 00:11:02: 179.164\n231: 04/06/2017 00:11:07: 183.415\n232: 04/06/2017 00:11:12: 179.151\n233: 04/06/2017 00:11:17: 178.957\n234: 04/06/2017 00:11:22: 179.135\n235: 04/06/2017 00:11:27: 179.023\n236: 04/06/2017 00:11:32: 179.271\n237: 04/06/2017 00:11:37: 184.602\n238: 04/06/2017 00:11:42: 188.117\n239: 04/06/2017 00:11:47: 179.016\n240: 04/06/2017 00:11:52: 180.396\n241: 04/06/2017 00:11:57: 179.673\n242: 04/06/2017 00:12:02: 179.04\n243: 04/06/2017 00:12:07: 182.56\n244: 04/06/2017 00:12:12: 181.491\n245: 04/06/2017 00:12:17: 185.674\n246: 04/06/2017 00:12:22: 179.031\n247: 04/06/2017 00:12:27: 179.076\n248: 04/06/2017 00:12:32: 178.971\n249: 04/06/2017 00:12:37: 181.512\n250: 04/06/2017 00:12:42: 179.112\n251: 04/06/2017 00:12:47: 187.029\n252: 04/06/2017 00:12:52: 179.076\n253: 04/06/2017 00:12:57: 192.696\n254: 04/06/2017 00:13:02: 207.165\n255: 04/06/2017 00:13:07: 178.987\n256: 04/06/2017 00:13:12: 246.511\n257: 04/06/2017 00:13:17: 368.072\n258: 04/06/2017 00:13:22: 179.013\n259: 04/06/2017 00:13:27: 179.052\n260: 04/06/2017 00:13:32: 179.118\n261: 04/06/2017 00:13:37: 181.83\n262: 04/06/2017 00:13:42: 179.055\n263: 04/06/2017 00:13:47: 179.565\n264: 04/06/2017 00:13:52: 179.062\n265: 04/06/2017 00:13:57: 179.059\n266: 04/06/2017 00:14:02: 178.97\n267: 04/06/2017 00:14:07: 179.068\n268: 04/06/2017 00:14:12: 179.04\n269: 04/06/2017 00:14:17: 179.232\n270: 04/06/2017 00:14:22: 179.056\n271: 04/06/2017 00:14:27: 179.148\n272: 04/06/2017 00:14:32: 179.068\n273: 04/06/2017 00:14:37: 178.953\n274: 04/06/2017 00:14:42: 178.952\n275: 04/06/2017 00:14:47: 179.044\n276: 04/06/2017 00:14:52: 179.03\n277: 04/06/2017 00:14:57: 179.099\n278: 04/06/2017 00:15:02: 179.06\n279: 04/06/2017 00:15:07: 179.059\n280: 04/06/2017 00:15:12: 179.041\n281: 04/06/2017 00:15:17: 179.235\n282: 04/06/2017 00:15:22: 179.077\n283: 04/06/2017 00:15:27: 179.458\n284: 04/06/2017 00:15:32: 179.036\n285: 04/06/2017 00:15:37: 179.073\n286: 04/06/2017 00:15:42: 179.205\n287: 04/06/2017 00:15:47: 178.98\n288: 04/06/2017 00:15:52: 182.483\n289: 04/06/2017 00:15:57: 179.016\n290: 04/06/2017 00:16:02: 193.341\n291: 04/06/2017 00:16:07: 180.653\n292: 04/06/2017 00:16:12: 180.242\n293: 04/06/2017 00:16:17: 182.025\n294: 04/06/2017 00:16:22: 180.385\n295: 04/06/2017 00:16:27: 179.11\n296: 04/06/2017 00:16:32: 179.193\n297: 04/06/2017 00:16:37: 179.831\n298: 04/06/2017 00:16:42: 179.902\n299: 04/06/2017 00:16:47: 180.632\n300: 04/06/2017 00:16:52: 181.196\n301: 04/06/2017 00:16:57: 191.315\n302: 04/06/2017 00:17:02: 200.782\n303: 04/06/2017 00:17:08: 1436.56\n304: 04/06/2017 00:17:12: 205.927\n305: 04/06/2017 00:17:18: 741.887\n306: 04/06/2017 00:17:22: 237.084\n307: 04/06/2017 00:17:27: 179.035\n308: 04/06/2017 00:17:32: 179.129\n309: 04/06/2017 00:17:37: 239.594\n310: 04/06/2017 00:17:42: 184.739\n311: 04/06/2017 00:17:47: 182.101\n312: 04/06/2017 00:17:52: 198.042\n313: 04/06/2017 00:17:57: 179.802\n314: 04/06/2017 00:18:02: 194.099\n315: 04/06/2017 00:18:07: 178.985\n316: 04/06/2017 00:18:12: 181.749\n317: 04/06/2017 00:18:17: 203.885\n318: 04/06/2017 00:18:22: 184.299\n319: 04/06/2017 00:18:27: 179.059\n320: 04/06/2017 00:18:32: 179.032\n321: 04/06/2017 00:18:37: 192.238\n322: 04/06/2017 00:18:42: 178.962\n323: 04/06/2017 00:18:47: 179.035\n324: 04/06/2017 00:18:52: 245.336\n325: 04/06/2017 00:18:57: 179.049\n326: 04/06/2017 00:19:02: 179.059\n327: 04/06/2017 00:19:07: 179.069\n328: 04/06/2017 00:19:12: 179.049\n329: 04/06/2017 00:19:18: 661.23\n330: 04/06/2017 00:19:22: 196.436\n331: 04/06/2017 00:19:27: 179.073\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
d02fb4eeffd1db8f842ec3a7d0a60016fc3e3537
225,270
ipynb
Jupyter Notebook
Topics of Deep Learning Lab/Lab-3/GNN.ipynb
Abhishek-Aditya-bs/Lab-Projects-and-Assignments
fd2681a1c7453367a4df1790e58afb312f13998c
[ "MIT" ]
null
null
null
Topics of Deep Learning Lab/Lab-3/GNN.ipynb
Abhishek-Aditya-bs/Lab-Projects-and-Assignments
fd2681a1c7453367a4df1790e58afb312f13998c
[ "MIT" ]
null
null
null
Topics of Deep Learning Lab/Lab-3/GNN.ipynb
Abhishek-Aditya-bs/Lab-Projects-and-Assignments
fd2681a1c7453367a4df1790e58afb312f13998c
[ "MIT" ]
null
null
null
162.767341
121,921
0.830448
[ [ [ "# GNN Implementation\n\n- Name: Abhishek Aditya BS\n- SRN: PES1UG19CS019\n- VI Semester 'A' Section\n- Date: 27-04-2022", "_____no_output_____" ] ], [ [ "import sys\nif 'google.colab' in sys.modules:\n %pip install -q stellargraph[demos]==1.2.1", "_____no_output_____" ], [ "import pandas as pd\nimport os\n", "_____no_output_____" ], [ "import stellargraph as sg\nfrom stellargraph.mapper import FullBatchNodeGenerator\nfrom stellargraph.layer import GCN", "_____no_output_____" ], [ "from tensorflow.keras import layers, optimizers, losses, metrics, Model\nfrom sklearn import preprocessing, model_selection\nfrom IPython.display import display, HTML\nimport matplotlib.pyplot as plt\n", "_____no_output_____" ], [ "dataset=sg.datasets.Cora()\ndisplay(HTML(dataset.description))\nG, node_subjects = dataset.load()", "_____no_output_____" ], [ "print(G.info())", "StellarGraph: Undirected multigraph\n Nodes: 2708, Edges: 5429\n\n Node types:\n paper: [2708]\n Features: float32 vector, length 1433\n Edge types: paper-cites->paper\n\n Edge types:\n paper-cites->paper: [5429]\n Weights: all 1 (default)\n Features: none\n" ], [ "node_subjects.value_counts().to_frame()", "_____no_output_____" ], [ "train_subjects, test_subjects = model_selection.train_test_split(node_subjects, train_size=140, test_size=None, stratify=node_subjects)\nval_subjects, test_subjects = model_selection.train_test_split(test_subjects, train_size=500, test_size=None, stratify=test_subjects)", "_____no_output_____" ], [ "train_subjects.value_counts().to_frame()", "_____no_output_____" ], [ "target_encoding=preprocessing.LabelBinarizer()", "_____no_output_____" ], [ "train_targets=target_encoding.fit_transform(train_subjects)\nval_targets=target_encoding.transform(val_subjects)\ntest_targets=target_encoding.transform(test_subjects)", "_____no_output_____" ], [ "from stellargraph.mapper.full_batch_generators import FullBatchGenerator\ngenerator = FullBatchNodeGenerator(G, method=\"gcn\")", "Using GCN (local pooling) filters...\n" ], [ "train_gen=generator.flow(train_subjects.index, train_targets)", "_____no_output_____" ], [ "gcn=GCN(layer_sizes=[16,16], activations=['relu', 'relu'], generator=generator, dropout=0.5)", "_____no_output_____" ], [ "x_inp, x_out = gcn.in_out_tensors()\nx_out", "_____no_output_____" ], [ "predictions=layers.Dense(units=train_targets.shape[1], activation=\"softmax\")(x_out)", "_____no_output_____" ], [ "model=Model(inputs=x_inp, outputs=predictions)\nmodel.compile(optimizer=optimizers.Adam(lr=0.01), loss=losses.categorical_crossentropy, metrics=[\"acc\"])", "/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/adam.py:105: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n super(Adam, self).__init__(name, **kwargs)\n" ], [ "val_gen = generator.flow(val_subjects.index, val_targets)", "_____no_output_____" ], [ "from tensorflow.keras.callbacks import EarlyStopping ", "_____no_output_____" ], [ "os_callback = EarlyStopping(monitor=\"val_acc\", patience=50, restore_best_weights=True)", "_____no_output_____" ], [ "history = model.fit(train_gen, epochs=200, validation_data=val_gen, verbose=2, shuffle=False, callbacks=[os_callback])", "Epoch 1/200\n1/1 - 1s - loss: 1.9483 - acc: 0.1357 - val_loss: 1.9074 - val_acc: 0.3040 - 1s/epoch - 1s/step\nEpoch 2/200\n1/1 - 0s - loss: 1.8903 - acc: 0.3500 - val_loss: 1.8605 - val_acc: 0.4040 - 89ms/epoch - 89ms/step\nEpoch 3/200\n1/1 - 0s - loss: 1.8179 - acc: 0.4571 - val_loss: 1.8018 - val_acc: 0.4680 - 96ms/epoch - 96ms/step\nEpoch 4/200\n1/1 - 0s - loss: 1.7500 - acc: 0.4571 - val_loss: 1.7377 - val_acc: 0.3960 - 84ms/epoch - 84ms/step\nEpoch 5/200\n1/1 - 0s - loss: 1.6773 - acc: 0.4429 - val_loss: 1.6712 - val_acc: 0.3700 - 84ms/epoch - 84ms/step\nEpoch 6/200\n1/1 - 0s - loss: 1.5647 - acc: 0.4143 - val_loss: 1.5990 - val_acc: 0.3760 - 84ms/epoch - 84ms/step\nEpoch 7/200\n1/1 - 0s - loss: 1.4856 - acc: 0.5071 - val_loss: 1.5159 - val_acc: 0.4200 - 89ms/epoch - 89ms/step\nEpoch 8/200\n1/1 - 0s - loss: 1.3913 - acc: 0.4786 - val_loss: 1.4307 - val_acc: 0.4860 - 88ms/epoch - 88ms/step\nEpoch 9/200\n1/1 - 0s - loss: 1.2517 - acc: 0.6000 - val_loss: 1.3499 - val_acc: 0.5480 - 97ms/epoch - 97ms/step\nEpoch 10/200\n1/1 - 0s - loss: 1.1596 - acc: 0.6143 - val_loss: 1.2785 - val_acc: 0.5840 - 89ms/epoch - 89ms/step\nEpoch 11/200\n1/1 - 0s - loss: 1.0817 - acc: 0.6571 - val_loss: 1.2145 - val_acc: 0.6100 - 87ms/epoch - 87ms/step\nEpoch 12/200\n1/1 - 0s - loss: 1.0354 - acc: 0.6929 - val_loss: 1.1537 - val_acc: 0.6380 - 95ms/epoch - 95ms/step\nEpoch 13/200\n1/1 - 0s - loss: 0.9270 - acc: 0.7214 - val_loss: 1.0977 - val_acc: 0.6520 - 89ms/epoch - 89ms/step\nEpoch 14/200\n1/1 - 0s - loss: 0.8728 - acc: 0.7071 - val_loss: 1.0487 - val_acc: 0.6660 - 90ms/epoch - 90ms/step\nEpoch 15/200\n1/1 - 0s - loss: 0.7716 - acc: 0.7786 - val_loss: 1.0043 - val_acc: 0.6840 - 91ms/epoch - 91ms/step\nEpoch 16/200\n1/1 - 0s - loss: 0.7007 - acc: 0.8143 - val_loss: 0.9627 - val_acc: 0.7020 - 90ms/epoch - 90ms/step\nEpoch 17/200\n1/1 - 0s - loss: 0.6841 - acc: 0.8071 - val_loss: 0.9252 - val_acc: 0.7220 - 130ms/epoch - 130ms/step\nEpoch 18/200\n1/1 - 0s - loss: 0.5838 - acc: 0.8500 - val_loss: 0.8922 - val_acc: 0.7320 - 135ms/epoch - 135ms/step\nEpoch 19/200\n1/1 - 0s - loss: 0.5390 - acc: 0.8643 - val_loss: 0.8629 - val_acc: 0.7340 - 97ms/epoch - 97ms/step\nEpoch 20/200\n1/1 - 0s - loss: 0.5334 - acc: 0.8643 - val_loss: 0.8366 - val_acc: 0.7500 - 84ms/epoch - 84ms/step\nEpoch 21/200\n1/1 - 0s - loss: 0.4836 - acc: 0.8643 - val_loss: 0.8128 - val_acc: 0.7780 - 83ms/epoch - 83ms/step\nEpoch 22/200\n1/1 - 0s - loss: 0.3883 - acc: 0.9214 - val_loss: 0.7950 - val_acc: 0.7780 - 86ms/epoch - 86ms/step\nEpoch 23/200\n1/1 - 0s - loss: 0.3951 - acc: 0.9071 - val_loss: 0.7843 - val_acc: 0.7720 - 84ms/epoch - 84ms/step\nEpoch 24/200\n1/1 - 0s - loss: 0.2895 - acc: 0.9286 - val_loss: 0.7784 - val_acc: 0.7660 - 83ms/epoch - 83ms/step\nEpoch 25/200\n1/1 - 0s - loss: 0.2545 - acc: 0.9786 - val_loss: 0.7725 - val_acc: 0.7740 - 83ms/epoch - 83ms/step\nEpoch 26/200\n1/1 - 0s - loss: 0.2735 - acc: 0.9357 - val_loss: 0.7678 - val_acc: 0.7820 - 93ms/epoch - 93ms/step\nEpoch 27/200\n1/1 - 0s - loss: 0.2675 - acc: 0.9500 - val_loss: 0.7623 - val_acc: 0.7860 - 83ms/epoch - 83ms/step\nEpoch 28/200\n1/1 - 0s - loss: 0.1899 - acc: 0.9714 - val_loss: 0.7564 - val_acc: 0.7840 - 89ms/epoch - 89ms/step\nEpoch 29/200\n1/1 - 0s - loss: 0.2176 - acc: 0.9500 - val_loss: 0.7520 - val_acc: 0.7820 - 86ms/epoch - 86ms/step\nEpoch 30/200\n1/1 - 0s - loss: 0.1386 - acc: 0.9857 - val_loss: 0.7509 - val_acc: 0.7900 - 89ms/epoch - 89ms/step\nEpoch 31/200\n1/1 - 0s - loss: 0.1627 - acc: 0.9714 - val_loss: 0.7539 - val_acc: 0.7920 - 89ms/epoch - 89ms/step\nEpoch 32/200\n1/1 - 0s - loss: 0.1246 - acc: 0.9786 - val_loss: 0.7596 - val_acc: 0.7880 - 91ms/epoch - 91ms/step\nEpoch 33/200\n1/1 - 0s - loss: 0.1223 - acc: 0.9714 - val_loss: 0.7650 - val_acc: 0.7900 - 84ms/epoch - 84ms/step\nEpoch 34/200\n1/1 - 0s - loss: 0.1741 - acc: 0.9571 - val_loss: 0.7690 - val_acc: 0.7920 - 90ms/epoch - 90ms/step\nEpoch 35/200\n1/1 - 0s - loss: 0.1168 - acc: 0.9714 - val_loss: 0.7731 - val_acc: 0.7900 - 89ms/epoch - 89ms/step\nEpoch 36/200\n1/1 - 0s - loss: 0.0982 - acc: 0.9857 - val_loss: 0.7785 - val_acc: 0.7860 - 88ms/epoch - 88ms/step\nEpoch 37/200\n1/1 - 0s - loss: 0.1039 - acc: 0.9571 - val_loss: 0.7864 - val_acc: 0.7880 - 94ms/epoch - 94ms/step\nEpoch 38/200\n1/1 - 0s - loss: 0.0934 - acc: 0.9857 - val_loss: 0.7985 - val_acc: 0.7840 - 89ms/epoch - 89ms/step\nEpoch 39/200\n1/1 - 0s - loss: 0.1115 - acc: 0.9500 - val_loss: 0.8190 - val_acc: 0.7900 - 103ms/epoch - 103ms/step\nEpoch 40/200\n1/1 - 0s - loss: 0.0944 - acc: 0.9643 - val_loss: 0.8443 - val_acc: 0.7800 - 169ms/epoch - 169ms/step\nEpoch 41/200\n1/1 - 0s - loss: 0.0980 - acc: 0.9786 - val_loss: 0.8673 - val_acc: 0.7800 - 141ms/epoch - 141ms/step\nEpoch 42/200\n1/1 - 0s - loss: 0.1040 - acc: 0.9643 - val_loss: 0.8863 - val_acc: 0.7780 - 143ms/epoch - 143ms/step\nEpoch 43/200\n1/1 - 0s - loss: 0.1166 - acc: 0.9429 - val_loss: 0.8887 - val_acc: 0.7780 - 127ms/epoch - 127ms/step\nEpoch 44/200\n1/1 - 0s - loss: 0.0772 - acc: 0.9857 - val_loss: 0.8880 - val_acc: 0.7860 - 142ms/epoch - 142ms/step\nEpoch 45/200\n1/1 - 0s - loss: 0.0727 - acc: 0.9786 - val_loss: 0.8871 - val_acc: 0.7900 - 152ms/epoch - 152ms/step\nEpoch 46/200\n1/1 - 0s - loss: 0.0744 - acc: 0.9714 - val_loss: 0.8875 - val_acc: 0.7920 - 175ms/epoch - 175ms/step\nEpoch 47/200\n1/1 - 0s - loss: 0.0713 - acc: 0.9786 - val_loss: 0.8850 - val_acc: 0.7900 - 160ms/epoch - 160ms/step\nEpoch 48/200\n1/1 - 0s - loss: 0.0575 - acc: 0.9857 - val_loss: 0.8844 - val_acc: 0.7920 - 206ms/epoch - 206ms/step\nEpoch 49/200\n1/1 - 0s - loss: 0.0379 - acc: 1.0000 - val_loss: 0.8849 - val_acc: 0.7860 - 160ms/epoch - 160ms/step\nEpoch 50/200\n1/1 - 0s - loss: 0.0639 - acc: 0.9786 - val_loss: 0.8867 - val_acc: 0.7900 - 175ms/epoch - 175ms/step\nEpoch 51/200\n1/1 - 0s - loss: 0.0628 - acc: 0.9929 - val_loss: 0.8902 - val_acc: 0.7900 - 187ms/epoch - 187ms/step\nEpoch 52/200\n1/1 - 0s - loss: 0.0439 - acc: 0.9857 - val_loss: 0.8918 - val_acc: 0.7900 - 145ms/epoch - 145ms/step\nEpoch 53/200\n1/1 - 0s - loss: 0.0482 - acc: 0.9857 - val_loss: 0.8947 - val_acc: 0.7980 - 194ms/epoch - 194ms/step\nEpoch 54/200\n1/1 - 0s - loss: 0.0739 - acc: 0.9786 - val_loss: 0.9012 - val_acc: 0.8020 - 146ms/epoch - 146ms/step\nEpoch 55/200\n1/1 - 0s - loss: 0.0518 - acc: 0.9857 - val_loss: 0.9109 - val_acc: 0.7980 - 205ms/epoch - 205ms/step\nEpoch 56/200\n1/1 - 0s - loss: 0.0529 - acc: 0.9929 - val_loss: 0.9211 - val_acc: 0.7940 - 154ms/epoch - 154ms/step\nEpoch 57/200\n1/1 - 0s - loss: 0.0668 - acc: 0.9786 - val_loss: 0.9239 - val_acc: 0.7940 - 208ms/epoch - 208ms/step\nEpoch 58/200\n1/1 - 0s - loss: 0.0509 - acc: 0.9714 - val_loss: 0.9246 - val_acc: 0.8040 - 177ms/epoch - 177ms/step\nEpoch 59/200\n1/1 - 0s - loss: 0.0357 - acc: 0.9929 - val_loss: 0.9250 - val_acc: 0.7960 - 165ms/epoch - 165ms/step\nEpoch 60/200\n1/1 - 0s - loss: 0.0328 - acc: 0.9929 - val_loss: 0.9266 - val_acc: 0.8020 - 148ms/epoch - 148ms/step\nEpoch 61/200\n1/1 - 0s - loss: 0.0341 - acc: 0.9929 - val_loss: 0.9302 - val_acc: 0.7940 - 178ms/epoch - 178ms/step\nEpoch 62/200\n1/1 - 0s - loss: 0.0317 - acc: 1.0000 - val_loss: 0.9356 - val_acc: 0.7960 - 164ms/epoch - 164ms/step\nEpoch 63/200\n1/1 - 0s - loss: 0.0603 - acc: 0.9857 - val_loss: 0.9448 - val_acc: 0.7940 - 151ms/epoch - 151ms/step\nEpoch 64/200\n1/1 - 0s - loss: 0.0299 - acc: 0.9929 - val_loss: 0.9549 - val_acc: 0.7920 - 189ms/epoch - 189ms/step\nEpoch 65/200\n1/1 - 0s - loss: 0.0229 - acc: 0.9929 - val_loss: 0.9652 - val_acc: 0.7920 - 128ms/epoch - 128ms/step\nEpoch 66/200\n1/1 - 0s - loss: 0.0511 - acc: 0.9857 - val_loss: 0.9723 - val_acc: 0.7920 - 240ms/epoch - 240ms/step\nEpoch 67/200\n1/1 - 0s - loss: 0.0293 - acc: 0.9929 - val_loss: 0.9784 - val_acc: 0.7920 - 136ms/epoch - 136ms/step\nEpoch 68/200\n1/1 - 0s - loss: 0.0440 - acc: 0.9857 - val_loss: 0.9829 - val_acc: 0.7920 - 190ms/epoch - 190ms/step\nEpoch 69/200\n1/1 - 0s - loss: 0.0254 - acc: 1.0000 - val_loss: 0.9886 - val_acc: 0.7960 - 183ms/epoch - 183ms/step\nEpoch 70/200\n1/1 - 0s - loss: 0.0577 - acc: 0.9786 - val_loss: 0.9961 - val_acc: 0.7960 - 127ms/epoch - 127ms/step\nEpoch 71/200\n1/1 - 0s - loss: 0.0480 - acc: 0.9929 - val_loss: 1.0013 - val_acc: 0.7940 - 248ms/epoch - 248ms/step\nEpoch 72/200\n1/1 - 0s - loss: 0.0169 - acc: 1.0000 - val_loss: 1.0058 - val_acc: 0.7980 - 134ms/epoch - 134ms/step\nEpoch 73/200\n1/1 - 0s - loss: 0.0355 - acc: 0.9929 - val_loss: 1.0119 - val_acc: 0.7980 - 204ms/epoch - 204ms/step\nEpoch 74/200\n1/1 - 0s - loss: 0.0170 - acc: 0.9929 - val_loss: 1.0228 - val_acc: 0.7880 - 144ms/epoch - 144ms/step\nEpoch 75/200\n1/1 - 0s - loss: 0.0152 - acc: 0.9929 - val_loss: 1.0343 - val_acc: 0.7880 - 161ms/epoch - 161ms/step\nEpoch 76/200\n1/1 - 0s - loss: 0.0096 - acc: 1.0000 - val_loss: 1.0466 - val_acc: 0.7880 - 286ms/epoch - 286ms/step\nEpoch 77/200\n1/1 - 0s - loss: 0.0688 - acc: 0.9857 - val_loss: 1.0527 - val_acc: 0.7880 - 142ms/epoch - 142ms/step\nEpoch 78/200\n1/1 - 0s - loss: 0.0309 - acc: 0.9929 - val_loss: 1.0560 - val_acc: 0.7880 - 217ms/epoch - 217ms/step\nEpoch 79/200\n1/1 - 0s - loss: 0.0513 - acc: 0.9786 - val_loss: 1.0571 - val_acc: 0.7880 - 224ms/epoch - 224ms/step\nEpoch 80/200\n1/1 - 0s - loss: 0.0295 - acc: 0.9929 - val_loss: 1.0582 - val_acc: 0.7860 - 186ms/epoch - 186ms/step\nEpoch 81/200\n1/1 - 0s - loss: 0.0318 - acc: 0.9857 - val_loss: 1.0589 - val_acc: 0.7860 - 267ms/epoch - 267ms/step\nEpoch 82/200\n1/1 - 0s - loss: 0.0233 - acc: 1.0000 - val_loss: 1.0573 - val_acc: 0.7880 - 242ms/epoch - 242ms/step\nEpoch 83/200\n1/1 - 0s - loss: 0.0239 - acc: 0.9929 - val_loss: 1.0557 - val_acc: 0.7900 - 172ms/epoch - 172ms/step\nEpoch 84/200\n1/1 - 0s - loss: 0.0181 - acc: 1.0000 - val_loss: 1.0536 - val_acc: 0.7860 - 210ms/epoch - 210ms/step\nEpoch 85/200\n1/1 - 0s - loss: 0.0217 - acc: 0.9929 - val_loss: 1.0547 - val_acc: 0.7860 - 180ms/epoch - 180ms/step\nEpoch 86/200\n1/1 - 0s - loss: 0.0281 - acc: 0.9929 - val_loss: 1.0528 - val_acc: 0.7860 - 247ms/epoch - 247ms/step\nEpoch 87/200\n1/1 - 0s - loss: 0.0204 - acc: 1.0000 - val_loss: 1.0528 - val_acc: 0.7860 - 142ms/epoch - 142ms/step\nEpoch 88/200\n1/1 - 0s - loss: 0.0337 - acc: 0.9857 - val_loss: 1.0550 - val_acc: 0.7880 - 145ms/epoch - 145ms/step\nEpoch 89/200\n1/1 - 0s - loss: 0.0293 - acc: 0.9857 - val_loss: 1.0552 - val_acc: 0.7900 - 258ms/epoch - 258ms/step\nEpoch 90/200\n1/1 - 0s - loss: 0.0243 - acc: 0.9929 - val_loss: 1.0575 - val_acc: 0.7900 - 155ms/epoch - 155ms/step\nEpoch 91/200\n1/1 - 0s - loss: 0.0172 - acc: 1.0000 - val_loss: 1.0607 - val_acc: 0.7940 - 132ms/epoch - 132ms/step\nEpoch 92/200\n1/1 - 0s - loss: 0.0195 - acc: 0.9929 - val_loss: 1.0646 - val_acc: 0.7920 - 190ms/epoch - 190ms/step\nEpoch 93/200\n1/1 - 0s - loss: 0.0229 - acc: 1.0000 - val_loss: 1.0692 - val_acc: 0.7880 - 166ms/epoch - 166ms/step\nEpoch 94/200\n1/1 - 0s - loss: 0.0316 - acc: 0.9929 - val_loss: 1.0748 - val_acc: 0.7840 - 139ms/epoch - 139ms/step\nEpoch 95/200\n1/1 - 0s - loss: 0.0205 - acc: 0.9929 - val_loss: 1.0833 - val_acc: 0.7840 - 144ms/epoch - 144ms/step\nEpoch 96/200\n1/1 - 0s - loss: 0.0331 - acc: 0.9857 - val_loss: 1.0911 - val_acc: 0.7820 - 211ms/epoch - 211ms/step\nEpoch 97/200\n1/1 - 0s - loss: 0.0216 - acc: 1.0000 - val_loss: 1.0974 - val_acc: 0.7780 - 126ms/epoch - 126ms/step\nEpoch 98/200\n1/1 - 0s - loss: 0.0209 - acc: 1.0000 - val_loss: 1.1007 - val_acc: 0.7800 - 317ms/epoch - 317ms/step\nEpoch 99/200\n1/1 - 0s - loss: 0.0134 - acc: 1.0000 - val_loss: 1.1021 - val_acc: 0.7800 - 150ms/epoch - 150ms/step\nEpoch 100/200\n1/1 - 0s - loss: 0.0194 - acc: 1.0000 - val_loss: 1.1042 - val_acc: 0.7800 - 157ms/epoch - 157ms/step\nEpoch 101/200\n1/1 - 0s - loss: 0.0130 - acc: 1.0000 - val_loss: 1.1088 - val_acc: 0.7820 - 148ms/epoch - 148ms/step\nEpoch 102/200\n1/1 - 0s - loss: 0.0214 - acc: 1.0000 - val_loss: 1.1142 - val_acc: 0.7820 - 192ms/epoch - 192ms/step\nEpoch 103/200\n1/1 - 0s - loss: 0.0253 - acc: 0.9929 - val_loss: 1.1189 - val_acc: 0.7840 - 216ms/epoch - 216ms/step\nEpoch 104/200\n1/1 - 0s - loss: 0.0079 - acc: 1.0000 - val_loss: 1.1239 - val_acc: 0.7880 - 157ms/epoch - 157ms/step\nEpoch 105/200\n1/1 - 0s - loss: 0.0347 - acc: 0.9857 - val_loss: 1.1276 - val_acc: 0.7760 - 145ms/epoch - 145ms/step\nEpoch 106/200\n1/1 - 0s - loss: 0.0209 - acc: 1.0000 - val_loss: 1.1307 - val_acc: 0.7760 - 290ms/epoch - 290ms/step\nEpoch 107/200\n1/1 - 0s - loss: 0.0147 - acc: 0.9929 - val_loss: 1.1318 - val_acc: 0.7780 - 159ms/epoch - 159ms/step\nEpoch 108/200\n1/1 - 0s - loss: 0.0118 - acc: 1.0000 - val_loss: 1.1343 - val_acc: 0.7800 - 229ms/epoch - 229ms/step\n" ], [ "sg.utils.plot_history(history)", "_____no_output_____" ], [ "test_gen=generator.flow(test_subjects.index, test_targets)", "_____no_output_____" ], [ "all_nodes=node_subjects.index\nall_gen=generator.flow(all_nodes)\nall_predictions=model.predict(all_gen)", "_____no_output_____" ], [ "node_predictions=target_encoding.inverse_transform(all_predictions.squeeze())", "_____no_output_____" ], [ "df=pd.DataFrame({\"Predicted\":node_predictions, \"True\":node_subjects})\ndf.head(20)", "_____no_output_____" ], [ "embedding_model=Model(inputs=x_inp, outputs=x_out)\nemb=embedding_model.predict(all_gen)\nemb.shape", "_____no_output_____" ], [ "from sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nX=emb.squeeze(0)\nX.shape", "_____no_output_____" ], [ "transform = TSNE\ntrans=transform(n_components=2)\nX_reduced=trans.fit_transform(X)\nX_reduced.shape", "/usr/local/lib/python3.7/dist-packages/sklearn/manifold/_t_sne.py:783: FutureWarning: The default initialization in TSNE will change from 'random' to 'pca' in 1.2.\n FutureWarning,\n/usr/local/lib/python3.7/dist-packages/sklearn/manifold/_t_sne.py:793: FutureWarning: The default learning rate in TSNE will change from 200.0 to 'auto' in 1.2.\n FutureWarning,\n" ], [ "fig, ax = plt.subplots(figsize=(7, 7))\nax.scatter(\n X_reduced[:, 0],\n X_reduced[:, 1],\n c=node_subjects.astype(\"category\").cat.codes,\n cmap=\"jet\",\n alpha=0.7,\n)\nax.set(\n aspect=\"equal\",\n xlabel=\"$X_1$\",\n ylabel=\"$X_2$\",\n title=f\"{transform.__name__} visualization of GCN embeddings for cora dataset\",\n)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d02fb6cc4c36450f697673507ece4f54c1c9a7a0
2,923
ipynb
Jupyter Notebook
abe0/ignore_process_csv.ipynb
awsm-research/gpt2sp
59b741674197889703cb2ab22179acc90ea0f402
[ "MIT" ]
null
null
null
abe0/ignore_process_csv.ipynb
awsm-research/gpt2sp
59b741674197889703cb2ab22179acc90ea0f402
[ "MIT" ]
null
null
null
abe0/ignore_process_csv.ipynb
awsm-research/gpt2sp
59b741674197889703cb2ab22179acc90ea0f402
[ "MIT" ]
1
2022-03-15T01:29:58.000Z
2022-03-15T01:29:58.000Z
30.134021
169
0.48375
[ [ [ "### Within repo", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ntrain_file = [\"mesos\", \"usergrid\", \"appceleratorstudio\", \"appceleratorstudio\", \"titanium\", \"aptanastudio\", \"mule\", \"mulestudio\"]\ntest_file = [\"usergrid\", \"mesos\", \"aptanastudio\", \"titanium\", \"appceleratorstudio\", \"titanium\", \"mulestudio\", \"mule\"]\nmae = [1.07, 1.14, 2.75, 1.99, 2.85, 3.41, 3.14, 2.31]\n\ndf_gpt = pd.DataFrame(data={\"group\": [\"Within Repository\" for i in range(8)],\n \"approach\": [\"Deep-SE\" for i in range(8)],\n \"train_file\": train_file,\n \"test_file\": test_file,\n \"mae\": mae})\n\ndf = pd.read_csv(\"./within_repo_abe0.csv\")\ndf = df.append(df_gpt)\ndf.to_csv(\"./within_repo_abe0.csv\", index=False)", "_____no_output_____" ] ], [ [ "### Cross repo", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ntrain_file = [\"clover\", \"talendesb\", \"talenddataquality\", \"mule\", \"talenddataquality\", \"mulestudio\", \"appceleratorstudio\", \"appceleratorstudio\"]\ntest_file = [\"usergrid\", \"mesos\", \"aptanastudio\", \"titanium\", \"appceleratorstudio\", \"titanium\", \"mulestudio\", \"mule\"]\nmae = [1.57, 2.08, 5.37, 6.36, 5.55, 2.67, 4.24, 2.7]\n\ndf = pd.read_csv(\"./cross_repo_abe0.csv\")\ndf_gpt = pd.DataFrame(data={\"group\": [\"Cross Repository\" for i in range(8)],\n \"approach\": [\"Deep-SE\" for i in range(8)],\n \"train_file\": train_file,\n \"test_file\": test_file,\n \"mae\": mae})\ndf = df.append(df_gpt)\ndf.to_csv(\"./cross_repo_abe0.csv\", index=False)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d02fbf2b229b52d29efd751cce80a41cf7331a2f
7,199
ipynb
Jupyter Notebook
puzzle_notebooks/puzzle5.ipynb
fromdatavistodatascience/adventofcode2019
21d4650fb4b2073ba2bc10e640c7774ccf4e9ba9
[ "MIT" ]
null
null
null
puzzle_notebooks/puzzle5.ipynb
fromdatavistodatascience/adventofcode2019
21d4650fb4b2073ba2bc10e640c7774ccf4e9ba9
[ "MIT" ]
null
null
null
puzzle_notebooks/puzzle5.ipynb
fromdatavistodatascience/adventofcode2019
21d4650fb4b2073ba2bc10e640c7774ccf4e9ba9
[ "MIT" ]
null
null
null
28.56746
131
0.536324
[ [ [ "# Solution to puzzle number 5", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "data = pd.read_csv('../inputs/puzzle5_input.csv')", "_____no_output_____" ], [ "data = [val for val in data.columns]", "_____no_output_____" ], [ "data[:10]", "_____no_output_____" ] ], [ [ "## Part 5.1", "_____no_output_____" ], [ "### After providing 1 to the only input instruction and passing all the tests, what diagnostic code does the program produce?", "_____no_output_____" ], [ "More Rules:\n - Opcode 3 takes a single integer as input and saves it to the position given by its only parameter.\n - Opcode 4 outputs the value of its only parameter.\n \nFunctions now need to support the parameter mode 1 (Immediate mode):\n - Immediate mode\n - In immediate mode, a parameter is interpreted as a value - if the parameter is 50, its value is 50.", "_____no_output_____" ] ], [ [ "user_ID = 1", "_____no_output_____" ], [ "numbers = 1002,4,3,4,33", "_____no_output_____" ], [ "def opcode_instructions(intcode):\n \"Function that breaks the opcode instructions into pieces\"\n str_intcode = str(intcode)\n opcode = str_intcode[-2:]\n int_opcode = int(opcode)\n return int_opcode", "_____no_output_____" ], [ "def extract_p_modes(intcode):\n \"Function that extracts the p_modes\"\n str_p_modes = str(intcode)\n p_modes_dic = {}\n for n, val in enumerate(str_p_modes[:-2]):\n p_modes_dic[f'p_mode_{n+1}'] = val\n return p_modes_dic", "_____no_output_____" ], [ "def opcode_1(i, new_numbers, p_modes):\n \"Function that adds together numbers read from two positions and stores the result in a third position\"\n second_item = new_numbers[i+1]\n third_item = new_numbers[i+2]\n position_item = new_numbers[i+3]\n if (p_modes[0] == 0) & (p_modes[1] == 0):\n sum_of_second_and_third = new_numbers[second_item] + new_numbers[third_item]\n elif (p_modes[0] == 1) & (p_modes[1] == 0):\n sum_of_second_and_third = second_item + new_numbers[third_item]\n elif (p_modes[0] == 0) & (p_modes[1] == 1):\n sum_of_second_and_third = new_numbers[second_item] + third_item\n else:\n sum_of_second_and_third = second_item + third_item\n new_numbers[position_item] = sum_of_second_and_third\n return new_numbers", "_____no_output_____" ], [ "def opcode_2(i, new_numbers, p_modes):\n \"Function that multiplies together numbers read from two positions and stores the result in a third position\"\n second_item = new_numbers[i+1]\n third_item = new_numbers[i+2]\n position_item = new_numbers[i+3]\n if (p_modes[0] == 0) & (p_modes[1] == 0):\n m_of_second_and_third = new_numbers[second_item] * new_numbers[third_item]\n elif (p_modes[0] == 1) & (p_modes[1] == 0):\n m_of_second_and_third = second_item * new_numbers[third_item]\n elif (p_modes[0] == 0) & (p_modes[1] == 1):\n m_of_second_and_third = new_numbers[second_item] * third_item\n else:\n m_of_second_and_third = second_item * third_item\n new_numbers[position_item] = m_of_second_and_third\n return new_numbers", "_____no_output_____" ], [ "def opcode_3(i, new_numbers, inpt):\n \"Function takes a single integer as input and saves it to the position given by its only parameter\"\n val = input_value\n second_item = new_numbers[i+1]\n new_numbers[second_item] = val\n return new_numbers", "_____no_output_____" ], [ "# from puzzle n2 copy the intcode function\n\ndef modifiedintcodefunction(numbers, input_value):\n \"Function that similates that of an Intcode program but takes into account extra information.\"\n new_numbers = [num for num in numbers]\n i = 0\n output_values = []\n while i < len(new_numbers):\n opcode = opcode_instructions(new_numbers[i])\n p_modes = extract_p_modes(new_numbers[i])\n if new_numbers[i] == 1:\n new_numbers = opcode_1(i, new_numbers, p_modes)\n i = i + 4\n elif new_numbers[i] == 2:\n new_numbers = opcode_2(i, new_numbers, p_modes)\n i = i + 4\n elif new_numbers[i] == 3:\n new_numbers = opcode_3(i, new_numbers, inpt)\n i = i + 2\n elif new_numbers[i] == 4:\n output_values.append(new_numbers[i+1])\n i = i + 2\n elif new_numbers[i] == 99:\n break\n else:\n continue\n #Return the first item after the code has run.\n first_item = new_numbers[0]\n return first_item", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d02fd7407f42d310c9b48aceb94b58431c3a24f5
932,954
ipynb
Jupyter Notebook
state_of_union_main.ipynb
gequitz/State_of_The_Union_Analysis_NLP
af206afe20fb8ba2a5cce43fa5863c1d674fa0df
[ "MIT" ]
null
null
null
state_of_union_main.ipynb
gequitz/State_of_The_Union_Analysis_NLP
af206afe20fb8ba2a5cce43fa5863c1d674fa0df
[ "MIT" ]
null
null
null
state_of_union_main.ipynb
gequitz/State_of_The_Union_Analysis_NLP
af206afe20fb8ba2a5cce43fa5863c1d674fa0df
[ "MIT" ]
null
null
null
201.938095
271,812
0.855123
[ [ [ "import nltk\nfrom nltk.corpus import state_union\n\n\nimport pandas as pd\nimport os\n\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer \n\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import NMF\n#from sklearn.metrics.pairwise import cosine_similarity\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport pickle\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer", "_____no_output_____" ], [ "\n\n#path = 'state-of-the-union-corpus-1989-2017'\n#path = 'c:\\\\Users\\\\gabri\\\\AppData\\\\Roaming\\\\nltk_data\\\\corpora\\\\state_union' # file location\npath = 'c:\\\\Users\\\\gabri\\\\OneDrive\\\\Documents\\\\Metis_NLP_Kaggle\\\\Speeches\\\\sotu' # file location\ndirs = os.listdir(path) # reads all the files in that directory\nprint (len(dirs)) #tell how many files", "228\n" ], [ "dirs[:] # file names", "_____no_output_____" ] ], [ [ "# Selecting the first speech to see what we need to clean.", "_____no_output_____" ] ], [ [ "filename = os.path.join(path, dirs[0]) # dirs is a list, and we are going to study the first element dirs[0]\ntext_file = open(filename, 'r') #open the first file dirs[0]", "_____no_output_____" ], [ "lines = text_file.read() # read the file", "_____no_output_____" ], [ "lines # print what is in the file", "_____no_output_____" ], [ "lines.replace('\\n', ' ') # remove the \\n symbols by replacing with an empty space\n#print (lines)", "_____no_output_____" ], [ "sotu_data = [] #create an empty list\nsotu_dict = {} # create an empty dictionary so that we can use file names to list the speeches by name", "_____no_output_____" ] ], [ [ "# Putting all the speeches into a list, after cleaning them", "_____no_output_____" ] ], [ [ "#The filter() function returns an iterator were the items are filtered\n#through a function to test if the item is accepted or not.\n\n# str.isalpha : checks if it is an alpha character.\n\n# lower() : transform everything to lower case\n\n# split() : Split a string into a list where each word is a list item\n\n# loop over all the files:\nfor i in range(len(dirs)): # loop on all the speeches, dirs is the list of speeches\n filename = os.path.join(path, dirs[i]) # location of the speeches \n text_file = open(filename, 'r') # read the speeches \n \n lines = text_file.read() #read the speeches\n lines = lines.replace('\\n', ' ') #replace \\n by an empty string\n \n # tranform the speeches in lower cases, split them into a list and then filter to accept only alpha characters\n # finally it joins the words with an empty space\n clean_lines = ' '.join(filter(str.isalpha, lines.lower().split())) \n #print(clean_lines)\n \n sotu_data.append(clean_lines) # append the clean speeches to the sotu_data list.\n sotu_dict[filename] = clean_lines # store in dict so we can access clean_lines by filename.\n ", "_____no_output_____" ], [ "sotu_data[10] #11th speech/element", "_____no_output_____" ], [ "\nspeech_name = 'Wilson_1919.txt'\nsotu_dict[path + '\\\\' + speech_name]\n", "_____no_output_____" ] ], [ [ "# Count Vectorize", "_____no_output_____" ] ], [ [ "#from notebook\n#vectorizer = CountVectorizer(stop_words='english') #remove stop words: a, the, and, etc.\nvectorizer = TfidfVectorizer(stop_words='english', max_df = 0.42, min_df = 0.01) #remove stop words: a, the, and, etc.\n\ndoc_word = vectorizer.fit_transform(sotu_data) #transform into sparse matrix (0, 1, 2, etc. for instance(s) in document)\npairwise_similarity = doc_word * doc_word.T\ndoc_word.shape # 228 = number of documents, 20932 = # of unique words)\n#pairwise_similarity.toarray()", "_____no_output_____" ] ], [ [ "# Compare how similar speeches are to one another", "_____no_output_____" ] ], [ [ "df_similarity = pd.DataFrame(pairwise_similarity.toarray(), index = dirs, columns = dirs) \n\ndf_similarity.head() #similarity dataframe, compares each document to eachother", "_____no_output_____" ], [ "df_similarity.to_pickle(\"df_similarity.pkl\") #pickle file", "_____no_output_____" ], [ "df_similarity['Speech_str'] = dirs #matrix comparing speech similarity\n\ndf_similarity['Year'] =df_similarity['Speech_str'].replace('[^0-9]', '', regex=True)\ndf_similarity.drop(['Speech_str'], axis=1)\ndf_similarity = df_similarity.sort_values(by=['Year'])\ndf_similarity.head()", "_____no_output_____" ], [ "plt.subplots(2, 2, figsize=(30, 15), sharex=True) #4 speeches similarity\n#\n\nplt.rcParams.update({'font.size': 20})\n\nplt.subplot(2, 2, 1)\nplt.plot(df_similarity['Year'], df_similarity['Adams_1797.txt'])\nplt.title(\"Similarity for Adams 1797 speech\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Similarity\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\n\nplt.subplot(2, 2, 2)\nplt.plot(df_similarity['Year'], df_similarity['Roosevelt_1945.txt'])\nplt.title(\"Similarity for Roosevelt 1945 speech\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Similarity\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\nplt.subplot(2, 2, 3)\nplt.plot(df_similarity['Year'], df_similarity['Obama_2014.txt'])\nplt.title(\"Similarity for Obama 2014 speech\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Similarity\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\n\nplt.subplot(2, 2, 4)\nplt.plot(df_similarity['Year'], df_similarity['Trump_2018.txt'])\nplt.title(\"Similarity for Trump 2018 speech\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Similarity\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\nplt.subplots_adjust(top=0.90, bottom=0.02, wspace=0.30, hspace=0.3)\n#sns.set() \nplt.show()", "_____no_output_____" ], [ "#(sotu_dict.keys())\n#for i in range(0,len(dirs)):\n# print(dirs[i])", "_____no_output_____" ] ], [ [ "# Transforming the doc into a dataframe", "_____no_output_____" ] ], [ [ "# We have to convert `.toarray()` because the vectorizer returns a sparse matrix.\n# For a big corpus, we would skip the dataframe and keep the output sparse.\n#pd.DataFrame(doc_word.toarray(), index=sotu_data, columns=vectorizer.get_feature_names()).head(10) #doc_word.toarray() makes 7x19 table, otherwise it would be \n#represented in 2 columns\n\n#from notebook\npd.DataFrame(doc_word.toarray(), index=dirs, columns=vectorizer.get_feature_names()).head(95) #doc_word.toarray() makes 7x19 table, otherwise it would be \n#represented in 2 columns", "_____no_output_____" ] ], [ [ "# Topic Modeling using nmf", "_____no_output_____" ] ], [ [ "n_topics = 8 # number of topics\nnmf_model = NMF(n_topics) # create an object\ndoc_topic = nmf_model.fit_transform(doc_word) #break into 10 components like SVD", "_____no_output_____" ], [ "topic_word = pd.DataFrame(nmf_model.components_.round(3), #,\"component_9\",\"component_10\",\"component_11\",\"component_12\"\n index = [\"component_1\",\"component_2\",\"component_3\",\"component_4\",\"component_5\",\"component_6\",\"component_7\",\"component_8\"],\n columns = vectorizer.get_feature_names()) #8 components in final draft\ntopic_word", "_____no_output_____" ], [ "#https://stackoverflow.com/questions/16486252/is-it-possible-to-use-argsort-in-descending-order/16486299\n#list the top words for each Component:\ndef print_top_words(model, feature_names, n_top_words):\n for topic_idx, topic in enumerate(model.components_): # loop over the model components\n print(\"Component_\" + \"%d:\" % topic_idx ) # print the component \n # join the top words by an empty space\n # argsort : sorts the list in increasing order, meaning the top are the last words\n # then select the top words\n # -1 loops backwards\n # reading from the tail to find the largest elements\n print(\" \".join([feature_names[i]\n for i in topic.argsort()[:-n_top_words - 1:-1]])) \n print()", "_____no_output_____" ] ], [ [ "# Top 15 words in each component", "_____no_output_____" ] ], [ [ "n_top_words = 15 \nfeature_names = vectorizer.get_feature_names()\nprint_top_words(nmf_model, feature_names, n_top_words)", "Component_0:\nsilver gold cent bonds products postal diplomatic consular notes spain indians currency coinage tariff spanish\nComponent_1:\njobs tonight budget families businesses cut child parents job deficit thank percent spending college nuclear\nComponent_2:\nprogram programs billion farm major budget housing today achieve assistance basic areas insurance inflation wage\nComponent_3:\nspain tribes objects france french militia article ports gentlemen execution navigation commissioners colonies ensuing respecting\nComponent_4:\ninterstate industrial tariff corporations court forest conference method islands agriculture canal methods bureau board panama\nComponent_5:\nsoviet communist fighting japanese threat weapons rulers fight atomic aggression peoples planes task allies win\nComponent_6:\nmexico texas mexican bank paper specie currency banks whilst notes territorial consequence slavery california kansas\nComponent_7:\niraqi terrorists iraq al terrorist qaeda iraqis saddam fight women terror workers tonight weapons middle\n\n" ], [ "#Component x Speech\n\nH = pd.DataFrame(doc_topic.round(5), index=dirs, #,\"component_9\",\"component_10\" \n columns = [\"component_1\",\"component_2\", \"component_3\",\"component_4\",\"component_5\",\"component_6\",\"component_7\",\"component_8\"])", "_____no_output_____" ], [ "H.head()", "_____no_output_____" ], [ "H.iloc[30:35]", "_____no_output_____" ], [ "H.iloc[60:70]", "_____no_output_____" ], [ "H.iloc[225:230]", "_____no_output_____" ] ], [ [ "# Use NMF to plot top 15 words for each of 8 components", "_____no_output_____" ], [ "def plot_top_words(model, feature_names, n_top_words, title):\n fig, axes = plt.subplots(2, 4, figsize=(30, 15), sharex=True)\n axes = axes.flatten()\n for topic_idx, topic in enumerate(model.components_):\n top_features_ind = topic.argsort()[:-n_top_words - 1:-1]\n top_features = [feature_names[i] for i in top_features_ind]\n weights = topic[top_features_ind]\n\n ax = axes[topic_idx]\n ax.barh(top_features, weights, height=0.7)\n ax.set_title(f'Topic {topic_idx +1}',\n fontdict={'fontsize': 30})\n ax.invert_yaxis()\n ax.tick_params(axis='both', which='major', labelsize=20)\n for i in 'top right left'.split():\n ax.spines[i].set_visible(False)\n fig.suptitle(title, fontsize=40)\n\n plt.subplots_adjust(top=0.90, bottom=0.05, wspace=0.90, hspace=0.3)\n plt.show()\n", "_____no_output_____" ] ], [ [ "n_top_words = 12\nfeature_names = vectorizer.get_feature_names()\nplot_top_words(nmf_model, feature_names, n_top_words,\n 'Topics in NMF model') #title\n", "_____no_output_____" ] ], [ [ "# Sort speeches Chronologically", "_____no_output_____" ] ], [ [ "H1 = H\nH1['Speech_str'] = dirs\nH1['Year'] = H1['Speech_str'].replace('[^0-9]', '', regex=True)\nH1 = H1.sort_values(by = ['Year'])\nH1.to_csv(\"Data_H1.csv\", index = False) #Save chronologically sorted speeches in this csv\nH1.head()", "_____no_output_____" ], [ "H1.to_pickle(\"H1.pkl\") #pickle chronological csv file", "_____no_output_____" ] ], [ [ "# Plots of Components over Time (check Powerpoint/Readme for more insights)", "_____no_output_____" ] ], [ [ "plt.subplots(4, 2, figsize=(30, 15), sharex=True)\n\nplt.rcParams.update({'font.size': 20})\n\n\nplt.subplot(4, 2, 1)\nplt.plot(H1['Year'], H1['component_1'] ) #Label axis and titles for all plots\nplt.title(\"19th Century Economic Terms\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_1\")\n\n\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\n\n\nplt.subplot(4, 2, 2)\nplt.plot(H1['Year'], H1['component_2'])\nplt.title(\"Modern Economic Language\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_2\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\nplt.subplot(4, 2, 3)\nplt.plot(H1['Year'], H1['component_3'])\nplt.title(\"Growth of US Gov't & Programs\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_3\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\nplt.subplot(4, 2, 4)\nplt.plot(H1['Year'], H1['component_4'])\nplt.title(\"Early Foreign Policy & War\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_4\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\nplt.subplot(4, 2, 5)\nplt.plot(H1['Year'], H1['component_5'])\nplt.title(\"Progressive Era & Roaring 20s\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_5\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\nplt.subplot(4, 2, 6)\nplt.plot(H1['Year'], H1['component_6'])\nplt.title(\"Before, During, After the Civil War\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_6\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\nplt.subplot(4, 2, 7)\nplt.plot(H1['Year'], H1['component_7'])\nplt.title(\"World War & Cold War\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_7\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\n\nplt.subplot(4, 2, 8)\nplt.plot(H1['Year'], H1['component_8'])\nplt.title(\"Iraq War & Terrorism\")\nplt.xlabel(\"Year\")\nplt.ylabel(\"Component_8\")\nplt.axhline(y=0.0, color='k', linestyle='-')\n\nplt.xticks(['1800', '1850','1900','1950','2000']) # Set label locations.\n\nplt.subplots_adjust(top=0.90, bottom=0.02, wspace=0.30, hspace=0.4)\n\nplt.show()", "_____no_output_____" ] ], [ [ "## Component 1: 19th Century Economics", "_____no_output_____" ] ], [ [ "H1.iloc[75:85] #Starts 1831. Peak starts 1868 (apex=1894), Nosedive in 1901 w/ Teddy. 4 Yr resurgence under Taft (1909-1912)", "_____no_output_____" ] ], [ [ "## Component 2: Modern Economic Language", "_____no_output_____" ] ], [ [ "H1.iloc[205:215] #1960s: Starts under JFK in 1961, peaks w/ Clinton, dips post 9/11 Bush, resurgence under Obama", "_____no_output_____" ] ], [ [ "## Component 3: Growth of US Government and Federal Programs", "_____no_output_____" ] ], [ [ "H1.iloc[155:165] #1921, 1929-1935. Big peak in 1946-1950 (1951 Cold War). 1954-1961 Eisenhower. Low after Reagan Revolution (1984)", "_____no_output_____" ] ], [ [ "## Component 4: Early Foreign Policy and War", "_____no_output_____" ] ], [ [ "H1.iloc[30:40] #Highest from 1790-1830, Washington to Jackson", "_____no_output_____" ] ], [ [ "## Component 5: Progressive Era, Roaring 20s", "_____no_output_____" ] ], [ [ "H1.iloc[115:125] #Peaks in 1900-1930.Especially Teddy Roosevelt. Dip around WW1", "_____no_output_____" ] ], [ [ "## Component 6: War Before, During, and After the Civil War", "_____no_output_____" ] ], [ [ "H1.iloc[70:80] #Starts w/ Jackson 1829, Peaks w/ Mexican-American War (1846-1848). Drops 60% w/ Lincoln. Peak ends w/ Johnson 1868. Remains pretty low after 1876 (Reconstruction ends)", "_____no_output_____" ] ], [ [ "## Component 7: World Wars and Korean War", "_____no_output_____" ] ], [ [ "H1.iloc[155:165] #Minor Peak around WW1. Masssive spike a response of Cold War, Korean War (1951). Eisenhower drops (except 1960 U2). Johnson Vietnam. Peaks again 1980 (Jimmy Carter foreign policy crises)", "_____no_output_____" ] ], [ [ "## Component 8: Iraq War and Terrorism", "_____no_output_____" ] ], [ [ "H1.iloc[210:220] #Minor peak w/ Bush 1990. BIG peak w/ Bush 2002. Ends w/ Obama 2009. Resurgence in 2016/18 (ISIS?)", "_____no_output_____" ] ], [ [ "# Word Cloud", "_____no_output_____" ] ], [ [ "from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator", "_____no_output_____" ], [ "speech_name = 'Lincoln_1864.txt'\nsotu_dict[path + '\\\\' + speech_name]\n#example = sotu_data[0]\nexample = sotu_dict[path + '\\\\' + speech_name]\nwordcloud = WordCloud(max_words=100).generate(example)\nplt.title(\"WordCloud of \" + speech_name)\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d02ff3e5af9bb39ff4f53dc0dbfb0dc23d3ed70a
529,952
ipynb
Jupyter Notebook
jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb
ljk233/R249
791d28361c1ed58c7e9f977c04add799618199e3
[ "MIT" ]
null
null
null
jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb
ljk233/R249
791d28361c1ed58c7e9f977c04add799618199e3
[ "MIT" ]
null
null
null
jupyter/2_time_series/2_03_ljk_decompose_seasonal.ipynb
ljk233/R249
791d28361c1ed58c7e9f977c04add799618199e3
[ "MIT" ]
null
null
null
205.806602
10,010
0.667974
[ [ [ "# Average Monthly Temperatures, 1970-2004\n\n**Date:** 2021-12-02\n\n**Reference:**", "_____no_output_____" ] ], [ [ "library(TTR)", "_____no_output_____" ], [ "options(\n jupyter.plot_mimetypes = \"image/svg+xml\",\n repr.plot.width = 7,\n repr.plot.height = 5\n)", "_____no_output_____" ] ], [ [ "## Summary\n\nThe aim of this notebook was to show how to decompose seasonal time series data using **R** so the trend, seasonal and irregular components can be estimated.\nData on the average monthly temperatures in central England from January 1970 to December 2004 was plotted.\nThe series was decomposed using the `decompose` function from `R.stats` and the seasonal factors displayed as a `matrix`.\nA seasonally adjusted series was calculated by subtracting the seasonal factors from the original series.\nThe seasonally adjusted series was used to plot an estimate of the trend component by taking a simple moving average.\nThe irregular component was estimated by subtracting the estimate of the trend and seasonal components from the original time series.", "_____no_output_____" ], [ "## Get the data\n\nData on the average monthly temperatures in central England January 1970 to December 2004 is shown below.", "_____no_output_____" ] ], [ [ "monthlytemps <- read.csv(\"..\\\\..\\\\data\\\\moderntemps.csv\")\nhead(monthlytemps)", "_____no_output_____" ], [ "modtemps <- monthlytemps$temperature", "_____no_output_____" ] ], [ [ "## Plot the time series", "_____no_output_____" ] ], [ [ "ts_modtemps <- ts(modtemps, start = c(1970, 1), frequency = 12)\nplot.ts(ts_modtemps, xlab = \"year\", ylab = \"temperature\")", "_____no_output_____" ] ], [ [ "The time series is highly seasonal with little evidence of a trend.\nThere appears to be a constant level of approximately 10$^{\\circ}$C.", "_____no_output_____" ], [ "## Decompose the data\n\nUse the `decompose` function from `R.stats` to return estimates of the trend, seasonal, and irregular components of the time series.", "_____no_output_____" ] ], [ [ "decomp_ts <- decompose(ts_modtemps)", "_____no_output_____" ] ], [ [ "## Seasonal factors\n\nCalculate the seasonal factors of the decomposed time series.\nCast the `seasonal` time series object held in `decomp_ts` to a `vector`, slice the new vector to isolate a single period, and then cast the sliced vector to a named `matrix`.", "_____no_output_____" ] ], [ [ "sf <- as.vector(decomp_ts$seasonal)\n(matrix(sf[1:12], dimnames = list(month.abb, c(\"factors\"))))", "_____no_output_____" ] ], [ [ "_Add a comment_", "_____no_output_____" ], [ "## Plot the components\n\nPlot the trend, seasonal, and irregular components in a single graphic.", "_____no_output_____" ] ], [ [ "plot(decomp_ts, xlab = \"year\")", "_____no_output_____" ] ], [ [ "Plot the individual components of the decomposition by accessing the variables held in the `tsdecomp`.\nThis will generally make the components easier to understand.", "_____no_output_____" ] ], [ [ "plot(decomp_ts$trend, xlab = \"year\", ylab = \"temperature (Celsius)\")\ntitle(main = \"Trend component\")", "_____no_output_____" ], [ "plot(decomp_ts$seasonal, xlab = \"year\", ylab = \"temperature (Celsius)\")\ntitle(main = \"Seasonal component\")", "_____no_output_____" ], [ "plot(decomp_ts$random, xlab = \"year\", ylab = \"temperature (Celsius)\")\ntitle(main = \"Irregular component\")", "_____no_output_____" ] ], [ [ "_Add comment on trend, seasonal, and irregular components._\n\n_Which component dominates the series?_", "_____no_output_____" ], [ "## Seasonal adjusted plot\n\nPlot the seasonally adjusted series by subtracting the seasonal factors from the original series.", "_____no_output_____" ] ], [ [ "adjusted_ts <- ts_modtemps - decomp_ts$seasonal\nplot(adjusted_ts, xlab = \"year\", ylab = \"temperature (Celsius)\")\ntitle(main = \"Seasonally adjusted series\")", "_____no_output_____" ] ], [ [ "This new seasonally adjusted series only contains the trend and irregular components, so it can be treated as if it is non-seasonal data.\nEstimate the trend component by taking the simple moving order of order 35.", "_____no_output_____" ] ], [ [ "sma35_adjusted_ts <- SMA(adjusted_ts, n = 35)\nplot.ts(sma35_adjusted_ts, xlab = \"year\", ylab = \"temperature (Celsius)\")\ntitle(main = \"Trend component (ma35)\")", "_____no_output_____" ] ], [ [ "Note that this is a different estimate of the trend component to what is contained in `decomp_ts`, as it uses a different order for the simple moving average.", "_____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", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d02ff3f8c715d09afb75b304b3d08059bfa6f139
463,202
ipynb
Jupyter Notebook
code/Group07_Review_Sentiment_Analysis.ipynb
toshalpatel/AirbnbPricingStrategyAnalysis
e1af232f99686496f252e60e6f483ceae53e7091
[ "MIT" ]
null
null
null
code/Group07_Review_Sentiment_Analysis.ipynb
toshalpatel/AirbnbPricingStrategyAnalysis
e1af232f99686496f252e60e6f483ceae53e7091
[ "MIT" ]
null
null
null
code/Group07_Review_Sentiment_Analysis.ipynb
toshalpatel/AirbnbPricingStrategyAnalysis
e1af232f99686496f252e60e6f483ceae53e7091
[ "MIT" ]
null
null
null
334.441877
300,088
0.91048
[ [ [ "import pandas as pd\nimport numpy as np\nimport math\nfrom pprint import pprint\nimport pandas as pd\nimport numpy as np\nimport nltk\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nnltk.download('vader_lexicon')\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nstop_words = stopwords.words('english')\nfrom nltk.tokenize import word_tokenize, RegexpTokenizer\ntokenizer = RegexpTokenizer(r'\\w+')\nimport datetime as dt\nfrom langdetect import detect", "[nltk_data] Downloading package vader_lexicon to\n[nltk_data] /Users/sonakshimendiratta/nltk_data...\n[nltk_data] Package vader_lexicon is already up-to-date!\n[nltk_data] Downloading package stopwords to\n[nltk_data] /Users/sonakshimendiratta/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "# detects the language of the comment\ndef language_detection(text):\n try:\n return detect(text)\n except:\n return None", "_____no_output_____" ], [ "raw_data = pd.read_csv(\"/IS5126airbnb_reviews_full.csv\",low_memory = False)", "_____no_output_____" ], [ "raw_data.head()", "_____no_output_____" ], [ "raw_data_filtered= raw_data[['listing_id','id','comments']]", "_____no_output_____" ], [ "raw_data_filtered.dtypes", "_____no_output_____" ], [ "# group by hosts and count the number of unique listings --> cast it to a dataframe\nreviews_per_listing = pd.DataFrame(raw_data.groupby('listing_id')['id'].nunique())\n\n# sort unique values descending and show the Top20\nreviews_per_listing.sort_values(by=['id'], ascending=False, inplace=True)\nreviews_per_listing.head(20)", "_____no_output_____" ], [ "def language_detection(text):\n try:\n return detect(text)\n except:\n return None", "_____no_output_____" ], [ "raw_data_filtered['language'] = raw_data_filtered['comments'].apply(language_detection)", "_____no_output_____" ], [ "raw_data_filtered.language.value_counts().head(10)", "_____no_output_____" ], [ "# visualizing the comments' languages a) quick and dirty\nax = raw_data_filtered.language.value_counts(normalize=True).head(6).sort_values().plot(kind='barh', figsize=(9,5));", "_____no_output_____" ], [ "df_eng = raw_data_filtered[(raw_data_filtered['language']=='en')]", "_____no_output_____" ], [ "# import necessary libraries\nfrom nltk.corpus import stopwords\nfrom wordcloud import WordCloud\nfrom collections import Counter\nfrom PIL import Image\n\nimport re\nimport string", "_____no_output_____" ], [ "def plot_wordcloud(wordcloud, language):\n plt.figure(figsize=(12, 10))\n plt.imshow(wordcloud, interpolation = 'bilinear')\n plt.axis(\"off\")\n plt.title('Word Cloud for Comments\\n', fontsize=18, fontweight='bold')\n plt.show()", "_____no_output_____" ], [ "wordcloud = WordCloud(max_font_size=None, max_words=200, background_color=\"lightgrey\", \n width=3000, height=2000,\n stopwords=stopwords.words('english')).generate(str(raw_data_filtered.comments.values))\n\nplot_wordcloud(wordcloud, 'English')", "_____no_output_____" ], [ "# load the SentimentIntensityAnalyser object in\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n# assign it to another name to make it easier to use\nanalyzer = SentimentIntensityAnalyzer()\n# use the polarity_scores() method to get the sentiment metrics\ndef print_sentiment_scores(sentence):\n snt = analyzer.polarity_scores(sentence)\n print(\"{:-<40} {}\".format(sentence, str(snt)))", "_____no_output_____" ], [ "# getting only the negative score\ndef negative_score(text):\n negative_value = analyzer.polarity_scores(str(text))['neg']\n return negative_value\n\n# getting only the neutral score\ndef neutral_score(text):\n neutral_value = analyzer.polarity_scores(str(text))['neu']\n return neutral_value\n\n# getting only the positive score\ndef positive_score(text):\n positive_value = analyzer.polarity_scores(str(text))['pos']\n return positive_value\n\n# getting only the compound score\ndef compound_score(text):\n compound_value = analyzer.polarity_scores(str(text))['compound']\n return compound_value", "_____no_output_____" ], [ "raw_data_filtered['sentiment_neg'] = raw_data_filtered['comments'].apply(negative_score)\nraw_data_filtered['sentiment_neu'] = raw_data_filtered['comments'].apply(neutral_score)\nraw_data_filtered['sentiment_pos'] = raw_data_filtered['comments'].apply(positive_score)\nraw_data_filtered['sentiment_compound'] = raw_data_filtered['comments'].apply(compound_score)", "_____no_output_____" ], [ "# all scores in 4 histograms\nfig, axes = plt.subplots(2, 2, figsize=(10,8))\n\n# plot all 4 histograms\ndf_eng.hist('sentiment_neg', bins=25, ax=axes[0,0], color='lightcoral', alpha=0.6)\naxes[0,0].set_title('Negative Sentiment Score')\ndf_eng.hist('sentiment_neu', bins=25, ax=axes[0,1], color='lightsteelblue', alpha=0.6)\naxes[0,1].set_title('Neutral Sentiment Score')\ndf_eng.hist('sentiment_pos', bins=25, ax=axes[1,0], color='chartreuse', alpha=0.6)\naxes[1,0].set_title('Positive Sentiment Score')\ndf_eng.hist('sentiment_compound', bins=25, ax=axes[1,1], color='navajowhite', alpha=0.6)\naxes[1,1].set_title('Compound')\n\n# plot common x- and y-label\nfig.text(0.5, 0.04, 'Sentiment Scores', fontweight='bold', ha='center')\nfig.text(0.04, 0.5, 'Number of Reviews', fontweight='bold', va='center', rotation='vertical')\n\n# plot title\nplt.suptitle('Sentiment Analysis of Airbnb Reviews for Singapore\\n\\n', fontsize=12, fontweight='bold');", "_____no_output_____" ], [ "percentiles = df_eng.sentiment_compound.describe(percentiles=[.05, .1, .2, .3, .4, .5, .6, .7, .8, .9])\npercentiles", "_____no_output_____" ], [ "# assign the data\nneg = percentiles['10%']\nmid = percentiles['30%']\npos = percentiles['max']\nnames = ['Negative Comments', 'Okayish Comments','Positive Comments']\nsize = [neg, mid, pos]\n\n# call a pie chart\nplt.pie(size, labels=names, colors=['lightcoral', 'lightsteelblue', 'chartreuse'], \n autopct='%.5f%%', pctdistance=0.8,\n wedgeprops={'linewidth':7, 'edgecolor':'white' })\n\n# create circle for the center of the plot to make the pie look like a donut\nmy_circle = plt.Circle((0,0), 0.6, color='white')\n\n# plot the donut chart\nfig = plt.gcf()\nfig.set_size_inches(7,7)\nfig.gca().add_artist(my_circle)\nplt.show()", "_____no_output_____" ], [ "df_eng.head()", "_____no_output_____" ], [ "pd.set_option(\"max_colwidth\", 1000)", "_____no_output_____" ], [ "df_neu = df_eng.loc[df_eng.sentiment_compound <= 0.5]", "_____no_output_____" ], [ "# full dataframe with POSITIVE comments\ndf_pos = df_eng.loc[df_eng.sentiment_compound >= 0.95]\n\n# only corpus of POSITIVE comments\npos_comments = df_pos['comments'].tolist()", "_____no_output_____" ], [ "# full dataframe with NEGATIVE comments\ndf_neg = df_eng.loc[df_eng.sentiment_compound < 0.0]\n\n# only corpus of NEGATIVE comments\nneg_comments = df_neg['comments'].tolist()", "_____no_output_____" ], [ "df_pos['text_length'] = df_pos['comments'].apply(len)\ndf_neg['text_length'] = df_neg['comments'].apply(len)\n\nsns.set_style(\"whitegrid\")\nplt.figure(figsize=(8,5))\n\nsns.distplot(df_pos['text_length'], kde=True, bins=50, color='chartreuse')\nsns.distplot(df_neg['text_length'], kde=True, bins=50, color='lightcoral')\n\nplt.title('\\nDistribution Plot for Length of Comments\\n')\nplt.legend(['Positive Comments', 'Negative Comments'])\nplt.xlabel('\\nText Length')\nplt.ylabel('Percentage of Comments\\n');", "/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \"\"\"Entry point for launching an IPython kernel.\n/opt/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n \n" ], [ "df_eng.head()", "_____no_output_____" ], [ "merged_reviews = pd.merge(left=df_eng, right=raw_data, left_on='id', right_on='id')", "_____no_output_____" ], [ "merged_reviews.head()", "_____no_output_____" ], [ "merged_reviews.drop(['id', 'comments_x', 'language', 'listing_id_y','reviewer_id','reviewer_name','comments_y'], inplace=True, axis=1)", "_____no_output_____" ], [ "merged_reviews['month'] = pd.to_datetime(merged_reviews['date']).dt.month\nmerged_reviews['year'] = pd.to_datetime(merged_reviews['date']).dt.year\nsummary_reviews=merged_reviews.groupby(['year','month','listing_id_x'],as_index=False).mean()", "_____no_output_____" ], [ "summary_reviews['time_period']=summary_reviews['month'].astype(str)+'-'+summary_reviews['year'].astype(str)", "_____no_output_____" ], [ "summary_reviews.head()", "_____no_output_____" ], [ "summary_reviews.to_csv('/Users/sonakshimendiratta/Documents/NUS/YR 2 SEM 2/IS5126/Final Project/data/review_sentiments.csv')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d02ff510a38b377551b3c9e6dd8f79e20df5a8a0
74,755
ipynb
Jupyter Notebook
pyschools/analysis2.ipynb
tri-bui/sandbox-analytics
9aa3ea1c721fe8240c6c50f3a22a8ab5d1a444a7
[ "MIT" ]
null
null
null
pyschools/analysis2.ipynb
tri-bui/sandbox-analytics
9aa3ea1c721fe8240c6c50f3a22a8ab5d1a444a7
[ "MIT" ]
null
null
null
pyschools/analysis2.ipynb
tri-bui/sandbox-analytics
9aa3ea1c721fe8240c6c50f3a22a8ab5d1a444a7
[ "MIT" ]
null
null
null
32.488049
169
0.361742
[ [ [ "# PySchools without Thomas High School 9th graders", "_____no_output_____" ], [ "### Dependencies and data", "_____no_output_____" ] ], [ [ "# Dependencies\nimport os\nimport numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "# School data\nschool_path = os.path.join('data', 'schools.csv') # school data path\nschool_df = pd.read_csv(school_path)\n\n# Student data\nstudent_path = os.path.join('data', 'students.csv') # student data path\nstudent_df = pd.read_csv(student_path)\n\nschool_df.shape, student_df.shape", "_____no_output_____" ], [ "# Change Thomas High School 9th grade scores to NaN\nstudent_df.loc[(student_df['school_name'].str.contains('Thomas')) & (student_df['grade'] == '9th'), \n ['reading_score', 'math_score']] = np.NaN\nstudent_df.loc[(student_df['school_name'].str.contains('Thomas')) & (student_df['grade'] == '9th'), \n ['reading_score', 'math_score']].head(3)", "_____no_output_____" ] ], [ [ "### Clean student names", "_____no_output_____" ] ], [ [ "# Prefixes to remove: \"Miss \", \"Dr. \", \"Mr. \", \"Ms. \", \"Mrs. \"\n# Suffixes to remove: \" MD\", \" DDS\", \" DVM\", \" PhD\"\nfixes_to_remove = ['Miss ', '\\w+\\. ', ' [DMP]\\w?[DMS]'] # regex for prefixes and suffixes\nstr_to_remove = r'|'.join(fixes_to_remove) # join into a single raw str\n\n# Remove inappropriate prefixes and suffixes\nstudent_df['student_name'] = student_df['student_name'].str.replace(str_to_remove, '', regex=True)", "_____no_output_____" ], [ "# Check prefixes and suffixes\nstudent_names = [n.split() for n in student_df['student_name'].tolist() if len(n.split()) > 2]\npre = list(set([name[0] for name in student_names if len(name[0]) <= 4])) # prefixes\nsuf = list(set([name[-1] for name in student_names if len(name[-1]) <= 4])) # suffixes\nprint(pre, suf)", "['Juan', 'Noah', 'Cory', 'Omar', 'Eric', 'Ryan', 'Sean', 'Jon', 'Cody', 'Todd', 'Erik', 'Greg', 'Adam', 'Seth', 'Tony', 'Mark'] ['V', 'IV', 'Jr.', 'III', 'II']\n" ] ], [ [ "### Merge data", "_____no_output_____" ] ], [ [ "# Add binary vars for passing score\nstudent_df['pass_read'] = (student_df.reading_score >= 70).astype(int) # passing reading score\nstudent_df['pass_math'] = (student_df.math_score >= 70).astype(int) # passing math score\nstudent_df['pass_both'] = np.min([student_df.pass_read, student_df.pass_math], axis=0) # passing both scores\nstudent_df.head(3)", "_____no_output_____" ], [ "# Add budget per student var\nschool_df['budget_per_student'] = (school_df['budget'] / school_df['size']).round().astype(int)\n\n# Bin budget per student\nschool_df['spending_lvl'] = pd.qcut(school_df['budget_per_student'], 4, \n labels=range(1, 5))\n\n# Bin school size\nschool_df['school_size'] = pd.qcut(school_df['size'], 3, labels=['Small', 'Medium', 'Large'])\n\nschool_df", "_____no_output_____" ], [ "# Merge data\ndf = pd.merge(student_df, school_df, on='school_name', how='left')\ndf.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 39170 entries, 0 to 39169\nData columns (total 17 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Student ID 39170 non-null int64 \n 1 student_name 39170 non-null object \n 2 gender 39170 non-null object \n 3 grade 39170 non-null object \n 4 school_name 39170 non-null object \n 5 reading_score 38709 non-null float64 \n 6 math_score 38709 non-null float64 \n 7 pass_read 39170 non-null int64 \n 8 pass_math 39170 non-null int64 \n 9 pass_both 39170 non-null int64 \n 10 School ID 39170 non-null int64 \n 11 type 39170 non-null object \n 12 size 39170 non-null int64 \n 13 budget 39170 non-null int64 \n 14 budget_per_student 39170 non-null int64 \n 15 spending_lvl 39170 non-null category\n 16 school_size 39170 non-null category\ndtypes: category(2), float64(2), int64(8), object(5)\nmemory usage: 4.9+ MB\n" ] ], [ [ "### District summary", "_____no_output_____" ] ], [ [ "# District summary\ndistrict_summary = pd.DataFrame(school_df[['size', 'budget']].sum(), columns=['District']).T\ndistrict_summary['Total Schools'] = school_df.shape[0]\ndistrict_summary = district_summary[['Total Schools', 'size', 'budget']]\ndistrict_summary_cols = ['Total Schools', 'Total Students', 'Total Budget']\ndistrict_summary", "_____no_output_____" ], [ "# Score cols\nscore_cols = ['reading_score', 'math_score', 'pass_read', 'pass_math', 'pass_both']\nscore_cols_new = ['Average Reading Score', 'Average Math Score', '% Passing Reading', '% Passing Math', '% Passing Overall']\n\n# Add scores to district summary\nfor col, val in df[score_cols].mean().items():\n if 'pass' in col:\n val *= 100\n district_summary[col] = val\n \ndistrict_summary", "_____no_output_____" ], [ "# Rename cols\ndistrict_summary.columns = district_summary_cols + score_cols_new\ndistrict_summary\n\n# Format columns\nfor col in district_summary.columns:\n if 'Total' in col:\n district_summary[col] = district_summary[col].apply('{:,}'.format)\n if 'Average' in col:\n district_summary[col] = district_summary[col].round(2)\n if '%' in col:\n district_summary[col] = district_summary[col].round().astype(int)\n \ndistrict_summary", "_____no_output_____" ] ], [ [ "### School summary", "_____no_output_____" ] ], [ [ "# School cols\nschool_cols = ['type', 'size', 'budget', 'budget_per_student', \n 'reading_score', 'math_score', 'pass_read', 'pass_math', 'pass_both']\nschool_cols_new = ['School Type', 'Total Students', 'Total Budget', 'Budget Per Student']\nschool_cols_new += score_cols_new\n\n# School summary\nschool_summary = df.groupby('school_name')[school_cols].agg({\n 'type': 'max',\n 'size': 'max',\n 'budget': 'max',\n 'budget_per_student': 'max',\n 'reading_score': 'mean',\n 'math_score': 'mean',\n 'pass_read': 'mean',\n 'pass_math': 'mean',\n 'pass_both': 'mean'\n})\nschool_summary.head(3)", "_____no_output_____" ], [ "# Rename cols\nschool_summary.index.name = None\nschool_summary.columns = school_cols_new\n\n# Format values\nfor col in school_summary.columns:\n if 'Total' in col:\n school_summary[col] = school_summary[col].apply('{:,}'.format)\n if 'Average' in col:\n school_summary[col] = school_summary[col].round(2)\n if '%' in col:\n school_summary[col] = (school_summary[col] * 100).round().astype(int)\n \nschool_summary", "_____no_output_____" ] ], [ [ "### Scores by grade", "_____no_output_____" ] ], [ [ "# Reading scores by grade of each school\ngrade_read_scores = pd.pivot_table(df, index='school_name', columns='grade', \n values='reading_score', aggfunc='mean').round(2)\ngrade_read_scores.index.name = None\ngrade_read_scores.columns.name = 'Reading scores'\ngrade_read_scores = grade_read_scores[['9th', '10th', '11th', '12th']]\ngrade_read_scores", "_____no_output_____" ], [ "# Math scores by grade of each school\ngrade_math_scores = pd.pivot_table(df, index='school_name', columns='grade', \n values='math_score', aggfunc='mean').round(2)\ngrade_math_scores.index.name = None\ngrade_math_scores.columns.name = 'Math Scores'\ngrade_math_scores = grade_math_scores[['9th', '10th', '11th', '12th']]\ngrade_math_scores", "_____no_output_____" ] ], [ [ "### Scores by budget per student", "_____no_output_____" ] ], [ [ "# Scores by spending\nspending_scores = df.groupby('spending_lvl')[score_cols].mean().round(2)\nfor col in spending_scores.columns:\n if \"pass\" in col:\n spending_scores[col] = (spending_scores[col] * 100).astype(int)\nspending_scores", "_____no_output_____" ], [ "# Formatting\nspending_scores.index.name = 'Spending Level'\nspending_scores.columns = score_cols_new\nspending_scores", "_____no_output_____" ] ], [ [ "### Scores by school size", "_____no_output_____" ] ], [ [ "# Scores by school size\nsize_scores = df.groupby('school_size')[score_cols].mean().round(2)\nfor col in size_scores.columns:\n if \"pass\" in col:\n size_scores[col] = (size_scores[col] * 100).astype(int)\nsize_scores", "_____no_output_____" ], [ "# Formatting\nsize_scores.index.name = 'School Size'\nsize_scores.columns = score_cols_new\nsize_scores", "_____no_output_____" ] ], [ [ "### Scores by school type", "_____no_output_____" ] ], [ [ "# Scores by school type\ntype_scores = df.groupby('type')[score_cols].mean().round(2)\nfor col in type_scores.columns:\n if \"pass\" in col:\n type_scores[col] = (type_scores[col] * 100).astype(int)\ntype_scores", "_____no_output_____" ], [ "# Formatting\ntype_scores.index.name = 'School Type'\ntype_scores.columns = score_cols_new\ntype_scores", "_____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" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d02ff66bd7fe6868ba5dd9e31ae7e45244dfd98f
2,461
ipynb
Jupyter Notebook
resources/whales/tasks/task5.ipynb
pknut/minerva
365df730ca8abd07f15b833f471d6a5eed4cf0a1
[ "MIT" ]
19
2018-05-25T03:51:14.000Z
2021-12-27T12:43:47.000Z
resources/whales/tasks/task5.ipynb
pknut/minerva
365df730ca8abd07f15b833f471d6a5eed4cf0a1
[ "MIT" ]
37
2017-12-21T12:17:29.000Z
2018-03-29T10:49:44.000Z
resources/whales/tasks/task5.ipynb
pknut/minerva
365df730ca8abd07f15b833f471d6a5eed4cf0a1
[ "MIT" ]
5
2017-12-12T10:39:01.000Z
2018-03-09T07:26:58.000Z
26.180851
143
0.588379
[ [ [ "# Instructions\n\nImplement multi output cross entropy loss in pytorch.\n\nThroughout this whole problem we use multioutput models:\n* predicting 4 localization coordinates\n* predicting 4 keypoint coordinates + whale id and callosity pattern\n* predicting whale id and callosity pattern\n\nIn order for that to work your loss function needs to cooperate.\nRemember that for the simple single output models the following function will work:\n\n```python\nimport torch.nn.functional as F\nsingle_output_loss = F.nll_loss(output, target)\n```\n", "_____no_output_____" ], [ "# Your Solution\nYour solution function should be called solution. In this case we leave it for consistency but you don't need to do anything with it. \n\nCONFIG is a dictionary with all parameters that you want to pass to your solution function.", "_____no_output_____" ] ], [ [ "def solution(outputs, targets):\n \"\"\"\n Args:\n outputs: list of torch.autograd.Variables containing model outputs\n targets: list of torch.autograd.Variables containing targets for each output\n Returns:\n loss_value: torch.autograd.Variable object\n \"\"\"\n return loss_value", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ] ]
d03005826b5089cc3610bb9f4325f37357ae6a66
45,432
ipynb
Jupyter Notebook
Chapter_2/simple_linear_regression_using_keras_API.ipynb
PacktPublishing/Deep-Learning-with-TensorFlow-and-Keras-3rd-edition
96e0573da19318da2238b57a2aca1796e251f094
[ "MIT" ]
2
2022-01-02T17:09:02.000Z
2022-01-19T02:55:10.000Z
Chapter_2/simple_linear_regression_using_keras_API.ipynb
PacktPublishing/Deep-Learning-with-TensorFlow-and-Keras-3rd-edition
96e0573da19318da2238b57a2aca1796e251f094
[ "MIT" ]
null
null
null
Chapter_2/simple_linear_regression_using_keras_API.ipynb
PacktPublishing/Deep-Learning-with-TensorFlow-and-Keras-3rd-edition
96e0573da19318da2238b57a2aca1796e251f094
[ "MIT" ]
4
2022-01-02T17:09:04.000Z
2022-03-22T17:57:01.000Z
100.070485
15,186
0.702919
[ [ [ "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport tensorflow.keras as K\nfrom tensorflow.keras.layers import Dense", "_____no_output_____" ], [ "#Generate a random data\nnp.random.seed(0)\narea = 2.5 * np.random.randn(100) + 25\nprice = 25 * area + 5 + np.random.randint(20,50, size = len(area))\ndata = np.array([area, price])\ndata = pd.DataFrame(data = data.T, columns=['area','price'])\nplt.scatter(data['area'], data['price'])\nplt.show()", "_____no_output_____" ], [ "data = (data - data.min()) / (data.max() - data.min()) #Normalize", "_____no_output_____" ], [ "model = K.Sequential([\n #normalizer,\n Dense(1, input_shape = [1,], activation=None)\n])\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n dense (Dense) (None, 1) 2 \n \n=================================================================\nTotal params: 2\nTrainable params: 2\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(loss='mean_squared_error', optimizer='sgd')", "_____no_output_____" ], [ "model.fit(x=data['area'],y=data['price'], epochs=100, batch_size=32, verbose=1, validation_split=0.2)", "Epoch 1/100\n3/3 [==============================] - 0s 78ms/step - loss: 1.2643 - val_loss: 1.4828\nEpoch 2/100\n3/3 [==============================] - 0s 13ms/step - loss: 1.0987 - val_loss: 1.3029\nEpoch 3/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.9576 - val_loss: 1.1494\nEpoch 4/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.8376 - val_loss: 1.0156\nEpoch 5/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.7339 - val_loss: 0.8971\nEpoch 6/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.6444 - val_loss: 0.7989\nEpoch 7/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.5689 - val_loss: 0.7082\nEpoch 8/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.5016 - val_loss: 0.6331\nEpoch 9/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.4468 - val_loss: 0.5710\nEpoch 10/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.4007 - val_loss: 0.5119\nEpoch 11/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.3581 - val_loss: 0.4596\nEpoch 12/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.3212 - val_loss: 0.4156\nEpoch 13/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.2909 - val_loss: 0.3796\nEpoch 14/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.2661 - val_loss: 0.3476\nEpoch 15/100\n3/3 [==============================] - 0s 35ms/step - loss: 0.2448 - val_loss: 0.3206\nEpoch 16/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.2267 - val_loss: 0.2961\nEpoch 17/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.2106 - val_loss: 0.2747\nEpoch 18/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.1969 - val_loss: 0.2558\nEpoch 19/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.1849 - val_loss: 0.2386\nEpoch 20/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.1744 - val_loss: 0.2240\nEpoch 21/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.1656 - val_loss: 0.2109\nEpoch 22/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.1578 - val_loss: 0.1990\nEpoch 23/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.1508 - val_loss: 0.1880\nEpoch 24/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1448 - val_loss: 0.1797\nEpoch 25/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1399 - val_loss: 0.1707\nEpoch 26/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1349 - val_loss: 0.1621\nEpoch 27/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.1304 - val_loss: 0.1550\nEpoch 28/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1269 - val_loss: 0.1496\nEpoch 29/100\n3/3 [==============================] - 0s 19ms/step - loss: 0.1241 - val_loss: 0.1443\nEpoch 30/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1214 - val_loss: 0.1387\nEpoch 31/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.1187 - val_loss: 0.1340\nEpoch 32/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1166 - val_loss: 0.1306\nEpoch 33/100\n3/3 [==============================] - 0s 12ms/step - loss: 0.1149 - val_loss: 0.1268\nEpoch 34/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.1132 - val_loss: 0.1229\nEpoch 35/100\n3/3 [==============================] - 0s 24ms/step - loss: 0.1116 - val_loss: 0.1204\nEpoch 36/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1103 - val_loss: 0.1174\nEpoch 37/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.1093 - val_loss: 0.1153\nEpoch 38/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.1082 - val_loss: 0.1135\nEpoch 39/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.1073 - val_loss: 0.1110\nEpoch 40/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.1063 - val_loss: 0.1089\nEpoch 41/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.1055 - val_loss: 0.1078\nEpoch 42/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.1050 - val_loss: 0.1069\nEpoch 43/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1043 - val_loss: 0.1057\nEpoch 44/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.1038 - val_loss: 0.1046\nEpoch 45/100\n3/3 [==============================] - 0s 19ms/step - loss: 0.1032 - val_loss: 0.1029\nEpoch 46/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.1025 - val_loss: 0.1012\nEpoch 47/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.1018 - val_loss: 0.1002\nEpoch 48/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.1012 - val_loss: 0.0988\nEpoch 49/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.1007 - val_loss: 0.0979\nEpoch 50/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.1002 - val_loss: 0.0974\nEpoch 51/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0998 - val_loss: 0.0967\nEpoch 52/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.0994 - val_loss: 0.0954\nEpoch 53/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.0988 - val_loss: 0.0944\nEpoch 54/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0983 - val_loss: 0.0937\nEpoch 55/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0979 - val_loss: 0.0928\nEpoch 56/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0974 - val_loss: 0.0923\nEpoch 57/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.0971 - val_loss: 0.0916\nEpoch 58/100\n3/3 [==============================] - 0s 20ms/step - loss: 0.0966 - val_loss: 0.0908\nEpoch 59/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.0962 - val_loss: 0.0900\nEpoch 60/100\n3/3 [==============================] - 0s 21ms/step - loss: 0.0958 - val_loss: 0.0897\nEpoch 61/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.0954 - val_loss: 0.0891\nEpoch 62/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0950 - val_loss: 0.0885\nEpoch 63/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0947 - val_loss: 0.0876\nEpoch 64/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.0941 - val_loss: 0.0872\nEpoch 65/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.0938 - val_loss: 0.0864\nEpoch 66/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.0935 - val_loss: 0.0854\nEpoch 67/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0930 - val_loss: 0.0847\nEpoch 68/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0927 - val_loss: 0.0844\nEpoch 69/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0922 - val_loss: 0.0842\nEpoch 70/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.0919 - val_loss: 0.0840\nEpoch 71/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0915 - val_loss: 0.0837\nEpoch 72/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0911 - val_loss: 0.0830\nEpoch 73/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0907 - val_loss: 0.0828\nEpoch 74/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.0904 - val_loss: 0.0824\nEpoch 75/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.0900 - val_loss: 0.0820\nEpoch 76/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0897 - val_loss: 0.0815\nEpoch 77/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.0893 - val_loss: 0.0810\nEpoch 78/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0889 - val_loss: 0.0805\nEpoch 79/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.0886 - val_loss: 0.0805\nEpoch 80/100\n3/3 [==============================] - 0s 13ms/step - loss: 0.0882 - val_loss: 0.0799\nEpoch 81/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.0879 - val_loss: 0.0793\nEpoch 82/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0875 - val_loss: 0.0790\nEpoch 83/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.0871 - val_loss: 0.0788\nEpoch 84/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.0869 - val_loss: 0.0787\nEpoch 85/100\n3/3 [==============================] - 0s 20ms/step - loss: 0.0864 - val_loss: 0.0783\nEpoch 86/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0861 - val_loss: 0.0781\nEpoch 87/100\n3/3 [==============================] - 0s 16ms/step - loss: 0.0857 - val_loss: 0.0781\nEpoch 88/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0854 - val_loss: 0.0776\nEpoch 89/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0850 - val_loss: 0.0774\nEpoch 90/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0847 - val_loss: 0.0769\nEpoch 91/100\n3/3 [==============================] - 0s 19ms/step - loss: 0.0845 - val_loss: 0.0770\nEpoch 92/100\n3/3 [==============================] - 0s 18ms/step - loss: 0.0841 - val_loss: 0.0767\nEpoch 93/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0837 - val_loss: 0.0761\nEpoch 94/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0834 - val_loss: 0.0758\nEpoch 95/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0831 - val_loss: 0.0758\nEpoch 96/100\n3/3 [==============================] - 0s 22ms/step - loss: 0.0827 - val_loss: 0.0755\nEpoch 97/100\n3/3 [==============================] - 0s 17ms/step - loss: 0.0824 - val_loss: 0.0750\nEpoch 98/100\n3/3 [==============================] - 0s 14ms/step - loss: 0.0821 - val_loss: 0.0747\nEpoch 99/100\n3/3 [==============================] - 0s 21ms/step - loss: 0.0818 - val_loss: 0.0740\nEpoch 100/100\n3/3 [==============================] - 0s 15ms/step - loss: 0.0815 - val_loss: 0.0740\n" ], [ "y_pred = model.predict(data['area'])", "_____no_output_____" ], [ "plt.plot(data['area'], y_pred, color='red',label=\"Predicted Price\")\nplt.scatter(data['area'], data['price'], label=\"Training Data\")\nplt.xlabel(\"Area\")\nplt.ylabel(\"Price\")\nplt.legend()", "_____no_output_____" ], [ "model.weights", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d0301c3bf867d6c72073d4fd99e37fb9bd4a1c98
449,937
ipynb
Jupyter Notebook
Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb
MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT
b4e21b417508d9bd95047f25ec7fc56b0e701453
[ "MIT" ]
null
null
null
Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb
MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT
b4e21b417508d9bd95047f25ec7fc56b0e701453
[ "MIT" ]
null
null
null
Moringa_Data_Science_Core_W2_Independent_Project_2021_09_Moreen_Mugambi_Python_Notebook_ipyn.ipynb
MoreenMarutaData/FINANCIAL-INCLUSION-IN-EAST-AFRICA-MORINGA-CORE-WEEK-2-PROJECT
b4e21b417508d9bd95047f25ec7fc56b0e701453
[ "MIT" ]
null
null
null
449,937
449,937
0.867539
[ [ [ "# **ANALYSIS OF FINANCIAL INCLUSION IN EAST AFRICA BETWEEN 2016 TO 2018**", "_____no_output_____" ], [ "##DEFINING QUESTION", "_____no_output_____" ], [ "The research problem is to figure out how we can predict which individuals are most likely to have or use a bank account.", "_____no_output_____" ], [ "### METRIC FOR SUCCESS", "_____no_output_____" ], [ " My solution procedure will be to help provide an indication of the state of financial inclusion in Kenya, Rwanda, Tanzania, and Uganda, while providing insights into some of the key demographic factors that might drive individuals financial outcomes.", "_____no_output_____" ], [ "###THE CONTEXT", "_____no_output_____" ], [ "Financial Inclusion remains one of the main obstacles to economic and human development in Africa. For example, across Kenya, Rwanda, Tanzania, and Uganda only 9.1 million adults (or 13.9% of the adult population) have access to or use a commercial bank account.\n\nTraditionally, access to bank accounts has been regarded as an indicator of financial inclusion. Despite the proliferation of mobile money in Africa and the growth of innovative fintech solutions, banks still play a pivotal role in facilitating access to financial services. Access to bank accounts enables households to save and facilitate payments while also helping businesses build up their credit-worthiness and improve their access to other financial services. Therefore, access to bank accounts is an essential contributor to long-term economic growth.", "_____no_output_____" ], [ "### EXPERIMENTAL DESIGN TAKEN", "_____no_output_____" ], [ "The procedure taken is:\n1. Definition of the question\n2. Reading and checking of the data\n3. External data source validation\n4. Cleaning of the dataset\n5. Exploratory analysis\n", "_____no_output_____" ], [ "### DATA RELEVANCE", "_____no_output_____" ], [ "\nData to be used contains demographic information and what financial services are used by individuals in East Africa. The data is extracted from various Finsscope surveys and is ranging from 2016 to 2018. The data files include:\n\nVariable Definitions: http://bit.ly/VariableDefinitions\n\nDataset: http://bit.ly/FinancialDataset\n\nFinAccess Kenya 2018: https://fsdkenya.org/publication/finaccess2019/\n\nFinscope Rwanda 2016: http://www.statistics.gov.rw/publication/finscope-rwanda-2016 \n\nFinscope Tanzania 2017: http://www.fsdt.or.tz/finscope/\n\nFinscope Uganda 2018: http://fsduganda.or.ug/finscope-2018-survey-report/\n\nThis data is relevant in this project since it provides important insights that will help in solving the research question.", "_____no_output_____" ], [ "## LOADING LIBRARIES", "_____no_output_____" ] ], [ [ "# importing libraries\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## READING AND CHECKING DATA", "_____no_output_____" ] ], [ [ "# loading and viewing variable definitions dataset\n\nurl = \"http://bit.ly/VariableDefinitions\"\nvb_df = pd.read_csv(url)\nvb_df", "_____no_output_____" ], [ "# loading and viewing financial dataset\nurl2 = \"http://bit.ly/FinancialDataset\"\nfds = pd.read_csv(url2)\nfds", "_____no_output_____" ], [ "fds.shape", "_____no_output_____" ], [ "fds.head()", "_____no_output_____" ], [ "fds.tail()", "_____no_output_____" ], [ "fds.dtypes", "_____no_output_____" ], [ "fds.columns\n", "_____no_output_____" ], [ "fds.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 23524 entries, 0 to 23523\nData columns (total 13 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 country 23510 non-null object \n 1 year 23524 non-null int64 \n 2 uniqueid 23524 non-null object \n 3 Has a Bank account 23488 non-null object \n 4 Type of Location 23509 non-null object \n 5 Cell Phone Access 23513 non-null object \n 6 household_size 23496 non-null float64\n 7 Respondent Age 23490 non-null float64\n 8 gender_of_respondent 23490 non-null object \n 9 The relathip with head 23520 non-null object \n 10 marital_status 23492 non-null object \n 11 Level of Educuation 23495 non-null object \n 12 Type of Job 23494 non-null object \ndtypes: float64(2), int64(1), object(10)\nmemory usage: 2.3+ MB\n" ], [ "fds.describe()", "_____no_output_____" ], [ "fds.describe(include=object)", "_____no_output_____" ], [ "len(fds)", "_____no_output_____" ], [ "fds.nunique()", "_____no_output_____" ], [ "fds.count()", "_____no_output_____" ] ], [ [ "## EXTERNAL DATA SOURCE VALIDATION", "_____no_output_____" ], [ "\nFinAccess Kenya 2018: https://fsdkenya.org/publication/finaccess2019/\n\nFinscope Rwanda 2016: http://www.statistics.gov.rw/publication/finscope-rwanda-2016 \n\nFinscope Tanzania 2017: http://www.fsdt.or.tz/finscope/\n\nFinscope Uganda 2018: http://fsduganda.or.ug/finscope-2018-survey-report/", "_____no_output_____" ], [ "## CLEANING THE DATASET", "_____no_output_____" ] ], [ [ "fds.head(2)", "_____no_output_____" ], [ "# CHECKING FOR OUTLIERS IN YEAR COLUMN\n\nsns.boxplot(x=fds['year'])\n", "_____no_output_____" ], [ "fds.shape", "_____no_output_____" ], [ "# dropping year column outliers\nfds1= fds[fds['year']<2020]\n \nfds1.shape ", "_____no_output_____" ], [ "# CHECKING FOR OUTLIERS IN HOUSEHOLD SIZE COLUMN\n\nsns.boxplot(x=fds1['household_size'])", "_____no_output_____" ], [ "# dropping household size outliers\nfds2 =fds1[fds1['household_size']<10]\nfds2.shape", "_____no_output_____" ], [ "# CHECKING FOR OUTLIERS IN AGE OF RESPONDENT\nsns.boxplot(x=fds2['Respondent Age'])", "_____no_output_____" ], [ "# dropping age of respondent outliers\n\nfds3 = fds2[fds2['Respondent Age']<82]\nfds3.shape", "_____no_output_____" ], [ "# plotting the final boxplots\n\nfig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2, figsize=(10, 7))\nfig.suptitle('Boxplots')\nsns.boxplot(fds3['Respondent Age'], ax=ax1)\nsns.boxplot(fds3['year'], ax=ax2)\nsns.boxplot(fds3['household_size'], ax=ax3)\n\nplt.show()\n\n# the outliers have finally been droppped", "/usr/local/lib/python3.7/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n/usr/local/lib/python3.7/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n/usr/local/lib/python3.7/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n FutureWarning\n" ], [ "# CHECKING FOR NULLL OR MISSING DATA \nfds3.isnull().sum()", "_____no_output_____" ], [ "# dropping nulls \nfds4 = fds3.dropna()\nfds4.shape", "_____no_output_____" ], [ "# dropping duplicates\nfds4.drop_duplicates().head(2)\n", "_____no_output_____" ], [ "# changing column names and columns to lowercase\n#for columns in fds.columns:\n #fds1[columns] = fds[columns].astype(str).str.lower()\n#fds1\n\n#fds1.rename(columns=str.lower)\n# renaming columns\n\nfds5 = fds4.rename(columns={'Type of Location':'location_type', 'Has a Bank account' : 'bank account','Cell Phone Access':'cellphone_access', 'Respondent Age': 'age_of_respondent',\n 'The relathip with head': 'relationship_with_head', 'Level of Educuation' : 'education_level', 'Type of Job': 'job_type'})\n\nfds5.head(2)", "_____no_output_____" ], [ "fds5.shape", "_____no_output_____" ], [ "fds5.size", "_____no_output_____" ], [ "fds5.nunique()", "_____no_output_____" ], [ "fds5['country'].unique()", "_____no_output_____" ], [ "fds5['year'].unique()", "_____no_output_____" ], [ "fds5['bank account'].unique()", "_____no_output_____" ], [ "fds5['location_type'].unique()", "_____no_output_____" ], [ "fds5['cellphone_access'].unique()", "_____no_output_____" ], [ "fds5['education_level'].unique()", "_____no_output_____" ], [ "fds5.drop(fds5.loc[fds5['education_level'] ==6].index, inplace=True)", "_____no_output_____" ], [ "fds5['education_level'].unique()", "_____no_output_____" ], [ "fds5['gender_of_respondent'].unique()", "_____no_output_____" ], [ "fds5['household_size'].unique()", "_____no_output_____" ], [ "fds5.drop(fds5.loc[fds5['household_size'] == 0].index, inplace=True)", "_____no_output_____" ], [ "fds5['household_size'].unique()", "_____no_output_____" ], [ "fds5['job_type'].unique()", "_____no_output_____" ], [ "fds5['relationship_with_head'].unique()", "_____no_output_____" ], [ "fds5['age_of_respondent'].unique()", "_____no_output_____" ] ], [ [ "## **EXPLORATORY ANALYSIS**", "_____no_output_____" ], [ "### 1.UNIVARIATE ANALYSIS", "_____no_output_____" ], [ "#### a. NUMERICAL VARIABLES", "_____no_output_____" ], [ "##### MODE\n", "_____no_output_____" ] ], [ [ "\nfds5['year'].mode()", "_____no_output_____" ], [ "fds5['household_size'].mode()", "_____no_output_____" ], [ "fds5['age_of_respondent'].mode()", "_____no_output_____" ] ], [ [ "##### MEAN", "_____no_output_____" ] ], [ [ "fds5['age_of_respondent'].mean()", "_____no_output_____" ], [ "fds5['household_size'].mean()", "_____no_output_____" ], [ "fds5.mean()", "_____no_output_____" ] ], [ [ "##### MEDIAN", "_____no_output_____" ] ], [ [ "fds5['age_of_respondent'].median()", "_____no_output_____" ], [ "fds5['household_size'].median()", "_____no_output_____" ], [ "fds5.median()", "_____no_output_____" ] ], [ [ "##### RANGE", "_____no_output_____" ] ], [ [ "a = fds5['age_of_respondent'].max()\nb = fds5['age_of_respondent'].min()\n\nc = a-b\nprint('The range of the age for the respondents is', c)", "The range of the age for the respondents is 65.0\n" ], [ "d = fds5['household_size'].max()\ne = fds5['household_size'].min()\n\nf = d-e\nprint('The range of the household_sizes is', f)", "The range of the household_sizes is 8.0\n" ] ], [ [ "##### QUANTILE AND INTERQUANTILE", "_____no_output_____" ] ], [ [ "fds5.quantile([0.25,0.5,0.75])", "_____no_output_____" ], [ "# FINDING THE INTERQUANTILE RANGE = IQR\nQ3 = fds5['age_of_respondent'].quantile(0.75)\nQ2 = fds5['age_of_respondent'].quantile(0.25)\nIQR= Q3-Q2\nprint('The IQR for the respondents age is', IQR)", "The IQR for the respondents age is 22.0\n" ], [ "q3 = fds5['household_size'].quantile(0.75)\nq2 = fds5['household_size'].quantile(0.25)\niqr = q3-q2\nprint('The IQR for household sizes is', iqr)", "The IQR for household sizes is 3.0\n" ], [ "", "_____no_output_____" ] ], [ [ "##### STANDARD DEVIATION", "_____no_output_____" ] ], [ [ "fds5.std()", "_____no_output_____" ] ], [ [ "##### VARIANCE", "_____no_output_____" ] ], [ [ "fds5.var()", "_____no_output_____" ] ], [ [ "##### KURTOSIS", "_____no_output_____" ] ], [ [ "fds5.kurt()", "_____no_output_____" ] ], [ [ "##### SKEWNESS", "_____no_output_____" ] ], [ [ "fds5.skew()", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "#### b. CATEGORICAL", "_____no_output_____" ], [ "##### MODE\n", "_____no_output_____" ] ], [ [ "fds5.mode().head(1)", "_____no_output_____" ], [ "fds5['age_of_respondent'].plot(kind=\"hist\")\nplt.xlabel('ages of respondents')\nplt.ylabel('frequency')\nplt.title(' Frequency of the ages of the respondents')", "_____no_output_____" ], [ "country=fds5['country'].value_counts()\nprint(country)\n\n# Plotting the pie chart\ncolors=['pink','white','cyan','yellow']\ncountry.plot(kind='pie',colors=colors,autopct='%1.1f%%',shadow=True,startangle=90)\nplt.title('Distribution of the respondents by country')", "Rwanda 8483\nTanzania 6374\nKenya 5848\nUganda 1920\nName: country, dtype: int64\n" ], [ "bank =fds5['bank account'].value_counts()\n\n# Plotting the pie chart\ncolors=['plum', 'aqua']\nbank.plot(kind='pie',colors=colors,autopct='%1.1f%%',shadow=True,startangle=90)\nplt.title('availability of bank accounts')", "_____no_output_____" ], [ "location=fds5['location_type'].value_counts()\n\n# Plotting the pie chart\ncolors=['aquamarine','beige']\nlocation.plot(kind='pie',colors=colors,autopct='%1.3f%%',shadow=True,startangle=00)\nplt.title('Distribution of the respondents according to location')", "_____no_output_____" ], [ "celly =fds5['cellphone_access'].value_counts()\n\n# Plotting the pie chart\ncolors=['plum','lavender']\ncelly.plot(kind='pie',colors=colors,autopct='%1.1f%%',shadow=True,startangle=0)\nplt.title('cellphone access for the respondents')", "_____no_output_____" ], [ "gen =fds5['gender_of_respondent'].value_counts()\n\n# Plotting the pie chart\ncolors=['red','lavender']\ngen.plot(kind='pie',colors=colors,autopct='%1.1f%%',shadow=True,startangle=0)\nplt.title('gender distribution')", "_____no_output_____" ] ], [ [ "##### CONCLUSION AND RECOMMENDATION", "_____no_output_____" ], [ "Most of the data was collected in Rwanda.\nMost of the data was collected in Rural areas.\nMost of those who were interviewed were women.\nMost of the population has mobile phones.\nThere were several outliers.\n\nSince 75% of the population has phones, phones should be used as the main channel for information and awareness of bank accessories.\n", "_____no_output_____" ], [ "### 2. BIVARIATE ANALYSIS", "_____no_output_____" ] ], [ [ "fds5.head()", "_____no_output_____" ], [ "#@title Since i am predicting the likelihood of the respondents using the bank,I shall be comparing all variables against the bank account column.\n", "_____no_output_____" ] ], [ [ "##### NUMERICAL VS NUMERICAL", "_____no_output_____" ] ], [ [ "sns.pairplot(fds5)\nplt.show()", "_____no_output_____" ], [ "# pearson correlation of numerical variables\n\nsns.heatmap(fds5.corr(),annot=True)\nplt.show()\n\n# possible weak correlation", "_____no_output_____" ], [ "fds5.corr()", "_____no_output_____" ] ], [ [ "##### CATEGORICAL VS CATEGORICAL", "_____no_output_____" ] ], [ [ "# Grouping bank usage by country\ncountry1 = fds5.groupby('country')['bank account'].value_counts(normalize=True).unstack()\n\ncolors= ['lightpink', 'skyblue']\n\ncountry1.plot(kind='bar', figsize=(8, 6), color=colors, stacked=True)\nplt.title('Bank usage by country', fontsize=15, y=1.015)\nplt.xlabel('country', fontsize=14, labelpad=15)\nplt.xticks(rotation = 360)\nplt.ylabel('Bank usage by country', fontsize=14, labelpad=15)\n\nplt.show()", "_____no_output_____" ], [ "# Bank usage by gender\ngender1 = fds5.groupby('gender_of_respondent')['bank account'].value_counts(normalize=True).unstack()\n\ncolors= ['lightpink', 'skyblue']\n\ngender1.plot(kind='bar', figsize=(8, 6), color=colors, stacked=True)\nplt.title('Bank usage by gender', fontsize=17, y=1.015)\nplt.xlabel('gender', fontsize=17, labelpad=17)\nplt.xticks(rotation = 360)\nplt.ylabel('Bank usage by gender', fontsize=17, labelpad=17)\n\nplt.show()", "_____no_output_____" ], [ "# Bank usage depending on level of education\n\ned2 = fds5.groupby('education_level')['bank account'].value_counts(normalize=True).unstack()\n\ncolors= ['cyan', 'darkcyan']\n\ned2.plot(kind='barh', figsize=(8, 6), color=colors, stacked=True)\nplt.title('Bank usage by level of education', fontsize=17, y=1.015)\nplt.xlabel('frequency', fontsize=17, labelpad=17)\nplt.xticks(rotation = 360)\nplt.ylabel('level of education', fontsize=17, labelpad=17)\n\nplt.show()", "_____no_output_____" ], [ "\n\n\nms = fds5.groupby('marital_status')['bank account'].value_counts(normalize=True).unstack()\n\ncolors= ['coral', 'orange']\n\nms.plot(kind='barh', figsize=(8, 6), color=colors, stacked=True)\nplt.title('Bank usage by marital status', fontsize=17, y=1.015)\nplt.xlabel('frequency', fontsize=17, labelpad=17)\nplt.xticks(rotation = 360)\nplt.ylabel('marital status', fontsize=17, labelpad=17)", "_____no_output_____" ], [ "\ngj = fds5.groupby('gender_of_respondent')['job_type'].value_counts(normalize=True).unstack()\n\n#colors= ['coral', 'orange']\n\ngj.plot(kind='bar', figsize=(8, 6), stacked=True)\nplt.title('job type by gender', fontsize=17, y=1.015)\nplt.xlabel('gender_of_respondent', fontsize=17, labelpad=17)\nplt.xticks(rotation = 360)\nplt.ylabel('job type', fontsize=17, labelpad=17)", "_____no_output_____" ] ], [ [ "##### NUMERICAL VS CATEGORICAL", "_____no_output_____" ], [ "##### IMPLEMENTING AND CHALLENGING SOLUTION", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "Most of those interviewed do not have bank accounts of which 80% is the uneducated.\nMost of the population that participated is married,followed by single/never married.\nMost of the population has primary school education level.\nMost of the population is involved in farming followed by self employment.\nBank usage has more males than females.\n\n\nMore channeling needs to be done in Kenya as it has the least bank users.", "_____no_output_____" ], [ "###3. MULTIVARIATE ANALYSIS", "_____no_output_____" ] ], [ [ "# Multivariate analysis - This is a statistical analysis that involves observation and analysis of more than one statistical outcome variable at a time\n", "_____no_output_____" ], [ "# LETS MAKE A COPY\nfds_new = fds5.copy()", "_____no_output_____" ], [ "fds_new.columns", "_____no_output_____" ], [ "fds_new.dtypes", "_____no_output_____" ], [ "# IMPORTING THE LABEL ENCODER\n\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\n\n# encoding categorial values\n\nfds_new['country']=le.fit_transform(fds_new['country'].astype(str))\n\nfds_new['location_type']=le.fit_transform(fds_new['location_type'].astype(str))\n\nfds_new['cellphone_access']=le.fit_transform(fds_new['cellphone_access'].astype(str))\n\nfds_new['gender_of_respondent']=le.fit_transform(fds_new['gender_of_respondent'].astype(str))\n\nfds_new['relationship_with_head']=le.fit_transform(fds_new['relationship_with_head'].astype(str))\n\nfds_new['marital_status']=le.fit_transform(fds_new['marital_status'].astype(str))\n\nfds_new['education_level']=le.fit_transform(fds_new['education_level'].astype(str))\n\nfds_new['job_type']=le.fit_transform(fds_new['job_type'].astype(str))", "_____no_output_____" ], [ "fds_new.sample(5)", "_____no_output_____" ], [ "# dropping unnecessary columns\nfds_new.drop(['age_of_respondent','uniqueid','year'], axis=1).head(2)", "_____no_output_____" ] ], [ [ "##### FACTOR ANALYSIS", "_____no_output_____" ] ], [ [ "\n# Installing factor analyzer \n!pip install factor_analyzer==0.2.3\n\nfrom factor_analyzer.factor_analyzer import calculate_bartlett_sphericity\n\nchi_square_value,p_value=calculate_bartlett_sphericity(fds_new)\nchi_square_value, p_value\n\n# In Bartlett ’s test, the p-value is 0. The test was statistically significant, \n# indicating that the observed correlation matrix is not an identity matrix.", "Requirement already satisfied: factor_analyzer==0.2.3 in /usr/local/lib/python3.7/dist-packages (0.2.3)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from factor_analyzer==0.2.3) (1.19.5)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from factor_analyzer==0.2.3) (1.1.5)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from factor_analyzer==0.2.3) (1.4.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->factor_analyzer==0.2.3) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->factor_analyzer==0.2.3) (2.8.2)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->factor_analyzer==0.2.3) (1.15.0)\n" ], [ "# Value of KMO less than 0.6 is considered inadequate.\n# \n#from factor_analyzer.factor_analyzer import calculate_kmo\n\n#kmo_all,kmo_model=calculate_kmo(fds_new)\n#calculate_kmo(fds_new)", "_____no_output_____" ], [ "# Choosing the Number of Factors\n \nfrom factor_analyzer.factor_analyzer import FactorAnalyzer\n\n# Creating factor analysis object and perform factor analysis\nfa = FactorAnalyzer()\nfa.analyze(fds_new, 10, rotation=None)\n\n# Checking the Eigenvalues\nev, v = fa.get_eigenvalues()\nev\n\n# We choose the factors that are > 1.\n# so we choose 4 factors only", "_____no_output_____" ], [ "# PERFOMING FACTOR ANALYSIS FOR 4 FACTORS\nfa = FactorAnalyzer()\n\nfa.analyze(fds_new, 4, rotation=\"varimax\")\nfa.loadings\n", "_____no_output_____" ], [ "# GETTING VARIANCE FOR THE FACTORS\nfa.get_factor_variance()", "_____no_output_____" ] ], [ [ "##### CONCLUSION\n", "_____no_output_____" ], [ "The reduction method used was factor analysis.\nFour factors had an eigen value greater than 1.\n", "_____no_output_____" ], [ "##### CHALLENGING SOLUTION", "_____no_output_____" ], [ "There is room for modification because there are other methodologies that could be used for analysis. \nThere is also an assumption that this data is accurate to the real world.", "_____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", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "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" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
d0301c6c833f565bbd44ca50a23d1c3cdee0b985
23,796
ipynb
Jupyter Notebook
reports/80_cluster_anc_triplet-initial.ipynb
rootsdev/nama
1210a24e8ee7689619e800653bd11341d667462d
[ "MIT" ]
null
null
null
reports/80_cluster_anc_triplet-initial.ipynb
rootsdev/nama
1210a24e8ee7689619e800653bd11341d667462d
[ "MIT" ]
8
2021-10-16T19:24:20.000Z
2021-11-25T02:28:32.000Z
reports/80_cluster_anc_triplet-initial.ipynb
rootsdev/nama
1210a24e8ee7689619e800653bd11341d667462d
[ "MIT" ]
null
null
null
30.007566
151
0.546394
[ [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "import numpy as np\nimport random\nimport torch\nfrom collections import defaultdict\nfrom scipy.sparse import csr_matrix\nfrom sklearn.cluster import AgglomerativeClustering\nfrom tqdm.auto import tqdm\n\nfrom src.data.filesystem import fopen\nfrom src.data.ancestry import load_train_test\nfrom src.data.prepare import normalize\nfrom src.models.utils import add_padding, remove_padding, build_token_idx_maps, convert_names_to_model_inputs, get_best_matches", "_____no_output_____" ] ], [ [ "### Configure", "_____no_output_____" ] ], [ [ "sample_size = 0\nmax_closure_size = 10000\nmax_distance = 0.22\ncluster_distance_threshold = 0.155\nsuper_cluster_distance_threshold = 0.205\nnum_candidates = 1000\neps = 0.000001\nmodel_filename = '../data/models/anc-triplet-bilstm-100-512-40-05.pth'\n\n# process_nicknames = True\n# werelate_names_filename = 'givenname_similar_names.werelate.20210414.tsv'\n# nicknames_filename = '../data/models/givenname_nicknames.txt'\n# name_freqs_filename = 'given-final.normal.txt'\n# clusters_filename = 'givenname_clusters.tsv'\n# super_clusters_filename = 'givenname_super_clusters.tsv'\n\nwerelate_names_filename = '../data/external/surname_similar_names.werelate.20210414.tsv'\nnicknames_filename = ''\nname_freqs_filename = '../data/external/surname-final.normal.txt'\nclusters_filename = '../data/models/ancestry_surname_clusters-20211028.tsv'\nsuper_clusters_filename = '../data/models/ancestry_surname_super_clusters-20211028.tsv'\nis_surname = True", "_____no_output_____" ] ], [ [ "### Read WeRelate names into all_names\nLater, we'll want to read frequent FS names into all_names", "_____no_output_____" ] ], [ [ "# TODO rewrite this in just a few lines using pandas\ndef load_werelate_names(path, is_surname):\n name_variants = defaultdict(set)\n with fopen(path, mode=\"r\", encoding=\"utf-8\") as f:\n is_header = True\n for line in f:\n if is_header:\n is_header = False\n continue\n fields = line.rstrip().split(\"\\t\")\n # normalize should only return a single name piece, but loop just in case\n for name_piece in normalize(fields[0], is_surname):\n confirmed_variants = fields[1].strip().split(\" \") if len(fields) >= 2 else []\n computer_variants = fields[2].strip().split(\" \") if len(fields) == 3 else []\n variants = confirmed_variants + computer_variants\n for variant in variants:\n for variant_piece in normalize(variant, is_surname):\n name_variants[name_piece].add(variant_piece)\n return name_variants", "_____no_output_____" ], [ "all_names = set()\n\nname_variants = load_werelate_names(werelate_names_filename, is_surname)\nprint(len(name_variants))\nfor k, v in name_variants.items():\n all_names.add(add_padding(k))\n all_names.update(add_padding(variant) for variant in v)\nprint(len(all_names), next(iter(all_names)))\n\nname_variants = None", "_____no_output_____" ] ], [ [ "### Read nicknames and remove from names", "_____no_output_____" ] ], [ [ "def load_nicknames(path):\n nicknames = defaultdict(set)\n with fopen(path, mode=\"r\", encoding=\"utf-8\") as f:\n for line in f:\n names = line.rstrip().split(\" \")\n # normalize should only return a single name piece, but loop just in case\n for name_piece in normalize(names[0], False):\n orig_name = add_padding(name_piece)\n for nickname in names[1:]:\n for nickname_piece in normalize(nickname, False):\n nicknames[add_padding(nickname_piece)].add(orig_name)\n return nicknames", "_____no_output_____" ], [ "name_nicks = defaultdict(set)\nif not is_surname:\n nick_names = load_nicknames(nicknames_filename)\n for nick, names in nick_names.items():\n for name in names:\n name_nicks[name].add(nick)\n print(next(iter(nick_names.items())), \"nick_names\", len(nick_names.keys()), \"name_nicks\", len(name_nicks.keys()))\n all_names -= set(nickname for nickname in nick_names.keys())\n print(len(all_names))", "_____no_output_____" ] ], [ [ "### Map names to ids", "_____no_output_____" ] ], [ [ "def map_names_to_ids(names):\n ids = range(len(names))\n return dict(zip(names, ids)), dict(zip(ids, names))", "_____no_output_____" ], [ "name_ids, id_names = map_names_to_ids(all_names)\nprint(next(iter(name_ids.items())), next(iter(id_names.items())))", "_____no_output_____" ] ], [ [ "### Read name frequencies", "_____no_output_____" ] ], [ [ "# TODO rewrite this using pandas too\ndef load_name_freqs(path, is_surname):\n name_freqs = defaultdict(int)\n with fopen(path, mode=\"r\", encoding=\"utf-8\") as f:\n for line in f:\n fields = line.rstrip().split(\"\\t\")\n for name_piece in normalize(fields[0], is_surname):\n name_freqs[name_piece] = int(fields[1])\n return name_freqs", "_____no_output_____" ], [ "name_freqs = load_name_freqs(name_freqs_filename, is_surname)\n# keep only entries in all_names\nname_freqs = dict((add_padding(k),v) for k,v in name_freqs.items() if add_padding(k) in all_names)\nprint(len(name_freqs), next(iter(name_freqs.items())))", "_____no_output_____" ] ], [ [ "### Load model", "_____no_output_____" ] ], [ [ "model = torch.load(model_filename)", "_____no_output_____" ] ], [ [ "### Encode names", "_____no_output_____" ] ], [ [ "MAX_NAME_LENGTH=30\nchar_to_idx_map, idx_to_char_map = build_token_idx_maps()", "_____no_output_____" ] ], [ [ "#### Take a sample because encoded names require a lot of memory", "_____no_output_____" ] ], [ [ "if sample_size <= 0 or sample_size >= len(all_names):\n names_sample = np.array(list(all_names))\nelse:\n names_sample = np.array(random.sample(all_names, sample_size))\nprint(names_sample.shape)", "_____no_output_____" ] ], [ [ "#### Compute encodings", "_____no_output_____" ] ], [ [ "# Get embeddings\nnames_tensor, _ = convert_names_to_model_inputs(names_sample,\n char_to_idx_map,\n MAX_NAME_LENGTH)", "_____no_output_____" ], [ "# Get encodings for the names from the encoder\n# TODO why do I need to encode in chunks?\nchunk_size = 10000\nnps = []\nfor begin in tqdm(range(0, len(names_tensor), chunk_size)):\n nps.append(model(names_tensor[begin:begin+chunk_size], just_encoder=True).detach().numpy())", "_____no_output_____" ], [ "names_encoded = np.concatenate(nps, axis=0)\nnps = None\nnames_encoded.shape", "_____no_output_____" ] ], [ [ "### Compute distances", "_____no_output_____" ] ], [ [ "name_candidates = get_best_matches(names_encoded,\n names_encoded,\n names_sample,\n num_candidates=num_candidates,\n metric='euclidean')", "_____no_output_____" ], [ "# what's going on here?\ndistances = np.hstack((np.repeat(names_sample, num_candidates)[:, np.newaxis], name_candidates.reshape(-1,2)))\n# remove distances > max_distance\ndistances = distances[distances[:, -1].astype('float') <= max_distance]\n# sort \ndistances = distances[distances[:, -1].astype('float').argsort()]\nprint(distances.shape)\nname_candidates = None", "_____no_output_____" ] ], [ [ "### Compute closures", "_____no_output_____" ] ], [ [ "# iterate over all distances, create closures and save scores\nnext_closure = 0\nclosure_ids = {}\nid_closure = {}\nrow_ixs = []\ncol_ixs = []\ndists = []\nmax_size = 0\n\nfor row in tqdm(distances):\n name1 = row[0]\n name2 = row[1]\n id1 = name_ids[name1]\n id2 = name_ids[name2]\n # each distance is in distances twice\n if id1 > id2:\n continue\n distance = max(eps, float(row[2]))\n closure1 = id_closure.get(id1)\n closure2 = id_closure.get(id2)\n if closure1 is None and closure2 is not None: \n id1, id2 = id2, id1\n name1, name2 = name2, name1\n closure1, closure2 = closure2, closure1\n # add to distance matrix\n row_ixs.append(id1)\n col_ixs.append(id2)\n dists.append(distance)\n # skip if names are the same\n if id1 == id2:\n continue\n row_ixs.append(id2)\n col_ixs.append(id1)\n dists.append(distance)\n # create closures\n if closure1 is None:\n # if closure1 is None, then closure2 must be none also due to the above\n # so create a new closure with id1 and id2\n closure1 = next_closure\n next_closure += 1\n id_closure[id1] = closure1\n id_closure[id2] = closure1\n closure_ids[closure1] = [id1, id2]\n next_closure += 1\n elif closure2 is None:\n # put id2 into id1's closure\n id_closure[id2] = closure1\n closure_ids[closure1].append(id2)\n elif closure1 != closure2 and len(closure_ids[closure1]) + len(closure_ids[closure2]) <= max_closure_size:\n # move all ids in closure2 into closure1\n for id in closure_ids[closure2]:\n id_closure[id] = closure1\n closure_ids[closure1].append(id)\n del closure_ids[closure2]\n if len(closure_ids[closure1]) > max_size:\n max_size = len(closure_ids[closure1])\n\n# create distances matrix\ndist_matrix = csr_matrix((dists, (row_ixs, col_ixs)))\n\nprint(\"max closure_size\", max_size)\nprint(\"number of closures\", len(closure_ids), \"number of names enclosed\", len(id_closure))", "_____no_output_____" ] ], [ [ "### Compute clusters", "_____no_output_____" ] ], [ [ "def compute_clusters(closure_ids, id_names, dist_matrix, linkage, distance_threshold, eps, max_dist):\n cluster_names = defaultdict(set)\n name_cluster = {}\n for closure, ids in tqdm(closure_ids.items()):\n clusterer = AgglomerativeClustering(n_clusters=None, affinity='precomputed', linkage=linkage, distance_threshold=distance_threshold)\n X = dist_matrix[ids][:, ids].todense()\n X[X < eps] = max_dist\n labels = clusterer.fit_predict(X)\n for id, label in zip(ids, labels):\n name = id_names[id]\n cluster = f'{closure}_{label}'\n cluster_names[cluster].add(name)\n name_cluster[name] = cluster\n return cluster_names, name_cluster", "_____no_output_____" ], [ "# try ward, average, single\ncluster_linkage = 'average'\nmax_dist = 10.0\n\ncluster_names, name_cluster = compute_clusters(closure_ids, id_names, dist_matrix, cluster_linkage, cluster_distance_threshold, eps, max_dist)\nprint(len(cluster_names))", "_____no_output_____" ] ], [ [ "#### Add unclustered names as singleton clusters", "_____no_output_____" ] ], [ [ "def add_singleton_names(cluster_names, name_cluster, names_sample):\n for ix, name in enumerate(names_sample):\n if name not in name_cluster:\n cluster = f'{ix}'\n cluster_names[cluster].add(name)\n name_cluster[name] = cluster\n return cluster_names, name_cluster", "_____no_output_____" ], [ "cluster_names, name_cluster = add_singleton_names(cluster_names, name_cluster, names_sample)\nprint(len(cluster_names))", "_____no_output_____" ] ], [ [ "### Eval cluster P/R over Ancestry test data", "_____no_output_____" ] ], [ [ "train, test = load_train_test(\"../data/raw/records25k_data_train.csv\", \"../data/raw/records25k_data_test.csv\")\n\n_, _, candidates_train = train\ninput_names_test, weighted_relevant_names_test, candidates_test = test\n\nall_candidates = np.concatenate((candidates_train, candidates_test))", "_____no_output_____" ], [ "def get_precision_recall(names_sample, all_candidates, input_names_test, weighted_relevant_names_test, cluster_names, name_cluster):\n names_sample_set = set(names_sample.tolist())\n all_candidates_set = set(all_candidates.tolist())\n\n precisions = []\n recalls = []\n for input_name, weighted_relevant_names in zip(input_names_test, weighted_relevant_names_test):\n if input_name not in names_sample_set:\n continue\n cluster_id = name_cluster[input_name]\n names_in_cluster = cluster_names[cluster_id] & all_candidates_set\n found_recall = 0.0\n total_recall = 0.0\n found_count = 0\n for name, weight, _ in weighted_relevant_names:\n if name in names_sample_set:\n total_recall += weight\n if name in names_in_cluster:\n found_recall += weight\n found_count += 1\n if total_recall == 0.0:\n continue\n precision = found_count / len(names_in_cluster) if len(names_in_cluster) > 0 else 1.0\n recall = found_recall / total_recall\n precisions.append(precision)\n recalls.append(recall)\n avg_precision = sum(precisions) / len(precisions)\n avg_recall = sum(recalls) / len(recalls)\n return avg_precision, avg_recall, len(precisions)", "_____no_output_____" ], [ "precision, recall, total = get_precision_recall(names_sample, all_candidates, input_names_test,\n weighted_relevant_names_test, cluster_names, name_cluster)\nprint(\"Total=\", total, \" Precision=\", precision, \" Recall=\", recall)", "_____no_output_____" ] ], [ [ "### Write clusters", "_____no_output_____" ] ], [ [ "def write_clusters(path, cluster_names, name_freqs, name_nicks):\n cluster_id_name_map = {}\n with fopen(path, mode=\"w\", encoding=\"utf-8\") as f:\n for cluster_id, names in cluster_names.items():\n # get most-frequent name\n cluster_name = max(names, key=(lambda name: name_freqs.get(name, 0)))\n # map cluster id to cluster name\n cluster_id_name_map[cluster_id] = cluster_name\n # add nicknames\n nicknames = set()\n if name_nicks:\n for name in names:\n if name in name_nicks:\n nicknames.update(name_nicks[name])\n # remove padding \n cluster_name = remove_padding(cluster_name)\n names = [remove_padding(name) for name in names | nicknames]\n # write cluster\n f.write(f'{cluster_name}\\t{\" \".join(names)}\\n')\n return cluster_id_name_map", "_____no_output_____" ], [ "cluster_id_name_map = write_clusters(clusters_filename, cluster_names, name_freqs, name_nicks)", "_____no_output_____" ] ], [ [ "### Create super-clusters", "_____no_output_____" ] ], [ [ "super_cluster_names, name_super_cluster = compute_clusters(closure_ids, id_names, dist_matrix, cluster_linkage, \n super_cluster_distance_threshold, eps, max_dist)\nprint(len(super_cluster_names))", "_____no_output_____" ], [ "super_cluster_names, name_super_cluster = add_singleton_names(super_cluster_names, name_super_cluster, names_sample)\nprint(len(super_cluster_names))", "_____no_output_____" ], [ "precision, recall, total = get_precision_recall(names_sample, all_candidates, input_names_test, weighted_relevant_names_test, \n super_cluster_names, name_super_cluster)\nprint(\"Total=\", total, \" Precision=\", precision, \" Recall=\", recall)", "_____no_output_____" ], [ "# get cluster names for each name in super cluster\nsuper_cluster_clusters = {id: set([cluster_id_name_map[name_cluster[name]] for name in names]) for id, names in super_cluster_names.items()}", "_____no_output_____" ] ], [ [ "### Write super-clusters", "_____no_output_____" ] ], [ [ "_ = write_clusters(super_clusters_filename, super_cluster_clusters, name_freqs, None)", "_____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" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d0301f3268c33cf9bf0b8733e2b05f91f4554c85
2,619
ipynb
Jupyter Notebook
docs/examples/try_me_out/voyages_congestion_breakdown.ipynb
V0RT3X4/python-sdk
4cffae83b90a58a56f1a534057fa1ca1c8671e05
[ "Apache-2.0" ]
9
2019-11-13T17:14:55.000Z
2019-11-18T16:06:13.000Z
docs/examples/try_me_out/voyages_congestion_breakdown.ipynb
V0RT3X4/python-sdk
4cffae83b90a58a56f1a534057fa1ca1c8671e05
[ "Apache-2.0" ]
84
2019-11-14T16:57:12.000Z
2020-01-06T04:00:21.000Z
docs/examples/try_me_out/voyages_congestion_breakdown.ipynb
V0RT3X4/python-sdk
4cffae83b90a58a56f1a534057fa1ca1c8671e05
[ "Apache-2.0" ]
null
null
null
22.973684
139
0.560137
[ [ [ "### This notebook gives a 30 second introduction to the Vortexa SDK", "_____no_output_____" ], [ "First let's import our requirements", "_____no_output_____" ] ], [ [ "from datetime import datetime\nimport vortexasdk as v", "_____no_output_____" ] ], [ [ "Now let's load a dataframe of a sum of vessels in congestion.", "_____no_output_____" ], [ "You'll need to enter your Vortexa API key when prompted.", "_____no_output_____" ] ], [ [ "df = v.VoyagesCongestionBreakdown()\\\n .search(\n time_min=datetime(2021, 8, 1, 0),\n time_max=datetime(2021, 8, 1, 23))\\\n .to_df()", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "That's it! You've successfully loaded data using the Vortexa SDK. Check out https://vortechsa.github.io/python-sdk/ for more examples", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d03027dae62dddc212cf4e9f91fa1da9a6f37f74
43,941
ipynb
Jupyter Notebook
site/en/r2/tutorials/load_data/images.ipynb
Terahezi/docs
b5bfd2e53de4efbe1b5eef234d26b72a4fedb147
[ "Apache-2.0" ]
null
null
null
site/en/r2/tutorials/load_data/images.ipynb
Terahezi/docs
b5bfd2e53de4efbe1b5eef234d26b72a4fedb147
[ "Apache-2.0" ]
null
null
null
site/en/r2/tutorials/load_data/images.ipynb
Terahezi/docs
b5bfd2e53de4efbe1b5eef234d26b72a4fedb147
[ "Apache-2.0" ]
null
null
null
26.614779
282
0.486516
[ [ [ "##### Copyright 2019 The TensorFlow Authors.", "_____no_output_____" ] ], [ [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n", "_____no_output_____" ] ], [ [ "# Load images with tf.data", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/beta/tutorials/load_data/images\"><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/r2/tutorials/load_data/images.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/r2/tutorials/load_data/images.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/r2/tutorials/load_data/images.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>", "_____no_output_____" ], [ "This tutorial provides a simple example of how to load an image dataset using `tf.data`.\n\nThe dataset used in this example is distributed as directories of images, with one class of image per directory.", "_____no_output_____" ], [ "## Setup", "_____no_output_____" ] ], [ [ "from __future__ import absolute_import, division, print_function, unicode_literals\n\n!pip install tensorflow==2.0.0-beta1\nimport tensorflow as tf", "_____no_output_____" ], [ "AUTOTUNE = tf.data.experimental.AUTOTUNE", "_____no_output_____" ] ], [ [ "## Download and inspect the dataset", "_____no_output_____" ], [ "### Retrieve the images\n\nBefore you start any training, you will need a set of images to teach the network about the new classes you want to recognize. You have already created an archive of creative-commons licensed flower photos to use initially:", "_____no_output_____" ] ], [ [ "import pathlib\ndata_root_orig = tf.keras.utils.get_file(origin='https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',\n fname='flower_photos', untar=True)\ndata_root = pathlib.Path(data_root_orig)\nprint(data_root)", "_____no_output_____" ] ], [ [ "After downloading 218MB, you should now have a copy of the flower photos available:", "_____no_output_____" ] ], [ [ "for item in data_root.iterdir():\n print(item)", "_____no_output_____" ], [ "import random\nall_image_paths = list(data_root.glob('*/*'))\nall_image_paths = [str(path) for path in all_image_paths]\nrandom.shuffle(all_image_paths)\n\nimage_count = len(all_image_paths)\nimage_count", "_____no_output_____" ], [ "all_image_paths[:10]", "_____no_output_____" ] ], [ [ "### Inspect the images\nNow let's have a quick look at a couple of the images, so you know what you are dealing with:", "_____no_output_____" ] ], [ [ "import os\nattributions = (data_root/\"LICENSE.txt\").open(encoding='utf-8').readlines()[4:]\nattributions = [line.split(' CC-BY') for line in attributions]\nattributions = dict(attributions)", "_____no_output_____" ], [ "import IPython.display as display\n\ndef caption_image(image_path):\n image_rel = pathlib.Path(image_path).relative_to(data_root)\n return \"Image (CC BY 2.0) \" + ' - '.join(attributions[str(image_rel)].split(' - ')[:-1])\n", "_____no_output_____" ], [ "for n in range(3):\n image_path = random.choice(all_image_paths)\n display.display(display.Image(image_path))\n print(caption_image(image_path))\n print()", "_____no_output_____" ] ], [ [ "### Determine the label for each image", "_____no_output_____" ], [ "List the available labels:", "_____no_output_____" ] ], [ [ "label_names = sorted(item.name for item in data_root.glob('*/') if item.is_dir())\nlabel_names", "_____no_output_____" ] ], [ [ "Assign an index to each label:", "_____no_output_____" ] ], [ [ "label_to_index = dict((name, index) for index, name in enumerate(label_names))\nlabel_to_index", "_____no_output_____" ] ], [ [ "Create a list of every file, and its label index:", "_____no_output_____" ] ], [ [ "all_image_labels = [label_to_index[pathlib.Path(path).parent.name]\n for path in all_image_paths]\n\nprint(\"First 10 labels indices: \", all_image_labels[:10])", "_____no_output_____" ] ], [ [ "### Load and format the images", "_____no_output_____" ], [ "TensorFlow includes all the tools you need to load and process images:", "_____no_output_____" ] ], [ [ "img_path = all_image_paths[0]\nimg_path", "_____no_output_____" ] ], [ [ "Here is the raw data:", "_____no_output_____" ] ], [ [ "img_raw = tf.io.read_file(img_path)\nprint(repr(img_raw)[:100]+\"...\")", "_____no_output_____" ] ], [ [ "Decode it into an image tensor:", "_____no_output_____" ] ], [ [ "img_tensor = tf.image.decode_image(img_raw)\n\nprint(img_tensor.shape)\nprint(img_tensor.dtype)", "_____no_output_____" ] ], [ [ "Resize it for your model:", "_____no_output_____" ] ], [ [ "img_final = tf.image.resize(img_tensor, [192, 192])\nimg_final = img_final/255.0\nprint(img_final.shape)\nprint(img_final.numpy().min())\nprint(img_final.numpy().max())\n", "_____no_output_____" ] ], [ [ "Wrap up these up in simple functions for later.", "_____no_output_____" ] ], [ [ "def preprocess_image(image):\n image = tf.image.decode_jpeg(image, channels=3)\n image = tf.image.resize(image, [192, 192])\n image /= 255.0 # normalize to [0,1] range\n\n return image", "_____no_output_____" ], [ "def load_and_preprocess_image(path):\n image = tf.io.read_file(path)\n return preprocess_image(image)", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nimage_path = all_image_paths[0]\nlabel = all_image_labels[0]\n\nplt.imshow(load_and_preprocess_image(img_path))\nplt.grid(False)\nplt.xlabel(caption_image(img_path))\nplt.title(label_names[label].title())\nprint()", "_____no_output_____" ] ], [ [ "## Build a `tf.data.Dataset`", "_____no_output_____" ], [ "### A dataset of images", "_____no_output_____" ], [ "The easiest way to build a `tf.data.Dataset` is using the `from_tensor_slices` method.\n\nSlicing the array of strings, results in a dataset of strings:", "_____no_output_____" ] ], [ [ "path_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)", "_____no_output_____" ] ], [ [ "The `shapes` and `types` describe the content of each item in the dataset. In this case it is a set of scalar binary-strings", "_____no_output_____" ] ], [ [ "print(path_ds)", "_____no_output_____" ] ], [ [ "Now create a new dataset that loads and formats images on the fly by mapping `preprocess_image` over the dataset of paths.", "_____no_output_____" ] ], [ [ "image_ds = path_ds.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(8,8))\nfor n, image in enumerate(image_ds.take(4)):\n plt.subplot(2,2,n+1)\n plt.imshow(image)\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n plt.xlabel(caption_image(all_image_paths[n]))\n plt.show()", "_____no_output_____" ] ], [ [ "### A dataset of `(image, label)` pairs", "_____no_output_____" ], [ "Using the same `from_tensor_slices` method you can build a dataset of labels:", "_____no_output_____" ] ], [ [ "label_ds = tf.data.Dataset.from_tensor_slices(tf.cast(all_image_labels, tf.int64))", "_____no_output_____" ], [ "for label in label_ds.take(10):\n print(label_names[label.numpy()])", "_____no_output_____" ] ], [ [ "Since the datasets are in the same order you can just zip them together to get a dataset of `(image, label)` pairs:", "_____no_output_____" ] ], [ [ "image_label_ds = tf.data.Dataset.zip((image_ds, label_ds))", "_____no_output_____" ] ], [ [ "The new dataset's `shapes` and `types` are tuples of shapes and types as well, describing each field:", "_____no_output_____" ] ], [ [ "print(image_label_ds)", "_____no_output_____" ] ], [ [ "Note: When you have arrays like `all_image_labels` and `all_image_paths` an alternative to `tf.data.dataset.Dataset.zip` is to slice the pair of arrays.", "_____no_output_____" ] ], [ [ "ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels))\n\n# The tuples are unpacked into the positional arguments of the mapped function\ndef load_and_preprocess_from_path_label(path, label):\n return load_and_preprocess_image(path), label\n\nimage_label_ds = ds.map(load_and_preprocess_from_path_label)\nimage_label_ds", "_____no_output_____" ] ], [ [ "### Basic methods for training", "_____no_output_____" ], [ "To train a model with this dataset you will want the data:\n\n* To be well shuffled.\n* To be batched.\n* To repeat forever.\n* Batches to be available as soon as possible.\n\nThese features can be easily added using the `tf.data` api.", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 32\n\n# Setting a shuffle buffer size as large as the dataset ensures that the data is\n# completely shuffled.\nds = image_label_ds.shuffle(buffer_size=image_count)\nds = ds.repeat()\nds = ds.batch(BATCH_SIZE)\n# `prefetch` lets the dataset fetch batches in the background while the model is training.\nds = ds.prefetch(buffer_size=AUTOTUNE)\nds", "_____no_output_____" ] ], [ [ "There are a few things to note here:\n\n1. The order is important.\n\n * A `.shuffle` after a `.repeat` would shuffle items across epoch boundaries (some items will be seen twice before others are seen at all).\n * A `.shuffle` after a `.batch` would shuffle the order of the batches, but not shuffle the items across batches.\n\n1. You use a `buffer_size` the same size as the dataset for a full shuffle. Up to the dataset size, large values provide better randomization, but use more memory.\n\n1. The shuffle buffer is filled before any elements are pulled from it. So a large `buffer_size` may cause a delay when your `Dataset` is starting.\n\n1. The shuffeled dataset doesn't report the end of a dataset until the shuffle-buffer is completely empty. The `Dataset` is restarted by `.repeat`, causing another wait for the shuffle-buffer to be filled.\n\nThis last point can be addressed by using the `tf.data.Dataset.apply` method with the fused `tf.data.experimental.shuffle_and_repeat` function:", "_____no_output_____" ] ], [ [ "ds = image_label_ds.apply(\n tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))\nds = ds.batch(BATCH_SIZE)\nds = ds.prefetch(buffer_size=AUTOTUNE)\nds", "_____no_output_____" ] ], [ [ "### Pipe the dataset to a model\n\nFetch a copy of MobileNet v2 from `tf.keras.applications`.\n\nThis will be used for a simple transfer learning example.\n\nSet the MobileNet weights to be non-trainable:", "_____no_output_____" ] ], [ [ "mobile_net = tf.keras.applications.MobileNetV2(input_shape=(192, 192, 3), include_top=False)\nmobile_net.trainable=False", "_____no_output_____" ] ], [ [ "This model expects its input to be normalized to the `[-1,1]` range:\n\n```\nhelp(keras_applications.mobilenet_v2.preprocess_input)\n```\n\n<pre>\n...\nThis function applies the \"Inception\" preprocessing which converts\nthe RGB values from [0, 255] to [-1, 1]\n...\n</pre>", "_____no_output_____" ], [ "Before you pass the input to the MobilNet model, you need to convert it from a range of `[0,1]` to `[-1,1]`:", "_____no_output_____" ] ], [ [ "def change_range(image,label):\n return 2*image-1, label\n\nkeras_ds = ds.map(change_range)", "_____no_output_____" ] ], [ [ "The MobileNet returns a `6x6` spatial grid of features for each image.\n\nPass it a batch of images to see:", "_____no_output_____" ] ], [ [ "# The dataset may take a few seconds to start, as it fills its shuffle buffer.\nimage_batch, label_batch = next(iter(keras_ds))", "_____no_output_____" ], [ "feature_map_batch = mobile_net(image_batch)\nprint(feature_map_batch.shape)", "_____no_output_____" ] ], [ [ "Build a model wrapped around MobileNet and use `tf.keras.layers.GlobalAveragePooling2D` to average over those space dimensions before the output `tf.keras.layers.Dense` layer:", "_____no_output_____" ] ], [ [ "model = tf.keras.Sequential([\n mobile_net,\n tf.keras.layers.GlobalAveragePooling2D(),\n tf.keras.layers.Dense(len(label_names))])", "_____no_output_____" ] ], [ [ "Now it produces outputs of the expected shape:", "_____no_output_____" ] ], [ [ "logit_batch = model(image_batch).numpy()\n\nprint(\"min logit:\", logit_batch.min())\nprint(\"max logit:\", logit_batch.max())\nprint()\n\nprint(\"Shape:\", logit_batch.shape)", "_____no_output_____" ] ], [ [ "Compile the model to describe the training procedure:", "_____no_output_____" ] ], [ [ "model.compile(optimizer=tf.keras.optimizers.Adam(),\n loss='sparse_categorical_crossentropy',\n metrics=[\"accuracy\"])", "_____no_output_____" ] ], [ [ "There are 2 trainable variables - the Dense `weights` and `bias`:", "_____no_output_____" ] ], [ [ "len(model.trainable_variables)", "_____no_output_____" ], [ "model.summary()", "_____no_output_____" ] ], [ [ "You are ready to train the model.\n\nNote that for demonstration purposes you will only run 3 steps per epoch, but normally you would specify the real number of steps, as defined below, before passing it to `model.fit()`:", "_____no_output_____" ] ], [ [ "steps_per_epoch=tf.math.ceil(len(all_image_paths)/BATCH_SIZE).numpy()\nsteps_per_epoch", "_____no_output_____" ], [ "model.fit(ds, epochs=1, steps_per_epoch=3)", "_____no_output_____" ] ], [ [ "## Performance\n\nNote: This section just shows a couple of easy tricks that may help performance. For an in depth guide see [Input Pipeline Performance](https://www.tensorflow.org/guide/performance/datasets).\n\nThe simple pipeline used above reads each file individually, on each epoch. This is fine for local training on CPU, but may not be sufficient for GPU training and is totally inappropriate for any sort of distributed training.", "_____no_output_____" ], [ "To investigate, first build a simple function to check the performance of our datasets:", "_____no_output_____" ] ], [ [ "import time\ndefault_timeit_steps = 2*steps_per_epoch+1\n\ndef timeit(ds, steps=default_timeit_steps):\n overall_start = time.time()\n # Fetch a single batch to prime the pipeline (fill the shuffle buffer),\n # before starting the timer\n it = iter(ds.take(steps+1))\n next(it)\n\n start = time.time()\n for i,(images,labels) in enumerate(it):\n if i%10 == 0:\n print('.',end='')\n print()\n end = time.time()\n\n duration = end-start\n print(\"{} batches: {} s\".format(steps, duration))\n print(\"{:0.5f} Images/s\".format(BATCH_SIZE*steps/duration))\n print(\"Total time: {}s\".format(end-overall_start))", "_____no_output_____" ] ], [ [ "The performance of the current dataset is:", "_____no_output_____" ] ], [ [ "ds = image_label_ds.apply(\n tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))\nds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)\nds", "_____no_output_____" ], [ "timeit(ds)", "_____no_output_____" ] ], [ [ "### Cache", "_____no_output_____" ], [ "Use `tf.data.Dataset.cache` to easily cache calculations across epochs. This is very efficient, especially when the data fits in memory.\n\nHere the images are cached, after being pre-precessed (decoded and resized):", "_____no_output_____" ] ], [ [ "ds = image_label_ds.cache()\nds = ds.apply(\n tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))\nds = ds.batch(BATCH_SIZE).prefetch(buffer_size=AUTOTUNE)\nds", "_____no_output_____" ], [ "timeit(ds)", "_____no_output_____" ] ], [ [ "One disadvantage to using an in memory cache is that the cache must be rebuilt on each run, giving the same startup delay each time the dataset is started:", "_____no_output_____" ] ], [ [ "timeit(ds)", "_____no_output_____" ] ], [ [ "If the data doesn't fit in memory, use a cache file:", "_____no_output_____" ] ], [ [ "ds = image_label_ds.cache(filename='./cache.tf-data')\nds = ds.apply(\n tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))\nds = ds.batch(BATCH_SIZE).prefetch(1)\nds", "_____no_output_____" ], [ "timeit(ds)", "_____no_output_____" ] ], [ [ "The cache file also has the advantage that it can be used to quickly restart the dataset without rebuilding the cache. Note how much faster it is the second time:", "_____no_output_____" ] ], [ [ "timeit(ds)", "_____no_output_____" ] ], [ [ "### TFRecord File", "_____no_output_____" ], [ "#### Raw image data\n\nTFRecord files are a simple format to store a sequence of binary blobs. By packing multiple examples into the same file, TensorFlow is able to read multiple examples at once, which is especially important for performance when using a remote storage service such as GCS.\n\nFirst, build a TFRecord file from the raw image data:", "_____no_output_____" ] ], [ [ "image_ds = tf.data.Dataset.from_tensor_slices(all_image_paths).map(tf.io.read_file)\ntfrec = tf.data.experimental.TFRecordWriter('images.tfrec')\ntfrec.write(image_ds)", "_____no_output_____" ] ], [ [ "Next, build a dataset that reads from the TFRecord file and decodes/reformats the images using the `preprocess_image` function you defined earlier:", "_____no_output_____" ] ], [ [ "image_ds = tf.data.TFRecordDataset('images.tfrec').map(preprocess_image)", "_____no_output_____" ] ], [ [ "Zip that dataset with the labels dataset you defined earlier to get the expected `(image,label)` pairs:", "_____no_output_____" ] ], [ [ "ds = tf.data.Dataset.zip((image_ds, label_ds))\nds = ds.apply(\n tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))\nds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)\nds", "_____no_output_____" ], [ "timeit(ds)", "_____no_output_____" ] ], [ [ "This is slower than the `cache` version because you have not cached the preprocessing.", "_____no_output_____" ], [ "#### Serialized Tensors", "_____no_output_____" ], [ "To save some preprocessing to the TFRecord file, first make a dataset of the processed images, as before:", "_____no_output_____" ] ], [ [ "paths_ds = tf.data.Dataset.from_tensor_slices(all_image_paths)\nimage_ds = paths_ds.map(load_and_preprocess_image)\nimage_ds", "_____no_output_____" ] ], [ [ "Now instead of a dataset of `.jpeg` strings, you have a dataset of tensors.\n\nTo serialize this to a TFRecord file you first convert the dataset of tensors to a dataset of strings:", "_____no_output_____" ] ], [ [ "ds = image_ds.map(tf.io.serialize_tensor)\nds", "_____no_output_____" ], [ "tfrec = tf.data.experimental.TFRecordWriter('images.tfrec')\ntfrec.write(ds)", "_____no_output_____" ] ], [ [ "With the preprocessing cached, data can be loaded from the TFrecord file quite efficiently - just remember to de-serialize tensor before using it:", "_____no_output_____" ] ], [ [ "ds = tf.data.TFRecordDataset('images.tfrec')\n\ndef parse(x):\n result = tf.io.parse_tensor(x, out_type=tf.float32)\n result = tf.reshape(result, [192, 192, 3])\n return result\n\nds = ds.map(parse, num_parallel_calls=AUTOTUNE)\nds", "_____no_output_____" ] ], [ [ "Now, add the labels and apply the same standard operations, as before:", "_____no_output_____" ] ], [ [ "ds = tf.data.Dataset.zip((ds, label_ds))\nds = ds.apply(\n tf.data.experimental.shuffle_and_repeat(buffer_size=image_count))\nds=ds.batch(BATCH_SIZE).prefetch(AUTOTUNE)\nds", "_____no_output_____" ], [ "timeit(ds)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d030301a6bf9145d39aadd3250ba11101d58a861
16,557
ipynb
Jupyter Notebook
nbs/01a_losses.ipynb
aaminggo/fastai
fbc60a2bbfc13a92a71af657e0052761116ab447
[ "Apache-2.0" ]
1
2022-02-06T22:11:10.000Z
2022-02-06T22:11:10.000Z
nbs/01a_losses.ipynb
aaminggo/fastai
fbc60a2bbfc13a92a71af657e0052761116ab447
[ "Apache-2.0" ]
null
null
null
nbs/01a_losses.ipynb
aaminggo/fastai
fbc60a2bbfc13a92a71af657e0052761116ab447
[ "Apache-2.0" ]
null
null
null
33.858896
557
0.593586
[ [ [ "#hide\n#skip\n! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab", "_____no_output_____" ], [ "# default_exp losses\n# default_cls_lvl 3", "_____no_output_____" ], [ "#export\nfrom fastai.imports import *\nfrom fastai.torch_imports import *\nfrom fastai.torch_core import *\nfrom fastai.layers import *", "_____no_output_____" ], [ "#hide\nfrom nbdev.showdoc import *", "_____no_output_____" ] ], [ [ "# Loss Functions\n> Custom fastai loss functions", "_____no_output_____" ] ], [ [ "F.binary_cross_entropy_with_logits(torch.randn(4,5), torch.randint(0, 2, (4,5)).float(), reduction='none')", "_____no_output_____" ], [ "funcs_kwargs", "_____no_output_____" ], [ "# export\n@log_args\nclass BaseLoss():\n \"Same as `loss_cls`, but flattens input and target.\"\n activation=decodes=noops\n def __init__(self, loss_cls, *args, axis=-1, flatten=True, floatify=False, is_2d=True, **kwargs):\n store_attr(\"axis,flatten,floatify,is_2d\")\n self.func = loss_cls(*args,**kwargs)\n functools.update_wrapper(self, self.func)\n\n def __repr__(self): return f\"FlattenedLoss of {self.func}\"\n @property\n def reduction(self): return self.func.reduction\n @reduction.setter\n def reduction(self, v): self.func.reduction = v\n\n def __call__(self, inp, targ, **kwargs):\n inp = inp .transpose(self.axis,-1).contiguous()\n targ = targ.transpose(self.axis,-1).contiguous()\n if self.floatify and targ.dtype!=torch.float16: targ = targ.float()\n if targ.dtype in [torch.int8, torch.int16, torch.int32]: targ = targ.long()\n if self.flatten: inp = inp.view(-1,inp.shape[-1]) if self.is_2d else inp.view(-1)\n return self.func.__call__(inp, targ.view(-1) if self.flatten else targ, **kwargs)", "_____no_output_____" ] ], [ [ "Wrapping a general loss function inside of `BaseLoss` provides extra functionalities to your loss functions:\n- flattens the tensors before trying to take the losses since it's more convenient (with a potential tranpose to put `axis` at the end)\n- a potential `activation` method that tells the library if there is an activation fused in the loss (useful for inference and methods such as `Learner.get_preds` or `Learner.predict`)\n- a potential <code>decodes</code> method that is used on predictions in inference (for instance, an argmax in classification)", "_____no_output_____" ], [ "The `args` and `kwargs` will be passed to `loss_cls` during the initialization to instantiate a loss function. `axis` is put at the end for losses like softmax that are often performed on the last axis. If `floatify=True`, the `targs` will be converted to floats (useful for losses that only accept float targets like `BCEWithLogitsLoss`), and `is_2d` determines if we flatten while keeping the first dimension (batch size) or completely flatten the input. We want the first for losses like Cross Entropy, and the second for pretty much anything else.", "_____no_output_____" ] ], [ [ "# export\n@log_args\n@delegates()\nclass CrossEntropyLossFlat(BaseLoss):\n \"Same as `nn.CrossEntropyLoss`, but flattens input and target.\"\n y_int = True\n @use_kwargs_dict(keep=True, weight=None, ignore_index=-100, reduction='mean')\n def __init__(self, *args, axis=-1, **kwargs): super().__init__(nn.CrossEntropyLoss, *args, axis=axis, **kwargs)\n def decodes(self, x): return x.argmax(dim=self.axis)\n def activation(self, x): return F.softmax(x, dim=self.axis)", "_____no_output_____" ], [ "tst = CrossEntropyLossFlat()\noutput = torch.randn(32, 5, 10)\ntarget = torch.randint(0, 10, (32,5))\n#nn.CrossEntropy would fail with those two tensors, but not our flattened version.\n_ = tst(output, target)\ntest_fail(lambda x: nn.CrossEntropyLoss()(output,target))\n\n#Associated activation is softmax\ntest_eq(tst.activation(output), F.softmax(output, dim=-1))\n#This loss function has a decodes which is argmax\ntest_eq(tst.decodes(output), output.argmax(dim=-1))", "_____no_output_____" ], [ "#In a segmentation task, we want to take the softmax over the channel dimension\ntst = CrossEntropyLossFlat(axis=1)\noutput = torch.randn(32, 5, 128, 128)\ntarget = torch.randint(0, 5, (32, 128, 128))\n_ = tst(output, target)\n\ntest_eq(tst.activation(output), F.softmax(output, dim=1))\ntest_eq(tst.decodes(output), output.argmax(dim=1))", "_____no_output_____" ], [ "# export\n@log_args\n@delegates()\nclass BCEWithLogitsLossFlat(BaseLoss):\n \"Same as `nn.BCEWithLogitsLoss`, but flattens input and target.\"\n @use_kwargs_dict(keep=True, weight=None, reduction='mean', pos_weight=None)\n def __init__(self, *args, axis=-1, floatify=True, thresh=0.5, **kwargs):\n super().__init__(nn.BCEWithLogitsLoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)\n self.thresh = thresh\n\n def decodes(self, x): return x>self.thresh\n def activation(self, x): return torch.sigmoid(x)", "_____no_output_____" ], [ "tst = BCEWithLogitsLossFlat()\noutput = torch.randn(32, 5, 10)\ntarget = torch.randn(32, 5, 10)\n#nn.BCEWithLogitsLoss would fail with those two tensors, but not our flattened version.\n_ = tst(output, target)\ntest_fail(lambda x: nn.BCEWithLogitsLoss()(output,target))\noutput = torch.randn(32, 5)\ntarget = torch.randint(0,2,(32, 5))\n#nn.BCEWithLogitsLoss would fail with int targets but not our flattened version.\n_ = tst(output, target)\ntest_fail(lambda x: nn.BCEWithLogitsLoss()(output,target))\n\n#Associated activation is sigmoid\ntest_eq(tst.activation(output), torch.sigmoid(output))", "_____no_output_____" ], [ "# export\n@log_args(to_return=True)\n@use_kwargs_dict(weight=None, reduction='mean')\ndef BCELossFlat(*args, axis=-1, floatify=True, **kwargs):\n \"Same as `nn.BCELoss`, but flattens input and target.\"\n return BaseLoss(nn.BCELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)", "_____no_output_____" ], [ "tst = BCELossFlat()\noutput = torch.sigmoid(torch.randn(32, 5, 10))\ntarget = torch.randint(0,2,(32, 5, 10))\n_ = tst(output, target)\ntest_fail(lambda x: nn.BCELoss()(output,target))", "_____no_output_____" ], [ "# export\n@log_args(to_return=True)\n@use_kwargs_dict(reduction='mean')\ndef MSELossFlat(*args, axis=-1, floatify=True, **kwargs):\n \"Same as `nn.MSELoss`, but flattens input and target.\"\n return BaseLoss(nn.MSELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)", "_____no_output_____" ], [ "tst = MSELossFlat()\noutput = torch.sigmoid(torch.randn(32, 5, 10))\ntarget = torch.randint(0,2,(32, 5, 10))\n_ = tst(output, target)\ntest_fail(lambda x: nn.MSELoss()(output,target))", "_____no_output_____" ], [ "#hide\n#cuda\n#Test losses work in half precision\noutput = torch.sigmoid(torch.randn(32, 5, 10)).half().cuda()\ntarget = torch.randint(0,2,(32, 5, 10)).half().cuda()\nfor tst in [BCELossFlat(), MSELossFlat()]: _ = tst(output, target)", "_____no_output_____" ], [ "# export\n@log_args(to_return=True)\n@use_kwargs_dict(reduction='mean')\ndef L1LossFlat(*args, axis=-1, floatify=True, **kwargs):\n \"Same as `nn.L1Loss`, but flattens input and target.\"\n return BaseLoss(nn.L1Loss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)", "_____no_output_____" ], [ "#export\n@log_args\nclass LabelSmoothingCrossEntropy(Module):\n y_int = True\n def __init__(self, eps:float=0.1, reduction='mean'): self.eps,self.reduction = eps,reduction\n\n def forward(self, output, target):\n c = output.size()[-1]\n log_preds = F.log_softmax(output, dim=-1)\n if self.reduction=='sum': loss = -log_preds.sum()\n else:\n loss = -log_preds.sum(dim=-1) #We divide by that size at the return line so sum and not mean\n if self.reduction=='mean': loss = loss.mean()\n return loss*self.eps/c + (1-self.eps) * F.nll_loss(log_preds, target.long(), reduction=self.reduction)\n\n def activation(self, out): return F.softmax(out, dim=-1)\n def decodes(self, out): return out.argmax(dim=-1)", "_____no_output_____" ] ], [ [ "On top of the formula we define:\n- a `reduction` attribute, that will be used when we call `Learner.get_preds`\n- an `activation` function that represents the activation fused in the loss (since we use cross entropy behind the scenes). It will be applied to the output of the model when calling `Learner.get_preds` or `Learner.predict`\n- a <code>decodes</code> function that converts the output of the model to a format similar to the target (here indices). This is used in `Learner.predict` and `Learner.show_results` to decode the predictions ", "_____no_output_____" ] ], [ [ "#export\n@log_args\n@delegates()\nclass LabelSmoothingCrossEntropyFlat(BaseLoss):\n \"Same as `LabelSmoothingCrossEntropy`, but flattens input and target.\"\n y_int = True\n @use_kwargs_dict(keep=True, eps=0.1, reduction='mean')\n def __init__(self, *args, axis=-1, **kwargs): super().__init__(LabelSmoothingCrossEntropy, *args, axis=axis, **kwargs)\n def activation(self, out): return F.softmax(out, dim=-1)\n def decodes(self, out): return out.argmax(dim=-1)", "_____no_output_____" ] ], [ [ "## Export -", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.export import *\nnotebook2script()", "Converted 00_torch_core.ipynb.\nConverted 01_layers.ipynb.\nConverted 02_data.load.ipynb.\nConverted 03_data.core.ipynb.\nConverted 04_data.external.ipynb.\nConverted 05_data.transforms.ipynb.\nConverted 06_data.block.ipynb.\nConverted 07_vision.core.ipynb.\nConverted 08_vision.data.ipynb.\nConverted 09_vision.augment.ipynb.\nConverted 09b_vision.utils.ipynb.\nConverted 09c_vision.widgets.ipynb.\nConverted 10_tutorial.pets.ipynb.\nConverted 11_vision.models.xresnet.ipynb.\nConverted 12_optimizer.ipynb.\nConverted 13_callback.core.ipynb.\nConverted 13a_learner.ipynb.\nConverted 13b_metrics.ipynb.\nConverted 14_callback.schedule.ipynb.\nConverted 14a_callback.data.ipynb.\nConverted 15_callback.hook.ipynb.\nConverted 15a_vision.models.unet.ipynb.\nConverted 16_callback.progress.ipynb.\nConverted 17_callback.tracker.ipynb.\nConverted 18_callback.fp16.ipynb.\nConverted 18a_callback.training.ipynb.\nConverted 19_callback.mixup.ipynb.\nConverted 20_interpret.ipynb.\nConverted 20a_distributed.ipynb.\nConverted 21_vision.learner.ipynb.\nConverted 22_tutorial.imagenette.ipynb.\nConverted 23_tutorial.vision.ipynb.\nConverted 24_tutorial.siamese.ipynb.\nConverted 24_vision.gan.ipynb.\nConverted 30_text.core.ipynb.\nConverted 31_text.data.ipynb.\nConverted 32_text.models.awdlstm.ipynb.\nConverted 33_text.models.core.ipynb.\nConverted 34_callback.rnn.ipynb.\nConverted 35_tutorial.wikitext.ipynb.\nConverted 36_text.models.qrnn.ipynb.\nConverted 37_text.learner.ipynb.\nConverted 38_tutorial.text.ipynb.\nConverted 40_tabular.core.ipynb.\nConverted 41_tabular.data.ipynb.\nConverted 42_tabular.model.ipynb.\nConverted 43_tabular.learner.ipynb.\nConverted 44_tutorial.tabular.ipynb.\nConverted 45_collab.ipynb.\nConverted 46_tutorial.collab.ipynb.\nConverted 50_tutorial.datablock.ipynb.\nConverted 60_medical.imaging.ipynb.\nConverted 61_tutorial.medical_imaging.ipynb.\nConverted 65_medical.text.ipynb.\nConverted 70_callback.wandb.ipynb.\nConverted 71_callback.tensorboard.ipynb.\nConverted 72_callback.neptune.ipynb.\nConverted 73_callback.captum.ipynb.\nConverted 74_callback.cutmix.ipynb.\nConverted 97_test_utils.ipynb.\nConverted 99_pytorch_doc.ipynb.\nConverted index.ipynb.\nConverted tutorial.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d030349993ca10ae3b8b23ff27ae189c4fab3c5d
14,729
ipynb
Jupyter Notebook
index.ipynb
Chibikuri/qiskit-tutorials
15c121b95249de17e311c869fbc455210b2fcf5e
[ "Apache-2.0" ]
null
null
null
index.ipynb
Chibikuri/qiskit-tutorials
15c121b95249de17e311c869fbc455210b2fcf5e
[ "Apache-2.0" ]
null
null
null
index.ipynb
Chibikuri/qiskit-tutorials
15c121b95249de17e311c869fbc455210b2fcf5e
[ "Apache-2.0" ]
1
2021-10-30T18:09:36.000Z
2021-10-30T18:09:36.000Z
57.988189
654
0.681377
[ [ [ "<img src=\"images/qiskit-heading.gif\" alt=\"Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook\" width=\"500 px\" align=\"left\">", "_____no_output_____" ], [ "# Qiskit Tutorials\n\n***\n\n\nWelcome Qiskitters.\n\nThe easiest way to get started is to use [the Binder image](https://mybinder.org/v2/gh/qiskit/qiskit-tutorials/master?filepath=index.ipynb), which lets you use the notebooks via the web. This means that you don't need to download or install anything, but is also means that you should not insert any private information into the notebooks (such as your API key). We recommend that after you are done using mybinder that you regenerate your token. \n\nThe tutorials can be downloaded by clicking [here](https://github.com/Qiskit/qiskit-tutorials/archive/master.zip) and to set them up follow the installation instructions [here](https://github.com/Qiskit/qiskit-tutorial/blob/master/INSTALL.md).\n\n***\n\n## Contents\nWe have organized the tutorials into two sections:\n\n\n### 1. Qiskit\n\nThese tutorials aim to explain how to use Qiskit. We assume you have installed Qiskit if not please look at [qiskit.org](http://www.qiskit.org) or the install [documentation](https://github.com/qiskit/qiskit-tutorial/blob/master/INSTALL.md). \n\n\nWe've collected a core reference set of notebooks in this section outlining the features of Qiskit. We will be keeping them up to date with the latest Qiskit version, currently 0.7. The focus of this section will be how to use Qiskit and not so much on teaching you about quantum computing. For those interested in learning about quantum computing we recommend the awesome notebooks in the community section.\n\n\nQiskit is made up of four elements: Terra, Aer, Ignis, and Aqua with each element having its own goal and together they make the full Qiskit framework. \n\n#### 1.1 Getting started with Qiskit\n\nA central goal of Qiskit is to build a software stack that makes it easy for anyone to use quantum computers. To get developers and researchers going we have a set of tutorials on the basics. \n\n * [Getting started with Qiskit](qiskit/basics/getting_started_with_qiskit.ipynb) - how to use Qiskit\n * [The IBM Q provider](qiskit/basics/the_ibmq_provider.ipynb) - working with the IBM Q devices\n * [Plotting data in Qiskit](qiskit/basics/plotting_data_in_qiskit.ipynb) - illustrates the different ways of plotting data in Qiskit\n \n#### 1.2 Qiskit Terra\n\nTerra, the ‘earth’ element, is the foundation on which the rest of the software lies. Terra provides a bedrock for composing quantum programs at the level of circuits and pulses, to optimize them for the constraints of a particular device, and to manage the execution of batches of experiments on remote-access devices. Terra defines the interfaces for a desirable end-user experience, as well as the efficient handling of layers of optimization, pulse scheduling and backend communication.\n * [Quantum circuits](qiskit/terra/quantum_circuits.ipynb) - gives a summary of the `QuantumCircuit` object\n * [Visualizing a quantum circuit](qiskit/terra/visualizing_a_quantum_circuit.ipynb) - details on drawing your quantum circuits\n * [Summary of quantum operations](qiskit/terra/summary_of_quantum_operations.ipynb) - list of quantum operations (gates, reset, measurements) in Qiskit Terra\n * [Monitoring jobs and backends](qiskit/terra/backend_monitoring_tools.ipynb) - tools for monitoring jobs and backends\n * [Parallel tools](qiskit/terra/terra_parallel_tools.ipynb) - executing tasks in parallel using `parallel_map` and tracking progress\n * [Creating a new provider](qiskit/terra/creating_a_provider.ipynb) - a guide to integration of a new provider with Qiskit structures and interfaces\n \n#### 1.3 Qiskit Interacitve Plotting and Jupyter Tools\n\nTo improve the Qiskit user experience we have made many of the visualizations interactive and developed some very cool new job monitoring tools in Jupyter.\n\n * [Jupyter tools for Monitoring jobs and backends](qiskit/jupyter/jupyter_backend_tools.ipynb) - Jupyter tools for monitoring jobs and backends\n\n#### 1.4 Qiskit Aer\n\nAer, the ‘air’ element, permeates all Qiskit elements. To really speed up development of quantum computers we need better simulators with the ability to model realistic noise processes that occur during computation on actual devices. Aer provides a high-performance simulator framework for studying quantum computing algorithms and applications in the noisy intermediate scale quantum regime. \n * [Aer provider](qiskit/aer/aer_provider.ipynb) - gives a summary of the Qiskit Aer provider containing the Qasm, statevector, and unitary simulator\n * [Device noise simulation](qiskit/aer/device_noise_simulation.ipynb) - shows how to use the Qiskit Aer noise module to automatically generate a basic noise model for simulating hardware backends\n \n#### 1.5 Qiskit Ignis\nIgnis, the ‘fire’ element, is dedicated to fighting noise and errors and to forging a new path. This includes better characterization of errors, improving gates, and computing in the presence of noise. Ignis is meant for those who want to design quantum error correction codes, or who wish to study ways to characterize errors through methods such as tomography, or even to find a better way for using gates by exploring dynamical decoupling and optimal control. While we have already released parts of this element as part of libraries in Terra, an official stand-alone release will come soon. For now we have some tutorials for you to explore.\n * [Relaxation and decoherence](qiskit/ignis/relaxation_and_decoherence.ipynb) - how to measure coherence times on the real quantum hardware\n * [Quantum state tomography](qiskit/ignis/state_tomography.ipynb) - how to identify a quantum state using state tomography, in which the state is prepared repeatedly and measured in different bases\n * [Quantum process tomography](qiskit/ignis/process_tomography.ipynb) - using quantum process tomography to reconstruct the behavior of a quantum process and measure its fidelity, i.e., how closely it matches the ideal version\n\n#### 1.6 Qiskit Aqua\nAqua, the ‘water’ element, is the element of life. To make quantum computing live up to its expectations, we need to find real-world applications. Aqua is where algorithms for NISQ computers are built. These algorithms can be used to build applications for quantum computing. Aqua is accessible to domain experts in chemistry, optimization, AI or finance, who want to explore the benefits of using quantum computers as accelerators for specific computational tasks, without needing to worry about how to translate the problem into the language of quantum machines.\n * [Chemistry](qiskit/aqua/chemistry/index.ipynb) - using variational quantum eigensolver to experiment with molecular ground-state energy on a quantum computer\n * [Optimization](qiskit/aqua/optimization/index.ipynb) - using variational quantum eigensolver to experiment with optimization problems (maxcut and traveling salesman problem) on a quantum computer \n * [Artificial Intelligence](qiskit/aqua/artificial_intelligence/index.ipynb) - using quantum-enhanced support vector machine to experiment with classification problems on a quantum computer\n * [Finance](qiskit/aqua/finance/index.ipynb) - using variational quantum eigensolver to optimize portfolio on a quantum computer \n\n### 2. Community Notebooks\n\nTeaching quantum and qiskit has so many different paths of learning. We love our community and we love the contributions so keep them coming. Because Qiskit is changing so much we can't keep this updated (we will try our best) but there are some great notebooks in here.\n\n#### 2.1 [Hello, Quantum World with Qiskit](community/hello_world/) \nLearn from the community how to write your first quantum program.\n\n#### 2.2 [Quantum Games with Qiskit](community/games/)\nLearn quantum computing by having fun. How is there a better way!\n\n#### 2.3 [Quantum Information Science with Qiskit Terra](community/terra/index.ipynb)\nLearn about and how to program quantum circuits using Qiskit Terra. \n\n#### 2.4 [Textbook Quantum Algorithms with Qiskit Terra](community/algorithms/index.ipynb)\nLearn about textbook quantum algorithms, like Deutsch-Jozsa, Grover, and Shor using Qiskit Terra. \n\n#### 2.5 [Developing Quantum Applications with Qiskit Aqua](community/aqua/index.ipynb)\nLearn how to develop and the fundamentals of quantum applications using Qiskit Aqua\n\n#### 2.6 Awards\nLearn from the great contributions to the [IBM Q Awards](https://qe-awards.mybluemix.net/)\n* [Teach Me Qiskit 2018](community/awards/teach_me_qiskit_2018/index.ipynb)\n* [Teach Me Quantum 2018](community/awards/teach_me_quantum_2018/index.ipynb)\n\n\n", "_____no_output_____" ] ], [ [ "from IPython.display import display, Markdown\nwith open('index.md', 'r') as readme: content = readme.read(); display(Markdown(content))", "_____no_output_____" ] ], [ [ "*** \n\n## License\nThis project is licensed under the Apache License 2.0 - see the [LICENSE](https://github.com/Qiskit/qiskit-tutorials/blob/master/LICENSE) file for details.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
d03052028d036682f1c1f9fa02c114fb72d3e6b1
8,158
ipynb
Jupyter Notebook
packages/nbinteract-core/example-notebooks/examples_central_limit_theorem.ipynb
samlaf/nbinteract
502b0a8e5f6236ed23d4a3d0dcc22db72f6d31e4
[ "BSD-3-Clause" ]
214
2017-12-11T21:32:15.000Z
2022-02-07T23:18:32.000Z
packages/nbinteract-core/example-notebooks/examples_central_limit_theorem.ipynb
samlaf/nbinteract
502b0a8e5f6236ed23d4a3d0dcc22db72f6d31e4
[ "BSD-3-Clause" ]
98
2017-12-21T06:48:23.000Z
2022-03-08T07:20:10.000Z
packages/nbinteract-core/example-notebooks/examples_central_limit_theorem.ipynb
samlaf/nbinteract
502b0a8e5f6236ed23d4a3d0dcc22db72f6d31e4
[ "BSD-3-Clause" ]
21
2018-01-25T09:10:20.000Z
2021-04-11T21:22:38.000Z
29.557971
333
0.557857
[ [ [ "# HIDDEN\nfrom datascience import *\n%matplotlib inline\nimport matplotlib.pyplot as plots\nplots.style.use('fivethirtyeight')\nimport math\nimport numpy as np\nfrom scipy import stats\nimport ipywidgets as widgets\nimport nbinteract as nbi", "_____no_output_____" ] ], [ [ "### The Central Limit Theorem ###\nVery few of the data histograms that we have seen in this course have been bell shaped. When we have come across a bell shaped distribution, it has almost invariably been an empirical histogram of a statistic based on a random sample.", "_____no_output_____" ], [ "**The Central Limit Theorem says that the probability distribution of the sum or average of a large random sample drawn with replacement will be roughly normal, *regardless of the distribution of the population from which the sample is drawn*.**\n\nAs we noted when we were studying Chebychev's bounds, results that can be applied to random samples *regardless of the distribution of the population* are very powerful, because in data science we rarely know the distribution of the population.\n\nThe Central Limit Theorem makes it possible to make inferences with very little knowledge about the population, provided we have a large random sample. That is why it is central to the field of statistical inference.", "_____no_output_____" ], [ "### Proportion of Purple Flowers ###\nRecall Mendel's probability model for the colors of the flowers of a species of pea plant. The model says that the flower colors of the plants are like draws made at random with replacement from {Purple, Purple, Purple, White}.\n\nIn a large sample of plants, about what proportion will have purple flowers? We would expect the answer to be about 0.75, the proportion purple in the model. And, because proportions are means, the Central Limit Theorem says that the distribution of the sample proportion of purple plants is roughly normal.\n\nWe can confirm this by simulation. Let's simulate the proportion of purple-flowered plants in a sample of 200 plants.", "_____no_output_____" ] ], [ [ "colors = make_array('Purple', 'Purple', 'Purple', 'White')\n\nmodel = Table().with_column('Color', colors)\n\nmodel", "_____no_output_____" ], [ "props = make_array()\n\nnum_plants = 200\nrepetitions = 1000\n\nfor i in np.arange(repetitions):\n sample = model.sample(num_plants)\n new_prop = np.count_nonzero(sample.column('Color') == 'Purple')/num_plants\n props = np.append(props, new_prop)\nprops[:5]", "_____no_output_____" ], [ "opts = {\n 'title': 'Distribution of sample proportions',\n 'xlabel': 'Sample Proportion',\n 'ylabel': 'Percent per unit',\n 'xlim': (0.64, 0.84),\n 'ylim': (0, 25),\n 'bins': 20,\n}\nnbi.hist(props, options=opts)", "_____no_output_____" ] ], [ [ "There's that normal curve again, as predicted by the Central Limit Theorem, centered at around 0.75 just as you would expect.\n\nHow would this distribution change if we increased the sample size? We can copy our sampling code into a function and then use interaction to see how the distribution changes as the sample size increases.\n\nWe will keep the number of `repetitions` the same as before so that the two columns have the same length.", "_____no_output_____" ] ], [ [ "def empirical_props(num_plants):\n props = make_array()\n for i in np.arange(repetitions):\n sample = model.sample(num_plants)\n new_prop = np.count_nonzero(sample.column('Color') == 'Purple')/num_plants\n props = np.append(props, new_prop)\n return props", "_____no_output_____" ], [ "nbi.hist(empirical_props, options=opts,\n num_plants=widgets.ToggleButtons(options=[100, 200, 400, 800]))", "_____no_output_____" ] ], [ [ "All of the above distributions are approximately normal but become more narrow as the sample size increases. For example, the proportions based on a sample size of 800 are more tightly clustered around 0.75 than those from a sample size of 200. Increasing the sample size has decreased the variability in the sample proportion.", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d0305fd133873d27012609f0cd334e7fbba0ba38
230,512
ipynb
Jupyter Notebook
doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb
peterkolp/pyam
d0208d587a18bfde2b8c1c57a9bb110c73b3e61a
[ "Apache-2.0" ]
null
null
null
doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb
peterkolp/pyam
d0208d587a18bfde2b8c1c57a9bb110c73b3e61a
[ "Apache-2.0" ]
3
2019-01-25T17:09:30.000Z
2019-11-17T20:19:42.000Z
doc/source/tutorials/aggregating_variables_and_plotting_with_negative_values.ipynb
peterkolp/pyam
d0208d587a18bfde2b8c1c57a9bb110c73b3e61a
[ "Apache-2.0" ]
1
2019-02-09T20:24:25.000Z
2019-02-09T20:24:25.000Z
658.605714
56,476
0.94553
[ [ [ "# Plotting aggregate variables\n\nPyam offers many great visualisation and analysis tools. In this notebook we highlight the `aggregate` and `stack_plot` methods of an `IamDataFrame`. ", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\n\nimport pyam", "_____no_output_____" ], [ "%matplotlib inline\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "Here we provide some sample data for this tutorial. This data is for a single model-scenario-region combination but provides multiple subsectors of CO$_2$ emissions. The emissions in the subsectors are both positive and negative and so provide a good test of the flexibility of our aggregation and plotting routines.", "_____no_output_____" ] ], [ [ "df = pyam.IamDataFrame(pd.DataFrame([\n ['IMG', 'a_scen', 'World', 'Emissions|CO2|Energy|Oil', 'Mt CO2/yr', 2, 3.2, 2.0, 1.8],\n ['IMG', 'a_scen', 'World', 'Emissions|CO2|Energy|Gas', 'Mt CO2/yr', 1.3, 1.6, 1.0, 0.7],\n ['IMG', 'a_scen', 'World', 'Emissions|CO2|Energy|BECCS', 'Mt CO2/yr', 0.0, 0.4, -0.4, 0.3],\n ['IMG', 'a_scen', 'World', 'Emissions|CO2|Cars', 'Mt CO2/yr', 1.6, 3.8, 3.0, 2.5],\n ['IMG', 'a_scen', 'World', 'Emissions|CO2|Tar', 'Mt CO2/yr', 0.3, 0.35, 0.35, 0.33],\n ['IMG', 'a_scen', 'World', 'Emissions|CO2|Agg', 'Mt CO2/yr', 0.5, -0.1, -0.5, -0.7],\n ['IMG', 'a_scen', 'World', 'Emissions|CO2|LUC', 'Mt CO2/yr', -0.3, -0.6, -1.2, -1.0]\n ],\n columns=['model', 'scenario', 'region', 'variable', 'unit', 2005, 2010, 2015, 2020],\n))\ndf.head()", "_____no_output_____" ] ], [ [ "Pyam's `stack_plot` method plots the stacks in the clearest way possible, even when some emissions are negative. The optional `total` keyword arguments also allows the user to include a total line on their plot.", "_____no_output_____" ] ], [ [ "df.stack_plot();", "_____no_output_____" ], [ "df.stack_plot(total=True);", "_____no_output_____" ] ], [ [ "The appearance of the stackplot can be simply controlled via ``kwargs``. The appearance of the total line is controlled by passing a dictionary to the `total_kwargs` keyword argument.", "_____no_output_____" ] ], [ [ "df.stack_plot(alpha=0.5, total={\"color\": \"grey\", \"ls\": \"--\", \"lw\": 2.0});", "_____no_output_____" ] ], [ [ "If the user wishes, they can firstly filter their data before plotting.", "_____no_output_____" ] ], [ [ "df.filter(variable=\"Emissions|CO2|Energy*\").stack_plot(total=True);", "_____no_output_____" ] ], [ [ "Using `aggregate`, it is possible to create arbitrary sums of sub-sectors before plotting.", "_____no_output_____" ] ], [ [ "pdf = df.copy()\nafoluluc_vars = [\"Emissions|CO2|LUC\", \"Emissions|CO2|Agg\"]\nfossil_vars = list(set(pdf.variables()) - set(afoluluc_vars))\npdf.aggregate(\n \"Emissions|CO2|AFOLULUC\", \n components=afoluluc_vars, \n append=True\n)\npdf.aggregate(\n \"Emissions|CO2|Fossil\", \n components=fossil_vars, \n append=True\n)\npdf.filter(variable=[\n \"Emissions|CO2|AFOLULUC\",\n \"Emissions|CO2|Fossil\"\n]).stack_plot(total=True);", "_____no_output_____" ] ] ]
[ "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" ] ]
d0306f47d605fd3959ec0c32ca8de1d35734e1f0
33,737
ipynb
Jupyter Notebook
_posts/ipython-notebooks/ukelectionbbg.ipynb
jacolind/documentation
9d1be48c4e3ace06d9aab1b510fd48f25eb55b74
[ "CC-BY-3.0" ]
null
null
null
_posts/ipython-notebooks/ukelectionbbg.ipynb
jacolind/documentation
9d1be48c4e3ace06d9aab1b510fd48f25eb55b74
[ "CC-BY-3.0" ]
null
null
null
_posts/ipython-notebooks/ukelectionbbg.ipynb
jacolind/documentation
9d1be48c4e3ace06d9aab1b510fd48f25eb55b74
[ "CC-BY-3.0" ]
null
null
null
40.745169
727
0.57717
[ [ [ "Author: Saeed Amen (@thalesians) - Managing Director & Co-founder of [the Thalesians](http://www.thalesians.com)", "_____no_output_____" ], [ "## Introduction", "_____no_output_____" ], [ "With the UK general election in early May 2015, we thought it would be a fun exercise to demonstrate how you can investigate market price action over historial elections. We shall be using Python, together with Plotly for plotting. Plotly is a free web-based platform for making graphs. You can keep graphs private, make them public, and run Plotly on your [Plotly Enterprise on your own servers](https://plot.ly/product/enterprise/). You can find more details [here](https://plot.ly/python/getting-started/).", "_____no_output_____" ], [ "## Getting market data with Bloomberg", "_____no_output_____" ], [ "To get market data, we shall be using Bloomberg. As a starting point, we have used bbg_py from [Brian Smith's TIA project](https://github.com/bpsmith/tia/tree/master/tia/bbg), which allows you to access Bloomberg via COM (older method), modifying it to make it compatible for Python 3.4. Whilst, we shall note use it to access historical daily data, there are functions which enable us to download intraday data. This method is only compatible with 32 bit versions of Python and assumes you are running the code on a Bloomberg terminal (it won't work without a valid Bloomberg licence).\n\nIn my opinion a better way to access Bloomberg via Python, is via the official Bloomberg open source Python Open Source Graphing Library, however, at time of writing the official version is not yet compatible with Python 3.4. Fil Mackay has created a Python 3.4 compatible version of this [here](https://github.com/filmackay/blpapi-py), which I have used successfully. Whilst it takes slightly more time to configure (and compile using Windows SDK 7.1), it has the benefit of being compatible with 64 bit Python, which I have found invaluable in my analysis (have a read of [this](http://ta.speot.is/2012/04/09/visual-studio-2010-sp1-windows-sdk-7-1-install-order/) in case of failed installations of Windows SDK 7.1).\n\nQuandl can be used as an alternative data source, if you don't have access to a Bloomberg terminal, which I have also included in the code.", "_____no_output_____" ], [ "## Breaking down the steps in Python", "_____no_output_____" ], [ "Our project will consist of several parts:\n- bbg_com - low level interaction with BBG COM object (adapted for Python 3.4) (which we are simply calling)\n- datadownloader - wrapper for BBG COM, Quandl and CSV access to data\n- eventplot - reusuable functions for interacting with Plotly and creating event studies\n- ukelection - kicks off the whole script process", "_____no_output_____" ], [ "### Downloading the market data", "_____no_output_____" ], [ "As with any sort of financial market analysis, the first step is obtaining market data. We create the DataDownloader class, which acts a wrapper for Bloomberg, Quandl and CSV market data. We write a single function \"download_time_series\" for this. We could of course extend this for other data sources such as Yahoo Finance. Our output will be Pandas based dataframes. We want to make this code generic, so the tickers are not hard coded.", "_____no_output_____" ] ], [ [ "# for time series manipulation\nimport pandas\n\nclass DataDownloader:\n def download_time_series(self, vendor_ticker, pretty_ticker, start_date, source, csv_file = None):\n\n if source == 'Quandl':\n import Quandl\n # Quandl requires API key for large number of daily downloads\n # https://www.quandl.com/help/api\n spot = Quandl.get(vendor_ticker) # Bank of England's database on Quandl\n spot = pandas.DataFrame(data=spot['Value'], index=spot.index)\n spot.columns = [pretty_ticker]\n\n elif source == 'Bloomberg':\n from bbg_com import HistoricalDataRequest\n req = HistoricalDataRequest([vendor_ticker], ['PX_LAST'], start = start_date)\n req.execute()\n\n spot = req.response_as_single()\n spot.columns = [pretty_ticker]\n elif source == 'CSV':\n dateparse = lambda x: pandas.datetime.strptime(x, '%Y-%m-%d')\n\n # in case you want to use a source other than Bloomberg/Quandl\n spot = pandas.read_csv(csv_file, index_col=0, parse_dates=0, date_parser=dateparse)\n\n return spot", "_____no_output_____" ] ], [ [ "### Generic functions for event study and Plotly plotting", "_____no_output_____" ], [ "We now focus our efforts on the EventPlot class. Here we shall do our basic analysis. We shall aslo create functions for creating plotly traces and layouts that we shall reuse a number of times. The analysis we shall conduct is fairly simple. Given a time series of spot, and a number of dates, we shall create an event study around these times for that asset. We also include the \"Mean\" move over all the various dates.", "_____no_output_____" ] ], [ [ "# for dates\nimport datetime\n\n# time series manipulation\nimport pandas\n\n# for plotting data\nimport plotly\nfrom plotly.graph_objs import *\n\nclass EventPlot: \n def event_study(self, spot, dates, pre, post, mean_label = 'Mean'):\n # event_study - calculates the asset price moves over windows around event days\n #\n # spot = price of asset to study\n # dates = event days to anchor our event study\n # pre = days before the event day to start our study\n # post = days after the event day to start our study\n #\n\n data_frame = pandas.DataFrame()\n\n # for each date grab spot data the days before and after\n for i in range(0, len(dates)):\n mid_index = spot.index.searchsorted(dates[i])\n start_index = mid_index + pre\n finish_index = mid_index + post + 1\n\n x = (spot.ix[start_index:finish_index])[spot.columns.values[0]]\n\n data_frame[dates[i]] = x.values\n\n data_frame.index = range(pre, post + 1)\n\n data_frame = data_frame / data_frame.shift(1) - 1 # returns\n\n # add the mean on to the end\n data_frame[mean_label] = data_frame.mean(axis=1)\n\n data_frame = 100.0 * (1.0 + data_frame).cumprod() # index\n data_frame.ix[pre,:] = 100\n\n return data_frame", "_____no_output_____" ] ], [ [ "We write a function to convert dates represented in a string format to Python format.", "_____no_output_____" ] ], [ [ " def parse_dates(self, str_dates):\n # parse_dates - parses string dates into Python format\n #\n # str_dates = dates to be parsed in the format of day/month/year\n #\n\n dates = []\n\n for d in str_dates:\n dates.append(datetime.datetime.strptime(d, '%d/%m/%Y'))\n\n return dates\n \n EventPlot.parse_dates = parse_dates", "_____no_output_____" ] ], [ [ "Our next focus is on the Plotly functions which create a layout. This enables us to specify axes labels, the width and height of the final plot and so on. We could of course add further properties into it.", "_____no_output_____" ] ], [ [ " def create_layout(self, title, xaxis, yaxis, width = -1, height = -1):\n # create_layout - populates a layout object\n # title = title of the plot\n # xaxis = xaxis label\n # yaxis = yaxis label\n # width (optional) = width of plot\n # height (optional) = height of plot\n #\n\n layout = Layout(\n title = title,\n xaxis = plotly.graph_objs.XAxis(\n title = xaxis,\n showgrid = False\n ),\n yaxis = plotly.graph_objs.YAxis(\n title= yaxis,\n showline = False\n )\n )\n\n if width > 0 and height > 0:\n layout['width'] = width\n layout['height'] = height\n\n return layout\n \n EventPlot.create_layout = create_layout", "_____no_output_____" ] ], [ [ "Earlier, in the DataDownloader class, our output was Pandas based dataframes. Our convert_df_plotly function will convert these each series from Pandas dataframe into plotly traces. Along the way, we shall add various properties such as markers with varying levels of opacity, graduated coloring of lines (which uses colorlover) and so on.", "_____no_output_____" ] ], [ [ " def convert_df_plotly(self, dataframe, axis_no = 1, color_def = ['default'],\n special_line = 'Mean', showlegend = True, addmarker = False, gradcolor = None):\n # convert_df_plotly - converts a Pandas data frame to Plotly format for line plots\n # dataframe = data frame due to be converted\n # axis_no = axis for plot to be drawn (default = 1)\n # special_line = make lines named this extra thick\n # color_def = color scheme to be used (default = ['default']), colour will alternate in the list\n # showlegend = True or False to show legend of this line on plot\n # addmarker = True or False to add markers\n # gradcolor = Create a graduated color scheme for the lines\n #\n # Also see http://nbviewer.ipython.org/gist/nipunreddevil/7734529 for converting dataframe to traces\n # Also see http://moderndata.plot.ly/color-scales-in-ipython-notebook/\n\n x = dataframe.index.values\n\n traces = []\n\n # will be used for market opacity for the markers\n increments = 0.95 / float(len(dataframe.columns))\n\n if gradcolor is not None:\n try:\n import colorlover as cl\n color_def = cl.scales[str(len(dataframe.columns))]['seq'][gradcolor]\n except:\n print('Check colorlover installation...')\n\n i = 0\n\n for key in dataframe:\n scatter = plotly.graph_objs.Scatter(\n x = x,\n y = dataframe[key].values,\n name = key,\n xaxis = 'x' + str(axis_no),\n yaxis = 'y' + str(axis_no),\n showlegend = showlegend)\n\n # only apply color/marker properties if not \"default\"\n if color_def[i % len(color_def)] != \"default\":\n if special_line in str(key):\n # special case for lines labelled \"mean\"\n # make line thicker\n scatter['mode'] = 'lines'\n scatter['line'] = plotly.graph_objs.Line(\n color = color_def[i % len(color_def)],\n width = 2\n )\n else:\n line_width = 1\n\n # set properties for the markers which change opacity\n # for markers make lines thinner\n if addmarker:\n opacity = 0.05 + (increments * i)\n scatter['mode'] = 'markers+lines'\n scatter['marker'] = plotly.graph_objs.Marker(\n color=color_def[i % len(color_def)], # marker color\n opacity = opacity,\n size = 5)\n line_width = 0.2\n\n else:\n scatter['mode'] = 'lines'\n\n scatter['line'] = plotly.graph_objs.Line(\n color = color_def[i % len(color_def)],\n width = line_width)\n \n i = i + 1\n\n traces.append(scatter)\n\n return traces\n \n EventPlot.convert_df_plotly = convert_df_plotly", "_____no_output_____" ] ], [ [ "### UK election analysis", "_____no_output_____" ], [ "We've now created several generic functions for downloading data, doing an event study and also for helping us out with plotting via Plotly. We now start work on the ukelection.py script, for pulling it all together. As a very first step we need to provide credentials for Plotly (you can get your own Plotly key and username [here](https://plot.ly/python/getting-started/)).", "_____no_output_____" ] ], [ [ "# for time series/maths\nimport pandas\n\n# for plotting data\nimport plotly\nimport plotly.plotly as py\nfrom plotly.graph_objs import *\n\ndef ukelection(): \n # Learn about API authentication here: https://plot.ly/python/getting-started\n # Find your api_key here: https://plot.ly/settings/api\n plotly_username = \"thalesians\"\n plotly_api_key = \"XXXXXXXXX\"\n\n plotly.tools.set_credentials_file(username=plotly_username, api_key=plotly_api_key)", "_____no_output_____" ] ], [ [ "Let's download our market data that we need (GBP/USD spot data) using the DataDownloader class. As a default, I've opted to use Bloomberg data. You can try other currency pairs or markets (for example FTSE), to compare results for the event study. Note that obviously each data vendor will have a different ticker in their system for what could well be the same asset. With FX, care must be taken to know which close the vendor is snapping. As a default we have opted for BGN, which for GBP/USD is the NY close value.", "_____no_output_____" ] ], [ [ " ticker = 'GBPUSD' # will use in plot titles later (and for creating Plotly URL)\n\n ##### download market GBP/USD data from Quandl, Bloomberg or CSV file\n source = \"Bloomberg\"\n # source = \"Quandl\"\n # source = \"CSV\"\n\n csv_file = None\n\n event_plot = EventPlot()\n \n data_downloader = DataDownloader()\n start_date = event_plot.parse_dates(['01/01/1975'])\n\n if source == 'Quandl':\n vendor_ticker = \"BOE/XUDLUSS\"\n elif source == 'Bloomberg':\n vendor_ticker = 'GBPUSD BGN Curncy'\n elif source == 'CSV':\n vendor_ticker = 'GBPUSD'\n csv_file = 'D:/GBPUSD.csv'\n\n spot = data_downloader.download_time_series(vendor_ticker, ticker, start_date[0], source, csv_file = csv_file)", "_____no_output_____" ] ], [ [ "The most important part of the study is getting the historical UK election dates! We can obtain these from Wikipedia. We then convert into Python format. We need to make sure we filter the UK election dates, for where we have spot data available.", "_____no_output_____" ] ], [ [ " labour_wins = ['28/02/1974', '10/10/1974', '01/05/1997', '07/06/2001', '05/05/2005']\n conservative_wins = ['03/05/1979', '09/06/1983', '11/06/1987', '09/04/1992', '06/05/2010']\n\n # convert to more easily readable format\n labour_wins_d = event_plot.parse_dates(labour_wins)\n conservative_wins_d = event_plot.parse_dates(conservative_wins)\n\n # only takes those elections where we have data\n labour_wins_d = [d for d in labour_wins_d if d > spot.index[0].to_pydatetime()]\n conservative_wins_d = [d for d in conservative_wins_d if d > spot.index[0].to_pydatetime()]\n\n spot.index.name = 'Date'", "_____no_output_____" ] ], [ [ "We then call our event study function in EventPlot on our spot data, which compromises of the 20 days before up till the 20 days after the UK general election. We shall plot these lines later.", "_____no_output_____" ] ], [ [ " # number of days before and after for our event study\n pre = -20\n post = 20\n\n # calculate spot path during Labour wins\n labour_wins_spot = event_plot.event_study(spot, labour_wins_d, pre, post, mean_label = 'Labour Mean')\n\n # calculate spot path during Conservative wins\n conservative_wins_spot = event_plot.event_study(spot, conservative_wins_d, pre, post, mean_label = 'Conservative Mean')", "_____no_output_____" ] ], [ [ "Define our xaxis and yaxis labels, as well as our source, which we shall later include in the title.", "_____no_output_____" ] ], [ [ " ##### Create separate plots of price action during Labour and Conservative wins\n xaxis = 'Days'\n yaxis = 'Index'\n source_label = \"Source: @thalesians/BBG/Wikipedia\"", "_____no_output_____" ] ], [ [ "We're finally ready for our first plot! We shall plot GBP/USD moves over Labour election wins, using the default palette and then we shall embed it into the sheet, using the URL given to us from the Plotly website.", "_____no_output_____" ] ], [ [ " ###### Plot market reaction during Labour UK election wins\n ###### Using default color scheme\n\n title = ticker + ' during UK gen elect - Lab wins' + '<BR>' + source_label\n\n fig = Figure(data=event_plot.convert_df_plotly(labour_wins_spot),\n layout=event_plot.create_layout(title, xaxis, yaxis)\n )\n\n py.iplot(fig, filename='labour-wins-' + ticker)", "_____no_output_____" ] ], [ [ "The \"iplot\" function will send it to Plotly's server (provided we have all the dependencies installed).", "_____no_output_____" ], [ "Alternatively, we could embed the HTML as an image, which we have taken from the Plotly website. Note this approach will yield a static image which is fetched from Plotly's servers. It also possible to write the image to disk. Later we shall show the embed function.", "_____no_output_____" ], [ "<div>\n <a href=\"https://plot.ly/~thalesians/244/\" target=\"_blank\" title=\"GBPUSD during UK gen elect - Lab wins&lt;br&gt;Source: @thalesians/BBG/Wikipedia\" style=\"display: block; text-align: center;\"><img src=\"https://plot.ly/~thalesians/244.png\" alt=\"GBPUSD during UK gen elect - Lab wins&lt;br&gt;Source: @thalesians/BBG/Wikipedia\" style=\"max-width: 100%;\" onerror=\"this.onerror=null;this.src='https://plot.ly/404.png';\" /></a>\n <script data-plotly=\"thalesians:244\" src=\"https://plot.ly/embed.js\" async></script>\n</div>\n", "_____no_output_____" ], [ "We next plot GBP/USD over Conservative wins. In this instance, however, we have a graduated 'Blues' color scheme, given obviously that blue is the color of the Conserative party in the UK!", "_____no_output_____" ] ], [ [ " ###### Plot market reaction during Conservative UK election wins\n ###### Using varying shades of blue for each line (helped by colorlover library)\n\n title = ticker + ' during UK gen elect - Con wins ' + '<BR>' + source_label\n\n # also apply graduated color scheme of blues (from light to dark)\n # see http://moderndata.plot.ly/color-scales-in-ipython-notebook/ for details on colorlover package\n # which allows you to set scales\n fig = Figure(data=event_plot.convert_df_plotly(conservative_wins_spot, gradcolor='Blues', addmarker=False),\n layout=event_plot.create_layout(title, xaxis, yaxis),\n )\n\n plot_url = py.iplot(fig, filename='conservative-wins-' + ticker)", "_____no_output_____" ] ], [ [ "Embed the chart into the document using \"embed\". This essentially embeds the Javascript code, necessary to make it interactive.", "_____no_output_____" ] ], [ [ "import plotly.tools as tls\n\ntls.embed(\"https://plot.ly/~thalesians/245\")", "_____no_output_____" ] ], [ [ "Our final plot, will consist of three subplots, Labour wins, Conservative wins, and average moves for both. We also add a grid and a grey background for each plot.", "_____no_output_____" ] ], [ [ " ##### Plot market reaction during Conservative UK election wins\n ##### create a plot consisting of 3 subplots (from left to right)\n ##### 1. Labour wins, 2. Conservative wins, 3. Conservative/Labour mean move\n\n # create a dataframe which grabs the mean from the respective Lab & Con election wins\n mean_wins_spot = pandas.DataFrame()\n mean_wins_spot['Labour Mean'] = labour_wins_spot['Labour Mean']\n mean_wins_spot['Conservative Mean'] = conservative_wins_spot['Conservative Mean']\n\n fig = plotly.tools.make_subplots(rows=1, cols=3)\n\n # apply different color scheme (red = Lab, blue = Con)\n # also add markets, which will have varying levels of opacity\n fig['data'] += Data(\n event_plot.convert_df_plotly(conservative_wins_spot, axis_no=1, \n color_def=['blue'], addmarker=True) +\n event_plot.convert_df_plotly(labour_wins_spot, axis_no=2, \n color_def=['red'], addmarker=True) +\n event_plot.convert_df_plotly(mean_wins_spot, axis_no=3, \n color_def=['red', 'blue'], addmarker=True, showlegend = False)\n )\n \n fig['layout'].update(title=ticker + ' during UK gen elects by winning party ' + '<BR>' + source_label)\n\n # use the scheme from https://plot.ly/python/bubble-charts-tutorial/\n # can use dict approach, rather than specifying each separately\n axis_style = dict(\n gridcolor='#FFFFFF', # white grid lines\n ticks='outside', # draw ticks outside axes\n ticklen=8, # tick length\n tickwidth=1.5 # and width\n )\n\n # create the various axes for the three separate charts\n fig['layout'].update(xaxis1=plotly.graph_objs.XAxis(axis_style, title=xaxis))\n fig['layout'].update(yaxis1=plotly.graph_objs.YAxis(axis_style, title=yaxis))\n\n fig['layout'].update(xaxis2=plotly.graph_objs.XAxis(axis_style, title=xaxis))\n fig['layout'].update(yaxis2=plotly.graph_objs.YAxis(axis_style))\n\n fig['layout'].update(xaxis3=plotly.graph_objs.XAxis(axis_style, title=xaxis))\n fig['layout'].update(yaxis3=plotly.graph_objs.YAxis(axis_style))\n\n fig['layout'].update(plot_bgcolor='#EFECEA') # set plot background to grey\n\n plot_url = py.iplot(fig, filename='labour-conservative-wins-'+ ticker + '-subplot')", "This is the format of your plot grid:\n[ (1,1) x1,y1 ] [ (1,2) x2,y2 ] [ (1,3) x3,y3 ]\n\n" ] ], [ [ "This time we use \"embed\", which grab the plot from Plotly's server, we did earlier (given we have already uploaded it).", "_____no_output_____" ] ], [ [ "import plotly.tools as tls\n\ntls.embed(\"https://plot.ly/~thalesians/246\")", "_____no_output_____" ] ], [ [ "<B>That's about it!</B> I hope the code I've written proves fruitful for creating some very cool Plotly plots and also for doing some very timely analysis ahead of the UK general election! Hoping this will be first of many blogs on using Plotly data.", "_____no_output_____" ], [ "The analysis in this blog is based on a report I wrote for Thalesians, a quant finance thinktank. If you are interested in getting access to the full copy of the report (Thalesians: My kingdom for a vote - The definitive quant guide to UK general elections), feel free to e-mail me at <b>saeed@thalesians.com</b> or tweet me <b>@thalesians</b>", "_____no_output_____" ], [ "## Want to hear more about global macro and UK election developments?", "_____no_output_____" ], [ "If you're interested in FX and the UK general election, come to our Thalesians panel in London on April 29th 2015 at 7.30pm in Canary Wharf, which will feature, Eric Burroughs (Reuters - FX Buzz Editor), Mark Cudmore (Bloomberg - First Word EM Strategist), Jordan Rochester (Nomura - FX strategist), Jeremy Wilkinson-Smith (Independent FX trader) and myself as the moderator. Tickets are available [here](http://www.meetup.com/thalesians/events/221147156/)", "_____no_output_____" ], [ "## Biography", "_____no_output_____" ], [ "<b>Saeed Amen</b> is the managing director and co-founder of the Thalesians. He has a decade of experience creating and successfully running systematic trading models at Lehman Brothers, Nomura and now at the Thalesians. Independently, he runs a systematic trading model with proprietary capital. He is the author of Trading Thalesians – What the ancient world can teach us about trading today (Palgrave Macmillan). He graduated with a first class honours master’s degree from Imperial College in Mathematics & Computer Science. He is also a fan of Python and has written an extensive library for financial market backtesting called PyThalesians.\n<BR>\n\nFollow the Thalesians on Twitter @thalesians and get my book on Amazon [here](http://www.amazon.co.uk/Trading-Thalesians-Saeed-Amen/dp/113739952X)", "_____no_output_____" ], [ "All the code here is available to download from the [Thalesians GitHub page](https://github.com/thalesians/pythalesians)", "_____no_output_____" ] ], [ [ "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 publisher --upgrade\nimport publisher\npublisher.publish(\n 'ukelectionbbg.ipynb', 'ipython-notebooks/ukelectionbbg/', 'Plotting GBP/USD price action around UK general elections', \n 'Create interactive graphs with market data, IPython Notebook and Plotly', name='Plot MP Action in GBP/USD around UK General Elections')", "Requirement already up-to-date: publisher in /Users/chriddyp/Repos/venvpy27/lib/python2.7/site-packages/publisher-0.4-py2.7.egg\r\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", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
d03070c9717b7b80f32b106f4e8643b230b81775
521,290
ipynb
Jupyter Notebook
manual/GPyOpt_reference_manual.ipynb
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
manual/GPyOpt_reference_manual.ipynb
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
manual/GPyOpt_reference_manual.ipynb
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
700.658602
149,816
0.938148
[ [ [ "# Introduction to Bayesian Optimization with GPyOpt \n\n\n### Written by Javier Gonzalez, Amazon Research Cambridge\n\n*Last updated Monday, 22 May 2017.*\n\n=====================================================================================================\n1. **How to use GPyOpt?**\n\n2. **The Basics of Bayesian Optimization**\n 1. Gaussian Processes\n 2. Acquisition functions\n 3. Applications of Bayesian Optimization \n\n3. **1D optimization example**\n\n4. **2D optimization example**\n\n=====================================================================================================", "_____no_output_____" ], [ "## 1. How to use GPyOpt?", "_____no_output_____" ], [ "We start by loading GPyOpt and GPy.", "_____no_output_____" ] ], [ [ "%pylab inline \nimport GPy\nimport GPyOpt\nfrom numpy.random import seed\nimport matplotlib", "Populating the interactive namespace from numpy and matplotlib\nwarning in stationary: failed to import cython module: falling back to numpy\n" ] ], [ [ "GPyOpt is easy to use as a black-box functions optimizer. To start you only need: \n\n* Your favorite function $f$ to minimize. We use $f(x)=2x^2$ in this toy example, whose global minimum is at x=0.", "_____no_output_____" ] ], [ [ "def myf(x):\n return (2*x)**2", "_____no_output_____" ] ], [ [ "* A set of box constrains, the interval [-1,1] in our case. You can define a list of dictionaries where each element defines the name, type and domain of the variables. ", "_____no_output_____" ] ], [ [ "bounds = [{'name': 'var_1', 'type': 'continuous', 'domain': (-1,1)}]", "_____no_output_____" ] ], [ [ "* A budget, or number of allowed evaluations of $f$.", "_____no_output_____" ] ], [ [ "max_iter = 15", "_____no_output_____" ] ], [ [ "With this three pieces of information GPyOpt has enough to find the minimum of $f$ in the selected region. GPyOpt solves the problem in two steps. First, you need to create a GPyOpt object that stores the problem (f and and box-constrains). You can do it as follows.", "_____no_output_____" ] ], [ [ "myProblem = GPyOpt.methods.BayesianOptimization(myf,bounds)", "_____no_output_____" ] ], [ [ "Next you need to run the optimization for the given budget of iterations. This bit it is a bit slow because many default options are used. In the next notebooks of this manual you can learn how to change other parameters to optimize the optimization performance.", "_____no_output_____" ] ], [ [ "myProblem.run_optimization(max_iter)", "_____no_output_____" ] ], [ [ "Now you can check the best found location $x^*$ by", "_____no_output_____" ] ], [ [ "myProblem.x_opt", "_____no_output_____" ] ], [ [ "and the predicted value value of $f$ at $x^*$ optimum by", "_____no_output_____" ] ], [ [ "myProblem.fx_opt", "_____no_output_____" ] ], [ [ "And that's it! Keep reading to learn how GPyOpt uses Bayesian Optimization to solve this an other optimization problem. You will also learn all the features and options that you can use to solve your problems efficiently. \n\n=====================================================================================================\n", "_____no_output_____" ], [ "## 2. The Basics of Bayesian Optimization\n\nBayesian optimization (BO) is an strategy for global optimization of black-box functions [(Snoek et al., 2012)](http://papers.nips.cc/paper/4522-practical-bayesian-optimization-of-machine-learning-algorithms.pdf). Let $f: {\\mathcal X} \\to R$ be a L-Lipschitz continuous function defined on a compact subset ${\\mathcal X} \\subseteq R^d$. We are interested in solving the global optimization problem of finding\n$$ x_{M} = \\arg \\min_{x \\in {\\mathcal X}} f(x). $$\n\nWe assume that $f$ is a *black-box* from which only perturbed evaluations of the type $y_i = f(x_i) + \\epsilon_i$, with $\\epsilon_i \\sim\\mathcal{N}(0,\\psi^2)$, are available. The goal is to make a series of $x_1,\\dots,x_N$ evaluations of $f$ such that the *cumulative regret* \n$$r_N= Nf(x_{M})- \\sum_{n=1}^N f(x_n),$$ \nis minimized. Essentially, $r_N$ is minimized if we start evaluating $f$ at $x_{M}$ as soon as possible. \n\nThere are two crucial bits in any Bayesian Optimization (BO) procedure approach.\n\n1. Define a **prior probability measure** on $f$: this function will capture the our prior beliefs on $f$. The prior will be updated to a 'posterior' using the available data.\n\n2. Define an **acquisition function** $acqu(x)$: this is a criteria to decide where to sample next in order to gain the maximum information about the location of the global maximum of $f$.\n\nEvery time a new data point is collected. The model is re-estimated and the acquisition function optimized again until convergence. Given a prior over the function $f$ and an acquisition function, a BO procedure will converge to the optimum of $f$ under some conditions [(Bull, 2011)](http://arxiv.org/pdf/1101.3501.pdf).", "_____no_output_____" ], [ "### 2.1 Prior probability meassure on $f$: Gaussian processes", "_____no_output_____" ], [ "A Gaussian process (GP) is a probability distribution across classes functions, typically smooth, such that each linear finite-dimensional restriction is multivariate Gaussian [(Rasmussen and Williams, 2006)](http://www.gaussianprocess.org/gpml). GPs are fully parametrized by a mean $\\mu(x)$ and a covariance function $k(x,x')$. Without loss of generality $\\mu(x)$ is assumed to be zero. The covariance function $k(x,x')$ characterizes the smoothness and other properties of $f$. It is known as the\nkernel of the process and has to be continuous, symmetric and positive definite. A widely used kernel is the square exponential, given by\n\n$$ k(x,x') = l \\cdot \\exp{ \\left(-\\frac{\\|x-x'\\|^2}{2\\sigma^2}\\right)} $$\nwhere $\\sigma^2$ and and $l$ are positive parameters. \n\nTo denote that $f$ is a sample from a GP with mean $\\mu$ and covariance $k$ we write \n\n$$f(x) \\sim \\mathcal{GP}(\\mu(x),k(x,x')).$$ \n\nFor regression tasks, the most important feature of GPs is that process priors are conjugate to the likelihood from finitely many observations $y= (y_1,\\dots,y_n)^T$ and $X =\\{x_1,...,x_n\\}$, $x_i\\in \\mathcal{X}$ of the form $y_i = f(x_i) + \\epsilon_i $\nwhere $\\epsilon_i \\sim \\mathcal{N} (0,\\sigma^2)$. We obtain the Gaussian posterior posterior $f(x^*)|X, y, \\theta \\sim \\mathcal{N}(\\mu(x^*),\\sigma^2(x^*))$, where $\\mu(x^*)$ and $\\sigma^2(x^*)$ have close form. See [(Rasmussen and Williams, 2006)](http://www.gaussianprocess.org/gpml) for details.", "_____no_output_____" ], [ "### 2.2 Acquisition Function\n\nAcquisition functions are designed represents our beliefs over the maximum of $f(x)$. Denote by $\\theta$ the parameters of the GP model and by $\\{x_i,y_i\\}$ the available sample. Three of the most common acquisition functions, all available in GPyOpt are:\n\n* **Maximum probability of improvement (MPI)**:\n\n$$acqu_{MPI}(x;\\{x_n,y_n\\},\\theta) = \\Phi(\\gamma(x)), \\mbox{where}\\ \\gamma(x)=\\frac{\\mu(x;\\{x_n,y_n\\},\\theta)-f(x_{best})-\\psi}{\\sigma(x;\\{x_n,y_n\\},\\theta)}.$$\n\n\n* **Expected improvement (EI)**:\n\n$$acqu_{EI}(x;\\{x_n,y_n\\},\\theta) = \\sigma(x;\\{x_n,y_n\\},\\theta) (\\gamma(x) \\Phi(\\gamma(x))) + N(\\gamma(x);0,1).$$\n\n* **Upper confidence bound (UCB)**:\n\n$$acqu_{UCB}(x;\\{x_n,y_n\\},\\theta) = -\\mu(x;\\{x_n,y_n\\},\\theta)+\\psi\\sigma(x;\\{x_n,y_n\\},\\theta).$$\n\n$\\psi$ is a tunable parameters that help to make the acquisition functions more flexible. Also, in the case of the UBC, the parameter $\\eta$ is useful to define the balance between the importance we give to the mean and the variance of the model. This is know as the **exploration/exploitation trade off**.", "_____no_output_____" ], [ "### 2.3 Applications of Bayesian Optimization\n\nBayesian Optimization has been applied to solve a wide range of problems. Among many other, some nice applications of Bayesian Optimization include: \n\n\n* Sensor networks (http://www.robots.ox.ac.uk/~parg/pubs/ipsn673-garnett.pdf),\n\n* Automatic algorithm configuration (http://www.cs.ubc.ca/labs/beta/Projects/SMAC/papers/11-LION5-SMAC.pdf), \n\n* Deep learning (http://www.mlss2014.com/files/defreitas_slides1.pdf), \n\n* Gene design (http://bayesopt.github.io/papers/paper5.pdf),\n\n* and a long etc!\n\nIn this Youtube video you can see Bayesian Optimization working in a real time in a robotics example. [(Calandra1 et al. 2008)](http://www.ias.tu-darmstadt.de/uploads/Site/EditPublication/Calandra_LION8.pdf) ", "_____no_output_____" ] ], [ [ "from IPython.display import YouTubeVideo\nYouTubeVideo('ualnbKfkc3Q')", "_____no_output_____" ] ], [ [ "## 3. One dimensional example\n\nIn this example we show how GPyOpt works in a one-dimensional example a bit more difficult that the one we analyzed in Section 3. Let's consider here the Forrester function \n\n$$f(x) =(6x-2)^2 \\sin(12x-4)$$ defined on the interval $[0, 1]$. \n\nThe minimum of this function is located at $x_{min}=0.78$. The Forrester function is part of the benchmark of functions of GPyOpt. To create the true function, the perturbed version and boundaries of the problem you need to run the following cell. ", "_____no_output_____" ] ], [ [ "%pylab inline \nimport GPy\nimport GPyOpt\n\n# Create the true and perturbed Forrester function and the boundaries of the problem\nf_true= GPyOpt.objective_examples.experiments1d.forrester() # noisy version\nbounds = [{'name': 'var_1', 'type': 'continuous', 'domain': (0,1)}] # problem constrains ", "Populating the interactive namespace from numpy and matplotlib\n" ] ], [ [ "We plot the true Forrester function.", "_____no_output_____" ] ], [ [ "f_true.plot()", "_____no_output_____" ] ], [ [ "As we did in Section 3, we need to create the GPyOpt object that will run the optimization. We specify the function, the boundaries and we add the type of acquisition function to use. ", "_____no_output_____" ] ], [ [ "# Creates GPyOpt object with the model and anquisition fucntion\nseed(123)\nmyBopt = GPyOpt.methods.BayesianOptimization(f=f_true.f, # function to optimize \n domain=bounds, # box-constrains of the problem\n acquisition_type='EI',\n exact_feval = True) # Selects the Expected improvement", "_____no_output_____" ] ], [ [ "Now we want to run the optimization. Apart from the number of iterations you can select \nhow do you want to optimize the acquisition function. You can run a number of local optimizers (acqu_optimize_restart) at random or in grid (acqu_optimize_method). ", "_____no_output_____" ] ], [ [ "# Run the optimization\nmax_iter = 15 # evaluation budget\nmax_time = 60 # time budget \neps = 10e-6 # Minimum allows distance between the las two observations\n\nmyBopt.run_optimization(max_iter, max_time, eps) ", "_____no_output_____" ] ], [ [ "When the optimization is done you should receive a message describing if the method converged or if the maximum number of iterations was reached. In one dimensional examples, you can see the result of the optimization as follows.", "_____no_output_____" ] ], [ [ "myBopt.plot_acquisition()", "_____no_output_____" ], [ "myBopt.plot_convergence()", "_____no_output_____" ] ], [ [ "In problems of any dimension two evaluations plots are available.\n\n* The distance between the last two observations.\n\n* The value of $f$ at the best location previous to each iteration.\n\nTo see these plots just run the following cell.", "_____no_output_____" ] ], [ [ "myBopt.plot_convergence()", "_____no_output_____" ] ], [ [ "Now let's make a video to track what the algorithm is doing in each iteration. Let's use the LCB in this case with parameter equal to 2.", "_____no_output_____" ], [ "## 4. Two dimensional example\n\nNext, we try a 2-dimensional example. In this case we minimize the use the Six-hump camel function \n\n$$f(x_1,x_2) = \\left(4-2.1x_1^2 = \\frac{x_1^4}{3} \\right)x_1^2 + x_1x_2 + (-4 +4x_2^2)x_2^2,$$\n\nin $[-3,3]\\times [-2,2]$. This functions has two global minimum, at $(0.0898,-0.7126)$ and $(-0.0898,0.7126)$. As in the previous case we create the function, which is already in GPyOpt. In this case we generate observations of the function perturbed with white noise of $sd=0.1$.", "_____no_output_____" ] ], [ [ "# create the object function\nf_true = GPyOpt.objective_examples.experiments2d.sixhumpcamel()\nf_sim = GPyOpt.objective_examples.experiments2d.sixhumpcamel(sd = 0.1)\nbounds =[{'name': 'var_1', 'type': 'continuous', 'domain': f_true.bounds[0]},\n {'name': 'var_2', 'type': 'continuous', 'domain': f_true.bounds[1]}]\nf_true.plot()", "_____no_output_____" ] ], [ [ "We create the GPyOpt object. In this case we use the Lower Confidence bound acquisition function to solve the problem.", "_____no_output_____" ] ], [ [ "# Creates three identical objects that we will later use to compare the optimization strategies \nmyBopt2D = GPyOpt.methods.BayesianOptimization(f_sim.f,\n domain=bounds,\n model_type = 'GP',\n acquisition_type='EI', \n normalize_Y = True,\n acquisition_weight = 2) ", "_____no_output_____" ] ], [ [ " We run the optimization for 40 iterations and show the evaluation plot and the acquisition function.", "_____no_output_____" ] ], [ [ "# runs the optimization for the three methods\nmax_iter = 40 # maximum time 40 iterations\nmax_time = 60 # maximum time 60 seconds\n\nmyBopt2D.run_optimization(max_iter,max_time,verbosity=False) ", "_____no_output_____" ] ], [ [ "Finally, we plot the acquisition function and the convergence plot.", "_____no_output_____" ] ], [ [ "myBopt2D.plot_acquisition() ", "_____no_output_____" ], [ "myBopt2D.plot_convergence()", "_____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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d0307313dc4061ec33728350c220205d512aa367
349,200
ipynb
Jupyter Notebook
1D_CNN_Attempts/1D_CNN_asof_111312FEB.ipynb
Cloblak/aipi540_deeplearning
1443528ab5309839563722b4f087fe49cc657ba4
[ "Apache-2.0" ]
null
null
null
1D_CNN_Attempts/1D_CNN_asof_111312FEB.ipynb
Cloblak/aipi540_deeplearning
1443528ab5309839563722b4f087fe49cc657ba4
[ "Apache-2.0" ]
null
null
null
1D_CNN_Attempts/1D_CNN_asof_111312FEB.ipynb
Cloblak/aipi540_deeplearning
1443528ab5309839563722b4f087fe49cc657ba4
[ "Apache-2.0" ]
null
null
null
83.182468
68,362
0.692168
[ [ [ "<a href=\"https://colab.research.google.com/github/Cloblak/aipi540_deeplearning/blob/main/1D_CNN_Attempts/1D_CNN_asof_111312FEB.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!pip install alpaca_trade_api", "Collecting alpaca_trade_api\n Downloading alpaca_trade_api-1.5.0-py3-none-any.whl (45 kB)\n\u001b[?25l\r\u001b[K |███████▏ | 10 kB 27.1 MB/s eta 0:00:01\r\u001b[K |██████████████▍ | 20 kB 20.0 MB/s eta 0:00:01\r\u001b[K |█████████████████████▋ | 30 kB 10.7 MB/s eta 0:00:01\r\u001b[K |████████████████████████████▊ | 40 kB 8.8 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 45 kB 1.8 MB/s \n\u001b[?25hRequirement already satisfied: numpy>=1.11.1 in /usr/local/lib/python3.7/dist-packages (from alpaca_trade_api) (1.19.5)\nCollecting aiohttp==3.7.4\n Downloading aiohttp-3.7.4-cp37-cp37m-manylinux2014_x86_64.whl (1.3 MB)\n\u001b[K |████████████████████████████████| 1.3 MB 8.8 MB/s \n\u001b[?25hCollecting PyYAML==5.4.1\n Downloading PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl (636 kB)\n\u001b[K |████████████████████████████████| 636 kB 66.2 MB/s \n\u001b[?25hRequirement already satisfied: urllib3<2,>1.24 in /usr/local/lib/python3.7/dist-packages (from alpaca_trade_api) (1.24.3)\nCollecting msgpack==1.0.2\n Downloading msgpack-1.0.2-cp37-cp37m-manylinux1_x86_64.whl (273 kB)\n\u001b[K |████████████████████████████████| 273 kB 48.3 MB/s \n\u001b[?25hCollecting deprecation==2.1.0\n Downloading deprecation-2.1.0-py2.py3-none-any.whl (11 kB)\nRequirement already satisfied: pandas>=0.18.1 in /usr/local/lib/python3.7/dist-packages (from alpaca_trade_api) (1.3.5)\nCollecting websockets<10,>=8.0\n Downloading websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103 kB)\n\u001b[K |████████████████████████████████| 103 kB 73.8 MB/s \n\u001b[?25hCollecting websocket-client<2,>=0.56.0\n Downloading websocket_client-1.2.3-py3-none-any.whl (53 kB)\n\u001b[K |████████████████████████████████| 53 kB 2.1 MB/s \n\u001b[?25hRequirement already satisfied: requests<3,>2 in /usr/local/lib/python3.7/dist-packages (from alpaca_trade_api) (2.23.0)\nCollecting multidict<7.0,>=4.5\n Downloading multidict-6.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (94 kB)\n\u001b[K |████████████████████████████████| 94 kB 4.0 MB/s \n\u001b[?25hCollecting async-timeout<4.0,>=3.0\n Downloading async_timeout-3.0.1-py3-none-any.whl (8.2 kB)\nRequirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp==3.7.4->alpaca_trade_api) (21.4.0)\nRequirement already satisfied: chardet<4.0,>=2.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp==3.7.4->alpaca_trade_api) (3.0.4)\nCollecting yarl<2.0,>=1.0\n Downloading yarl-1.7.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (271 kB)\n\u001b[K |████████████████████████████████| 271 kB 32.5 MB/s \n\u001b[?25hRequirement already satisfied: typing-extensions>=3.6.5 in /usr/local/lib/python3.7/dist-packages (from aiohttp==3.7.4->alpaca_trade_api) (3.10.0.2)\nRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from deprecation==2.1.0->alpaca_trade_api) (21.3)\nRequirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.18.1->alpaca_trade_api) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.18.1->alpaca_trade_api) (2.8.2)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas>=0.18.1->alpaca_trade_api) (1.15.0)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>2->alpaca_trade_api) (2021.10.8)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>2->alpaca_trade_api) (2.10)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->deprecation==2.1.0->alpaca_trade_api) (3.0.7)\nInstalling collected packages: multidict, yarl, async-timeout, websockets, websocket-client, PyYAML, msgpack, deprecation, aiohttp, alpaca-trade-api\n Attempting uninstall: PyYAML\n Found existing installation: PyYAML 3.13\n Uninstalling PyYAML-3.13:\n Successfully uninstalled PyYAML-3.13\n Attempting uninstall: msgpack\n Found existing installation: msgpack 1.0.3\n Uninstalling msgpack-1.0.3:\n Successfully uninstalled msgpack-1.0.3\nSuccessfully installed PyYAML-5.4.1 aiohttp-3.7.4 alpaca-trade-api-1.5.0 async-timeout-3.0.1 deprecation-2.1.0 msgpack-1.0.2 multidict-6.0.2 websocket-client-1.2.3 websockets-9.1 yarl-1.7.2\n" ] ], [ [ "Features To Consider\n - Targets are only predicting sell within market hours, i.e. at 1530, target is prediciting price for 1100 the next day. Data from pre and post market is taken into consideration, and a sell or buy will be indicated if the price will flucuate after close.", "_____no_output_____" ] ], [ [ "# Import Dependencies\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.autograd import Variable\nfrom torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv2d, MaxPool2d, Module, Softmax, BatchNorm2d, Dropout\nfrom torch.optim import Adam, SGD\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchsummary import summary\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom tqdm.notebook import tqdm\nimport alpaca_trade_api as tradeapi\nfrom datetime import datetime, timedelta, tzinfo, timezone, time\nimport os.path\nimport ast\nimport threading\nimport math\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nimport warnings", "_____no_output_____" ], [ "random_seed = 182\ntorch.manual_seed(random_seed)", "_____no_output_____" ], [ "PAPER_API_KEY = \"PKE39LILN9SL1FMJMFV7\"\nPAPER_SECRET_KEY = \"TkU7fXH6WhP15MewgWlSnQG5RUoHGOPQ7yqlD6xq\"\nPAPER_BASE_URL = 'https://paper-api.alpaca.markets'", "_____no_output_____" ], [ "api = tradeapi.REST(PAPER_API_KEY, PAPER_SECRET_KEY, PAPER_BASE_URL, api_version='v2')", "_____no_output_____" ], [ "def prepost_train_test_validate_offset_data(api, ticker, interval, train_days=180, test_days=60, validate_days=30, offset_days = 0):\n ticker_data_dict = None\n ticker_data_dict = {}\n monthly_data_dict = None\n monthly_data_dict = {}\n interval_loop_data = None\n interval_loop_data = pd.DataFrame()\n stock_data = None\n \n days_to_collect = train_days + test_days + validate_days + offset_days\n\n TZ = 'US/Eastern'\n\n start = pd.to_datetime((datetime.now() - timedelta(days=days_to_collect)).strftime(\"%Y-%m-%d %H:%M\"), utc=True)\n end = pd.to_datetime(datetime.now().strftime(\"%Y-%m-%d %H:%M\"), utc=True)\n\n stock_data = api.get_bars(ticker, interval, start = start.isoformat(), end=end.isoformat(), adjustment=\"raw\").df\n \n interval_loop_data = interval_loop_data.append(stock_data)\n df_start_ref = interval_loop_data.index[0]\n start_str_ref = pd.to_datetime(start, utc=True)\n\n while start_str_ref.value < ( pd.to_datetime(df_start_ref, utc=True) - pd.Timedelta(days=2.5)).value:\n end_new = pd.to_datetime(interval_loop_data.index[0].strftime(\"%Y-%m-%d %H:%M\"), utc=True).isoformat()\n stock_data_new = None\n stock_data_new = api.get_bars(ticker, interval, start=start, end=end_new, adjustment=\"raw\").df\n #stock_data_new = stock_data_new.reset_index()\n interval_loop_data = interval_loop_data.append(stock_data_new).sort_values(by=['index'], ascending=True)\n df_start_ref = interval_loop_data.index[0]\n \n stock_yr_min_df = interval_loop_data.copy()\n stock_yr_min_df[\"Open\"] = stock_yr_min_df['open']\n stock_yr_min_df[\"High\"]= stock_yr_min_df[\"high\"]\n stock_yr_min_df[\"Low\"] = stock_yr_min_df[\"low\"]\n stock_yr_min_df[\"Close\"] = stock_yr_min_df[\"close\"]\n stock_yr_min_df[\"Volume\"] = stock_yr_min_df[\"volume\"]\n stock_yr_min_df[\"VolumeWeightedAvgPrice\"] = stock_yr_min_df[\"vwap\"]\n stock_yr_min_df[\"Time\"] = stock_yr_min_df.index.tz_convert(TZ)\n stock_yr_min_df.index = stock_yr_min_df.index.tz_convert(TZ)\n final_df = stock_yr_min_df.filter([\"Time\", \"Open\", \"High\", \"Low\", \"Close\", \"Volume\", \"VolumeWeightedAvgPrice\"], axis = 1)\n \n first_day = final_df.index[0]\n traintest_day = final_df.index[-1] - pd.Timedelta(days= test_days+validate_days+offset_days)\n valtest_day = final_df.index[-1] - pd.Timedelta(days= test_days+offset_days)\n last_day = final_df.index[-1] - pd.Timedelta(days= offset_days)\n training_df = final_df.loc[first_day:traintest_day] #(data_split - pd.Timedelta(days=1))]\n validate_df = final_df.loc[traintest_day:valtest_day]\n testing_df = final_df.loc[valtest_day:last_day]\n full_train = final_df.loc[first_day:last_day]\n offset_df = final_df.loc[last_day:]\n\n return training_df, validate_df, testing_df, full_train, offset_df, final_df, traintest_day, valtest_day\n\nfrom datetime import date\n\ntrain_start = date(2017, 1, 1)\ntrain_end = date(2020, 3, 29)\ntrain_delta = train_end - train_start\nprint(f'Number of days of Training Data {train_delta.days}')\n\nval_day_num = 400\nprint(f'Number of days of Validation Data {val_day_num}')\n\ntest_start = train_end + timedelta(val_day_num)\ntest_end = date.today()\ntest_delta = (test_end - test_start)\nprint(f'Number of days of Holdout Test Data {test_delta.days}')\n\nticker = \"CORN\" # Ticker Symbol to Test\ninterval = \"5Min\" # Interval of bars\ntrain_day_int = train_delta.days # Size of training set (Jan 2010 - Oct 2017)\nval_day_int = val_day_num # Size of validation set\ntest_day_int = test_delta.days # Size of test set\noffset_day_int = 0 # Number of days to off set the training data\ntrain_raw, val_raw, test_raw, full_raw, offset_raw, complete_raw, traintest_day, testval_day = prepost_train_test_validate_offset_data(api, ticker, \n interval, \n train_days=train_day_int, \n test_days=test_day_int, \n validate_days=val_day_int,\n offset_days = offset_day_int)\n\ndef timeFilterAndBackfill(df):\n \"\"\" \n Prep df to be filled out for each trading day:\n Time Frame: 0930-1930\n Backfilling NaNs\n Adjusting Volume to Zero if no Trading data is present\n - Assumption is that there were no trades duing that time \n\n We will build over lapping arrays by 30 min to give ourselfs more\n oppurtunities to predict during a given trading day \n \"\"\"\n \n df = df.between_time('07:29','17:29') # intial sorting of data\n\n TZ = 'US/Eastern' # define the correct timezone\n\n start_dateTime = pd.Timestamp(year = df.index[0].year, \n month = df.index[0].month, \n day = df.index[0].day, \n hour = 7, minute = 25, tz = TZ)\n\n end_dateTime = pd.Timestamp(year = df.index[-1].year, \n month = df.index[-1].month, \n day = df.index[-1].day, \n hour = 17, minute = 35, tz = TZ)\n\n # build blank index that has ever 5 min interval represented\n dateTime_index = pd.date_range(start_dateTime,\n end_dateTime, \n freq='5min').tolist()\n\n dateTime_index_df = pd.DataFrame()\n dateTime_index_df[\"Time\"] = dateTime_index \n filtered_df = pd.merge_asof(dateTime_index_df, df, \n on='Time').set_index(\"Time\").between_time('09:29','17:29')\n\n # create the close array by back filling NA, to represent no change in close\n closeset_list = []\n prev_c = None\n\n for c in filtered_df[\"Close\"]:\n\n if prev_c == None:\n if math.isnan(c):\n prev_c = 0\n closeset_list.append(0)\n else:\n prev_c = c\n closeset_list.append(c)\n \n elif prev_c != None:\n if c == prev_c:\n closeset_list.append(c)\n elif math.isnan(c):\n closeset_list.append(prev_c)\n else:\n closeset_list.append(c)\n prev_c = c\n \n filtered_df[\"Close\"] = closeset_list\n\n # create the volume\n volumeset_list = []\n prev_v = None\n\n for v in filtered_df[\"Volume\"]:\n \n if prev_v == None:\n if math.isnan(v):\n prev_v = 0\n volumeset_list.append(0)\n else:\n prev_v = v\n volumeset_list.append(v)\n\n elif prev_v != None:\n if v == prev_v:\n volumeset_list.append(0)\n prev_v = v\n elif math.isnan(v):\n volumeset_list.append(0)\n prev_v = 0\n else:\n volumeset_list.append(v)\n prev_v = v\n\n filtered_df[\"Volume\"] = volumeset_list\n \n adjvolumeset_list = []\n prev_v = None\n\n for v in filtered_df[\"VolumeWeightedAvgPrice\"]:\n if prev_v == None:\n if math.isnan(v):\n prev_v = 0\n adjvolumeset_list.append(0)\n else:\n prev_v = v\n adjvolumeset_list.append(v)\n elif prev_v != None:\n if v == prev_v:\n adjvolumeset_list.append(0)\n prev_v = v\n elif math.isnan(v):\n adjvolumeset_list.append(0)\n prev_v = 0\n else:\n adjvolumeset_list.append(v)\n prev_v = v\n\n filtered_df[\"VolumeWeightedAvgPrice\"] = adjvolumeset_list\n\n preped_df = filtered_df.backfill()\n\n return preped_df ", "Number of days of Training Data 1183\nNumber of days of Validation Data 400\nNumber of days of Holdout Test Data 284\n" ], [ "train_raw[275:300]", "_____no_output_____" ], [ "def buildTargets_VolOnly(full_df = full_raw, train_observations = train_raw.shape[0], \n val_observations = val_raw.shape[0], \n test_observations = test_raw.shape[0], \n alph = .55, volity_int = 10):\n\n \"\"\" \n This function will take a complete set of train, val, and test data and return the targets.\n Volitility will be calculated over the 252 5min incriments \n The Target shift is looking at 2 hours shift from current time\n \"\"\"\n\n returns = np.log(full_df['Close']/(full_df['Close'].shift()))\n returns.fillna(0, inplace=True)\n volatility = returns.rolling(window=(volity_int)).std()*np.sqrt(volity_int)\n\n\n\n return volatility\n #return train_targets, val_targets, test_targets, full_targets\n\nvolatility = buildTargets_VolOnly()\n\nfig = plt.figure(figsize=(15, 7))\nax1 = fig.add_subplot(1, 1, 1)\nvolatility.plot(ax=ax1, color = \"red\")\nax1.set_xlabel('Date')\nax1.set_ylabel('Volatility', color = \"red\")\nax1.set_title(f'Annualized volatility for {ticker}')\nax2 = ax1.twinx()\nfull_raw.Close.plot(ax=ax2, color = \"blue\")\nax2.set_ylabel('Close', color = \"blue\")\nax2.axvline(x=full_raw.index[train_raw.shape[0]])\nax2.axvline(x=full_raw.index[val_raw.shape[0]+train_raw.shape[0]])\nplt.show()", "_____no_output_____" ], [ "train = timeFilterAndBackfill(train_raw)\nval = timeFilterAndBackfill(val_raw)\ntest = timeFilterAndBackfill(test_raw)\n\ntrain = train[train.index.dayofweek <= 4].copy()\nval = val[val.index.dayofweek <= 4].copy()\ntest = test[test.index.dayofweek <= 4].copy()\n\ntrain[\"Open\"] = np.where((train[\"Volume\"] == 0), train[\"Close\"], train[\"Open\"])\ntrain[\"High\"] = np.where((train[\"Volume\"] == 0), train[\"Close\"], train[\"High\"])\ntrain[\"Low\"] = np.where((train[\"Volume\"] == 0), train[\"Close\"], train[\"Low\"])\n\nval[\"Open\"] = np.where((val[\"Volume\"] == 0), val[\"Close\"], val[\"Open\"])\nval[\"High\"] = np.where((val[\"Volume\"] == 0), val[\"Close\"], val[\"High\"])\nval[\"Low\"] = np.where((val[\"Volume\"] == 0), val[\"Close\"], val[\"Low\"])\n\ntest[\"Open\"] = np.where((test[\"Volume\"] == 0), test[\"Close\"], test[\"Open\"])\ntest[\"High\"] = np.where((test[\"Volume\"] == 0), test[\"Close\"], test[\"High\"])\ntest[\"Low\"] = np.where((test[\"Volume\"] == 0), test[\"Close\"], test[\"Low\"])\n\ndef strided_axis0(a, L, overlap=1):\n if L==overlap:\n raise Exception(\"Overlap arg must be smaller than length of windows\")\n S = L - overlap\n nd0 = ((len(a)-L)//S)+1\n if nd0*S-S!=len(a)-L:\n warnings.warn(\"Not all elements were covered\")\n m,n = a.shape\n s0,s1 = a.strides\n return np.lib.stride_tricks.as_strided(a, shape=(nd0,L,n), strides=(S*s0,s0,s1))\n\n# OLDER CODE WITHOUT OVERLAP OF LABELING\n# def blockshaped(arr, nrows, ncols):\n# \"\"\"\n# Return an array of shape (n, nrows, ncols) where\n# n * nrows * ncols = arr.size\n\n# If arr is a 2D array, the returned array should look like n subblocks with\n# each subblock preserving the \"physical\" layout of arr.\n# \"\"\"\n# h, w = arr.shape\n# assert h % nrows == 0, f\"{h} rows is not evenly divisible by {nrows}\"\n# assert w % ncols == 0, f\"{w} cols is not evenly divisible by {ncols}\"\n# return np.flip(np.rot90((arr.reshape(h//nrows, nrows, -1, ncols)\n# .swapaxes(1,2)\n# .reshape(-1, nrows, ncols)), axes = (1, 2)), axis = 1)\n\n\ndef blockshaped(arr, nrows, ncols, overlapping_5min_intervals = 12):\n \"\"\"\n Return an array of shape (n, nrows, ncols) where\n n * nrows * ncols = arr.size\n\n If arr is a 2D array, the returned array should look like n subblocks with\n each subblock preserving the \"physical\" layout of arr.\n \"\"\"\n\n h, w = arr.shape\n assert h % nrows == 0, f\"{h} rows is not evenly divisible by {nrows}\"\n assert w % ncols == 0, f\"{w} cols is not evenly divisible by {ncols}\"\n\n return np.flip(np.rot90((strided_axis0(arr, 24, overlap=overlapping_5min_intervals).reshape(-1, nrows, ncols)), axes = (1, 2)), axis = 1)\n\ntrain_tonp = train[[\"Open\", \"High\", \"Low\", \"Close\", \"Volume\"]]\nval_tonp = val[[\"Open\", \"High\", \"Low\", \"Close\", \"Volume\"]]\ntest_tonp = test[[\"Open\", \"High\", \"Low\", \"Close\", \"Volume\"]]\ntrain_array = train_tonp.to_numpy()\nval_array = val_tonp.to_numpy()\ntest_array = test_tonp.to_numpy()\n\nX_train_pre_final = blockshaped(train_array, 24, 5, overlapping_5min_intervals = 12)\nX_val_pre_final = blockshaped(val_array, 24, 5, overlapping_5min_intervals = 12)\nX_test_pre_final = blockshaped(test_array, 24, 5, overlapping_5min_intervals = 12)\n\n# X_train_pre_final = blockshaped(train_array, 24, 5)\n# X_val_pre_final = blockshaped(val_array, 24, 5)\n# X_test_pre_final = blockshaped(test_array, 24, 5)", "_____no_output_____" ], [ "X_train_pre_final[0]", "_____no_output_____" ], [ "# create target from OHLC and Volume Data\ndef buildTargets(obs_array, \n alph = .55, \n volity_int = 10):\n\n \"\"\" \n This function will take a complete set of train, val, and test \n data and return the targets. Volitility will be calculated over \n the 24 5min incriments. The Target shift is looking at 2 hours \n shift from current time\n\n shift_2hour = The amount of time the data interval take to equal 2 hours \n (i.e. 5 min data interval is equal to 24)\n alph = The alpha value for calculating the shift in price\n volity_int = the number of incriments used to calculate volitility \n \"\"\"\n\n target_close_list =[]\n\n for arr in obs_array:\n target_close_list.append(arr[3][-1])\n \n target_close_df = pd.DataFrame()\n target_close_df[\"Close\"] = target_close_list\n\n target_close_df[\"Volitility\"] = target_close_df[\"Close\"].rolling(volity_int).std()\n\n # print(len(volatility), len(target_close_df[\"Close\"]))\n\n \n targets = [2] * len(target_close_df.Close)\n\n targets = np.where(target_close_df.Close.shift() >= (target_close_df.Close * (1 + alph * target_close_df[\"Volitility\"])), \n 1, targets)\n \n targets = np.where(target_close_df.Close.shift() <= (target_close_df.Close * (1 - alph * target_close_df[\"Volitility\"])), \n 0, targets)\n\n return targets", "_____no_output_____" ], [ "volity_val = 10\nalph = .015\ny_train_pre_final = buildTargets(X_train_pre_final, alph=alph, volity_int = volity_val)\ny_val_pre_final = buildTargets(X_val_pre_final, alph=alph, volity_int = volity_val)\ny_test_pre_final = buildTargets(X_test_pre_final, alph=alph, volity_int = volity_val)", "_____no_output_____" ], [ "def get_class_distribution(obj):\n count_dict = {\n \"up\": 0,\n \"flat\": 0,\n \"down\": 0,\n }\n \n for i in obj:\n if i == 1: \n count_dict['up'] += 1\n elif i == 0: \n count_dict['down'] += 1\n elif i == 2: \n count_dict['flat'] += 1 \n else:\n print(\"Check classes.\")\n \n return count_dict", "_____no_output_____" ], [ "bfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(25,7))\n# Train\nsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_train_pre_final)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Class Distribution in Train Set')\n# Validation\nsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_val_pre_final)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Class Distribution in Val Set')\n# Test\nsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_test_pre_final)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[2]).set_title('Class Distribution in Test Set')", "_____no_output_____" ], [ "def createFinalData_RemoveLateAfternoonData(arr, labels):\n\n assert arr.shape[0] == len(labels), \"X data do not match length of y labels\"\n\n step_count = 0\n filtered_y_labels = []\n\n for i in range(arr.shape[0]):\n\n if i == 0:\n final_arr = arr[i]\n filtered_y_labels.append(labels[i])\n #print(f'Appending index {i}, step_count: {step_count}')\n step_count += 1\n\n elif i == 1:\n\n final_arr = np.stack((final_arr, arr[i]))\n filtered_y_labels.append(labels[i])\n step_count += 1\n\n elif step_count == 0: \n final_arr = np.vstack((final_arr, arr[i][None]))\n filtered_y_labels.append(labels[i])\n #print(f'Appending index {i}, step_count: {step_count}')\n step_count += 1\n \n elif (step_count) % 5 == 0:\n #print(f'skipping {i} array, step_count: {step_count}')\n step_count += 1\n\n elif (step_count) % 6 == 0:\n #print(f'skipping {i} array, step_count: {step_count}')\n step_count += 1\n\n elif (step_count) % 7 == 0:\n #print(f'skipping {i} array, step_count: {step_count}')\n step_count = 0\n \n else:\n final_arr = np.vstack((final_arr, arr[i][None]))\n filtered_y_labels.append(labels[i])\n #print(f'Appending index {i}, step_count: {step_count}')\n step_count += 1\n \n return final_arr, filtered_y_labels\n\nX_train, y_train = createFinalData_RemoveLateAfternoonData(X_train_pre_final, y_train_pre_final)\nX_val, y_val = createFinalData_RemoveLateAfternoonData(X_val_pre_final, y_val_pre_final)\nX_test, y_test = createFinalData_RemoveLateAfternoonData(X_test_pre_final, y_test_pre_final)\n\ny_train = np.array(y_train)\ny_val = np.array(y_val)\ny_test = np.array(y_test)", "_____no_output_____" ], [ "# Check it arrays are made correctly\ntrain[12:48]", "_____no_output_____" ], [ "np.set_printoptions(threshold=200)\ny_train_pre_final[0:24]", "_____no_output_____" ], [ "######\n# Code fro scaling at a later date\n######\n\n# from sklearn.preprocessing import MinMaxScaler\n\nscalers = {}\nfor i in range(X_train.shape[1]):\n scalers[i] = MinMaxScaler()\n X_train[:, i, :] = scalers[i].fit_transform(X_train[:, i, :]) \n\nfor i in range(X_val.shape[1]):\n scalers[i] = MinMaxScaler()\n X_val[:, i, :] = scalers[i].fit_transform(X_val[:, i, :]) \n\nfor i in range(X_test.shape[1]):\n scalers[i] = MinMaxScaler()\n X_test[:, i, :] = scalers[i].fit_transform(X_test[:, i, :]) \n ", "_____no_output_____" ], [ "def get_class_distribution(obj):\n count_dict = {\n \"up\": 0,\n \"flat\": 0,\n \"down\": 0,\n }\n \n for i in obj:\n if i == 1: \n count_dict['up'] += 1\n elif i == 0: \n count_dict['down'] += 1\n elif i == 2: \n count_dict['flat'] += 1 \n else:\n print(\"Check classes.\")\n \n return count_dict", "_____no_output_____" ], [ "bfig, axes = plt.subplots(nrows=1, ncols=3, figsize=(25,7))\n# Train\nsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_train)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Class Distribution in Train Set')\n# Validation\nsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_val)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Class Distribution in Val Set')\n# Test\nsns.barplot(data = pd.DataFrame.from_dict([get_class_distribution(y_test)]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", ax=axes[2]).set_title('Class Distribution in Test Set')", "_____no_output_____" ], [ "###### ONLY EXECUTE FOR 2D CNN #####\n\nX_train = X_train.reshape(X_train.shape[0], 1,\n X_train.shape[1], \n X_train.shape[2])\nX_val = X_val.reshape(X_val.shape[0], 1,\n X_val.shape[1], \n X_val.shape[2])\nX_test = X_test.reshape(X_test.shape[0], 1,\n X_test.shape[1], \n X_test.shape[2])", "_____no_output_____" ], [ "print(f'X Train Length {X_train.shape}, y Train Label Length {y_train.shape}')\nprint(f'X Val Length {X_val.shape}, y Val Label Length {y_val.shape}')\nprint(f'X Test Length {X_test.shape}, y Test Label Length {y_test.shape}')", "X Train Length (4220, 1, 5, 24), y Train Label Length (4220,)\nX Val Length (1430, 1, 5, 24), y Val Label Length (1430,)\nX Test Length (1025, 1, 5, 24), y Test Label Length (1025,)\n" ] ], [ [ "# 2D CNN Build Model", "_____no_output_____" ] ], [ [ "trainset = TensorDataset(torch.from_numpy(X_train).float(), \n torch.from_numpy(y_train).long())\nvalset = TensorDataset(torch.from_numpy(X_val).float(), \n torch.from_numpy(y_val).long())\ntestset = TensorDataset(torch.from_numpy(X_test).float(), \n torch.from_numpy(y_test).long())", "_____no_output_____" ], [ "trainset", "_____no_output_____" ], [ "batch_size = 1\n\n# train_data = []\n# for i in range(len(X_train)):\n# train_data.append([X_train[i].astype('float'), y_train[i]])\n\ntrain_loader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=False)\ni1, l1 = next(iter(train_loader))\nprint(i1.shape)\n\n# val_data = []\n# for i in range(len(X_val)):\n# val_data.append([X_val[i].astype('float'), y_val[i]])\n\nval_loader = torch.utils.data.DataLoader(valset, batch_size=batch_size, shuffle=False)\ni1, l1 = next(iter(val_loader))\nprint(i1.shape)\n\ntest_loader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False)\ni1, l1 = next(iter(test_loader))\nprint(i1.shape)", "torch.Size([1, 1, 5, 24])\ntorch.Size([1, 1, 5, 24])\ntorch.Size([1, 1, 5, 24])\n" ], [ "# Get next batch of training images\nwindows, labels = iter(train_loader).next()\nprint(windows)\nwindows = windows.numpy()\n\n# plot the windows in the batch, along with the corresponding labels\nfor idx in range(batch_size):\n print(labels[idx])", "tensor([[[[8.2873e-01, 8.2556e-01, 8.2579e-01, 8.2903e-01, 8.3709e-01,\n 8.3360e-01, 8.3704e-01, 8.3333e-01, 8.3140e-01, 8.2735e-01,\n 8.2873e-01, 8.3367e-01, 8.3172e-01, 8.3516e-01, 8.3486e-01,\n 8.3770e-01, 8.4144e-01, 8.4127e-01, 8.4254e-01, 8.4299e-01,\n 8.4319e-01, 8.4807e-01, 8.5202e-01, 8.5319e-01],\n [8.2649e-01, 8.2967e-01, 8.2579e-01, 8.3489e-01, 8.3686e-01,\n 8.3348e-01, 8.3701e-01, 8.3080e-01, 8.3047e-01, 8.2735e-01,\n 8.2873e-01, 8.3367e-01, 8.3575e-01, 8.3516e-01, 8.3486e-01,\n 8.4028e-01, 8.4121e-01, 8.4116e-01, 8.4251e-01, 8.4044e-01,\n 8.4232e-01, 8.5221e-01, 8.5202e-01, 8.5319e-01],\n [8.3446e-01, 8.2579e-01, 8.2674e-01, 8.3017e-01, 8.3279e-01,\n 8.3475e-01, 8.3290e-01, 8.3356e-01, 8.2957e-01, 8.2735e-01,\n 8.2877e-01, 8.3170e-01, 8.3172e-01, 8.3516e-01, 8.3576e-01,\n 8.3885e-01, 8.4144e-01, 8.4105e-01, 8.4254e-01, 8.4320e-01,\n 8.4319e-01, 8.4807e-01, 8.5205e-01, 8.5439e-01],\n [8.2661e-01, 8.2555e-01, 8.2579e-01, 8.3512e-01, 8.3268e-01,\n 8.3475e-01, 8.3564e-01, 8.3126e-01, 8.2863e-01, 8.2735e-01,\n 8.2877e-01, 8.3171e-01, 8.3586e-01, 8.3516e-01, 8.3486e-01,\n 8.4160e-01, 8.4133e-01, 8.4243e-01, 8.4254e-01, 8.4088e-01,\n 8.4232e-01, 8.5083e-01, 8.5205e-01, 8.5439e-01],\n [1.2028e-02, 6.0699e-04, 0.0000e+00, 4.9582e-02, 2.3419e-02,\n 0.0000e+00, 1.3325e-02, 0.0000e+00, 1.4384e-02, 7.9232e-03,\n 0.0000e+00, 3.3546e-02, 6.7408e-03, 6.3636e-04, 5.6090e-03,\n 3.6610e-03, 1.1189e-02, 2.5785e-01, 0.0000e+00, 1.8960e-02,\n 1.6688e-02, 8.8472e-02, 0.0000e+00, 4.7923e-03]]]])\ntensor(2)\n" ], [ "# Set up dict for dataloaders\ndataloaders = {'train':train_loader,'val':val_loader}\n# Store size of training and validation sets\ndataset_sizes = {'train':len(trainset),'val':len(valset)}\n# Get class names associated with labels\nclasses = [0,1,2]", "_____no_output_____" ], [ "class StockShiftClassification(nn.Module):\n def __init__(self):\n super(StockShiftClassification, self).__init__()\n\n self.conv1 = nn.Conv2d(1, 32, kernel_size = (1,3), stride=1, padding = 1)\n self.pool1 = nn.MaxPool2d((1,4),4)\n\n self.conv2 = nn.Conv2d(32, 64, kernel_size = (1,3), stride=1, padding = 1)\n self.pool2 = nn.MaxPool2d((1,3),3) \n\n self.conv3 = nn.Conv2d(64, 128, kernel_size = (1,3), stride=1, padding = 1)\n self.pool3 = nn.MaxPool2d((1,2),2)\n\n self.fc1 = nn.Linear(256,1000) #calculate this\n self.fc2 = nn.Linear(1000, 500)\n #self.fc3 = nn.Linear(500, 3)\n\n def forward(self, x):\n\n x = F.relu(self.conv1(x))\n x = self.pool1(x)\n x = F.relu(self.conv2(x))\n x = self.pool2(x)\n x = F.relu(self.conv3(x))\n x = self.pool3(x)\n\n #print(x.size(1))\n\n x = x.view(x.size(0), -1)\n\n \n\n # Linear layer\n x = self.fc1(x)\n x = self.fc2(x)\n #x = self.fc3(x)\n\n output = x#F.softmax(x, dim=1)\n\n return output\n", "_____no_output_____" ], [ "# Instantiate the model\nnet = StockShiftClassification().float()\n\n# Display a summary of the layers of the model and output shape after each layer\nsummary(net,(windows.shape[1:]),batch_size=batch_size,device=\"cpu\")", "----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [1, 32, 7, 24] 128\n MaxPool2d-2 [1, 32, 2, 6] 0\n Conv2d-3 [1, 64, 4, 6] 6,208\n MaxPool2d-4 [1, 64, 2, 2] 0\n Conv2d-5 [1, 128, 4, 2] 24,704\n MaxPool2d-6 [1, 128, 2, 1] 0\n Linear-7 [1, 1000] 257,000\n Linear-8 [1, 500] 500,500\n================================================================\nTotal params: 788,540\nTrainable params: 788,540\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.00\nForward/backward pass size (MB): 0.08\nParams size (MB): 3.01\nEstimated Total Size (MB): 3.09\n----------------------------------------------------------------\n" ], [ "def train_model(model, criterion, optimizer, train_loaders, device, num_epochs=50, scheduler=onecycle_scheduler):\n\n model = model.to(device) # Send model to GPU if available\n\n writer = SummaryWriter() # Instantiate TensorBoard\n\n iter_num = {'train':0,'val':0} # Track total number of iterations\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Get the input images and labels, and send to GPU if available\n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # Zero the weight gradients\n optimizer.zero_grad()\n\n # Forward pass to get outputs and calculate loss\n # Track gradient only for training data\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n # print(outputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n # Backpropagation to get the gradients with respect to each weight\n # Only if in train\n if phase == 'train':\n loss.backward()\n # Update the weights\n optimizer.step()\n\n # Convert loss into a scalar and add it to running_loss\n running_loss += loss.item() * inputs.size(0)\n # Track number of correct predictions\n running_corrects += torch.sum(preds == labels.data)\n\n # Iterate count of iterations\n iter_num[phase] += 1\n\n # Write loss for batch to TensorBoard\n writer.add_scalar(\"{} / batch loss\".format(phase), loss.item(), iter_num[phase])\n\n # scheduler.step()\n\n # Calculate and display average loss and accuracy for the epoch\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n # Write loss and accuracy for epoch to TensorBoard\n writer.add_scalar(\"{} / epoch loss\".format(phase), epoch_loss, epoch)\n writer.add_scalar(\"{} / epoch accuracy\".format(phase), epoch_acc, epoch)\n\n writer.close()\n \n return", "_____no_output_____" ], [ "# Train the model\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Cross entropy loss combines softmax and nn.NLLLoss() in one single class.\nweights = torch.tensor([1.5, 2.25, 1.]).to(device)\ncriterion_weighted = nn.CrossEntropyLoss(weight=weights)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Define optimizer\n#optimizer = optim.SGD(net.parameters(), lr=0.001)\noptimizer = optim.Adam(net.parameters(), lr=0.001, weight_decay=0.00001)\n\n\nn_epochs= 10 # For demo purposes. Use epochs>100 for actual training\n\nonecycle_scheduler = optim.lr_scheduler.OneCycleLR(optimizer,\n max_lr=0.01,\n base_momentum = 0.8,\n steps_per_epoch=len(train_loader),\n epochs=n_epochs)\n\n\ntrain_model(net, criterion, optimizer, dataloaders, device, num_epochs=n_epochs) #, scheduler=onecycle_scheduler)", "Epoch 0/9\n----------\ntrain Loss: 1.1028 Acc: 0.3623\nval Loss: 1.1170 Acc: 0.2951\nEpoch 1/9\n----------\ntrain Loss: 1.1010 Acc: 0.3687\nval Loss: 1.1123 Acc: 0.2951\nEpoch 2/9\n----------\ntrain Loss: 1.1002 Acc: 0.3699\nval Loss: 1.1090 Acc: 0.3678\nEpoch 3/9\n----------\ntrain Loss: 1.0997 Acc: 0.3716\nval Loss: 1.1084 Acc: 0.3678\nEpoch 4/9\n----------\ntrain Loss: 1.0994 Acc: 0.3730\nval Loss: 1.1071 Acc: 0.3678\nEpoch 5/9\n----------\ntrain Loss: 1.0991 Acc: 0.3701\nval Loss: 1.1066 Acc: 0.3678\nEpoch 6/9\n----------\ntrain Loss: 1.0989 Acc: 0.3699\nval Loss: 1.1077 Acc: 0.3678\nEpoch 7/9\n----------\n" ], [ "def test_model(model,val_loader,device):\n # Turn autograd off\n with torch.no_grad():\n\n # Set the model to evaluation mode\n model = model.to(device)\n model.eval()\n\n # Set up lists to store true and predicted values\n y_true = []\n test_preds = []\n\n # Calculate the predictions on the test set and add to list\n for data in val_loader:\n \n inputs, labels = data[0].to(device), data[1].to(device)\n # Feed inputs through model to get raw scores\n logits = model.forward(inputs)\n\n #print(f'Logits: {logits}')\n\n # Convert raw scores to probabilities (not necessary since we just care about discrete probs in this case)\n probs = F.log_softmax(logits, dim=1)\n #print(f'Probs after LogSoft: {probs}')\n\n # Get discrete predictions using argmax\n preds = np.argmax(probs.cpu().numpy(),axis=1)\n # Add predictions and actuals to lists\n test_preds.extend(preds)\n y_true.extend(labels)\n\n # Calculate the accuracy\n test_preds = np.array(test_preds)\n y_true = np.array(y_true)\n test_acc = np.sum(test_preds == y_true)/y_true.shape[0]\n \n # Recall for each class\n recall_vals = []\n for i in range(3):\n class_idx = np.argwhere(y_true==i)\n total = len(class_idx)\n correct = np.sum(test_preds[class_idx]==i)\n recall = correct / total\n recall_vals.append(recall)\n\n \n return test_acc, recall_vals", "_____no_output_____" ], [ "# Calculate the test set accuracy and recall for each class\nacc,recall_vals = test_model(net,val_loader,device)\nprint('Test set accuracy is {:.3f}'.format(acc))\nfor i in range(3):\n print('For class {}, recall is {}'.format(classes[i],recall_vals[i]))", "Test set accuracy is 0.295\nFor class 0, recall is 0.0\nFor class 1, recall is 1.0\nFor class 2, recall is 0.0\n" ], [ "from sklearn.metrics import confusion_matrix\n\ndef plot_confusion_matrix(cm,\n target_names,\n title='Confusion matrix',\n cmap=None,\n normalize=True):\n \"\"\"\n given a sklearn confusion matrix (cm), make a nice plot\n\n Arguments\n ---------\n cm: confusion matrix from sklearn.metrics.confusion_matrix\n\n target_names: given classification classes such as [0, 1, 2]\n the class names, for example: ['high', 'medium', 'low']\n\n title: the text to display at the top of the matrix\n\n cmap: the gradient of the values displayed from matplotlib.pyplot.cm\n see http://matplotlib.org/examples/color/colormaps_reference.html\n plt.get_cmap('jet') or plt.cm.Blues\n\n normalize: If False, plot the raw numbers\n If True, plot the proportions\n\n Usage\n -----\n plot_confusion_matrix(cm = cm, # confusion matrix created by\n # sklearn.metrics.confusion_matrix\n normalize = True, # show proportions\n target_names = y_labels_vals, # list of names of the classes\n title = best_estimator_name) # title of graph\n\n Citiation\n ---------\n http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html\n\n \"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n import itertools\n\n accuracy = np.trace(cm) / np.sum(cm).astype('float')\n misclass = 1 - accuracy\n\n if cmap is None:\n cmap = plt.get_cmap('Blues')\n\n plt.figure(figsize=(8, 6))\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n\n if target_names is not None:\n tick_marks = np.arange(len(target_names))\n plt.xticks(tick_marks, target_names, rotation=45)\n plt.yticks(tick_marks, target_names)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n\n thresh = cm.max() / 1.5 if normalize else cm.max() / 2\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if normalize:\n plt.text(j, i, \"{:0.4f}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n else:\n plt.text(j, i, \"{:,}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\n plt.show()\n\nnb_classes = 9\n\n# Initialize the prediction and label lists(tensors)\npredlist=torch.zeros(0,dtype=torch.long, device='cpu')\nlbllist=torch.zeros(0,dtype=torch.long, device='cpu')\n\nwith torch.no_grad():\n for i, (inputs, classes) in enumerate(dataloaders['val']):\n inputs = inputs.to(device)\n classes = classes.to(device)\n outputs = net.forward(inputs)\n _, preds = torch.max(outputs, 1)\n\n # Append batch prediction results\n predlist=torch.cat([predlist,preds.view(-1).cpu()])\n lbllist=torch.cat([lbllist,classes.view(-1).cpu()])\n\n# Confusion matrix\nconf_mat=confusion_matrix(lbllist.numpy(), predlist.numpy())\nplot_confusion_matrix(conf_mat, [0,1,2])\n\nfrom sklearn.metrics import precision_score\n\nprecision_score(lbllist.numpy(), predlist.numpy(), average='weighted')\n\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(lbllist.numpy(), predlist.numpy(), target_names=[\"down\",\"up\",\"flat\"], digits=4))", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "train_x = torch.from_numpy(X_train).float()\ntrain_y = torch.from_numpy(y_train).long()\nval_x = torch.from_numpy(X_val).float()\nval_y = torch.from_numpy(y_val).long()", "_____no_output_____" ], [ "# defining the model\nmodel = net\n# defining the optimizer\noptimizer = Adam(model.parameters(), lr=0.07)\n# defining the loss function\ncriterion = CrossEntropyLoss()\n# checking if GPU is available\nif torch.cuda.is_available():\n model = model.cuda()\n criterion = criterion.cuda()", "_____no_output_____" ], [ "from torch.autograd import Variable\n\ndef train(epoch, train_x, train_y, val_x, val_y):\n model.train()\n tr_loss = 0\n # getting the training set\n x_train, y_train = Variable(train_x), Variable(train_y)\n # getting the validation set\n x_val, y_val = Variable(val_x), Variable(val_y)\n # converting the data into GPU format\n if torch.cuda.is_available():\n x_train = x_train.cuda()\n y_train = y_train.cuda()\n x_val = x_val.cuda()\n y_val = y_val.cuda()\n\n # clearing the Gradients of the model parameters\n optimizer.zero_grad()\n \n # prediction for training and validation set\n output_train = model(x_train)\n output_val = model(x_val)\n\n # computing the training and validation loss\n loss_train = criterion(output_train, y_train)\n loss_val = criterion(output_val, y_val)\n train_losses.append(loss_train)\n val_losses.append(loss_val)\n\n # computing the updated weights of all the model parameters\n loss_train.backward()\n optimizer.step()\n tr_loss = loss_train.item()\n if epoch%2 == 0:\n # printing the validation loss\n print('Epoch : ',epoch+1, '\\t', 'loss :', loss_val)", "_____no_output_____" ], [ "# defining the number of epochs\nn_epochs = 100\n# empty list to store training losses\ntrain_losses = []\n# empty list to store validation losses\nval_losses = []\n# training the model\nfor epoch in range(n_epochs):\n train(epoch, X_train, y_train, X_val, y_val)", "Epoch : 1 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 3 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 5 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 7 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 9 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 11 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 13 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 15 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 17 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 19 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 21 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 23 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 25 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 27 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 29 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 31 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 33 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 35 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 37 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 39 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 41 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 43 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 45 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 47 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 49 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 51 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 53 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 55 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 57 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 59 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 61 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 63 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 65 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 67 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 69 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 71 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 73 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 75 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 77 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 79 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 81 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 83 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 85 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 87 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 89 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 91 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 93 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 95 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 97 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\nEpoch : 99 \t loss : tensor(1.0988, device='cuda:0', grad_fn=<NllLossBackward0>)\n" ], [ "# plotting the training and validation loss\nplt.plot(train_losses, label='Training loss')\nplt.plot(val_losses, label='Validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\nfrom tqdm import tqdm\n\nwith torch.no_grad():\n output = model(X_val.cuda())\n \nsoftmax = torch.exp(output).cpu()\nprob = list(softmax.numpy())\npredictions = np.argmax(prob, axis=1)\n\n# accuracy on training set\naccuracy_score(y_val, predictions)", "_____no_output_____" ], [ "# defining the number of epochs\nn_epochs = 25\n# empty list to store training losses\ntrain_losses = []\n# empty list to store validation losses\nval_losses = []\n# training the model\nfor epoch in range(n_epochs):\n train(epoch)", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "def train_model(model, criterion, optimizer, train_loaders, device, num_epochs=50): #, scheduler=onecycle_scheduler):\n\n model = model.to(device) # Send model to GPU if available\n\n writer = SummaryWriter() # Instantiate TensorBoard\n\n iter_num = {'train':0,'val':0} # Track total number of iterations\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Get the input images and labels, and send to GPU if available\n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # Zero the weight gradients\n optimizer.zero_grad()\n\n # Forward pass to get outputs and calculate loss\n # Track gradient only for training data\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n # Backpropagation to get the gradients with respect to each weight\n # Only if in train\n if phase == 'train':\n loss.backward()\n # Update the weights\n optimizer.step()\n\n # Convert loss into a scalar and add it to running_loss\n running_loss += loss.item() * inputs.size(0)\n # Track number of correct predictions\n running_corrects += torch.sum(preds == labels.data)\n\n # Iterate count of iterations\n iter_num[phase] += 1\n\n # Write loss for batch to TensorBoard\n writer.add_scalar(\"{} / batch loss\".format(phase), loss.item(), iter_num[phase])\n\n # scheduler.step()\n\n # Calculate and display average loss and accuracy for the epoch\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n # Write loss and accuracy for epoch to TensorBoard\n writer.add_scalar(\"{} / epoch loss\".format(phase), epoch_loss, epoch)\n writer.add_scalar(\"{} / epoch accuracy\".format(phase), epoch_acc, epoch)\n\n writer.close()\n \n return", "_____no_output_____" ], [ "# Train the model\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Cross entropy loss combines softmax and nn.NLLLoss() in one single class.\nweights = torch.tensor([1.75, 2.25, 1.]).to(device)\ncriterion_weighted = nn.CrossEntropyLoss(weight=weights)\n\ncriterion = nn.CrossEntropyLoss()\n\n# Define optimizer\n#optimizer = optim.SGD(net.parameters(), lr=0.001)\noptimizer = optim.Adam(net.parameters(), lr=0.001, weight_decay=0.00001)\n\n\nn_epochs= 10 # For demo purposes. Use epochs>100 for actual training\n\n# onecycle_scheduler = optim.lr_scheduler.OneCycleLR(optimizer,\n# max_lr=0.01,\n# base_momentum = 0.8,\n# steps_per_epoch=len(train_loader),\n# epochs=n_epochs)\n\n\n\ntrain_model(net, criterion, optimizer, dataloaders, device, num_epochs=n_epochs) #, scheduler=onecycle_scheduler)", "Epoch 0/99\n----------\ntrain Loss: 1.3127 Acc: 0.3615\nval Loss: 1.0994 Acc: 0.3935\nEpoch 1/99\n----------\ntrain Loss: 1.1108 Acc: 0.3545\nval Loss: 1.1011 Acc: 0.3169\nEpoch 2/99\n----------\ntrain Loss: 1.1089 Acc: 0.3480\nval Loss: 1.1050 Acc: 0.3169\nEpoch 3/99\n----------\ntrain Loss: 1.1076 Acc: 0.3501\nval Loss: 1.1064 Acc: 0.3169\nEpoch 4/99\n----------\ntrain Loss: 1.1071 Acc: 0.3488\nval Loss: 1.1095 Acc: 0.3169\nEpoch 5/99\n----------\ntrain Loss: 1.1068 Acc: 0.3553\nval Loss: 1.1105 Acc: 0.3169\nEpoch 6/99\n----------\ntrain Loss: 1.1066 Acc: 0.3572\nval Loss: 1.1110 Acc: 0.3169\nEpoch 7/99\n----------\ntrain Loss: 1.1064 Acc: 0.3553\nval Loss: 1.1112 Acc: 0.3169\nEpoch 8/99\n----------\ntrain Loss: 1.1063 Acc: 0.3550\nval Loss: 1.1117 Acc: 0.3169\nEpoch 9/99\n----------\ntrain Loss: 1.1061 Acc: 0.3566\nval Loss: 1.1117 Acc: 0.3169\nEpoch 10/99\n----------\ntrain Loss: 1.1059 Acc: 0.3558\nval Loss: 1.1119 Acc: 0.3169\nEpoch 11/99\n----------\ntrain Loss: 1.1057 Acc: 0.3556\nval Loss: 1.1121 Acc: 0.3169\nEpoch 12/99\n----------\ntrain Loss: 1.1055 Acc: 0.3550\nval Loss: 1.1124 Acc: 0.3169\nEpoch 13/99\n----------\ntrain Loss: 1.1052 Acc: 0.3550\nval Loss: 1.1125 Acc: 0.3169\nEpoch 14/99\n----------\ntrain Loss: 1.1048 Acc: 0.3558\nval Loss: 1.1122 Acc: 0.3169\nEpoch 15/99\n----------\ntrain Loss: 1.1043 Acc: 0.3558\nval Loss: 1.1115 Acc: 0.2897\nEpoch 16/99\n----------\ntrain Loss: 1.1039 Acc: 0.3542\nval Loss: 1.1106 Acc: 0.2897\nEpoch 17/99\n----------\ntrain Loss: 1.1033 Acc: 0.3591\nval Loss: 1.1098 Acc: 0.2897\nEpoch 18/99\n----------\ntrain Loss: 1.1026 Acc: 0.3577\nval Loss: 1.1085 Acc: 0.2897\nEpoch 19/99\n----------\ntrain Loss: 1.1020 Acc: 0.3602\nval Loss: 1.1071 Acc: 0.2897\nEpoch 20/99\n----------\ntrain Loss: 1.1016 Acc: 0.3564\nval Loss: 1.1070 Acc: 0.2897\nEpoch 21/99\n----------\ntrain Loss: 1.1010 Acc: 0.3572\nval Loss: 1.1062 Acc: 0.2897\nEpoch 22/99\n----------\ntrain Loss: 1.1008 Acc: 0.3610\nval Loss: 1.1059 Acc: 0.2897\nEpoch 23/99\n----------\ntrain Loss: 1.1005 Acc: 0.3610\nval Loss: 1.1055 Acc: 0.2897\nEpoch 24/99\n----------\ntrain Loss: 1.1002 Acc: 0.3596\nval Loss: 1.1056 Acc: 0.2897\nEpoch 25/99\n----------\ntrain Loss: 1.1000 Acc: 0.3615\nval Loss: 1.1046 Acc: 0.2897\nEpoch 26/99\n----------\ntrain Loss: 1.0999 Acc: 0.3642\nval Loss: 1.1049 Acc: 0.2897\nEpoch 27/99\n----------\ntrain Loss: 1.0996 Acc: 0.3629\nval Loss: 1.1039 Acc: 0.2897\nEpoch 28/99\n----------\ntrain Loss: 1.0996 Acc: 0.3664\nval Loss: 1.1036 Acc: 0.2897\nEpoch 29/99\n----------\ntrain Loss: 1.0994 Acc: 0.3664\nval Loss: 1.1032 Acc: 0.2897\nEpoch 30/99\n----------\ntrain Loss: 1.0993 Acc: 0.3653\nval Loss: 1.1032 Acc: 0.2897\nEpoch 31/99\n----------\ntrain Loss: 1.0992 Acc: 0.3667\nval Loss: 1.1028 Acc: 0.2897\nEpoch 32/99\n----------\ntrain Loss: 1.0991 Acc: 0.3661\nval Loss: 1.1027 Acc: 0.2897\nEpoch 33/99\n----------\ntrain Loss: 1.0991 Acc: 0.3642\nval Loss: 1.1020 Acc: 0.2897\nEpoch 34/99\n----------\ntrain Loss: 1.0990 Acc: 0.3672\nval Loss: 1.1023 Acc: 0.2897\nEpoch 35/99\n----------\ntrain Loss: 1.0990 Acc: 0.3656\nval Loss: 1.1017 Acc: 0.2897\nEpoch 36/99\n----------\ntrain Loss: 1.0988 Acc: 0.3678\nval Loss: 1.1021 Acc: 0.2897\nEpoch 37/99\n----------\ntrain Loss: 1.0989 Acc: 0.3699\nval Loss: 1.1019 Acc: 0.2897\nEpoch 38/99\n----------\ntrain Loss: 1.0988 Acc: 0.3694\nval Loss: 1.1011 Acc: 0.2897\nEpoch 39/99\n----------\ntrain Loss: 1.0988 Acc: 0.3650\nval Loss: 1.1011 Acc: 0.2897\nEpoch 40/99\n----------\ntrain Loss: 1.0987 Acc: 0.3694\nval Loss: 1.1010 Acc: 0.2897\nEpoch 41/99\n----------\ntrain Loss: 1.0987 Acc: 0.3686\nval Loss: 1.1004 Acc: 0.2897\nEpoch 42/99\n----------\ntrain Loss: 1.0986 Acc: 0.3710\nval Loss: 1.1002 Acc: 0.2897\nEpoch 43/99\n----------\ntrain Loss: 1.0984 Acc: 0.3691\nval Loss: 1.0999 Acc: 0.2897\nEpoch 44/99\n----------\ntrain Loss: 1.0984 Acc: 0.3691\nval Loss: 1.1003 Acc: 0.2897\nEpoch 45/99\n----------\ntrain Loss: 1.0984 Acc: 0.3707\nval Loss: 1.1000 Acc: 0.2897\nEpoch 46/99\n----------\ntrain Loss: 1.0984 Acc: 0.3713\nval Loss: 1.1013 Acc: 0.2897\nEpoch 47/99\n----------\ntrain Loss: 1.0984 Acc: 0.3705\nval Loss: 1.0996 Acc: 0.2897\nEpoch 48/99\n----------\ntrain Loss: 1.0981 Acc: 0.3729\nval Loss: 1.1009 Acc: 0.2897\nEpoch 49/99\n----------\ntrain Loss: 1.0983 Acc: 0.3721\nval Loss: 1.1003 Acc: 0.2897\nEpoch 50/99\n----------\ntrain Loss: 1.0983 Acc: 0.3705\nval Loss: 1.0996 Acc: 0.2897\nEpoch 51/99\n----------\ntrain Loss: 1.0982 Acc: 0.3680\nval Loss: 1.1002 Acc: 0.2897\nEpoch 52/99\n----------\ntrain Loss: 1.0981 Acc: 0.3726\nval Loss: 1.0998 Acc: 0.2897\nEpoch 53/99\n----------\ntrain Loss: 1.0982 Acc: 0.3726\nval Loss: 1.0999 Acc: 0.2897\nEpoch 54/99\n----------\ntrain Loss: 1.0982 Acc: 0.3732\nval Loss: 1.1000 Acc: 0.2897\nEpoch 55/99\n----------\ntrain Loss: 1.0981 Acc: 0.3694\nval Loss: 1.0990 Acc: 0.2897\nEpoch 56/99\n----------\ntrain Loss: 1.0981 Acc: 0.3732\nval Loss: 1.1001 Acc: 0.2897\nEpoch 57/99\n----------\ntrain Loss: 1.0982 Acc: 0.3699\nval Loss: 1.0996 Acc: 0.2897\nEpoch 58/99\n----------\ntrain Loss: 1.0980 Acc: 0.3715\nval Loss: 1.0998 Acc: 0.2897\nEpoch 59/99\n----------\ntrain Loss: 1.0980 Acc: 0.3656\nval Loss: 1.0995 Acc: 0.2897\nEpoch 60/99\n----------\ntrain Loss: 1.0980 Acc: 0.3718\nval Loss: 1.0996 Acc: 0.2897\nEpoch 61/99\n----------\ntrain Loss: 1.0981 Acc: 0.3724\nval Loss: 1.0998 Acc: 0.2897\nEpoch 62/99\n----------\ntrain Loss: 1.0980 Acc: 0.3737\nval Loss: 1.0999 Acc: 0.2897\nEpoch 63/99\n----------\ntrain Loss: 1.0981 Acc: 0.3718\nval Loss: 1.0994 Acc: 0.2897\nEpoch 64/99\n----------\ntrain Loss: 1.0980 Acc: 0.3759\nval Loss: 1.0997 Acc: 0.2897\nEpoch 65/99\n----------\ntrain Loss: 1.0980 Acc: 0.3710\nval Loss: 1.0991 Acc: 0.2897\nEpoch 66/99\n----------\ntrain Loss: 1.0979 Acc: 0.3737\nval Loss: 1.1002 Acc: 0.2897\nEpoch 67/99\n----------\ntrain Loss: 1.0980 Acc: 0.3702\nval Loss: 1.0991 Acc: 0.2897\nEpoch 68/99\n----------\ntrain Loss: 1.0980 Acc: 0.3729\nval Loss: 1.0998 Acc: 0.2897\nEpoch 69/99\n----------\ntrain Loss: 1.0980 Acc: 0.3707\nval Loss: 1.0994 Acc: 0.2897\nEpoch 70/99\n----------\ntrain Loss: 1.0979 Acc: 0.3737\nval Loss: 1.0994 Acc: 0.2897\nEpoch 71/99\n----------\ntrain Loss: 1.0980 Acc: 0.3710\nval Loss: 1.0996 Acc: 0.2897\nEpoch 72/99\n----------\ntrain Loss: 1.0980 Acc: 0.3748\nval Loss: 1.0997 Acc: 0.2897\nEpoch 73/99\n----------\ntrain Loss: 1.0979 Acc: 0.3737\nval Loss: 1.0996 Acc: 0.2897\nEpoch 74/99\n----------\ntrain Loss: 1.0979 Acc: 0.3710\nval Loss: 1.0990 Acc: 0.2897\nEpoch 75/99\n----------\ntrain Loss: 1.0978 Acc: 0.3710\nval Loss: 1.0996 Acc: 0.2897\nEpoch 76/99\n----------\ntrain Loss: 1.0978 Acc: 0.3756\nval Loss: 1.0997 Acc: 0.2897\nEpoch 77/99\n----------\ntrain Loss: 1.0979 Acc: 0.3737\nval Loss: 1.0995 Acc: 0.2897\nEpoch 78/99\n----------\ntrain Loss: 1.0979 Acc: 0.3699\nval Loss: 1.0987 Acc: 0.2897\nEpoch 79/99\n----------\ntrain Loss: 1.0978 Acc: 0.3715\nval Loss: 1.1002 Acc: 0.2897\nEpoch 80/99\n----------\ntrain Loss: 1.0978 Acc: 0.3705\nval Loss: 1.0994 Acc: 0.2897\nEpoch 81/99\n----------\ntrain Loss: 1.0980 Acc: 0.3718\nval Loss: 1.0995 Acc: 0.2897\nEpoch 82/99\n----------\ntrain Loss: 1.0978 Acc: 0.3710\nval Loss: 1.0996 Acc: 0.2897\nEpoch 83/99\n----------\ntrain Loss: 1.0977 Acc: 0.3743\nval Loss: 1.0995 Acc: 0.2897\nEpoch 84/99\n----------\ntrain Loss: 1.0977 Acc: 0.3751\nval Loss: 1.0998 Acc: 0.2897\nEpoch 85/99\n----------\ntrain Loss: 1.0977 Acc: 0.3721\nval Loss: 1.0997 Acc: 0.2897\nEpoch 86/99\n----------\ntrain Loss: 1.0978 Acc: 0.3694\nval Loss: 1.0987 Acc: 0.2897\nEpoch 87/99\n----------\ntrain Loss: 1.0977 Acc: 0.3696\nval Loss: 1.1006 Acc: 0.2897\nEpoch 88/99\n----------\ntrain Loss: 1.0978 Acc: 0.3683\nval Loss: 1.0992 Acc: 0.2897\nEpoch 89/99\n----------\ntrain Loss: 1.0978 Acc: 0.3724\nval Loss: 1.0999 Acc: 0.2897\nEpoch 90/99\n----------\ntrain Loss: 1.0977 Acc: 0.3713\nval Loss: 1.0994 Acc: 0.2897\nEpoch 91/99\n----------\ntrain Loss: 1.0977 Acc: 0.3699\nval Loss: 1.0986 Acc: 0.2897\nEpoch 92/99\n----------\ntrain Loss: 1.0977 Acc: 0.3710\nval Loss: 1.1002 Acc: 0.2897\nEpoch 93/99\n----------\ntrain Loss: 1.0977 Acc: 0.3675\nval Loss: 1.0989 Acc: 0.2897\nEpoch 94/99\n----------\ntrain Loss: 1.0978 Acc: 0.3715\nval Loss: 1.0996 Acc: 0.2897\nEpoch 95/99\n----------\ntrain Loss: 1.0976 Acc: 0.3686\nval Loss: 1.0993 Acc: 0.2897\nEpoch 96/99\n----------\ntrain Loss: 1.0977 Acc: 0.3705\nval Loss: 1.0991 Acc: 0.2897\nEpoch 97/99\n----------\ntrain Loss: 1.0976 Acc: 0.3748\nval Loss: 1.0996 Acc: 0.2897\nEpoch 98/99\n----------\ntrain Loss: 1.0977 Acc: 0.3724\nval Loss: 1.0994 Acc: 0.2897\nEpoch 99/99\n----------\ntrain Loss: 1.0976 Acc: 0.3732\nval Loss: 1.0993 Acc: 0.2897\n" ], [ "def test_model(model,val_loader,device):\n # Turn autograd off\n with torch.no_grad():\n\n # Set the model to evaluation mode\n model.eval()\n\n # Set up lists to store true and predicted values\n y_true = []\n test_preds = []\n\n # Calculate the predictions on the test set and add to list\n for data in val_loader:\n \n inputs, labels = data[0].to(device), data[1].to(device)\n # Feed inputs through model to get raw scores\n logits = model.forward(inputs)\n\n #print(f'Logits: {logits}')\n\n # Convert raw scores to probabilities (not necessary since we just care about discrete probs in this case)\n probs = F.softmax(logits, dim=0)\n # print(f'Probs after LogSoft: {probs}')\n\n # Get discrete predictions using argmax\n preds = np.argmax(probs.cpu().numpy(),axis=1)\n # Add predictions and actuals to lists\n test_preds.extend(preds)\n y_true.extend(labels)\n\n # Calculate the accuracy\n test_preds = np.array(test_preds)\n y_true = np.array(y_true)\n test_acc = np.sum(test_preds == y_true)/y_true.shape[0]\n \n # Recall for each class\n recall_vals = []\n for i in range(2):\n class_idx = np.argwhere(y_true==i)\n total = len(class_idx)\n correct = np.sum(test_preds[class_idx]==i)\n recall = correct / total\n recall_vals.append(recall)\n\n \n return test_acc, recall_vals", "_____no_output_____" ], [ "# Calculate the test set accuracy and recall for each class\nacc,recall_vals = test_model(net,test_loader,device)\nprint('Test set accuracy is {:.3f}'.format(acc))\nfor i in range(2):\n print('For class {}, recall is {}'.format(classes[i],recall_vals[i]))", "Test set accuracy is 0.288\nFor class 0, recall is 1.0\nFor class 1, recall is 0.0\n" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "import time\n\ndef train(model, optimizer, loss_fn, train_dl, val_dl, epochs=100, device='cpu'):\n\n print('train() called: model=%s, opt=%s(lr=%f), epochs=%d, device=%s\\n' % \\\n (type(model).__name__, type(optimizer).__name__,\n optimizer.param_groups[0]['lr'], epochs, device))\n\n history = {} # Collects per-epoch loss and acc like Keras' fit().\n history['loss'] = []\n history['val_loss'] = []\n history['acc'] = []\n history['val_acc'] = []\n\n start_time_sec = time.time()\n\n for epoch in range(1, epochs+1):\n\n # --- TRAIN AND EVALUATE ON TRAINING SET -----------------------------\n model.train()\n train_loss = 0.0\n num_train_correct = 0\n num_train_examples = 0\n\n for batch in train_dl:\n\n optimizer.zero_grad()\n\n x = batch[0].to(device)\n y = batch[1].to(device)\n yhat = model(x)\n loss = loss_fn(yhat, y)\n\n loss.backward()\n optimizer.step()\n\n train_loss += loss.data.item() * x.size(0)\n num_train_correct += (torch.max(yhat, 1)[1] == y).sum().item()\n num_train_examples += x.shape[0]\n\n train_acc = num_train_correct / num_train_examples\n train_loss = train_loss / len(train_dl.dataset)\n\n\n # --- EVALUATE ON VALIDATION SET -------------------------------------\n model.eval()\n val_loss = 0.0\n num_val_correct = 0\n num_val_examples = 0\n\n for batch in val_dl:\n\n x = batch[0].to(device)\n y = batch[1].to(device)\n yhat = model(x)\n loss = loss_fn(yhat, y)\n\n val_loss += loss.data.item() * x.size(0)\n num_val_correct += (torch.max(yhat, 1)[1] == y).sum().item()\n num_val_examples += y.shape[0]\n\n val_acc = num_val_correct / num_val_examples\n val_loss = val_loss / len(val_dl.dataset)\n\n\n if epoch == 1 or epoch % 10 == 0:\n print('Epoch %3d/%3d, train loss: %5.2f, train acc: %5.2f, val loss: %5.2f, val acc: %5.2f' % \\\n (epoch, epochs, train_loss, train_acc, val_loss, val_acc))\n\n history['loss'].append(train_loss)\n history['val_loss'].append(val_loss)\n history['acc'].append(train_acc)\n history['val_acc'].append(val_acc)\n\n # END OF TRAINING LOOP\n\n\n end_time_sec = time.time()\n total_time_sec = end_time_sec - start_time_sec\n time_per_epoch_sec = total_time_sec / epochs\n print()\n print('Time total: %5.2f sec' % (total_time_sec))\n print('Time per epoch: %5.2f sec' % (time_per_epoch_sec))\n\n return history", "_____no_output_____" ], [ "y_flat_num = y_train[np.where(y_train == 2)].size\ny_down_weight = round((y_flat_num / y_train[np.where(y_train == 0)].size) * 1.2, 3) \ny_up_weight = round((y_flat_num / y_train[np.where(y_train == 1)].size) * 1.5, 3)\n\nprint(y_down_weight, y_up_weight, 1)", "0.0 0.0 1\n" ], [ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = net.to(device)\n\ncriterion = nn.CrossEntropyLoss() \n# weights = torch.tensor([y_down_weight, y_up_weight, 1.]).to(device)\n# criterion_weighted = nn.CrossEntropyLoss(weight=weights)\n\noptimizer = torch.optim.Adam(net.parameters(), lr = 0.001, weight_decay=0.00001)\nepochs = 20\n\nhistory = train(\n model = model,\n optimizer = optimizer,\n loss_fn = criterion,\n train_dl = train_loader,\n val_dl = test_loader,\n epochs=epochs,\n device=device)", "train() called: model=StockShiftClassification, opt=Adam(lr=0.001000), epochs=20, device=cuda\n\nEpoch 1/ 20, train loss: 1.02, train acc: 0.68, val loss: 0.64, val acc: 0.66\nEpoch 10/ 20, train loss: 0.61, train acc: 0.71, val loss: 0.65, val acc: 0.66\nEpoch 20/ 20, train loss: 0.61, train acc: 0.71, val loss: 0.64, val acc: 0.66\n\nTime total: 26.97 sec\nTime per epoch: 1.35 sec\n" ], [ "import matplotlib.pyplot as plt\n\nacc = history['acc']\nval_acc = history['val_acc']\nloss = history['loss']\nval_loss = history['val_loss']\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'b', label='Training acc')\nplt.plot(epochs, val_acc, 'r', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.legend()\nplt.figure()\nplt.plot(epochs, loss, 'b', label='Training loss')\nplt.plot(epochs, val_loss, 'r', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()", "_____no_output_____" ], [ "def test_model(model,val_loader,device):\n # Turn autograd off\n with torch.no_grad():\n\n # Set the model to evaluation mode\n model = model.to(device)\n model.eval()\n\n # Set up lists to store true and predicted values\n y_true = []\n test_preds = []\n\n # Calculate the predictions on the test set and add to list\n for data in val_loader:\n \n inputs, labels = data[0].to(device), data[1].to(device)\n # Feed inputs through model to get raw scores\n logits = model.forward(inputs)\n\n #print(f'Logits: {logits}')\n\n # Convert raw scores to probabilities (not necessary since we just care about discrete probs in this case)\n probs = F.softmax(logits)\n # print(f'Probs after LogSoft: {probs}')\n\n # Get discrete predictions using argmax\n preds = np.argmax(probs.cpu().numpy(),axis=1)\n # Add predictions and actuals to lists\n test_preds.extend(preds)\n y_true.extend(labels)\n\n # Calculate the accuracy\n test_preds = np.array(test_preds)\n y_true = np.array(y_true)\n test_acc = np.sum(test_preds == y_true)/y_true.shape[0]\n \n # Recall for each class\n recall_vals = []\n for i in range(2):\n class_idx = np.argwhere(y_true==i)\n total = len(class_idx)\n correct = np.sum(test_preds[class_idx]==i)\n recall = correct / total\n recall_vals.append(recall)\n\n \n return test_acc, recall_vals\n ", "_____no_output_____" ], [ "# Calculate the test set accuracy and recall for each class\nacc,recall_vals = test_model(model,test_loader,device)\nprint('Test set accuracy is {:.3f}'.format(acc))\nfor i in range(2):\n print('For class {}, recall is {}'.format(classes[i],recall_vals[i]))", "Test set accuracy is 0.662\nFor class 1, recall is 1.0\nFor class 0, recall is 0.0\n" ], [ "from sklearn.metrics import confusion_matrix\n\ndef plot_confusion_matrix(cm,\n target_names,\n title='Confusion matrix',\n cmap=None,\n normalize=True):\n \"\"\"\n given a sklearn confusion matrix (cm), make a nice plot\n\n Arguments\n ---------\n cm: confusion matrix from sklearn.metrics.confusion_matrix\n\n target_names: given classification classes such as [0, 1, 2]\n the class names, for example: ['high', 'medium', 'low']\n\n title: the text to display at the top of the matrix\n\n cmap: the gradient of the values displayed from matplotlib.pyplot.cm\n see http://matplotlib.org/examples/color/colormaps_reference.html\n plt.get_cmap('jet') or plt.cm.Blues\n\n normalize: If False, plot the raw numbers\n If True, plot the proportions\n\n Usage\n -----\n plot_confusion_matrix(cm = cm, # confusion matrix created by\n # sklearn.metrics.confusion_matrix\n normalize = True, # show proportions\n target_names = y_labels_vals, # list of names of the classes\n title = best_estimator_name) # title of graph\n\n Citiation\n ---------\n http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html\n\n \"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n import itertools\n\n accuracy = np.trace(cm) / np.sum(cm).astype('float')\n misclass = 1 - accuracy\n\n if cmap is None:\n cmap = plt.get_cmap('Blues')\n\n plt.figure(figsize=(8, 6))\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n\n if target_names is not None:\n tick_marks = np.arange(len(target_names))\n plt.xticks(tick_marks, target_names, rotation=45)\n plt.yticks(tick_marks, target_names)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n\n thresh = cm.max() / 1.5 if normalize else cm.max() / 2\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n if normalize:\n plt.text(j, i, \"{:0.4f}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n else:\n plt.text(j, i, \"{:,}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\n plt.show()\n\nnb_classes = 2\n\n# Initialize the prediction and label lists(tensors)\npredlist=torch.zeros(0,dtype=torch.long, device='cpu')\nlbllist=torch.zeros(0,dtype=torch.long, device='cpu')\n\nwith torch.no_grad():\n for i, (inputs, classes) in enumerate(dataloaders['val']):\n # print(inputs)\n inputs = inputs.to(device)\n classes = classes.to(device)\n outputs = model.forward(inputs)\n #print(outputs)\n _, preds = torch.max(outputs, 1)\n\n # Append batch prediction results\n predlist=torch.cat([predlist,preds.view(-1).cpu()])\n lbllist=torch.cat([lbllist,classes.view(-1).cpu()])\n\n# Confusion matrix\nconf_mat=confusion_matrix(lbllist.numpy(), predlist.numpy())\nplot_confusion_matrix(conf_mat, [0,1])\n\nfrom sklearn.metrics import precision_score\n\nprecision_score(lbllist.numpy(), predlist.numpy(), average='weighted')\n\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(lbllist.numpy(), predlist.numpy(), target_names=[\"down\",\"up\"], digits=4))", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "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", "code", "code" ] ]
d0308092b57c8eab5977662a5576da207237e5cf
7,062
ipynb
Jupyter Notebook
notebooks/spark-on-eks-cluster-mode.ipynb
aws-samples/eks-kubeflow-spot-sample
01cfb46831c040daf714a3e40ee3046fb585e7fb
[ "MIT-0" ]
12
2020-06-26T18:11:03.000Z
2022-03-21T17:58:49.000Z
notebooks/spark-on-eks-cluster-mode.ipynb
aws-samples/eks-kubeflow-spot-sample
01cfb46831c040daf714a3e40ee3046fb585e7fb
[ "MIT-0" ]
null
null
null
notebooks/spark-on-eks-cluster-mode.ipynb
aws-samples/eks-kubeflow-spot-sample
01cfb46831c040daf714a3e40ee3046fb585e7fb
[ "MIT-0" ]
10
2020-06-25T15:37:33.000Z
2021-11-03T00:40:32.000Z
27.913043
232
0.588077
[ [ [ "# Spark on Kubernetes", "_____no_output_____" ], [ "Preparing the notebook https://towardsdatascience.com/make-kubeflow-into-your-own-data-science-workspace-cc8162969e29", "_____no_output_____" ], [ "## Setup service account permissions", "_____no_output_____" ], [ "https://github.com/kubeflow/kubeflow/issues/4306 issue with launching spark-operator from jupyter notebook", "_____no_output_____" ], [ "Run command in your shell (not in notebook)\n\n```shell\nexport NAMESPACE=<your_namespace>\nkubectl create serviceaccount spark -n ${NAMESPACE}\nkubectl create clusterrolebinding spark-role --clusterrole=edit --serviceaccount=${NAMESPACE}:spark --namespace=${NAMESPACE}\n```", "_____no_output_____" ], [ "## Python version\n\n> Note: Make sure your driver python and executor python version matches.\n> Otherwise, you will see error msg like below\n\nException: Python in worker has different version 3.7 than that in driver 3.6, PySpark cannot run with different minor versions.Please check environment variables `PYSPARK_PYTHON` and `PYSPARK_DRIVER_PYTHON` are correctly set.", "_____no_output_____" ] ], [ [ "import sys\nprint(sys.version)", "_____no_output_____" ] ], [ [ "## Client Mode", "_____no_output_____" ] ], [ [ "import findspark, pyspark,socket\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SparkSession\n\nfindspark.init()\n\nlocalIpAddress = socket.gethostbyname(socket.gethostname())\n\nconf = SparkConf().setAppName('sparktest1')\nconf.setMaster('k8s://https://kubernetes.default.svc:443')\nconf.set(\"spark.submit.deployMode\", \"client\")\nconf.set(\"spark.executor.instances\", \"2\")\nconf.set(\"spark.driver.host\", localIpAddress)\nconf.set(\"spark.driver.port\", \"7778\")\nconf.set(\"spark.kubernetes.namespace\", \"yahavb\")\nconf.set(\"spark.kubernetes.container.image\", \"seedjeffwan/spark-py:v2.4.6\")\nconf.set(\"spark.kubernetes.pyspark.pythonVersion\", \"3\")\nconf.set(\"spark.kubernetes.authenticate.driver.serviceAccountName\", \"spark\")\nconf.set(\"spark.kubernetes.executor.annotation.sidecar.istio.io/inject\", \"false\")", "_____no_output_____" ], [ "sc = pyspark.context.SparkContext.getOrCreate(conf=conf)\n\n# following works as well\n# spark = SparkSession.builder.config(conf=conf).getOrCreate()", "_____no_output_____" ], [ "num_samples = 100000\n\ndef inside(p): \n x, y = random.random(), random.random()\n return x*x + y*y < 1\n\ncount = sc.parallelize(range(0, num_samples)).filter(inside).count()", "_____no_output_____" ], [ "sc.stop()", "_____no_output_____" ] ], [ [ "## Cluster Mode", "_____no_output_____" ], [ "## Java", "_____no_output_____" ] ], [ [ "%%bash\n\n/opt/spark-2.4.6/bin/spark-submit --master \"k8s://https://kubernetes.default.svc:443\" \\\n--deploy-mode cluster \\\n--name spark-java-pi \\\n--class org.apache.spark.examples.SparkPi \\\n--conf spark.executor.instances=30 \\\n--conf spark.kubernetes.namespace=yahavb \\\n--conf spark.kubernetes.driver.annotation.sidecar.istio.io/inject=false \\\n--conf spark.kubernetes.executor.annotation.sidecar.istio.io/inject=false \\\n--conf spark.kubernetes.container.image=seedjeffwan/spark:v2.4.6 \\\n--conf spark.kubernetes.driver.pod.name=spark-java-pi-driver \\\n--conf spark.kubernetes.executor.request.cores=4 \\\n--conf spark.kubernetes.node.selector.computetype=gpu \\\n--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark \\\nlocal:///opt/spark/examples/jars/spark-examples_2.11-2.4.6.jar 262144", "_____no_output_____" ], [ "%%bash\nkubectl -n yahavb delete po ` kubectl -n yahavb get po | grep spark-java-pi-driver | awk '{print $1}'`", "_____no_output_____" ] ], [ [ "## Python", "_____no_output_____" ] ], [ [ "%%bash\n\n/opt/spark-2.4.6/bin/spark-submit --master \"k8s://https://kubernetes.default.svc:443\" \\\n--deploy-mode cluster \\\n--name spark-python-pi \\\n--conf spark.executor.instances=50 \\\n--conf spark.kubernetes.container.image=seedjeffwan/spark-py:v2.4.6 \\\n--conf spark.kubernetes.driver.pod.name=spark-python-pi-driver \\\n--conf spark.kubernetes.namespace=yahavb \\\n--conf spark.kubernetes.driver.annotation.sidecar.istio.io/inject=false \\\n--conf spark.kubernetes.executor.annotation.sidecar.istio.io/inject=false \\\n--conf spark.kubernetes.pyspark.pythonVersion=3 \\\n--conf spark.kubernetes.executor.request.cores=4 \\\n--conf spark.kubernetes.authenticate.driver.serviceAccountName=spark /opt/spark/examples/src/main/python/pi.py 64000", "_____no_output_____" ], [ "%%bash\nkubectl -n yahavb delete po `kubectl -n yahavb get po | grep spark-python-pi-driver | awk '{print $1}'`", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d03083c321d4388103623bfcb846bf203b1c237e
2,872
ipynb
Jupyter Notebook
trainer/trainer.ipynb
darknight202/EasyOCR
6cbec2d34cf75c43f42891664cca7da0585947b9
[ "Apache-2.0" ]
2
2021-08-21T06:14:27.000Z
2021-08-21T18:54:20.000Z
trainer/trainer.ipynb
darknight202/EasyOCR
6cbec2d34cf75c43f42891664cca7da0585947b9
[ "Apache-2.0" ]
1
2021-09-17T04:51:47.000Z
2021-09-23T04:46:43.000Z
trainer/trainer.ipynb
darknight202/EasyOCR
6cbec2d34cf75c43f42891664cca7da0585947b9
[ "Apache-2.0" ]
1
2022-01-18T16:07:20.000Z
2022-01-18T16:07:20.000Z
24.758621
135
0.529944
[ [ [ "import os\nimport torch.backends.cudnn as cudnn\nimport yaml\nfrom train import train\nfrom utils import AttrDict\nimport pandas as pd", "_____no_output_____" ], [ "cudnn.benchmark = True\ncudnn.deterministic = False", "_____no_output_____" ], [ "def get_config(file_path):\n with open(file_path, 'r') as stream:\n opt = yaml.safe_load(stream)\n opt = AttrDict(opt)\n if opt.lang_char == 'None':\n characters = ''\n for data in opt['select_data'].split('-'):\n csv_path = os.path.join(opt['train_data'], data, 'labels.csv')\n df = pd.read_csv(csv_path, sep='^([^,]+),', engine='python', usecols=['filename', 'words'], keep_default_na=False)\n all_char = ''.join(df['words'])\n characters += ''.join(set(all_char))\n characters = sorted(set(characters))\n opt.character= ''.join(characters)\n else:\n opt.character = opt.number + opt.symbol + opt.lang_char\n os.makedirs(f'./saved_models/{opt.experiment_name}', exist_ok=True)\n return opt", "_____no_output_____" ], [ "opt = get_config(\"config_files/en_filtered_config.yaml\")\ntrain(opt, amp=False)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
d030850d9842fcd2b8acaf3424885d944dbf42c2
37,819
ipynb
Jupyter Notebook
run.ipynb
burhanusman/RL-Maze
aab7e533ac5e40acaa1e422e5c1ef050dea0c516
[ "MIT" ]
1
2020-07-07T10:39:12.000Z
2020-07-07T10:39:12.000Z
run.ipynb
burhanusman/RL-Maze
aab7e533ac5e40acaa1e422e5c1ef050dea0c516
[ "MIT" ]
null
null
null
run.ipynb
burhanusman/RL-Maze
aab7e533ac5e40acaa1e422e5c1ef050dea0c516
[ "MIT" ]
null
null
null
72.173664
3,132
0.800788
[ [ [ "from Maze import Maze\nfrom sarsa_agent import SarsaAgent\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom IPython.display import HTML", "_____no_output_____" ] ], [ [ "## Designing the maze", "_____no_output_____" ] ], [ [ "arr=np.array([[0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],\n [0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n [0,1,0,0,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,0],\n [0,1,0,0,1,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0],\n [0,0,0,0,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,0],\n [0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1,1,0,1,1],\n [1,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,1,0,0,0],\n [0,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1,0,1,0],\n [0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0],\n [0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,1,0,0,0,0],\n [1,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,0,1,0,0],\n [1,0,1,1,1,0,1,0,0,1,0,0,1,1,0,0,0,1,0,0],\n [1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0],\n [0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,1,1,0],\n [0,0,1,1,1,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0],\n [0,1,1,0,0,0,0,1,0,1,0,0,1,1,0,1,0,1,1,1],\n [0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0],\n [0,0,1,1,1,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0],\n [1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,1,1,1,0,0],\n [1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,1,0,0]\n ],dtype=float)\n\n#Position of the rat\nrat=(0,0)\n#If Cheese is None, cheese is placed in the bottom-right cell of the maze\ncheese=None\n#The maze object takes the maze \nmaze=Maze(arr,rat,cheese)\nmaze.show_maze()", "_____no_output_____" ] ], [ [ "## Defining a Agent [Sarsa Agent because it uses Sarsa to solve the maze]", "_____no_output_____" ] ], [ [ "agent=SarsaAgent(maze)", "_____no_output_____" ] ], [ [ "## Making the agent play episodes and learn", "_____no_output_____" ] ], [ [ "agent.learn(episodes=1000)", "_____no_output_____" ] ], [ [ "## Plotting the maze", "_____no_output_____" ] ], [ [ "nrow=maze.nrow\nncol=maze.ncol\nfig=plt.figure()\nax=fig.gca()\nax.set_xticks(np.arange(0.5,ncol,1))\nax.set_yticks(np.arange(0.5,nrow,1))\nax.set_xticklabels([])\nax.set_yticklabels([])\nax.grid('on')\nimg=ax.imshow(maze.maze,cmap=\"gray\",)\na=5", "_____no_output_____" ] ], [ [ "## Making Animation of the maze solution", "_____no_output_____" ] ], [ [ "def gen_func():\n maze=Maze(arr,rat,cheese)\n \n done=False\n while not done:\n row,col,_=maze.state\n cell=(row,col)\n action=agent.get_policy(cell)\n maze.step(action)\n done=maze.get_status()\n yield maze.get_canvas()\ndef update_plot(canvas):\n img.set_data(canvas)\nanim=animation.FuncAnimation(fig,update_plot,gen_func)\nHTML(anim.to_html5_video())", "_____no_output_____" ], [ "anim.save(\"big_maze.gif\",animation.PillowWriter())", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d03087944f0b06ddbb727cf1c87a03ffd1683bdc
20,246
ipynb
Jupyter Notebook
tutorials/vae_mnist.ipynb
Igevorse/botorch
1b547f9931defde41a6e3f68584d150636610241
[ "MIT" ]
null
null
null
tutorials/vae_mnist.ipynb
Igevorse/botorch
1b547f9931defde41a6e3f68584d150636610241
[ "MIT" ]
null
null
null
tutorials/vae_mnist.ipynb
Igevorse/botorch
1b547f9931defde41a6e3f68584d150636610241
[ "MIT" ]
1
2019-05-07T23:53:08.000Z
2019-05-07T23:53:08.000Z
47.193473
5,724
0.684333
[ [ [ "## VAE MNIST example: BO in a latent space", "_____no_output_____" ], [ "In this tutorial, we use the MNIST dataset and some standard PyTorch examples to show a synthetic problem where the input to the objective function is a `28 x 28` image. The main idea is to train a [variational auto-encoder (VAE)](https://arxiv.org/abs/1312.6114) on the MNIST dataset and run Bayesian Optimization in the latent space. We also refer readers to [this tutorial](http://krasserm.github.io/2018/04/07/latent-space-optimization/), which discusses [the method](https://arxiv.org/abs/1610.02415) of jointly training a VAE with a predictor (e.g., classifier), and shows a similar tutorial for the MNIST setting.", "_____no_output_____" ] ], [ [ "import os\nimport torch\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets # transforms\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\ndtype = torch.float", "_____no_output_____" ] ], [ [ "### Problem setup\n\nLet's first define our synthetic expensive-to-evaluate objective function. We assume that it takes the following form:\n\n$$\\text{image} \\longrightarrow \\text{image classifier} \\longrightarrow \\text{scoring function} \n\\longrightarrow \\text{score}.$$\n\nThe classifier is a convolutional neural network (CNN) trained using the architecture of the [PyTorch CNN example](https://github.com/pytorch/examples/tree/master/mnist).", "_____no_output_____" ] ], [ [ "class Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, 5, 1)\n self.conv2 = nn.Conv2d(20, 50, 5, 1)\n self.fc1 = nn.Linear(4 * 4 * 50, 500)\n self.fc2 = nn.Linear(500, 10)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.max_pool2d(x, 2, 2)\n x = F.relu(self.conv2(x))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 4*4*50)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)", "_____no_output_____" ] ], [ [ "We next instantiate the CNN for digit recognition and load a pre-trained model.\n\nHere, you may have to change `PRETRAINED_LOCATION` to the location of the `pretrained_models` folder on your machine.", "_____no_output_____" ] ], [ [ "PRETRAINED_LOCATION = \"./pretrained_models\"\n\ncnn_model = Net().to(device)\ncnn_state_dict = torch.load(os.path.join(PRETRAINED_LOCATION, \"mnist_cnn.pt\"), map_location=device)\ncnn_model.load_state_dict(cnn_state_dict);", "_____no_output_____" ] ], [ [ "Our VAE model follows the [PyTorch VAE example](https://github.com/pytorch/examples/tree/master/vae), except that we use the same data transform from the CNN tutorial for consistency. We then instantiate the model and again load a pre-trained model. To train these models, we refer readers to the PyTorch Github repository. ", "_____no_output_____" ] ], [ [ "class VAE(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 400)\n self.fc21 = nn.Linear(400, 20)\n self.fc22 = nn.Linear(400, 20)\n self.fc3 = nn.Linear(20, 400)\n self.fc4 = nn.Linear(400, 784)\n\n def encode(self, x):\n h1 = F.relu(self.fc1(x))\n return self.fc21(h1), self.fc22(h1)\n\n def reparameterize(self, mu, logvar):\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n return mu + eps*std\n\n def decode(self, z):\n h3 = F.relu(self.fc3(z))\n return torch.sigmoid(self.fc4(h3))\n\n def forward(self, x):\n mu, logvar = self.encode(x.view(-1, 784))\n z = self.reparameterize(mu, logvar)\n return self.decode(z), mu, logvar\n\nvae_model = VAE().to(device)\nvae_state_dict = torch.load(os.path.join(PRETRAINED_LOCATION, \"mnist_vae.pt\"), map_location=device)\nvae_model.load_state_dict(vae_state_dict);", "_____no_output_____" ] ], [ [ "We now define the scoring function that maps digits to scores. The function below prefers the digit '3'.", "_____no_output_____" ] ], [ [ "def score(y):\n \"\"\"Returns a 'score' for each digit from 0 to 9. It is modeled as a squared exponential\n centered at the digit '3'.\n \"\"\"\n return torch.exp(-2 * (y - 3)**2)", "_____no_output_____" ] ], [ [ "Given the scoring function, we can now write our overall objective, which as discussed above, starts with an image and outputs a score. Let's say the objective computes the expected score given the probabilities from the classifier.", "_____no_output_____" ] ], [ [ "def score_image_recognition(x):\n \"\"\"The input x is an image and an expected score based on the CNN classifier and\n the scoring function is returned.\n \"\"\"\n with torch.no_grad():\n probs = torch.exp(cnn_model(x)) # b x 10\n scores = score(torch.arange(10, device=device, dtype=dtype)).expand(probs.shape)\n return (probs * scores).sum(dim=1)", "_____no_output_____" ] ], [ [ "Finally, we define a helper function `decode` that takes as input the parameters `mu` and `logvar` of the variational distribution and performs reparameterization and the decoding. We use batched Bayesian optimization to search over the parameters `mu` and `logvar`", "_____no_output_____" ] ], [ [ "def decode(train_x):\n with torch.no_grad():\n decoded = vae_model.decode(train_x)\n return decoded.view(train_x.shape[0], 1, 28, 28)", "_____no_output_____" ] ], [ [ "#### Model initialization and initial random batch\n\nWe use a `SingleTaskGP` to model the score of an image generated by a latent representation. The model is initialized with points drawn from $[-6, 6]^{20}$.", "_____no_output_____" ] ], [ [ "from botorch.models import SingleTaskGP\nfrom gpytorch.mlls.exact_marginal_log_likelihood import ExactMarginalLogLikelihood\n\n\nbounds = torch.tensor([[-6.0] * 20, [6.0] * 20], device=device, dtype=dtype)\n\n\ndef initialize_model(n=5):\n # generate training data \n train_x = (bounds[1] - bounds[0]) * torch.rand(n, 20, device=device, dtype=dtype) + bounds[0]\n train_obj = score_image_recognition(decode(train_x))\n best_observed_value = train_obj.max().item()\n \n # define models for objective and constraint\n model = SingleTaskGP(train_X=train_x, train_Y=train_obj)\n model = model.to(train_x)\n \n mll = ExactMarginalLogLikelihood(model.likelihood, model)\n mll = mll.to(train_x)\n \n return train_x, train_obj, mll, model, best_observed_value", "_____no_output_____" ] ], [ [ "#### Define a helper function that performs the essential BO step\nThe helper function below takes an acquisition function as an argument, optimizes it, and returns the batch $\\{x_1, x_2, \\ldots x_q\\}$ along with the observed function values. For this example, we'll use a small batch of $q=3$.", "_____no_output_____" ] ], [ [ "from botorch.optim import joint_optimize\n\n\nBATCH_SIZE = 3\n\n\ndef optimize_acqf_and_get_observation(acq_func):\n \"\"\"Optimizes the acquisition function, and returns a new candidate and a noisy observation\"\"\"\n \n # optimize\n candidates = joint_optimize(\n acq_function=acq_func,\n bounds=bounds,\n q=BATCH_SIZE,\n num_restarts=10,\n raw_samples=200,\n )\n\n # observe new values \n new_x = candidates.detach()\n new_obj = score_image_recognition(decode(new_x))\n return new_x, new_obj", "_____no_output_____" ] ], [ [ "### Perform Bayesian Optimization loop with qEI\nThe Bayesian optimization \"loop\" for a batch size of $q$ simply iterates the following steps: (1) given a surrogate model, choose a batch of points $\\{x_1, x_2, \\ldots x_q\\}$, (2) observe $f(x)$ for each $x$ in the batch, and (3) update the surrogate model. We run `N_BATCH=75` iterations. The acquisition function is approximated using `MC_SAMPLES=2000` samples. We also initialize the model with 5 randomly drawn points.", "_____no_output_____" ] ], [ [ "from botorch import fit_gpytorch_model\nfrom botorch.acquisition.monte_carlo import qExpectedImprovement\nfrom botorch.acquisition.sampler import SobolQMCNormalSampler\n\nseed=1\ntorch.manual_seed(seed)\n\nN_BATCH = 50\nMC_SAMPLES = 2000\nbest_observed = []\n\n# call helper function to initialize model\ntrain_x, train_obj, mll, model, best_value = initialize_model(n=5)\nbest_observed.append(best_value)", "_____no_output_____" ] ], [ [ "We are now ready to run the BO loop (this make take a few minutes, depending on your machine).", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings(\"ignore\")\n\nprint(f\"\\nRunning BO \", end='')\nfrom matplotlib import pyplot as plt\n\n# run N_BATCH rounds of BayesOpt after the initial random batch\nfor iteration in range(N_BATCH): \n\n # fit the model\n fit_gpytorch_model(mll)\n\n # define the qNEI acquisition module using a QMC sampler\n qmc_sampler = SobolQMCNormalSampler(num_samples=MC_SAMPLES, seed=seed)\n qEI = qExpectedImprovement(model=model, sampler=qmc_sampler, best_f=best_value)\n\n # optimize and get new observation\n new_x, new_obj = optimize_acqf_and_get_observation(qEI)\n\n # update training points\n train_x = torch.cat((train_x, new_x))\n train_obj = torch.cat((train_obj, new_obj))\n\n # update progress\n best_value = score_image_recognition(decode(train_x)).max().item()\n best_observed.append(best_value)\n\n # reinitialize the model so it is ready for fitting on next iteration\n model.set_train_data(train_x, train_obj, strict=False)\n \n print(\".\", end='')", "\nRunning BO .................................................." ] ], [ [ "EI recommends the best point observed so far. We can visualize what the images corresponding to recommended points *would have* been if the BO process ended at various times. Here, we show the progress of the algorithm by examining the images at 0%, 10%, 25%, 50%, 75%, and 100% completion. The first image is the best image found through the initial random batch.", "_____no_output_____" ] ], [ [ "import numpy as np\n\nfrom matplotlib import pyplot as plt\n%matplotlib inline\n\n\nfig, ax = plt.subplots(1, 6, figsize=(14, 14))\npercentages = np.array([0, 10, 25, 50, 75, 100], dtype=np.float32)\ninds = (N_BATCH * BATCH_SIZE * percentages / 100 + 4).astype(int)\n\nfor i, ax in enumerate(ax.flat):\n b = torch.argmax(score_image_recognition(decode(train_x[:inds[i],:])), dim=0)\n img = decode(train_x[b].view(1, -1)).squeeze().cpu()\n ax.imshow(img, alpha=0.8, cmap='gray')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d030a8e433868419027e9e0f29d3320bc9d9ad6f
34,066
ipynb
Jupyter Notebook
deep_eeg.ipynb
Jose991019/PenarandaJose_Ejercicio27
ebae84f3de201b37b31571909918b304e60d6b29
[ "MIT" ]
null
null
null
deep_eeg.ipynb
Jose991019/PenarandaJose_Ejercicio27
ebae84f3de201b37b31571909918b304e60d6b29
[ "MIT" ]
null
null
null
deep_eeg.ipynb
Jose991019/PenarandaJose_Ejercicio27
ebae84f3de201b37b31571909918b304e60d6b29
[ "MIT" ]
null
null
null
172.050505
16,764
0.908325
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn.datasets\nimport sklearn.cluster\nimport sklearn.preprocessing\nimport sklearn.neural_network\nimport sklearn.linear_model\nimport sklearn.model_selection\nimport torch\nimport pandas as pd", "_____no_output_____" ], [ "datos = pd.read_csv('data.csv')", "_____no_output_____" ], [ "datos = np.array(datos,dtype = float)[:-1,1:]\nX = datos[:,:-1]\nY = datos[:,-1]\nY[Y != 1] = 0", "_____no_output_____" ], [ "X_train, X_test, Y_train, Y_test = sklearn.model_selection.train_test_split(X, Y, test_size=0.7)\nscaler = sklearn.preprocessing.StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)", "_____no_output_____" ], [ "model = torch.nn.Sequential(\n torch.nn.Conv1d(1, 15, kernel_size=15, stride=1),\n torch.nn.MaxPool1d(kernel_size=6),\n torch.nn.Conv1d(15, 1, kernel_size=2, stride=1),\n torch.nn.Linear(25, 2)\n)\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.2) #lr: learning rate\nepochs = 60\nloss_values = np.zeros(epochs)\nF1_values_train = np.zeros(epochs)\nF1_values_test = np.zeros(epochs)\n\n\nfor epoch in range(epochs):\n X_new = np.expand_dims(X_train, 1) \n inputs = torch.autograd.Variable(torch.Tensor(X_new).float())\n targets = torch.autograd.Variable(torch.Tensor(Y_train).long())\n \n optimizer.zero_grad()\n out = model(inputs)\n out = out.squeeze(dim=1) # necesario para quitar la dimension intermedia de channel\n loss = criterion(out, targets)\n loss.backward()\n optimizer.step()\n \n values, Y_predicted = torch.max(out.data, 1)\n loss_values[epoch] = loss.item()\n F1_values_train[epoch] = sklearn.metrics.f1_score(Y_train, Y_predicted, average='macro')\n \n X_new = np.expand_dims(X_test, 1)\n inputs_test = torch.autograd.Variable(torch.Tensor(X_new).float())\n out_test = model(inputs_test)\n out_test = out_test.squeeze(dim=1)\n values, Y_predicted_test = torch.max(out_test.data, 1)\n F1_values_test[epoch] = sklearn.metrics.f1_score(Y_test, Y_predicted_test, average='macro')", "_____no_output_____" ], [ "plt.plot(np.arange(epochs), loss_values)\nplt.xlabel('epoch')\nplt.ylabel('loss')", "_____no_output_____" ], [ "plt.plot(np.arange(epochs), F1_values_train, label='train')\nplt.plot(np.arange(epochs), F1_values_test, label='test')\nplt.xlabel('epoch')\nplt.ylabel('F1')\nplt.legend()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d030b3bc0df1ff29ebfb2bd317b37d243ba919f9
937,110
ipynb
Jupyter Notebook
lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb
tgrasty/CSCI574-Machine-Learning
bcf797262852c4b46a6702c69f69724b0b9e93f6
[ "CC-BY-3.0" ]
null
null
null
lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb
tgrasty/CSCI574-Machine-Learning
bcf797262852c4b46a6702c69f69724b0b9e93f6
[ "CC-BY-3.0" ]
null
null
null
lectures/ng/Lecture-09-Ensembles-Random-Forests.ipynb
tgrasty/CSCI574-Machine-Learning
bcf797262852c4b46a6702c69f69724b0b9e93f6
[ "CC-BY-3.0" ]
1
2021-09-17T17:03:58.000Z
2021-09-17T17:03:58.000Z
1,003.329764
269,824
0.954544
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib\n%matplotlib inline\n", "_____no_output_____" ], [ "matplotlib.rcParams['figure.figsize'] = (12, 8) # set default figure size, 8in by 6in", "_____no_output_____" ] ], [ [ "# Ensemble Learning\n\nSometimes aggregrates or ensembles of many different opinions on a question can perform as well or better than asking\na single expert on the same question. This is known as the *wisdom of the crowd* when the aggregrate opinion of\npeople on a question performs as well or better as a single isolated expert in predicting some outcome.\n\nLikewise, for machine learning predictors, a similar effect can also often occur. The aggregrate performance of\nmultiple predictors and often make a small but significant improvement on building a classifier or regression\npredictor for a complex set of data. A group of machine learning predictors is called an *ensemble*, and thus\nthis technique of combining the predictions of an ensemble is known as *Ensemble Learning* . \n\nFor exampl,e we could train a group of Decision Tree classifiers, each on a different random subset of the training\ndata. To make an ensemble prediciton, you just obtain the predictions of all individual trees, then predict the\nclass that gets the most votes. Such an ensemble of Decision Trees is called a *Random Forest*, and despite the\nrelative simplicity of decision tree predictors, it can be surprisingly powerful as a ML predictor.", "_____no_output_____" ], [ "# Voting Classifiers\n\nSay you have several classifiers for the same classification problem (say a Logistic Classifier, and SVM,\na Decision Tree and a KNN classifier and perhaps a few more). The simplest way to create an ensemble classifier\nis to aggregrate the predictions of each classifier and predict the class that gets the most votes. This\nmajority-vote classifier is called a *hard voting* classifier.\n\nSomewhat surprisingly, this voting classifier often achieves a higher accuracy than the best classifier in the\nensemble. In fact, even if each classifier is a *weak learner* (meaning it only does slightly better than\nrandom guessing), the ensemble can still be a *strong learner* (achieving high accuracy). The key to making\ngood ensemble predictors is that you need both a sufficient number of learners (even of weak learners), but\nalso maybe more importantly, the learners need to be \"sufficiently diverse\", where diverse is a bit fuzzy to\ndefine, but in general the classifiers must be as independent as possible, so that even if they are weak predictors,\nthey are weak in different and diverse ways.\n\n", "_____no_output_____" ] ], [ [ "def flip_unfair_coin(num_flips, head_ratio):\n \"\"\"Simulate flipping an unbalanced coin. We return a numpy array of size num_flips, with 0 to represent\n 1 to represent a head and 0 a tail flip. We generate a head or tail result using the head_ratio probability\n threshold drawn from a standard uniform distribution.\n \n \n \"\"\"\n # array of correct size to hold resulting simulated flips\n flips = np.empty(num_flips)\n \n # flip the coin the number of indicated times\n for flip in range(num_flips):\n flips[flip] = np.random.random() < head_ratio\n \n # return the resulting coin flip trials trials\n return flips\n\ndef running_heads_ratio(flips):\n \"\"\"Given a sequence of flips, where 1 represents a \"Head\" and 0 a \"Tail\" flip, return an array\n of the running ratio of heads / tails\n \"\"\"\n # array of correct size to hold resulting heads ratio seen at each point in the flips sequence\n num_flips = flips.shape[0]\n head_ratios = np.empty(num_flips)\n \n # keep track of number of heads seen so far, the ratio is num_heads / num_flips\n num_heads = 0.0\n \n # calculate ratio for each flips instance in the sequence\n for flip in range(num_flips):\n num_heads += flips[flip]\n head_ratios[flip] = num_heads / (flip + 1)\n \n # return the resulting sequence of head ratios seen in the flips\n return head_ratios", "_____no_output_____" ], [ "NUM_FLIPPERS = 10\nNUM_FLIPS = 10000\nHEAD_PERCENT = 0.51\n\n# create 3 separate sequences of flippers\nflippers = np.empty( (NUM_FLIPPERS, NUM_FLIPS) )\nfor flipper in range(NUM_FLIPPERS):\n flips = flip_unfair_coin(NUM_FLIPS, HEAD_PERCENT)\n head_ratios = running_heads_ratio(flips)\n flippers[flipper] = head_ratios\n \n# create an ensemble, in this case we will average the individual flippers\nensemble = flippers.mean(axis=0)\n\n# plot the resulting head ratio for our flippers\nflips = np.arange(1, NUM_FLIPS+1)\nfor flipper in range(NUM_FLIPPERS):\n plt.plot(flips, flippers[flipper], alpha=0.25)\nplt.plot(flips, ensemble, 'b-', alpha=1.0, label='ensemble decision')\nplt.ylim([0.42, 0.58])\nplt.plot([1, NUM_FLIPS], [HEAD_PERCENT, HEAD_PERCENT], 'k--', label='51 %')\nplt.plot([1, NUM_FLIPS], [0.5, 0.5], 'k-', label='50 %')\nplt.xlabel('Number of coin tosses')\nplt.ylabel('Heads ratio')\nplt.legend();\n", "_____no_output_____" ] ], [ [ "## Scikit-Learn Voting Classifier\n\nThe following code is an example of creating a voting classifier in Scikit-Learn. We are using the moons dataset\nshown.\n\nHere we create 3 separate classifiers by hand, a logistic regressor, a decision tree,\nand a support vector classifier (SVC). Notice we specify 'hard' voting for the voting classifier, which\nas we discussed is the simple method of choosing the class with the most votes.\n(This is a binary classification so 2 out of 3 or 3 out of 3 are the only possibilities. For a multiclass\nclassification, in case of a tie vote, the voting classifier may fall back to the probability scores the\nclassifiers give, assuming the provide probability/confidence measures of their prediction).", "_____no_output_____" ] ], [ [ "# helper functions to visualize decision boundaries for 2-feature classification tasks\n\n# create a scatter plot of the artificial multiclass dataset\nfrom matplotlib import cm\n\n# visualize the blobs using matplotlib. An example of a funciton we can reuse, since later\n# we want to plot the decision boundaries along with the scatter plot data\ndef plot_multiclass_data(X, y):\n \"\"\"Create a scatter plot of a set of multiclass data. We assume that X has 2 features so that\n we can plot on a 2D grid, and that y are integer labels [0,1,2,...] with a unique integer\n label for each class of the dataset.\n \n Parameters\n ----------\n X - A (m,2) shaped number array of m samples each with 2 features\n y - A (m,) shaped vector of integers with the labeled classes of each of the X input features\n \"\"\"\n # hardcoded to handle only up to 8 classes\n markers = ['o', '^', 's', 'd', '*', 'p', 'P', 'v']\n #colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k']\n \n # determine number of features in the data\n m = X.shape[0]\n \n # determine the class labels\n labels = np.unique(y)\n #colors = cm.rainbow(np.linspace(0.0, 1.0, labels.size))\n colors = cm.Set1.colors\n \n # loop to plot each\n for label, marker, color in zip(labels, markers, colors):\n X_label = X[y == label]\n y_label = y[y == label]\n label_text = 'Class %s' % label\n plt.plot(X_label[:,0], X_label[:,1], \n marker=marker, markersize=8.0, markeredgecolor='k',\n color=color, alpha=0.5, \n linestyle='',\n label=label_text)\n plt.xlabel('Feature 1')\n plt.ylabel('Feature 2')\n plt.legend();\n \n \ndef plot_multiclass_decision_boundaries(model, X, y):\n from matplotlib.colors import ListedColormap\n \"\"\"Use a mesh/grid to create a contour plot that will show the decision boundaries reached by\n a trained scikit-learn classifier. We expect that the model passed in is a trained scikit-learn\n classifier that supports/implements a predict() method, that will return predictions for the\n given set of X data.\n \n Parameters\n ----------\n model - A trained scikit-learn classifier that supports prediction using a predict() method\n X - A (m,2) shaped number array of m samples each with 2 features\n \"\"\"\n # determine the class labels\n labels = np.unique(y)\n #colors = cm.rainbow(np.linspace(0.0, 1.0, labels.size))\n #colors = cm.Set1.colors\n newcmp = ListedColormap(plt.cm.Set1.colors[:len(labels)])\n \n # create the mesh of points to use for the contour plot\n h = .02 # step size in the mesh\n x_min, x_max = X[:, 0].min() - h, X[:, 0].max() + h\n y_min, y_max = X[:, 1].min() - h, X[:, 1].max() + h\n\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n\n # create the predictions over the mesh using the trained models predict() function\n Z = model.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Create the actual contour plot, which will show the decision boundaries\n Z = Z.reshape(xx.shape)\n plt.contourf(xx, yy, Z, cmap=newcmp, alpha=0.33)\n #plt.colorbar()", "_____no_output_____" ], [ "from sklearn.datasets import make_moons\nX, y = make_moons(n_samples=2500, noise=0.3)\n\n# we will split data using a 75%/25% train/test split this time\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)", "_____no_output_____" ], [ "from sklearn.ensemble import VotingClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\n\nlog_clf = LogisticRegression(solver='lbfgs', C=5.0)\ntree_clf = DecisionTreeClassifier(max_depth=10)\nsvm_clf = SVC(gamma=100.0, C=1.0)\n\nvoting_clf = VotingClassifier(\n estimators=[('lr', log_clf), ('tree', tree_clf), ('svc', svm_clf)],\n voting='hard'\n)\n\nvoting_clf.fit(X_train, y_train)", "_____no_output_____" ], [ "plot_multiclass_decision_boundaries(voting_clf, X, y)\nplot_multiclass_data(X, y)", "_____no_output_____" ] ], [ [ "Lets look at each classifier's accuracy on the test set, including for the ensemble voting classifier:", "_____no_output_____" ] ], [ [ "from sklearn.metrics import accuracy_score\n\nfor clf in (log_clf, tree_clf, svm_clf, voting_clf):\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(clf.__class__.__name__, accuracy_score(y_test, y_pred))", "LogisticRegression 0.8576\nDecisionTreeClassifier 0.8768\nSVC 0.9056\nVotingClassifier 0.904\n" ] ], [ [ "The voting classifier will usually outperform all the individual classifier, if the data is sufficiently\nnonseparable to make it relatively hard (e.g. with less random noise in the moons data set, you can get\nreal good performance sometimes with random forest and/or svc, which will exceed the voting classifier).\n\nIf all classifiers are able to estimate class probabilities (i.e. in `scikit-learn` they support\n`predict_proba()` method), then you can tell `scikit-learn` to predict the class with the highest class\nprobability, averaged over all individual classifiers. You can think of this as each classifier having\nits vote weighted by its confidence of the prediction. This is called *soft voting*. It often achieves\nhigher performance than hard voting because it gives more weight to highly confident votes. All you\nneed to do is replace `voting='hard'` with `voting='soft'` and ensure that all classifiers can estimate\nclas sprobabilities. If you recall, support vector machine classifiers (`SVC`) do not estimate class probabilities by\ndefault, but if you set `SVC` `probability` hyperparameter to `True`, the `SVC` class will use cross-validation\nto estimate class probabilities. This slows training, but it makes the `predict_proba()` method valid\nfor `SVC`, and since both logistic regression and random forests support this confidence estimate, we\ncan then use soft voting for the voting classifier. ", "_____no_output_____" ] ], [ [ "log_clf = LogisticRegression(solver='lbfgs', C=5.0)\ntree_clf = DecisionTreeClassifier(max_depth=8)\nsvm_clf = SVC(gamma=1000.0, C=1.0, probability=True) # enable probability estimates for svm classifier\n\nvoting_clf = VotingClassifier(\n estimators=[('lr', log_clf), ('tree', tree_clf), ('svc', svm_clf)],\n voting='soft' # use soft voting this time\n)\n\nvoting_clf.fit(X_train, y_train)", "_____no_output_____" ], [ "plot_multiclass_decision_boundaries(voting_clf, X, y)\nplot_multiclass_data(X, y)", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score\n\nfor clf in (log_clf, tree_clf, svm_clf, voting_clf):\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(clf.__class__.__name__, accuracy_score(y_test, y_pred))", "LogisticRegression 0.8576\nDecisionTreeClassifier 0.8944\nSVC 0.8464\nVotingClassifier 0.8976\n" ] ], [ [ "# Bagging and Pasting\n\nOne way to get a diverse set of classifiers is to use very different training algorithms. The previous voting\nclassifier was an example of this, where we used 3 very different kinds of classifiers for the voting ensemble.\n\nAnother approach is to use the same training for every predictor, but to train them on different random\nsubsets of the training set. When sampling is performed with replacement, this method is called\n*bagging* (short for *bootstrap aggregrating*). When sampling is performed without replacement, it is\ncalled *pasting*.\n\nIn other words, both approaches are similar. In both cases you are sampling the training data to build\nmultiple instances of a classifier. In both cases a training item could be sampled and used to train\nmultiple instances in the collection of classifiers that is produced. In bagging, it is possible for a training\nsample to be sampled multiple times in the training for the same predictor. This type of bootstrap aggregration\nis a type of data enhancement, and it is used in other contexts as well in ML to artificially increase the size\nof the training set.\n\nOnce all predictors are trained, the ensemble can make predictions for a new instance by simply aggregating the\npredictions of all the predictors. The aggregration function is typically the *statistical mode* (i.e. the\nmost frequent prediction, just like hard voting) for classification, or the average for regression.\n\nEach individual predictor has a higher bias than if it were trained on the original training set (because you don't\nuse all of the training data on an individual bagged/pasted classifier). But the aggregration overall should usually\nreduce both bias and variance on the final performance. Generall the net result is that the ensemble has a similar\nbias but a lower variance than a single predictor trained on the whole original training set.\n\nComputationally bagging and pasting are very attractive because in theory and in practice all of the classifiers\ncan be trained in parallel. Thus if you have a large number of CPU cores, or even a distributed memory\ncomputing cluster, you can independently train the individual classifiers all in parallel.\n\n## Scikit-Learn Bagging and Pasting Examples\n\nThe ensemble API in `scikit-learn` for performing bagging and/or pasting is relatively simple. As with the voting\nclassifier, we specify which type of classifer we want to use. But since bagging/pasting train multiple\nclassifiers all of this type, we only have to specify 1. The `n_jobs` parameter tells `scikit-learn` the number of\ncpu cores to use for training and predictions (-1 tells `scikit-learn` to use all available cores).\n\nThe following trains an ensemble of 500 decision tree classifiers (`n_estimators`), each trained on 100 training\ninstances randomly sampled from the training set with replacement (`bootstrap=True`). If you want to use pasting\nwe simply set `bootstrap=False` instead.\n\n**NOTE**: The `BaggingClassifier` automatically performs soft voting instead of hard voting if the base classifier\ncan estimate class probabilities (i.e. it has a `predict_proba()` method).", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\nbag_clf = BaggingClassifier(\n DecisionTreeClassifier(max_leaf_nodes=20), n_estimators=500,\n max_samples=100, bootstrap=True, n_jobs=-1\n)\n\nbag_clf.fit(X_train, y_train)\ny_pred = bag_clf.predict(X_test)\nprint(bag_clf.__class__.__name__, accuracy_score(y_test, y_pred))", "BaggingClassifier 0.8944\n" ], [ "plot_multiclass_decision_boundaries(bag_clf, X, y)\nplot_multiclass_data(X, y)", "_____no_output_____" ] ], [ [ "## Out-of-Bag Evaluation\n\nWith bagging, some instances may be sampled several times for any given predictor, while others may not be\nsampled at all. By default a `BaggingClassifier` samples `m` training instances with replacement, where `m`\nis the size of the training set. This means that only about 63% of the training instances are sampled on average for\neach predictor. The remaining 37% of the training instances that are not sampled are called *out-of-bag* (oob)\ninstances. **NOTE**: they are not the same 37% for each resulting predictor, each predictor has a different oob.\n\nSince a predictor never sees the oob instances during training, it can be evaluated on these instances, without the need\nfor a separate validation set or cross-validation. You can evaluate the ensemble itself by averaging out the oob\nevaluations for each predictor.\n\nIn `scikit-learn` you can set `oob_score=True` when creating a `BaggingClassifier` to request an automatic oob\nevaluation after training:", "_____no_output_____" ] ], [ [ "bag_clf = BaggingClassifier(\n DecisionTreeClassifier(), n_estimators=500,\n bootstrap=True, n_jobs=-1, oob_score=True\n)\n\nbag_clf.fit(X_train, y_train)\nprint(bag_clf.oob_score_)\n\ny_pred = bag_clf.predict(X_test)\nprint(accuracy_score(y_test, y_pred))", "0.9056\n0.8976\n" ] ], [ [ "The oob decision function for each training instance is also available through the\n`oob_decision_function_` variable. ", "_____no_output_____" ] ], [ [ "bag_clf.oob_decision_function_", "_____no_output_____" ] ], [ [ "## Random Patches and Random Subspaces\n\nThe default behavior of the bagging/patching classifier is to only sample the training target outputs. However,\nit can also be useful to build classifiers that only use some of the feautres of the input data. We have looked\nat methods for adding features, for example by adding polynomial combinations of the feature inputs. But often for\nbig data, we might have thousands or even millions of input features. In that case, it can very well be that some\nor many of the features are not really all that useful, or even somewhat harmful, to building a truly good and\ngeneral classifier.\n\nSo one approach when we have large number of features is to build multiple classifiers (using bagging/patching)\non sampled subsets of the features. In `scikit-learn` `BaggingClassifier` this is controllerd by two\nhyperparameters: `max_features` and `bootstrap_features`. They work the same as `max_samples` and `bootstrap`\nbut for feature sampling instead of output instance sampling. Thus each predictor will be trained on a random subset\nof the input features. This is particularly useful when dealing with high-dimensional inputs. \n\nSampling from both training instances and features simultaneously is called the *Random Patches method*.\nKeeping all training instances, but sampling features is called *Random Subspaces method*.", "_____no_output_____" ], [ "# Random Forests\n\nAs we have already mentioned, a `RandomForest` is simply an ensemble of decision trees, generally trained via the\nbagging method, typically with `max_samples` set to the size of the training set. We could create a\nrandom forest by hand using `scikit-learn` `BaggingClassifier` on a DecisionTree, which is in fact what we just\ndid in the previous section. Our previous ensemble was an example of a random forest classifier.\n\nBut in `scikit-learn` instead of building the ensemble somewhat by hant, you can instead use the\n`RandomForestClassifier` class, which is more convenient and which has default hyperparameter settings\noptimized for random forests.\n\nThe following code trains a random forest classifier with 500 treas (each limited to a maximum of 16 nodes),\nusing all available CPU cores:", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\n\nrnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1)\nrnd_clf.fit(X_train, y_train)\n\ny_pred = rnd_clf.predict(X_test)\nprint(accuracy_score(y_test, y_pred))", "0.8976\n" ] ], [ [ "A random forest classifier has all of the hyperparameters of a `DecisionTreeClassifier` (to control\nhow trees are grown), plus all of the hyperparameters of a `BaggingClassifier` to control the ensemble itself.\n\nThe random forest algorithm introduces extra randomness when growing trees. Instead of searching\nfor the very best feature when splitting a node, it searches for the best feature among a random subset of\nfeatures. This results in a greater tree diversity, which trades a higher bias for a lower variance, generally yielding\na better overall ensemble model.\n\nThe following `BaggingClassifier` is roughly equivalent to the previous `RandomForestClassifier`:", "_____no_output_____" ] ], [ [ "bag_clf = BaggingClassifier(\n DecisionTreeClassifier(splitter='random', max_leaf_nodes=16),\n n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1 \n)\nbag_clf.fit(X_train, y_train)\n\ny_pred = bag_clf.predict(X_test)\nprint(accuracy_score(y_test, y_pred))", "0.8992\n" ] ], [ [ "## Extra-Trees\n\nWhen growing a tree in a random forest, at each node only a random subset of features is considered for splitting as\nwe just discussed. It is possible to make trees even more random by also using random thresholds for each\nfeature rather than searching for the best possible thresholds.\n\nA forest of such extremely random trees is called an *Extremely Randomized Trees* ensemble (or *Extra-Trees*\nfor short. \n\nYou can create an extra-trees classifier using `scikit-learn`s `ExtraTreesClassifier` class, its API is identical\nto the `RandomForestClassifier` class.\n\n**TIP:** It is hard to tell in advance whether a random forest or an extra-tree will perform better or worse on a\ngiven set of data. Generally the only way to know is to try both and compare them using cross-validation.", "_____no_output_____" ], [ "## Feature Importance\n\nLastly, if you look at a single decision tree, important features are likely to appear closer to the root of the\ntree, while unimportnat features will often appear closer to th eleaves (or not a all). Therefore another\nuse of random forests is to get an estimate on the importance of the features when making classification\npredictions. \n\nWe can get an estimate of a feature's importance by computing the average depth at which it appears across all\ntrees in a random forest. `scikit-learn` computes this automatically for every feature after training. You can\naccess the result using the `feature_importances_` variable.\n\nFor example, if we build a `RandomForestClassifier` on the iris data set (with 4 features), we can output each\nfeatures estimated importance.", "_____no_output_____" ] ], [ [ "from sklearn.datasets import load_iris\niris = load_iris()\n\nrnd_clf = RandomForestClassifier(n_estimators=500, n_jobs=-1)\nrnd_clf.fit(iris['data'], iris['target'])\n\nfor name, score in zip(iris['feature_names'], rnd_clf.feature_importances_):\n print(name, score)", "sepal length (cm) 0.0945223465095581\nsepal width (cm) 0.022011194440888737\npetal length (cm) 0.4251170433221595\npetal width (cm) 0.4583494157273937\n" ] ], [ [ "It seems the most importan feature is petal length, followed closely by petal width. Sepal length and especially\nsepal width are relatively less important.", "_____no_output_____" ], [ "# Boosting\n\n*Boosting* (originally called *hypothesis boosting* refers to any ensemble method that can combine several weak learners\ninto a strong learner. But unlike the ensembles we looked at before, the general idea is to train predictors\nsequentially, each trying to correct it predecessor. There are many boosting methods, the most popular being\n*AdaBoost* (short for *Adaptive Boosting*) and *Gradient Boosting*.\n\n## AdaBoost\n\n## Gradient Boost\n\n", "_____no_output_____" ], [ "# Stacking\n\nStacking works similar to the voting ensembles we have looked at. Multiple independent classifiers are trained\nin parallel and aggregrated. But instead of using a trivial aggregration method (like hard voting), we train\nyet another model to perform the aggregration. This final model (called a *blender* or *meta learner*) takes\nthe other trained predictors's output as input and makes a final prediciton from them. \n\n'Scikit-learn' does not support stacking directly (unlike voting ensembles and boosting). But it is not too difficult\nto hand roll basic implementations of stacking from `scikit-learn` apis.", "_____no_output_____" ] ], [ [ "import sys\nsys.path.append(\"../../src\") # add our class modules to the system PYTHON_PATH\n\nfrom ml_python_class.custom_funcs import version_information\nversion_information()", " Module Versions\n-------------------- ------------------------------------------------------------\n matplotlib: ['3.3.0']\n numpy: ['1.18.5']\n pandas: ['1.0.5']\n" ] ] ]
[ "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", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ] ]
d030b3d4f7f2207db71661e89a73caa107ed9366
2,196
ipynb
Jupyter Notebook
Gencianeo_Sunvick_A_Prelim1.ipynb
Sunvick/OPP-58001
06439e47c9bbecd8dc41bc3bf2088210bd983dfb
[ "Apache-2.0" ]
null
null
null
Gencianeo_Sunvick_A_Prelim1.ipynb
Sunvick/OPP-58001
06439e47c9bbecd8dc41bc3bf2088210bd983dfb
[ "Apache-2.0" ]
null
null
null
Gencianeo_Sunvick_A_Prelim1.ipynb
Sunvick/OPP-58001
06439e47c9bbecd8dc41bc3bf2088210bd983dfb
[ "Apache-2.0" ]
null
null
null
30.082192
241
0.485428
[ [ [ "<a href=\"https://colab.research.google.com/github/Sunvick/OPP-58001/blob/main/Gencianeo_Sunvick_A_Prelim1.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "class Student:\n def __init__ (self, Name, Student_No, Age, School, Course):\n self.Name = Name\n self.Student_No = Student_No\n self.Age = Age\n self.School = School\n self.Course = Course\n def self (self):\n print (\"Name: \", self.Name)\n print (\"Student Number: \", self.Student_No)\n print (\"Age : \", self.Age)\n print (\"School: \", self.School)\n print (\"Course: \", self.Course)\n\nMyself = Student (\"Gencianeo Sunvick A.\", 202117757, 18, \"Adamson University\", \"BS in Computer Engineering\")\nMyself.self ()", "Name: Gencianeo Sunvick A.\nStudent Number: 202117757\nAge : 18\nSchool: Adamson University\nCourse: BS in Computer Engineering\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
d030b3ef7aab44cf27104115bf338988384f497c
2,924
ipynb
Jupyter Notebook
arrays/smallest_difference.ipynb
codacy-badger/algorithms-1
bad63e6ec73c7196c3378d26ef3dbb9e172940e8
[ "MIT" ]
8
2019-08-19T21:43:44.000Z
2021-01-24T20:45:49.000Z
arrays/smallest_difference.ipynb
codacy-badger/algorithms-1
bad63e6ec73c7196c3378d26ef3dbb9e172940e8
[ "MIT" ]
74
2019-10-23T21:13:54.000Z
2021-01-26T22:24:13.000Z
arrays/smallest_difference.ipynb
codacy-badger/algorithms-1
bad63e6ec73c7196c3378d26ef3dbb9e172940e8
[ "MIT" ]
1
2022-01-21T12:02:33.000Z
2022-01-21T12:02:33.000Z
25.426087
134
0.496238
[ [ [ "## Problem\nFind the smallest difference between two arrays.\n\nThe function should take in two arrays and find the pair of numbers in the array whose absolute difference is closest to zero.\n", "_____no_output_____" ] ], [ [ "def smallest_difference(array_one, array_two):\n \"\"\"\n Complexity:\n Time: O(nlog(n)) + mlog(m))\n where n = length of first array, m = length of second array\n (the nlog n comes from sorting using an optimal sorting algorithm)\n\n Space: O(1)\n \"\"\"\n\n # first, we sort the arrays\n array_one.sort()\n array_two.sort()\n\n # init pointers that we'll use for each array\n idx_one = 0\n idx_two = 0\n\n current_diff = float('inf')\n smallest_diff = float('inf')\n\n while idx_one < len(array_one) and idx_two < len(array_two):\n first_num = array_one[idx_one]\n second_num = array_two[idx_two]\n\n # find absolute difference\n current_diff = abs(first_num - second_num)\n\n if first_num < second_num:\n # increment the index of first array\n idx_one += 1\n elif second_num < first_num:\n # increment the index of second array\n idx_two += 1\n else:\n return [first_num, second_num]\n\n if smallest_diff > current_diff:\n smallest_diff = current_diff\n smallest_pair = [first_num, second_num]\n\n return smallest_pair\n", "_____no_output_____" ], [ "array1 = [2, 1, 3, 5, 4]\narray2 = [4, 5, 6, 3, 2]\nsmallest_difference(array1, array2)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
d030b7462630b8b0d07ae8e766afa53c2c535415
12,588
ipynb
Jupyter Notebook
projects/exploratory_phase/code/notebooks/match_waterSystems_weatherStations.ipynb
TylerTsang/safe-water
8e3da323d587f6ea3640635d09628eaa9bca2d39
[ "MIT" ]
43
2018-10-02T23:08:21.000Z
2022-02-09T15:00:17.000Z
projects/exploratory_phase/code/notebooks/match_waterSystems_weatherStations.ipynb
TylerTsang/safe-water
8e3da323d587f6ea3640635d09628eaa9bca2d39
[ "MIT" ]
64
2019-02-06T00:33:32.000Z
2021-02-24T17:13:07.000Z
projects/exploratory_phase/code/notebooks/match_waterSystems_weatherStations.ipynb
TylerTsang/safe-water
8e3da323d587f6ea3640635d09628eaa9bca2d39
[ "MIT" ]
84
2018-09-28T12:43:02.000Z
2022-03-08T16:13:42.000Z
29.618824
95
0.46592
[ [ [ "import pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "weatherStation = pd.read_csv('weatherStationLocation.csv')\nwaterSystem = pd.read_csv('waterSystemLocation.csv')", "_____no_output_____" ], [ "# print(waterSystem.head)\nprint(waterSystem[:5])\nprint(weatherStation[:5])\n# print(waterSystem['PWSID'])", " PWSID LAT LON\n0 10106001 41.449482 -71.98233\n1 10109005 41.457198 -72.11459\n2 10307001 41.345578 -70.75145\n3 10502002 41.385256 -71.66813\n4 10502003 41.385256 -71.66813\n Station Lat Lon\n0 STOVEPIPE WELLS 1 SW 36.60200 -117.14490\n1 DEATH VALLEY 36.46220 -116.86690\n2 IMPERIAL COUNTY AP 32.83417 -115.57861\n3 YUMA 13.8 ESE 32.63410 -114.40560\n4 YUMA 7.7 SE 32.64320 -114.52300\n" ], [ "print(waterSystem.ix[146347])\nprint(waterSystem.ix[146341])", "PWSID WY5680260\nLAT 42.7298\nLON -108.632\nName: 146347, dtype: object\nPWSID WY5680250\nLAT 43.7015\nLON -110.832\nName: 146341, dtype: object\n" ], [ "weatherLatLong = weatherStation[['Lat','Lon']].values\nwaterLatLong = waterSystem[['LAT','LON']].values\n\nprint(waterLatLong.shape)\nprint(weatherLatLong.shape)", "(146351, 2)\n(9191, 2)\n" ], [ "import time\nimport scipy.spatial.distance", "_____no_output_____" ], [ "bestWeatherStations = []\n\nstart = time.time()\n\n# distances_test = np.sum(np.power(waterLatLong[ii,:] - weatherLatLong,2),axis=1)\n# bestWeatherStations.append(weatherStation['Station'][np.argsort(distances_test)[0]])\n\nY = scipy.spatial.distance.cdist(waterLatLong,weatherLatLong)\n\nprint(Y.shape)\n\nend = time.time()\n\n\nprint('Total computation time is ...', end-start, 'seconds.')\n", "(146351, 9191)\nTotal computation time is ... 14.421862125396729 seconds.\n" ], [ "start = time.time()\n\nbestOrder = np.argmin(Y,axis=1)\n\nend = time.time()\n\nprint('Total computation time is ...', end-start, 'seconds.')", "Total computation time is ... 47.458112955093384 seconds.\n" ], [ "nearestWeatherStations = weatherStation['Station'][bestOrder]\n\nprint(nearestWeatherStations)", "5448 NORWICH PUB UTILITY PLANT\n5448 NORWICH PUB UTILITY PLANT\n5830 WOODS HOLE GOLF CLUB\n5517 WESTERLY STATE AIRPORT\n5517 WESTERLY STATE AIRPORT\n7837 ALLEGANY STATE PARK\n7837 ALLEGANY STATE PARK\n3313 MASSENA INTL AP\n7837 ALLEGANY STATE PARK\n7837 ALLEGANY STATE PARK\n6318 DE WITT 1.4 WSW\n3106 NIAGARA FALLS INT'L AP\n7837 ALLEGANY STATE PARK\n7837 ALLEGANY STATE PARK\n8001 ATMORE\n7159 HOLLYWOOD NORTH PERRY AP\n7159 HOLLYWOOD NORTH PERRY AP\n7159 HOLLYWOOD NORTH PERRY AP\n7159 HOLLYWOOD NORTH PERRY AP\n8700 MIAMI INTERNATIONAL AP\n8700 MIAMI INTERNATIONAL AP\n8079 PHILADELPHIA 1 WSW\n8079 PHILADELPHIA 1 WSW\n8079 PHILADELPHIA 1 WSW\n8079 PHILADELPHIA 1 WSW\n6771 OCONALUFTEE\n6771 OCONALUFTEE\n6771 OCONALUFTEE\n6771 OCONALUFTEE\n6771 OCONALUFTEE\n ... \n1746 SHERIDAN 1.7 NW\n902 KEMMERER 2N\n2196 JACKSON\n1037 IDAHO FALLS - KIFI\n2196 JACKSON\n2196 JACKSON\n2196 JACKSON\n776 CODY 2.4 WSW\n776 CODY 2.4 WSW\n776 CODY 2.4 WSW\n1746 SHERIDAN 1.7 NW\n1746 SHERIDAN 1.7 NW\n657 SARATOGA 4N\n776 CODY 2.4 WSW\n776 CODY 2.4 WSW\n776 CODY 2.4 WSW\n776 CODY 2.4 WSW\n1746 SHERIDAN 1.7 NW\n1746 SHERIDAN 1.7 NW\n665 LARAMIE AP\n2584 MOOSE\n789 DUBOIS\n665 LARAMIE AP\n665 LARAMIE AP\n2196 JACKSON\n2196 JACKSON\n2170 LANDER 11 SSE\n2170 LANDER 11 SSE\n2170 LANDER 11 SSE\n1746 SHERIDAN 1.7 NW\nName: Station, Length: 146351, dtype: object\n" ], [ "print(waterSystem[['PWSID']].shape)\nprint(nearestWeatherStations.shape)", "(146351, 1)\n(146351,)\n" ], [ "print(isinstance(waterSystem[['PWSID']],pd.DataFrame))\nprint(isinstance(nearestWeatherStations,pd.DataFrame))\n\nnearestWeatherStations = pd.DataFrame(np.expand_dims(nearestWeatherStations,1))\n\nisinstance(nearestWeatherStations,pd.DataFrame)", "True\nFalse\n" ], [ "nearestWeatherStationResults = waterSystem[['PWSID']].join(nearestWeatherStations)", "_____no_output_____" ], [ "print(nearestWeatherStationResults)", " PWSID 0\n0 10106001 NORWICH PUB UTILITY PLANT\n1 10109005 NORWICH PUB UTILITY PLANT\n2 10307001 WOODS HOLE GOLF CLUB\n3 10502002 WESTERLY STATE AIRPORT\n4 10502003 WESTERLY STATE AIRPORT\n5 20000001 ALLEGANY STATE PARK\n6 20000004 ALLEGANY STATE PARK\n7 20000005 MASSENA INTL AP\n8 20000007 ALLEGANY STATE PARK\n9 20000008 ALLEGANY STATE PARK\n10 20000012 DE WITT 1.4 WSW\n11 20000015 NIAGARA FALLS INT'L AP\n12 20000016 ALLEGANY STATE PARK\n13 20011102 ALLEGANY STATE PARK\n14 40000002 ATMORE\n15 41200001 HOLLYWOOD NORTH PERRY AP\n16 41200002 HOLLYWOOD NORTH PERRY AP\n17 41200003 HOLLYWOOD NORTH PERRY AP\n18 41200004 HOLLYWOOD NORTH PERRY AP\n19 41210001 MIAMI INTERNATIONAL AP\n20 41210003 MIAMI INTERNATIONAL AP\n21 42800001 PHILADELPHIA 1 WSW\n22 42800002 PHILADELPHIA 1 WSW\n23 42800003 PHILADELPHIA 1 WSW\n24 42800004 PHILADELPHIA 1 WSW\n25 43700056 OCONALUFTEE\n26 43740008 OCONALUFTEE\n27 43740012 OCONALUFTEE\n28 43740013 OCONALUFTEE\n29 43740017 OCONALUFTEE\n... ... ...\n146321 WY5680184 SHERIDAN 1.7 NW\n146322 WY5680202 KEMMERER 2N\n146323 WY5680207 JACKSON\n146324 WY5680208 IDAHO FALLS - KIFI\n146325 WY5680210 JACKSON\n146326 WY5680211 JACKSON\n146327 WY5680212 JACKSON\n146328 WY5680218 CODY 2.4 WSW\n146329 WY5680221 CODY 2.4 WSW\n146330 WY5680224 CODY 2.4 WSW\n146331 WY5680231 SHERIDAN 1.7 NW\n146332 WY5680232 SHERIDAN 1.7 NW\n146333 WY5680233 SARATOGA 4N\n146334 WY5680235 CODY 2.4 WSW\n146335 WY5680236 CODY 2.4 WSW\n146336 WY5680237 CODY 2.4 WSW\n146337 WY5680240 CODY 2.4 WSW\n146338 WY5680243 SHERIDAN 1.7 NW\n146339 WY5680244 SHERIDAN 1.7 NW\n146340 WY5680249 LARAMIE AP\n146341 WY5680250 MOOSE\n146342 WY5680251 DUBOIS\n146343 WY5680252 LARAMIE AP\n146344 WY5680254 LARAMIE AP\n146345 WY5680258 JACKSON\n146346 WY5680259 JACKSON\n146347 WY5680260 LANDER 11 SSE\n146348 WY5680261 LANDER 11 SSE\n146349 WY5680262 LANDER 11 SSE\n146350 WY5680263 SHERIDAN 1.7 NW\n\n[146351 rows x 2 columns]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d030bb0a499b88a6371bae327b25b30b074c36e3
365,190
ipynb
Jupyter Notebook
tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb
sanchobarriga/course-content
a7cbe0fa40dee200bd964b349e685513bb9f71c4
[ "CC-BY-4.0" ]
1
2020-07-08T19:28:55.000Z
2020-07-08T19:28:55.000Z
tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb
sanchobarriga/course-content
a7cbe0fa40dee200bd964b349e685513bb9f71c4
[ "CC-BY-4.0" ]
1
2020-06-22T22:57:03.000Z
2020-06-22T22:57:03.000Z
tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb
sanchobarriga/course-content
a7cbe0fa40dee200bd964b349e685513bb9f71c4
[ "CC-BY-4.0" ]
null
null
null
178.751836
35,996
0.881533
[ [ [ "<a href=\"https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W1D2_ModelingPractice/student/W1D2_Tutorial2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "# Neuromatch Academy: Week1, Day 2, Tutorial 2", "_____no_output_____" ], [ "#Tutorial objectives\n\nWe are investigating a simple phenomena, working through the 10 steps of modeling ([Blohm et al., 2019](https://doi.org/10.1523/ENEURO.0352-19.2019)) in two notebooks: \n\n**Framing the question**\n1. finding a phenomenon and a question to ask about it\n2. understanding the state of the art\n3. determining the basic ingredients\n4. formulating specific, mathematically defined hypotheses\n**Implementing the model**\n5. selecting the toolkit\n6. planning the model\n7. implementing the model\n**Model testing**\n8. completing the model\n9. testing and evaluating the model\n**Publishing**\n10. publishing models\n\nWe did steps 1-5 in Tutorial 1 and will cover steps 6-10 in Tutorial 2 (this notebook).", "_____no_output_____" ], [ "# Utilities Setup and Convenience Functions\n\nPlease run the following **3** chunks to have functions and data available.", "_____no_output_____" ] ], [ [ "#@title Utilities and setup\n# set up the environment for this tutorial\n\nimport time # import time \nimport numpy as np # import numpy\nimport scipy as sp # import scipy\nfrom scipy.stats import gamma # import gamma distribution\nimport math # import basic math functions\nimport random # import basic random number generator functions\n\nimport matplotlib.pyplot as plt # import matplotlib\nfrom IPython import display \n\nfig_w, fig_h = (12, 8)\nplt.rcParams.update({'figure.figsize': (fig_w, fig_h)})\nplt.style.use('ggplot')\n\n%matplotlib inline\n#%config InlineBackend.figure_format = 'retina'\n\nfrom scipy.signal import medfilt\n\n# make", "_____no_output_____" ], [ "#@title Convenience functions: Plotting and Filtering\n# define some convenience functions to be used later\n\ndef my_moving_window(x, window=3, FUN=np.mean):\n '''\n Calculates a moving estimate for a signal\n\n Args:\n x (numpy.ndarray): a vector array of size N\n window (int): size of the window, must be a positive integer\n FUN (function): the function to apply to the samples in the window\n\n Returns:\n (numpy.ndarray): a vector array of size N, containing the moving average\n of x, calculated with a window of size window\n\n There are smarter and faster solutions (e.g. using convolution) but this \n function shows what the output really means. This function skips NaNs, and \n should not be susceptible to edge effects: it will simply use\n all the available samples, which means that close to the edges of the \n signal or close to NaNs, the output will just be based on fewer samples. By\n default, this function will apply a mean to the samples in the window, but \n this can be changed to be a max/min/median or other function that returns a \n single numeric value based on a sequence of values.\n '''\n\n # if data is a matrix, apply filter to each row:\n if len(x.shape) == 2:\n output = np.zeros(x.shape)\n for rown in range(x.shape[0]):\n output[rown,:] = my_moving_window(x[rown,:],window=window,FUN=FUN)\n return output\n\n # make output array of the same size as x:\n output = np.zeros(x.size)\n\n # loop through the signal in x\n for samp_i in range(x.size):\n\n values = []\n\n # loop through the window:\n for wind_i in range(int(-window), 1):\n\n if ((samp_i+wind_i) < 0) or (samp_i+wind_i) > (x.size - 1):\n # out of range\n continue\n \n # sample is in range and not nan, use it:\n if not(np.isnan(x[samp_i+wind_i])):\n values += [x[samp_i+wind_i]]\n \n # calculate the mean in the window for this point in the output:\n output[samp_i] = FUN(values)\n\n return output\n\n\ndef my_plot_percepts(datasets=None, plotconditions=False):\n\n if isinstance(datasets,dict):\n # try to plot the datasets\n # they should be named...\n # 'expectations', 'judgments', 'predictions'\n\n fig = plt.figure(figsize=(8, 8)) # set aspect ratio = 1? not really\n\n plt.ylabel('perceived self motion [m/s]')\n plt.xlabel('perceived world motion [m/s]')\n plt.title('perceived velocities')\n \n # loop through the entries in datasets\n # plot them in the appropriate way\n for k in datasets.keys():\n if k == 'expectations':\n \n expect = datasets[k]\n plt.scatter(expect['world'],expect['self'],marker='*',color='xkcd:green',label='my expectations')\n\n elif k == 'judgments':\n \n judgments = datasets[k]\n\n for condition in np.unique(judgments[:,0]):\n c_idx = np.where(judgments[:,0] == condition)[0]\n cond_self_motion = judgments[c_idx[0],1]\n cond_world_motion = judgments[c_idx[0],2]\n if cond_world_motion == -1 and cond_self_motion == 0:\n c_label = 'world-motion condition judgments' \n elif cond_world_motion == 0 and cond_self_motion == 1:\n c_label = 'self-motion condition judgments' \n else:\n c_label = 'condition [%d] judgments'%condition\n \n plt.scatter(judgments[c_idx,3],judgments[c_idx,4], label=c_label, alpha=0.2)\n\n elif k == 'predictions':\n \n predictions = datasets[k]\n\n for condition in np.unique(predictions[:,0]):\n c_idx = np.where(predictions[:,0] == condition)[0]\n cond_self_motion = predictions[c_idx[0],1]\n cond_world_motion = predictions[c_idx[0],2]\n if cond_world_motion == -1 and cond_self_motion == 0:\n c_label = 'predicted world-motion condition' \n elif cond_world_motion == 0 and cond_self_motion == 1:\n c_label = 'predicted self-motion condition' \n else:\n c_label = 'condition [%d] prediction'%condition\n \n plt.scatter(predictions[c_idx,4],predictions[c_idx,3], marker='x', label=c_label)\n\n else:\n print(\"datasets keys should be 'hypothesis', 'judgments' and 'predictions'\")\n\n \n if plotconditions:\n # this code is simplified but only works for the dataset we have:\n plt.scatter([1],[0],marker='<',facecolor='none',edgecolor='xkcd:black',linewidths=2,label='world-motion stimulus',s=80)\n plt.scatter([0],[1],marker='>',facecolor='none',edgecolor='xkcd:black',linewidths=2,label='self-motion stimulus',s=80)\n\n plt.legend(facecolor='xkcd:white')\n plt.show()\n\n else:\n if datasets is not None:\n print('datasets argument should be a dict')\n raise TypeError\n\ndef my_plot_motion_signals():\n dt = 1/10\n a = gamma.pdf( np.arange(0,10,dt), 2.5, 0 )\n t = np.arange(0,10,dt)\n v = np.cumsum(a*dt)\n\n fig, [ax1, ax2] = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(14,6))\n fig.suptitle('Sensory ground truth')\n\n ax1.set_title('world-motion condition')\n ax1.plot(t,-v,label='visual [$m/s$]')\n ax1.plot(t,np.zeros(a.size),label='vestibular [$m/s^2$]')\n ax1.set_xlabel('time [s]')\n ax1.set_ylabel('motion')\n ax1.legend(facecolor='xkcd:white')\n\n ax2.set_title('self-motion condition')\n ax2.plot(t,-v,label='visual [$m/s$]')\n ax2.plot(t,a,label='vestibular [$m/s^2$]')\n ax2.set_xlabel('time [s]')\n ax2.set_ylabel('motion')\n ax2.legend(facecolor='xkcd:white')\n\n plt.show()\n\n\n\ndef my_plot_sensorysignals(judgments, opticflow, vestibular, returnaxes=False, addaverages=False):\n \n wm_idx = np.where(judgments[:,0] == 0)\n sm_idx = np.where(judgments[:,0] == 1)\n \n opticflow = opticflow.transpose()\n wm_opticflow = np.squeeze(opticflow[:,wm_idx])\n sm_opticflow = np.squeeze(opticflow[:,sm_idx])\n \n vestibular = vestibular.transpose()\n wm_vestibular = np.squeeze(vestibular[:,wm_idx])\n sm_vestibular = np.squeeze(vestibular[:,sm_idx])\n \n X = np.arange(0,10,.1)\n \n fig, my_axes = plt.subplots(nrows=2, ncols=2, sharex='col', sharey='row', figsize=(15,10))\n fig.suptitle('Sensory signals')\n\n my_axes[0][0].plot(X,wm_opticflow, color='xkcd:light red', alpha=0.1)\n my_axes[0][0].plot([0,10], [0,0], ':', color='xkcd:black')\n if addaverages:\n my_axes[0][0].plot(X,np.average(wm_opticflow, axis=1), color='xkcd:red', alpha=1)\n my_axes[0][0].set_title('world-motion optic flow')\n my_axes[0][0].set_ylabel('[motion]')\n\n my_axes[0][1].plot(X,sm_opticflow, color='xkcd:azure', alpha=0.1)\n my_axes[0][1].plot([0,10], [0,0], ':', color='xkcd:black')\n if addaverages:\n my_axes[0][1].plot(X,np.average(sm_opticflow, axis=1), color='xkcd:blue', alpha=1)\n my_axes[0][1].set_title('self-motion optic flow')\n\n my_axes[1][0].plot(X,wm_vestibular, color='xkcd:light red', alpha=0.1)\n my_axes[1][0].plot([0,10], [0,0], ':', color='xkcd:black')\n if addaverages:\n my_axes[1][0].plot(X,np.average(wm_vestibular, axis=1), color='xkcd:red', alpha=1)\n my_axes[1][0].set_title('world-motion vestibular signal')\n my_axes[1][0].set_xlabel('time [s]')\n my_axes[1][0].set_ylabel('[motion]')\n\n my_axes[1][1].plot(X,sm_vestibular, color='xkcd:azure', alpha=0.1)\n my_axes[1][1].plot([0,10], [0,0], ':', color='xkcd:black')\n if addaverages:\n my_axes[1][1].plot(X,np.average(sm_vestibular, axis=1), color='xkcd:blue', alpha=1)\n my_axes[1][1].set_title('self-motion vestibular signal')\n my_axes[1][1].set_xlabel('time [s]')\n\n if returnaxes:\n return my_axes\n else:\n plt.show()\n\ndef my_plot_thresholds(thresholds, world_prop, self_prop, prop_correct):\n\n plt.figure(figsize=(12,8))\n plt.title('threshold effects')\n plt.plot([min(thresholds),max(thresholds)],[0,0],':',color='xkcd:black')\n plt.plot([min(thresholds),max(thresholds)],[0.5,0.5],':',color='xkcd:black')\n plt.plot([min(thresholds),max(thresholds)],[1,1],':',color='xkcd:black')\n plt.plot(thresholds, world_prop, label='world motion')\n plt.plot(thresholds, self_prop, label='self motion')\n plt.plot(thresholds, prop_correct, color='xkcd:purple', label='correct classification')\n plt.xlabel('threshold')\n plt.ylabel('proportion correct or classified as self motion')\n plt.legend(facecolor='xkcd:white')\n plt.show()\n\ndef my_plot_predictions_data(judgments, predictions):\n\n conditions = np.concatenate((np.abs(judgments[:,1]),np.abs(judgments[:,2])))\n veljudgmnt = np.concatenate((judgments[:,3],judgments[:,4]))\n velpredict = np.concatenate((predictions[:,3],predictions[:,4]))\n\n # self:\n conditions_self = np.abs(judgments[:,1])\n veljudgmnt_self = judgments[:,3]\n velpredict_self = predictions[:,3]\n\n # world:\n conditions_world = np.abs(judgments[:,2])\n veljudgmnt_world = judgments[:,4]\n velpredict_world = predictions[:,4]\n\n fig, [ax1, ax2] = plt.subplots(nrows=1, ncols=2, sharey='row', figsize=(12,5))\n\n ax1.scatter(veljudgmnt_self,velpredict_self, alpha=0.2)\n ax1.plot([0,1],[0,1],':',color='xkcd:black')\n ax1.set_title('self-motion judgments')\n ax1.set_xlabel('observed')\n ax1.set_ylabel('predicted')\n\n ax2.scatter(veljudgmnt_world,velpredict_world, alpha=0.2)\n ax2.plot([0,1],[0,1],':',color='xkcd:black')\n ax2.set_title('world-motion judgments')\n ax2.set_xlabel('observed')\n ax2.set_ylabel('predicted')\n\n plt.show()", "_____no_output_____" ], [ "#@title Data generation code (needs to go on OSF and deleted here)\ndef my_simulate_data(repetitions=100, conditions=[(0,-1),(+1,0)] ):\n \"\"\"\n Generate simulated data for this tutorial. You do not need to run this \n yourself.\n\n Args:\n repetitions: (int) number of repetitions of each condition (default: 30)\n conditions: list of 2-tuples of floats, indicating the self velocity and \n world velocity in each condition (default: returns data that is\n good for exploration: [(-1,0),(0,+1)] but can be flexibly\n extended)\n\n The total number of trials used (ntrials) is equal to:\n repetitions * len(conditions)\n\n Returns:\n dict with three entries:\n 'judgments': ntrials * 5 matrix\n 'opticflow': ntrials * 100 matrix\n 'vestibular': ntrials * 100 matrix\n \n The default settings would result in data where first 30 trials reflect a\n situation where the world (other train) moves in one direction, supposedly\n at 1 m/s (perhaps to the left: -1) while the participant does not move at\n all (0), and 30 trials from a second condition, where the world does not \n move, while the participant moves with 1 m/s in the opposite direction from\n where the world is moving in the first condition (0,+1). The optic flow \n should be the same, but the vestibular input is not.\n\n \"\"\"\n \n # reproducible output\n np.random.seed(1937)\n \n # set up some variables:\n ntrials = repetitions * len(conditions)\n\n # the following arrays will contain the simulated data:\n judgments = np.empty(shape=(ntrials,5))\n opticflow = np.empty(shape=(ntrials,100))\n vestibular = np.empty(shape=(ntrials,100))\n \n\n # acceleration:\n a = gamma.pdf(np.arange(0,10,.1), 2.5, 0 )\n # divide by 10 so that velocity scales from 0 to 1 (m/s)\n\n # max acceleration ~ .308 m/s^2\n # not realistic! should be about 1/10 of that\n\n # velocity:\n v = np.cumsum(a*.1)\n # position: (not necessary)\n #x = np.cumsum(v)\n \n #################################\n # REMOVE ARBITRARY SCALING & CORRECT NOISE PARAMETERS\n\n vest_amp = 1\n optf_amp = 1\n\n # we start at the first trial:\n trialN = 0\n\n # we start with only a single velocity, but it should be possible to extend this\n for conditionno in range(len(conditions)):\n\n condition = conditions[conditionno]\n\n for repetition in range(repetitions):\n \n # \n\n # generate optic flow signal\n OF = v * np.diff(condition) # optic flow: difference between self & world motion\n OF = (OF * optf_amp) # fairly large spike range\n OF = OF + (np.random.randn(len(OF)) * .1) # adding noise\n \n # generate vestibular signal\n VS = a * condition[0] # vestibular signal: only self motion\n VS = (VS * vest_amp) # less range\n VS = VS + (np.random.randn(len(VS)) * 1.) # acceleration is a smaller signal, what is a good noise level?\n \n # store in matrices, corrected for sign\n #opticflow[trialN,:] = OF * -1 if (np.sign(np.diff(condition)) < 0) else OF\n #vestibular[trialN,:] = VS * -1 if (np.sign(condition[1]) < 0) else VS\n opticflow[trialN,:], vestibular[trialN,:] = OF, VS\n\n #########################################################\n \n # store conditions in judgments matrix:\n judgments[trialN,0:3] = [ conditionno, condition[0], condition[1] ]\n \n # vestibular SD: 1.0916052957046194 and 0.9112684509277528\n # visual SD: 0.10228834313079663 and 0.10975472557444346\n\n # generate judgments:\n if (abs(np.average(np.cumsum(medfilt(VS/vest_amp,5)*.1)[70:90])) < 1):\n ###########################\n # NO self motion detected\n ###########################\n selfmotion_weights = np.array([.01,.01]) # there should be low/no self motion\n worldmotion_weights = np.array([.01,.99]) # world motion is dictated by optic flow\n \n\n else:\n ########################\n # self motion DETECTED\n ########################\n #if (abs(np.average(np.cumsum(medfilt(VS/vest_amp,15)*.1)[70:90]) - np.average(medfilt(OF,15)[70:90])) < 5):\n if True:\n ####################\n # explain all self motion by optic flow\n selfmotion_weights = np.array([.01,.99]) # there should be lots of self motion, but determined by optic flow\n worldmotion_weights = np.array([.01,.01]) # very low world motion?\n else:\n # we use both optic flow and vestibular info to explain both\n selfmotion_weights = np.array([ 1, 0]) # motion, but determined by vestibular signal\n worldmotion_weights = np.array([ 1, 1]) # very low world motion?\n \n # \n integrated_signals = np.array([\n np.average( np.cumsum(medfilt(VS/vest_amp,15))[90:100]*.1 ), \n np.average((medfilt(OF/optf_amp,15))[90:100]) \n ])\n selfmotion = np.sum(integrated_signals * selfmotion_weights)\n worldmotion = np.sum(integrated_signals * worldmotion_weights)\n #print(worldmotion,selfmotion)\n\n judgments[trialN,3] = abs(selfmotion)\n judgments[trialN,4] = abs(worldmotion)\n \n # this ends the trial loop, so we increment the counter:\n trialN += 1\n \n return {'judgments':judgments, \n 'opticflow':opticflow, \n 'vestibular':vestibular}\n\nsimulated_data = my_simulate_data()\n\njudgments = simulated_data['judgments']\nopticflow = simulated_data['opticflow']\nvestibular = simulated_data['vestibular']\n", "_____no_output_____" ] ], [ [ "#Micro-tutorial 6 - planning the model", "_____no_output_____" ] ], [ [ "#@title Video: Planning the model\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='daEtkVporBE', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo", "Video available at https://youtube.com/watch?v=daEtkVporBE\n" ] ], [ [ "\n###**Goal:** Identify the key components of the model and how they work together.\n\nOur goal all along has been to model our perceptual estimates of sensory data.\nNow that we have some idea of what we want to do, we need to line up the components of the model: what are the input and output? Which computations are done and in what order? \n\nThe figure below shows a generic model we will use to guide our code construction. \n![Model as code](https://i.ibb.co/hZdHmkk/modelfigure.jpg)\n\nOur model will have:\n* **inputs**: the values the system has available - for this tutorial the sensory information in a trial. We want to gather these together and plan how to process them. \n* **parameters**: unless we are lucky, our functions will have unknown parameters - we want to identify these and plan for them.\n* **outputs**: these are the predictions our model will make - for this tutorial these are the perceptual judgments on each trial. Ideally these are directly comparable to our data. \n* **Model functions**: A set of functions that perform the hypothesized computations.\n\n>Using Python (with Numpy and Scipy) we will define a set of functions that take our data and some parameters as input, can run our model, and output a prediction for the judgment data.\n\n#Recap of what we've accomplished so far:\n\nTo model perceptual estimates from our sensory data, we need to \n1. _integrate_ to ensure sensory information are in appropriate units\n2. _reduce noise and set timescale_ by filtering\n3. _threshold_ to model detection \n\nRemember the kind of operations we identified:\n* integration: `np.cumsum()`\n* filtering: `my_moving_window()`\n* threshold: `if` with a comparison (`>` or `<`) and `else`\n\nWe will collect all the components we've developed and design the code by:\n1. **identifying the key functions** we need\n2. **sketching the operations** needed in each. \n\n\n", "_____no_output_____" ], [ "**_Planning our model:_**\n\nWe know what we want the model to do, but we need to plan and organize the model into functions and operations. \n\nWe're providing a draft of the first function. \n\nFor each of the two other code chunks, write mostly comments and help text first. This should put into words what role each of the functions plays in the overall model, implementing one of the steps decided above. \n\n_______\nBelow is the main function with a detailed explanation of what the function is supposed to do: what input is expected, and what output will generated. \n\nThe code is not complete, and only returns nans for now. However, this outlines how most model code works: it gets some measured data (the sensory signals) and a set of parameters as input, and as output returns a prediction on other measured data (the velocity judgments). \n\nThe goal of this function is to define the top level of a simulation model which:\n* receives all input\n* loops through the cases\n* calls functions that computes predicted values for each case\n* outputs the predictions", "_____no_output_____" ], [ "### **TD 6.1**: Complete main model function\n\nThe function `my_train_illusion_model()` below should call one other function: `my_perceived_motion()`. What input do you think this function should get?", "_____no_output_____" ], [ "**Complete main model function**", "_____no_output_____" ] ], [ [ "def my_train_illusion_model(sensorydata, params):\n '''\n Generate output predictions of perceived self-motion and perceived world-motion velocity\n based on input visual and vestibular signals.\n \n Args (Input variables passed into function):\n\n sensorydata: (dict) dictionary with two named entries:\n opticflow: (numpy.ndarray of float) NxM array with N trials on rows\n and M visual signal samples in columns \n\n vestibular: (numpy.ndarray of float) NxM array with N trials on rows\n and M vestibular signal samples in columns\n \n params: (dict) dictionary with named entries:\n threshold: (float) vestibular threshold for credit assignment\n\n filterwindow: (list of int) determines the strength of filtering for\n the visual and vestibular signals, respectively\n\n integrate (bool): whether to integrate the vestibular signals, will \n be set to True if absent\n\n FUN (function): function used in the filter, will be set to \n np.mean if absent\n\n samplingrate (float): the number of samples per second in the \n sensory data, will be set to 10 if absent\n\n Returns:\n\n dict with two entries:\n\n selfmotion: (numpy.ndarray) vector array of length N, with predictions\n of perceived self motion \n\n worldmotion: (numpy.ndarray) vector array of length N, with predictions\n of perceived world motion \n '''\n\n # sanitize input a little\n if not('FUN' in params.keys()):\n params['FUN'] = np.mean\n if not('integrate' in params.keys()):\n params['integrate'] = True\n if not('samplingrate' in params.keys()):\n params['samplingrate'] = 10\n\n # number of trials:\n ntrials = sensorydata['opticflow'].shape[0]\n \n # set up variables to collect output\n selfmotion = np.empty(ntrials)\n worldmotion = np.empty(ntrials)\n\n # loop through trials?\n for trialN in range(ntrials):\n\n #these are our sensory variables (inputs)\n vis = sensorydata['opticflow'][trialN,:]\n ves = sensorydata['vestibular'][trialN,:]\n \n ########################################################\n # generate output predicted perception:\n ########################################################\n #our inputs our vis, ves, and params\n selfmotion[trialN], worldmotion[trialN] = [np.nan, np.nan]\n ########################################################\n # replace above with\n # selfmotion[trialN], worldmotion[trialN] = my_perceived_motion( ???, ???, params=params)\n # and fill in question marks\n ########################################################\n\n # comment this out when you've filled\n raise NotImplementedError(\"Student excercise: generate predictions\")\n\n return {'selfmotion':selfmotion, 'worldmotion':worldmotion}\n\n\n# uncomment the following lines to run the main model function:\n\n## here is a mock version of my_perceived motion.\n## so you can test my_train_illusion_model()\n#def my_perceived_motion(*args, **kwargs):\n #return np.random.rand(2)\n\n##let's look at the preditions we generated for two sample trials (0,100)\n##we should get a 1x2 vector of self-motion prediction and another for world-motion\n\n#sensorydata={'opticflow':opticflow[[0,100],:0], 'vestibular':vestibular[[0,100],:0]}\n#params={'threshold':0.33, 'filterwindow':[100,50]}\n#my_train_illusion_model(sensorydata=sensorydata, params=params)", "_____no_output_____" ] ], [ [ "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_685e0a13.py)\n\n", "_____no_output_____" ], [ "### **TD 6.2**: Draft perceived motion functions\n\nNow we draft a set of functions, the first of which is used in the main model function (see above) and serves to generate perceived velocities. The other two are used in the first one. Only write help text and/or comments, you don't have to write the whole function. Each time ask yourself these questions:\n\n* what sensory data is necessary? \n* what other input does the function need, if any?\n* which operations are performed on the input?\n* what is the output?\n\n(the number of arguments is correct)", "_____no_output_____" ], [ "**Template perceived motion**", "_____no_output_____" ] ], [ [ "# fill in the input arguments the function should have:\n# write the help text for the function:\ndef my_perceived_motion(arg1, arg2, arg3):\n '''\n Short description of the function\n\n Args:\n argument 1: explain the format and content of the first argument\n argument 2: explain the format and content of the second argument\n argument 3: explain the format and content of the third argument\n\n Returns:\n what output does the function generate?\n\n Any further description?\n '''\n\n # structure your code into two functions: \"my_selfmotion\" and \"my_worldmotion\"\n # write comments outlining the operations to be performed on the inputs by each of these functions\n # use the elements from micro-tutorials 3, 4, and 5 (found in W1D2 Tutorial Part 1)\n # \n # \n # \n \n # what kind of output should this function produce?\n return output", "_____no_output_____" ] ], [ [ "We've completed the `my_perceived_motion()` function for you below. Follow this example to complete the template for `my_selfmotion()` and `my_worldmotion()`. Write out the inputs and outputs, and the steps required to calculate the outputs from the inputs.\n\n**Perceived motion function**", "_____no_output_____" ] ], [ [ "#Full perceived motion function\ndef my_perceived_motion(vis, ves, params):\n '''\n Takes sensory data and parameters and returns predicted percepts\n\n Args:\n vis (numpy.ndarray): 1xM array of optic flow velocity data\n ves (numpy.ndarray): 1xM array of vestibular acceleration data \n params: (dict) dictionary with named entries:\n see my_train_illusion_model() for details\n \n Returns:\n [list of floats]: prediction for perceived self-motion based on \n vestibular data, and prediction for perceived world-motion based on \n perceived self-motion and visual data\n '''\n\n # estimate self motion based on only the vestibular data\n # pass on the parameters\n selfmotion = my_selfmotion(ves=ves, \n params=params) \n \n # estimate the world motion, based on the selfmotion and visual data\n # pass on the parameters as well\n worldmotion = my_worldmotion(vis=vis, \n selfmotion=selfmotion, \n params=params)\n\n return [selfmotion, worldmotion]", "_____no_output_____" ] ], [ [ "**Template calculate self motion**\nPut notes in the function below that describe the inputs, the outputs, and steps that transform the output from the input using elements from micro-tutorials 3,4,5.", "_____no_output_____" ] ], [ [ "def my_selfmotion(arg1, arg2):\n '''\n Short description of the function\n\n Args:\n argument 1: explain the format and content of the first argument\n argument 2: explain the format and content of the second argument\n\n Returns:\n what output does the function generate?\n\n Any further description?\n '''\n\n # what operations do we perform on the input?\n # use the elements from micro-tutorials 3, 4, and 5\n # 1.\n # 2.\n # 3.\n # 4.\n \n\n # what output should this function produce?\n return output", "_____no_output_____" ] ], [ [ "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_181325a9.py)\n\n", "_____no_output_____" ], [ "**Template calculate world motion**\nPut notes in the function below that describe the inputs, the outputs, and steps that transform the output from the input using elements from micro-tutorials 3,4,5.", "_____no_output_____" ] ], [ [ "def my_worldmotion(arg1, arg2, arg3):\n '''\n Short description of the function\n\n Args:\n argument 1: explain the format and content of the first argument\n argument 2: explain the format and content of the second argument\n argument 3: explain the format and content of the third argument\n\n Returns:\n what output does the function generate?\n\n Any further description?\n '''\n\n # what operations do we perform on the input?\n # use the elements from micro-tutorials 3, 4, and 5\n # 1.\n # 2.\n # 3. \n\n # what output should this function produce?\n return output ", "_____no_output_____" ] ], [ [ "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_8f913582.py)\n\n", "_____no_output_____" ], [ "#Micro-tutorial 7 - implement model", "_____no_output_____" ] ], [ [ "#@title Video: implement the model\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='gtSOekY8jkw', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo", "Video available at https://youtube.com/watch?v=gtSOekY8jkw\n" ] ], [ [ "\n**Goal:** We write the components of the model in actual code.\n\nFor the operations we picked, there function ready to use:\n* integration: `np.cumsum(data, axis=1)` (axis=1: per trial and over samples)\n* filtering: `my_moving_window(data, window)` (window: int, default 3)\n* average: `np.mean(data)`\n* threshold: if (value > thr): <operation 1> else: <operation 2>\n\n", "_____no_output_____" ], [ "###**TD 7.1:** Write code to estimate self motion\n\nUse the operations to finish writing the function that will calculate an estimate of self motion. Fill in the descriptive list of items with actual operations. Use the function for estimating world-motion below, which we've filled for you!\n\n**Template finish self motion function**", "_____no_output_____" ] ], [ [ "def my_selfmotion(ves, params):\n '''\n Estimates self motion for one vestibular signal\n\n Args:\n ves (numpy.ndarray): 1xM array with a vestibular signal\n params (dict): dictionary with named entries:\n see my_train_illusion_model() for details\n\n Returns:\n (float): an estimate of self motion in m/s\n '''\n\n ###uncomment the code below and fill in with your code\n\n ## 1. integrate vestibular signal\n #ves = np.cumsum(ves*(1/params['samplingrate']))\n\n ## 2. running window function to accumulate evidence: \n #selfmotion = YOUR CODE HERE\n \n ## 3. take final value of self-motion vector as our estimate\n #selfmotion =\n\n ## 4. compare to threshold. Hint the threshodl is stored in params['threshold']\n ## if selfmotion is higher than threshold: return value\n ## if it's lower than threshold: return 0\n\n #if YOURCODEHERE\n #selfmotion = YOURCODHERE \n\n # comment this out when you've filled\n raise NotImplementedError(\"Student excercise: estimate my_selfmotion\")\n\n return output", "_____no_output_____" ] ], [ [ "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_3ea16348.py)\n\n", "_____no_output_____" ], [ "### Estimate world motion\n\nWe have completed the `my_worldmotion()` function for you.\n\n**World motion function**", "_____no_output_____" ] ], [ [ "# World motion function\ndef my_worldmotion(vis, selfmotion, params):\n '''\n Short description of the function\n\n Args:\n vis (numpy.ndarray): 1xM array with the optic flow signal\n selfmotion (float): estimate of self motion\n params (dict): dictionary with named entries:\n see my_train_illusion_model() for details\n\n Returns:\n (float): an estimate of world motion in m/s\n\n '''\n\n # running average to smooth/accumulate sensory evidence\n visualmotion = my_moving_window(vis, \n window=params['filterwindows'][1], \n FUN=np.mean)\n\n # take final value\n visualmotion = visualmotion[-1]\n \n # subtract selfmotion from value\n worldmotion = visualmotion + selfmotion\n\n # return final value\n return worldmotion", "_____no_output_____" ] ], [ [ "#Micro-tutorial 8 - completing the model", "_____no_output_____" ] ], [ [ "#@title Video: completing the model\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='-NiHSv4xCDs', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo", "Video available at https://youtube.com/watch?v=-NiHSv4xCDs\n" ] ], [ [ "\n**Goal:** Make sure the model can speak to the hypothesis. Eliminate all the parameters that do not speak to the hypothesis.\n\nNow that we have a working model, we can keep improving it, but at some point we need to decide that it is finished. Once we have a model that displays the properties of a system we are interested in, it should be possible to say something about our hypothesis and question. Keeping the model simple makes it easier to understand the phenomenon and answer the research question. Here that means that our model should have illusory perception, and perhaps make similar judgments to those of the participants, but not much more.\n\nTo test this, we will run the model, store the output and plot the models' perceived self motion over perceived world motion, like we did with the actual perceptual judgments (it even uses the same plotting function).", "_____no_output_____" ], [ "### **TD 8.1:** See if the model produces illusions", "_____no_output_____" ] ], [ [ "#@title Run to plot model predictions of motion estimates\n# prepare to run the model again:\ndata = {'opticflow':opticflow, 'vestibular':vestibular}\nparams = {'threshold':0.6, 'filterwindows':[100,50], 'FUN':np.mean}\nmodelpredictions = my_train_illusion_model(sensorydata=data, params=params)\n\n# process the data to allow plotting...\npredictions = np.zeros(judgments.shape)\npredictions[:,0:3] = judgments[:,0:3]\npredictions[:,3] = modelpredictions['selfmotion']\npredictions[:,4] = modelpredictions['worldmotion'] *-1\nmy_plot_percepts(datasets={'predictions':predictions}, plotconditions=True)", "_____no_output_____" ] ], [ [ "**Questions:**\n\n* Why is the data distributed this way? How does it compare to the plot in TD 1.2?\n* Did you expect to see this?\n* Where do the model's predicted judgments for each of the two conditions fall?\n* How does this compare to the behavioral data?\n\nHowever, the main observation should be that **there are illusions**: the blue and red data points are mixed in each of the two sets of data. Does this mean the model can help us understand the phenomenon?", "_____no_output_____" ], [ "#Micro-tutorial 9 - testing and evaluating the model", "_____no_output_____" ] ], [ [ "#@title Video: Background\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='5vnDOxN3M_k', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo", "Video available at https://youtube.com/watch?v=5vnDOxN3M_k\n" ] ], [ [ "\n**Goal:** Once we have finished the model, we need a description of how good it is. The question and goals we set in micro-tutorial 1 and 4 help here. There are multiple ways to evaluate a model. Aside from the obvious fact that we want to get insight into the phenomenon that is not directly accessible without the model, we always want to quantify how well the model agrees with the data.\n", "_____no_output_____" ], [ "### Quantify model quality with $R^2$\n\nLet's look at how well our model matches the actual judgment data.", "_____no_output_____" ] ], [ [ "#@title Run to plot predictions over data\nmy_plot_predictions_data(judgments, predictions)", "_____no_output_____" ] ], [ [ "When model predictions are correct, the red points in the figure above should lie along the identity line (a dotted black line here). Points off the identity line represent model prediction errors. While in each plot we see two clusters of dots that are fairly close to the identity line, there are also two clusters that are not. For the trials that those points represent, the model has an illusion while the participants don't or vice versa.\n\nWe will use a straightforward, quantitative measure of how good the model is: $R^2$ (pronounced: \"R-squared\"), which can take values between 0 and 1, and expresses how much variance is explained by the relationship between two variables (here the model's predictions and the actual judgments). It is also called [coefficient of determination](https://en.wikipedia.org/wiki/Coefficient_of_determination), and is calculated here as the square of the correlation coefficient (r or $\\rho$). Just run the chunk below:", "_____no_output_____" ] ], [ [ "#@title Run to calculate R^2\nconditions = np.concatenate((np.abs(judgments[:,1]),np.abs(judgments[:,2])))\nveljudgmnt = np.concatenate((judgments[:,3],judgments[:,4]))\nvelpredict = np.concatenate((predictions[:,3],predictions[:,4]))\n\nslope, intercept, r_value, p_value, std_err = sp.stats.linregress(conditions,veljudgmnt)\nprint('conditions -> judgments R^2: %0.3f'%( r_value**2 ))\n\nslope, intercept, r_value, p_value, std_err = sp.stats.linregress(veljudgmnt,velpredict)\nprint('predictions -> judgments R^2: %0.3f'%( r_value**2 ))\n", "conditions -> judgments R^2: 0.032\npredictions -> judgments R^2: 0.256\n" ] ], [ [ "These $R^2$s express how well the experimental conditions explain the participants judgments and how well the models predicted judgments explain the participants judgments.\n\nYou will learn much more about model fitting, quantitative model evaluation and model comparison tomorrow!\n\nPerhaps the $R^2$ values don't seem very impressive, but the judgments produced by the participants are explained by the model's predictions better than by the actual conditions. In other words: the model tends to have the same illusions as the participants.", "_____no_output_____" ], [ "### **TD 9.1** Varying the threshold parameter to improve the model\n\nIn the code below, see if you can find a better value for the threshold parameter, to reduce errors in the models' predictions.\n\n**Testing thresholds**", "_____no_output_____" ] ], [ [ "# Testing thresholds\ndef test_threshold(threshold=0.33):\n \n # prepare to run model\n data = {'opticflow':opticflow, 'vestibular':vestibular}\n params = {'threshold':threshold, 'filterwindows':[100,50], 'FUN':np.mean}\n modelpredictions = my_train_illusion_model(sensorydata=data, params=params)\n\n # get predictions in matrix\n predictions = np.zeros(judgments.shape)\n predictions[:,0:3] = judgments[:,0:3]\n predictions[:,3] = modelpredictions['selfmotion']\n predictions[:,4] = modelpredictions['worldmotion'] *-1\n\n # get percepts from participants and model\n conditions = np.concatenate((np.abs(judgments[:,1]),np.abs(judgments[:,2])))\n veljudgmnt = np.concatenate((judgments[:,3],judgments[:,4]))\n velpredict = np.concatenate((predictions[:,3],predictions[:,4]))\n\n # calculate R2\n slope, intercept, r_value, p_value, std_err = sp.stats.linregress(veljudgmnt,velpredict)\n print('predictions -> judgments R2: %0.3f'%( r_value**2 ))\n\n\ntest_threshold(threshold=0.5) ", "predictions -> judgments R2: 0.267\n" ] ], [ [ "### **TD 9.2:** Credit assigmnent of self motion\n\nWhen we look at the figure in **TD 8.1**, we can see a cluster does seem very close to (1,0), just like in the actual data. The cluster of points at (1,0) are from the case where we conclude there is no self motion, and then set the self motion to 0. That value of 0 removes a lot of noise from the world-motion estimates, and all noise from the self-motion estimate. In the other case, where there is self motion, we still have a lot of noise (see also micro-tutorial 4).\n\nLet's change our `my_selfmotion()` function to return a self motion of 1 when the vestibular signal indicates we are above threshold, and 0 when we are below threshold. Edit the function here.\n\n**Template function for credit assigment of self motion**\n", "_____no_output_____" ] ], [ [ "# Template binary self-motion estimates\ndef my_selfmotion(ves, params):\n '''\n Estimates self motion for one vestibular signal\n\n Args:\n ves (numpy.ndarray): 1xM array with a vestibular signal\n params (dict): dictionary with named entries:\n see my_train_illusion_model() for details\n\n Returns:\n (float): an estimate of self motion in m/s\n '''\n\n # integrate signal:\n ves = np.cumsum(ves*(1/params['samplingrate']))\n \n # use running window to accumulate evidence:\n selfmotion = my_moving_window(ves, \n window=params['filterwindows'][0], \n FUN=params['FUN'])\n \n ## take the final value as our estimate:\n selfmotion = selfmotion[-1]\n\n ##########################################\n # this last part will have to be changed\n # compare to threshold, set to 0 if lower and else...\n if selfmotion < params['threshold']:\n selfmotion = 0 \n\n #uncomment the lines below and fill in with your code\n #else:\n #YOUR CODE HERE\n\n # comment this out when you've filled\n raise NotImplementedError(\"Student excercise: modify with credit assignment\")\n\n return selfmotion", "_____no_output_____" ] ], [ [ "[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D2_ModelingPractice/solutions/W1D2_Tutorial2_Solution_90571e21.py)\n\n", "_____no_output_____" ], [ "The function you just wrote will be used when we run the model again below.", "_____no_output_____" ] ], [ [ "#@title Run model credit assigment of self motion\n# prepare to run the model again:\ndata = {'opticflow':opticflow, 'vestibular':vestibular}\nparams = {'threshold':0.33, 'filterwindows':[100,50], 'FUN':np.mean}\nmodelpredictions = my_train_illusion_model(sensorydata=data, params=params)\n\n# no process the data to allow plotting...\npredictions = np.zeros(judgments.shape)\npredictions[:,0:3] = judgments[:,0:3]\npredictions[:,3] = modelpredictions['selfmotion']\npredictions[:,4] = modelpredictions['worldmotion'] *-1\nmy_plot_percepts(datasets={'predictions':predictions}, plotconditions=False)", "_____no_output_____" ] ], [ [ "That looks much better, and closer to the actual data. Let's see if the $R^2$ values have improved:", "_____no_output_____" ] ], [ [ "#@title Run to calculate R^2 for model with self motion credit assignment\nconditions = np.concatenate((np.abs(judgments[:,1]),np.abs(judgments[:,2])))\nveljudgmnt = np.concatenate((judgments[:,3],judgments[:,4]))\nvelpredict = np.concatenate((predictions[:,3],predictions[:,4]))\n\nmy_plot_predictions_data(judgments, predictions)\n\nslope, intercept, r_value, p_value, std_err = sp.stats.linregress(conditions,veljudgmnt)\nprint('conditions -> judgments R2: %0.3f'%( r_value**2 ))\n\nslope, intercept, r_value, p_value, std_err = sp.stats.linregress(velpredict,veljudgmnt)\nprint('predictions -> judgments R2: %0.3f'%( r_value**2 ))", "_____no_output_____" ] ], [ [ "While the model still predicts velocity judgments better than the conditions (i.e. the model predicts illusions in somewhat similar cases), the $R^2$ values are actually worse than those of the simpler model. What's really going on is that the same set of points that were model prediction errors in the previous model are also errors here. All we have done is reduce the spread.", "_____no_output_____" ], [ "### Interpret the model's meaning\n\nHere's what you should have learned: \n\n1. A noisy, vestibular, acceleration signal can give rise to illusory motion.\n2. However, disambiguating the optic flow by adding the vestibular signal simply adds a lot of noise. This is not a plausible thing for the brain to do.\n3. Our other hypothesis - credit assignment - is more qualitatively correct, but our simulations were not able to match the frequency of the illusion on a trial-by-trial basis.\n\n_It's always possible to refine our models to improve the fits._\n\nThere are many ways to try to do this. A few examples; we could implement a full sensory cue integration model, perhaps with Kalman filters (Week 2, Day 3), or we could add prior knowledge (at what time do the trains depart?). However, we decided that for now we have learned enough, so it's time to write it up.\n", "_____no_output_____" ], [ "# Micro-tutorial 10 - publishing the model", "_____no_output_____" ] ], [ [ "#@title Video: Background\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id='kf4aauCr5vA', width=854, height=480, fs=1)\nprint(\"Video available at https://youtube.com/watch?v=\" + video.id)\nvideo", "Video available at https://youtube.com/watch?v=kf4aauCr5vA\n" ] ], [ [ "\n**Goal:** In order for our model to impact the field, it needs to be accepted by our peers, and order for that to happen it matters how the model is published.", "_____no_output_____" ], [ "### **TD 10.1:** Write a summary of the project\n\nHere we will write up our model, by answering the following questions:\n* **What is the phenomena**? Here summarize the part of the phenomena which your model addresses.\n* **What is the key scientific question?**: Clearly articulate the question which your model tries to answer.\n* **What was our hypothesis?**: Explain the key relationships which we relied on to simulate the phenomena.\n* **How did your model work?** Give an overview of the model, it's main components, and how the model works. ''Here we ... ''\n* **What did we find? Did the model work?** Explain the key outcomes of your model evaluation. \n* **What can we conclude?** Conclude as much as you can _with reference to the hypothesis_, within the limits of the model. \n* **What did you learn? What is left to be learned?** Briefly argue the plausibility of the approach and what you think is _essential_ that may have been left out.\n\n### Guidance for the future\nThere are good guidelines for structuring and writing an effective paper (e.g. [Mensh & Kording, 2017](https://doi.org/10.1371/journal.pcbi.1005619)), all of which apply to papers about models. There are some extra considerations when publishing a model. In general, you should explain each of the steps in the paper:\n\n**Introduction:** Steps 1 & 2 (maybe 3)\n\n**Methods:** Steps 3-7, 9\n\n**Results:** Steps 8 & 9, going back to 1, 2 & 4\n\nIn addition, you should provide a visualization of the model, and upload the code implementing the model and the data it was trained and tested on to a repository (e.g. GitHub and OSF).\n\nThe audience for all of this should be experimentalists, as they are the ones who can test predictions made by your your model and collect new data. This way your models can impact future experiments, and that future data can then be modeled (see modeling process schematic below). Remember your audience - it is _always_ hard to clearly convey the main points of your work to others, especially if your audience doesn't necessarily create computational models themselves.\n\n![how-to-model process from Blohm et al 2019](https://deniseh.lab.yorku.ca/files/2020/06/HowToModel-ENEURO.0352-19.2019.full_.pdf.png)\n\n### Suggestion\n\nFor every modeling project, a very good exercise in this is to _**first**_ write a short, 100-word abstract of the project plan and expected impact, like the summary you wrote. This forces focussing on the main points: describing the relevance, question, model, answer and what it all means very succinctly. This allows you to decide to do this project or not **before you commit time writing code for no good purpose**. Notice that this is really what we've walked you through carefully in this tutorial! :)\n", "_____no_output_____" ], [ "# Post-script\n\nNote that the model we built here was extremely simple and used artificial data on purpose. It allowed us to go through all the steps of building a model, and hopefully you noticed that it is not always a linear process, you will go back to different steps if you hit a roadblock somewhere.\n\nHowever, if you're interested in how to actually approach modeling a similar phenomenon in a probabilistic way, we encourage you to read the paper by [Dokka et. al., 2019](https://doi.org/10.1073/pnas.1820373116), where the authors model how judgments of heading direction are influenced by objects that are also moving.", "_____no_output_____" ], [ "# Reading\n\nBlohm G, Kording KP, Schrater PR (2020). _A How-to-Model Guide for Neuroscience_ eNeuro, 7(1) ENEURO.0352-19.2019. https://doi.org/10.1523/ENEURO.0352-19.2019 \n\nDokka K, Park H, Jansen M, DeAngelis GC, Angelaki DE (2019). _Causal inference accounts for heading perception in the presence of object motion._ PNAS, 116(18):9060-9065. https://doi.org/10.1073/pnas.1820373116\n\nDrugowitsch J, DeAngelis GC, Klier EM, Angelaki DE, Pouget A (2014). _Optimal Multisensory Decision-Making in a Reaction-Time Task._ eLife, 3:e03005. https://doi.org/10.7554/eLife.03005\n\nHartmann, M, Haller K, Moser I, Hossner E-J, Mast FW (2014). _Direction detection thresholds of passive self-motion in artistic gymnasts._ Exp Brain Res, 232:1249–1258. https://doi.org/10.1007/s00221-014-3841-0\n\nMensh B, Kording K (2017). _Ten simple rules for structuring papers._ PLoS Comput Biol 13(9): e1005619. https://doi.org/10.1371/journal.pcbi.1005619\n\nSeno T, Fukuda H (2012). _Stimulus Meanings Alter Illusory Self-Motion (Vection) - Experimental Examination of the Train Illusion._ Seeing Perceiving, 25(6):631-45. https://doi.org/10.1163/18784763-00002394\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" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
d030ca9868272de8095b11665797c69a1829e8bf
9,490
ipynb
Jupyter Notebook
nbs/index.ipynb
isabella232/nbdev
682ef97d86a451d24ff7ec67d4624ddf1c8c9820
[ "Apache-2.0" ]
null
null
null
nbs/index.ipynb
isabella232/nbdev
682ef97d86a451d24ff7ec67d4624ddf1c8c9820
[ "Apache-2.0" ]
1
2021-02-23T22:53:25.000Z
2021-02-23T22:53:25.000Z
nbs/index.ipynb
isabella232/nbdev
682ef97d86a451d24ff7ec67d4624ddf1c8c9820
[ "Apache-2.0" ]
null
null
null
50.21164
540
0.679874
[ [ [ "# Welcome to nbdev\n> Create delightful python projects using Jupyter Notebooks\n\n- image:images/nbdev_source.gif", "_____no_output_____" ], [ "`nbdev` is a library that allows you to develop a python library in [Jupyter Notebooks](https://jupyter.org/), putting all your code, tests and documentation in one place. That is: you now have a true [literate programming](https://en.wikipedia.org/wiki/Literate_programming) environment, as envisioned by Donald Knuth back in 1983!\n\n`nbdev` makes debugging and refactor your code much easier relative to traditional programming environments. Furthermore, using nbdev promotes software engineering best practices because tests and documentation are first class citizens. ", "_____no_output_____" ], [ "## Features of Nbdev\n\n`nbdev` provides the following tools for developers:\n\n- **Automatically generate docs** from Jupyter notebooks. These docs are searchable and automatically hyperlinked to appropriate documentation pages by introspecting keywords you surround in backticks.\n- Utilities to **automate the publishing of pypi and conda packages** including version number management.\n- A robust, **two-way sync between notebooks and source code**, which allow you to use your IDE for code navigation or quick edits if desired.\n- **Fine-grained control on hiding/showing cells**: you can choose to hide entire cells, just the output, or just the input. Furthermore, you can embed cells in collapsible elements that are open or closed by default.\n- Ability to **write tests directly in notebooks** without having to learn special APIs. These tests get executed in parallel with a single CLI command. You can even define certain groups of tests such that you don't have to always run long-running tests. \n- Tools for **merge/conflict resolution** with notebooks in a **human readable format**.\n- **Continuous integration (CI) comes setup for you with [GitHub Actions](https://github.com/features/actions)** out of the box, that will run tests automatically for you. Even if you are not familiar with CI or GitHub Actions, this starts working right away for you without any manual intervention.\n- **Integration With GitHub Pages for docs hosting**: nbdev allows you to easily host your documentation for free, using GitHub pages.\n- Create Python modules, following **best practices such as automatically defining `__all__`** ([more details](http://xion.io/post/code/python-all-wild-imports.html)) with your exported functions, classes, and variables.\n- **Math equation support** with LaTeX.\n- ... and much more! See the [Getting Started](https://nbdev.fast.ai/#Getting-Started) section below for more information.", "_____no_output_____" ], [ "## A Motivating Example\n\nFor example, lets define a class that represents a playing card, with associated docs and tests in a Jupyter Notebook:\n\n![image.png](images/att_00027.png)\n\nIn the above screenshot, we have code, tests and documentation in one context! `nbdev` renders this into searchable docs (which are optionally hosted for free on GitHub Pages). Below is an annotated screenshot of the generated docs for further explanation:\n\n![image.png](images/att_00016.png)\n\nThe above illustration is a subset of [this nbdev tutorial with a minimal example](https://nbdev.fast.ai/example.html), which uses code from [Think Python 2](https://github.com/AllenDowney/ThinkPython2) by Allen Downey.\n\n### Explanation of annotations:\n\n1. The heading **Card** corresponds to the first `H1` heading in a notebook with a note block _API Details_ as the summary.\n2. `nbdev` automatically renders a Table of Contents for you.\n3. `nbdev` automatically renders the signature of your class or function as a heading. \n4. The cells where your code is defined will be hidden and replaced by standardized documentation of your function, showing its name, arguments, docstring, and link to the source code on github.\n5. This part of docs is rendered automatically from the docstring.\n6. The rest of the notebook is rendered as usual. You can hide entire cells, hide only cell input or hide only output by using the [flags described on this page](https://nbdev.fast.ai/export2html.html).\n7. nbdev supports special block quotes that render as colored boxes in the documentation. You can read more about them [here](https://nbdev.fast.ai/export2html.html#add_jekyll_notes). In this specific example, we are using the `Note` block quote. \n8. Words you surround in backticks will be automatically hyperlinked to the associated documentation where appropriate. This is a trivial case where `Card` class is defined immediately above, however this works across pages and modules. We will see another example of this in later steps.", "_____no_output_____" ], [ "## Installing", "_____no_output_____" ], [ "nbdev is on PyPI and conda so you can just run `pip install nbdev` or `conda install -c fastai nbdev`.\n\nFor an [editable install](https://stackoverflow.com/questions/35064426/when-would-the-e-editable-option-be-useful-with-pip-install), use the following:\n```\ngit clone https://github.com/fastai/nbdev\npip install -e nbdev\n```\n\n_Note that `nbdev` must be installed into the same python environment that you use for both your Jupyter Server and your workspace._", "_____no_output_____" ], [ "## Getting Started\n\nThe following are helpful resources for getting started with nbdev:\n\n- The [tutorial](https://nbdev.fast.ai/tutorial.html).\n- A [minimal, end-to-end example](https://nbdev.fast.ai/example.html) of using nbdev. We suggest replicating this example after reading through the tutorial to solidify your understanding.\n- The [docs](https://nbdev.fast.ai/).\n- [release notes](https://github.com/fastai/nbdev/blob/master/CHANGELOG.md).\n\n\n## If Someone Tells You That You Shouldn't Use Notebooks For Software Development\n\n[Watch this video](https://youtu.be/9Q6sLbz37gk).", "_____no_output_____" ], [ "## Contributing", "_____no_output_____" ], [ "If you want to contribute to `nbdev`, be sure to review the [contributions guidelines](https://github.com/fastai/nbdev/blob/master/CONTRIBUTING.md). This project adheres to fastai`s [code of conduct](https://github.com/fastai/nbdev/blob/master/CODE-OF-CONDUCT.md). By participating, you are expected to uphold this code. In general, the fastai project strives to abide by generally accepted best practices in open-source software development.\n\nMake sure you have the git hooks we use installed by running\n```\nnbdev_install_git_hooks\n```\nin the cloned repository folder. ", "_____no_output_____" ], [ "## Copyright", "_____no_output_____" ], [ "Copyright 2019 onwards, fast.ai, Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this project's files except in compliance with the License. A copy of the License is provided in the LICENSE file in this repository.", "_____no_output_____" ], [ "## Appendix\n\n### nbdev and fastai", "_____no_output_____" ], [ "`nbdev` has been used to build innovative software used by many developers, such as [fastai](https://docs.fast.ai/), a deep learning library which implements a [unique layered api and callback system](https://arxiv.org/abs/2002.04688), and [fastcore](https://fastcore.fast.ai/), an extension to the Python programming language. Furthermore, `nbdev` allows a very small number of developers to maintain and grow a [large ecosystem](https://github.com/fastai) of software engineering, data science, machine learning and devops tools.\n\nHere, for instance, is how `combined_cos` is defined and documented in the `fastai` library:", "_____no_output_____" ], [ "<img alt=\"Exporting from nbdev\" width=\"700\" caption=\"An example of a function defined in one cell (marked with the export flag) and explained, along with a visual example, in the following cells\" src=\"images/export_example.png\" />", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d030cc2ad22fdb5a2d0bcd18fb25332abec4a7b1
2,946
ipynb
Jupyter Notebook
Courses/study-path-and-where-to-find-resources.ipynb
AIwaffle/AIwaffle
9d7373de4810ea7330d581970a55645999c5064c
[ "MIT" ]
2
2020-03-04T13:51:32.000Z
2020-04-30T22:58:20.000Z
Courses/study-path-and-where-to-find-resources.ipynb
AIwaffle/AIwaffle
9d7373de4810ea7330d581970a55645999c5064c
[ "MIT" ]
4
2020-03-27T15:04:58.000Z
2021-11-05T07:59:36.000Z
Courses/study-path-and-where-to-find-resources.ipynb
AIwaffle/AIwaffle
9d7373de4810ea7330d581970a55645999c5064c
[ "MIT" ]
1
2020-05-31T12:47:52.000Z
2020-05-31T12:47:52.000Z
1,473
2,945
0.761711
[ [ [ "# Study Path And Where To Find Resources\n**Author: Yulun Wu** \n\nWelcome aboard! \nAI is one of the most prospective fields today. Personally I believe AI technology will start a technology revolution and totally revamp the world as well as our lives.\nThe definition of AI is broad, in AIwaffle Courses, *AI*, *Machine Learning*, *Deep Learning* means similar things, since deep learning is the mostly focused subfield in ML, which is the basis of AI technology.\nTo get started in Machine Learning, there is some basic skills you should acquire. \n## Python\nIf you don't know what is this, why are you reading? Go learn it first!\n## Linear Algebra: vectors, matrix multiplication\nThe AIwaffle Courses only require a subset of linear algebra. \nIf you know vectors and matrix multiplication, you are good to go. \n\nUseful resources: \nhttps://www.khanacademy.org/math/linear-algebra \nhttps://brilliant.org/wiki/matrices/ \n## Calculus: partial derivitives, gradients\nThat's all you need for now. \n\nUseful resources: \nhttps://www.khanacademy.org/math/multivariable-calculus \nhttps://brilliant.org/wiki/partial-derivatives/\n## Libraries for ML\n**Must**: [Numpy](https://numpy.org/), [Pytorch](https://pytorch.org/) \nGraphing library like: [Matplotlib](https://matplotlib.org/) or its high-level API [Seaborn](http://seaborn.pydata.org/index.html) or others. \n\nRemember: You don't have to be proficient at them. \nThe AIwaffle Courses will also lead you through Pytorch. The best is: if you are good at self-studying, skip AIwaffle Course 2-7 by going to pytorch.org\n## Other Useful Resources\nVideos from 3b1b - Make sure to watch them before you start an AIwaffle Course! These videos give you an intuitive understanding on *Neural Networks* and *Deep Learning*. \n[Youtube](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi) | [bilibili](https://space.bilibili.com/88461692/channel/detail?cid=26587)\n\n[Google Machine Learning Glossary](https://developers.google.com/machine-learning/glossary/) for you geeks\n\n[A lot of ML Cheat Sheets](https://becominghuman.ai/cheat-sheets-for-ai-neural-networks-machine-learning-deep-learning-big-data-science-pdf-f22dc900d2d7): Most of them are useless. Use at your own risk.\n\n## Where to ask questions\nCreate an issue in our [Github repo](https://github.com/AIwaffle/AIwaffle) \nAsk in our Forum: TBD \nSend an email to lunw1024@gmail.com \n\nEnough talk, jump into the next AIwaffle Course **Pytorch: Tensor Manipulation** to get your hands dirty!", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
d030d06560a15709c4cd7e3a3cb7fcd263173d79
21,444
ipynb
Jupyter Notebook
nbs/05_merge.ipynb
aviadr1/nbdev
2a097011437cf0c447c216bd56aa84b3489e5331
[ "Apache-2.0" ]
null
null
null
nbs/05_merge.ipynb
aviadr1/nbdev
2a097011437cf0c447c216bd56aa84b3489e5331
[ "Apache-2.0" ]
null
null
null
nbs/05_merge.ipynb
aviadr1/nbdev
2a097011437cf0c447c216bd56aa84b3489e5331
[ "Apache-2.0" ]
null
null
null
31.259475
932
0.497575
[ [ [ "from nbdev import *\n%nbdev_default_export merge", "Cells will be exported to nbdev.merge,\nunless a different module is specified after an export flag: `%nbdev_export special.module`\n" ], [ "#export\nfrom nbdev.imports import *", "_____no_output_____" ] ], [ [ "# Fix merge conflicts\n\n> Fix merge conflicts in jupyter notebooks", "_____no_output_____" ], [ "When working with jupyter notebooks (which are json files behind the scenes) and GitHub, it is very common that a merge conflict (that will add new lines in the notebook source file) will break some notebooks you are working on. This module defines the function `fix_conflicts` to fix those notebooks for you, and attempt to automatically merge standard conflicts. The remaining ones will be delimited by markdown cells like this:", "_____no_output_____" ], [ "<img alt=\"Fixed notebook\" width=\"700\" caption=\"A notebook fixed after a merged conflict. The file couldn't be opened before the command was run, but after it the conflict is higlighted by markdown cells.\" src=\"images/merge.PNG\" />", "_____no_output_____" ], [ "## Walk cells", "_____no_output_____" ] ], [ [ "#hide\ntst_nb=\"\"\"{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n<<<<<<< HEAD\n \"execution_count\": 6,\n \"metadata\": {},\n \"outputs\": [\n {\n \"data\": {\n \"text/plain\": [\n \"3\"\n ]\n },\n \"execution_count\": 6,\n \"metadata\": {},\n \"output_type\": \"execute_result\"\n }\n ],\n \"source\": [\n \"z=3\\n\",\n \"z\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": 7,\n=======\n \"execution_count\": 5,\n>>>>>>> a7ec1b0bfb8e23b05fd0a2e6cafcb41cd0fb1c35\n \"metadata\": {},\n \"outputs\": [\n {\n \"data\": {\n \"text/plain\": [\n \"6\"\n ]\n },\n<<<<<<< HEAD\n \"execution_count\": 7,\n=======\n \"execution_count\": 5,\n>>>>>>> a7ec1b0bfb8e23b05fd0a2e6cafcb41cd0fb1c35\n \"metadata\": {},\n \"output_type\": \"execute_result\"\n }\n ],\n \"source\": [\n \"x=3\\n\",\n \"y=3\\n\",\n \"x+y\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"Python 3\",\n \"language\": \"python\",\n \"name\": \"python3\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\"\"\"", "_____no_output_____" ] ], [ [ "This is an example of broken notebook we defined in `tst_nb`. The json format is broken by the lines automatically added by git. Such a file can't be opened again in jupyter notebook, leaving the user with no other choice than to fix the text file manually.", "_____no_output_____" ] ], [ [ "print(tst_nb)", "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n<<<<<<< HEAD\n \"execution_count\": 6,\n \"metadata\": {},\n \"outputs\": [\n {\n \"data\": {\n \"text/plain\": [\n \"3\"\n ]\n },\n \"execution_count\": 6,\n \"metadata\": {},\n \"output_type\": \"execute_result\"\n }\n ],\n \"source\": [\n \"z=3\n\",\n \"z\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": 7,\n=======\n \"execution_count\": 5,\n>>>>>>> a7ec1b0bfb8e23b05fd0a2e6cafcb41cd0fb1c35\n \"metadata\": {},\n \"outputs\": [\n {\n \"data\": {\n \"text/plain\": [\n \"6\"\n ]\n },\n<<<<<<< HEAD\n \"execution_count\": 7,\n=======\n \"execution_count\": 5,\n>>>>>>> a7ec1b0bfb8e23b05fd0a2e6cafcb41cd0fb1c35\n \"metadata\": {},\n \"output_type\": \"execute_result\"\n }\n ],\n \"source\": [\n \"x=3\n\",\n \"y=3\n\",\n \"x+y\"\n ]\n },\n {\n \"cell_type\": \"code\",\n \"execution_count\": null,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": []\n }\n ],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"Python 3\",\n \"language\": \"python\",\n \"name\": \"python3\"\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n" ] ], [ [ "Note that in this example, the second conflict is easily solved: it just concerns the execution count of the second cell and can be solved by choosing either option without really impacting your notebook. This is the kind of conflicts `fix_conflicts` will (by default) fix automatically. The first conflict is more complicated as it spans across two cells and there is a cell present in one version, not the other. Such a conflict (and generally the ones where the inputs of the cells change form one version to the other) aren't automatically fixed, but `fix_conflicts` will return a proper json file where the annotations introduced by git will be placed in markdown cells.\n\nThe first step to do this is to walk the raw text file to extract the cells. We can't read it as a JSON since it's broken, so we have to parse the text.", "_____no_output_____" ] ], [ [ "#export\ndef extract_cells(raw_txt):\n \"Manually extract cells in potential broken json `raw_txt`\"\n lines = raw_txt.split('\\n')\n cells = []\n i = 0\n while not lines[i].startswith(' \"cells\"'): i+=1\n i += 1\n start = '\\n'.join(lines[:i])\n while lines[i] != ' ],':\n while lines[i] != ' {': i+=1\n j = i\n while not lines[j].startswith(' }'): j+=1\n c = '\\n'.join(lines[i:j+1])\n if not c.endswith(','): c = c + ','\n cells.append(c)\n i = j+1\n end = '\\n'.join(lines[i:])\n return start,cells,end", "_____no_output_____" ] ], [ [ "This function returns the beginning of the text (before the cells are defined), the list of cells and the end of the text (after the cells are defined).", "_____no_output_____" ] ], [ [ "start,cells,end = extract_cells(tst_nb)\ntest_eq(len(cells), 3)\ntest_eq(cells[0], \"\"\" {\n \"cell_type\": \"code\",\n<<<<<<< HEAD\n \"execution_count\": 6,\n \"metadata\": {},\n \"outputs\": [\n {\n \"data\": {\n \"text/plain\": [\n \"3\"\n ]\n },\n \"execution_count\": 6,\n \"metadata\": {},\n \"output_type\": \"execute_result\"\n }\n ],\n \"source\": [\n \"z=3\\n\",\n \"z\"\n ]\n },\"\"\")", "_____no_output_____" ], [ "#hide\n#Test the whole text is there\n#We add a , to the last cell (because we might add some after for merge conflicts at the end, so we need to remove it)\ntest_eq(tst_nb, '\\n'.join([start] + cells[:-1] + [cells[-1][:-1]] + [end]))", "_____no_output_____" ] ], [ [ "When walking the broken cells, we will add conflicts marker before and after the cells with conflicts as markdown cells. To do that we use this function.", "_____no_output_____" ] ], [ [ "#export\ndef get_md_cell(txt):\n \"A markdown cell with `txt`\"\n return ''' {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"''' + txt + '''\"\n ]\n },'''", "_____no_output_____" ], [ "tst = ''' {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n \"A bit of markdown\"\n ]\n },'''\nassert get_md_cell(\"A bit of markdown\") == tst", "_____no_output_____" ], [ "#export\nconflicts = '<<<<<<< ======= >>>>>>>'.split()", "_____no_output_____" ], [ "#export\ndef _split_cell(cell, cf, names):\n \"Split `cell` between `conflicts` given state in `cf`, save `names` of branches if seen\"\n res1,res2 = [],[]\n for line in cell.split('\\n'):\n if line.startswith(conflicts[cf]):\n if names[cf//2] is None: names[cf//2] = line[8:]\n cf = (cf+1)%3\n continue\n if cf<2: res1.append(line)\n if cf%2==0: res2.append(line)\n return '\\n'.join(res1),'\\n'.join(res2),cf,names", "_____no_output_____" ], [ "#hide\ntst = '\\n'.join(['a', f'{conflicts[0]} HEAD', 'b', conflicts[1], 'c', f'{conflicts[2]} lala', 'd'])\nv1,v2,cf,names = _split_cell(tst, 0, [None,None])\nassert v1 == 'a\\nb\\nd'\nassert v2 == 'a\\nc\\nd'\nassert cf == 0\nassert names == ['HEAD', 'lala']", "_____no_output_____" ], [ "#hide\ntst = '\\n'.join(['a', f'{conflicts[0]} HEAD', 'b', conflicts[1], 'c', f'{conflicts[2]} lala', 'd', f'{conflicts[0]} HEAD', 'e'])\nv1,v2,cf,names = _split_cell(tst, 0, [None,None])\nassert v1 == 'a\\nb\\nd\\ne'\nassert v2 == 'a\\nc\\nd'\nassert cf == 1\nassert names == ['HEAD', 'lala']", "_____no_output_____" ], [ "#hide\ntst = '\\n'.join(['a', f'{conflicts[0]} HEAD', 'b', conflicts[1], 'c', f'{conflicts[2]} lala', 'd', f'{conflicts[0]} HEAD', 'e', conflicts[1]])\nv1,v2,cf,names = _split_cell(tst, 0, [None,None])\nassert v1 == 'a\\nb\\nd\\ne'\nassert v2 == 'a\\nc\\nd'\nassert cf == 2\nassert names == ['HEAD', 'lala']", "_____no_output_____" ], [ "#hide\ntst = '\\n'.join(['b', conflicts[1], 'c', f'{conflicts[2]} lala', 'd'])\nv1,v2,cf,names = _split_cell(tst, 1, ['HEAD',None])\nassert v1 == 'b\\nd'\nassert v2 == 'c\\nd'\nassert cf == 0\nassert names == ['HEAD', 'lala']", "_____no_output_____" ], [ "#hide\ntst = '\\n'.join(['c', f'{conflicts[2]} lala', 'd'])\nv1,v2,cf,names = _split_cell(tst, 2, ['HEAD',None])\nassert v1 == 'd'\nassert v2 == 'c\\nd'\nassert cf == 0\nassert names == ['HEAD', 'lala']", "_____no_output_____" ], [ "#export\n_re_conflict = re.compile(r'^<<<<<<<', re.MULTILINE)", "_____no_output_____" ], [ "#hide\nassert _re_conflict.search('a\\nb\\nc') is None\nassert _re_conflict.search('a\\n<<<<<<<\\nc') is not None", "_____no_output_____" ], [ "#export\ndef same_inputs(t1, t2):\n \"Test if the cells described in `t1` and `t2` have the same inputs\"\n if len(t1)==0 or len(t2)==0: return False\n try:\n c1,c2 = json.loads(t1[:-1]),json.loads(t2[:-1])\n return c1['source']==c2['source']\n except Exception as e: return False", "_____no_output_____" ], [ "ts = [''' {\n \"cell_type\": \"code\",\n \"source\": [\n \"'''+code+'''\"\n ]\n },''' for code in [\"a=1\", \"b=1\", \"a=1\"]]\nassert same_inputs(ts[0],ts[2])\nassert not same_inputs(ts[0], ts[1])", "_____no_output_____" ], [ "#export\ndef analyze_cell(cell, cf, names, prev=None, added=False, fast=True, trust_us=True):\n \"Analyze and solve conflicts in `cell`\"\n if cf==0 and _re_conflict.search(cell) is None: return cell,cf,names,prev,added\n old_cf = cf\n v1,v2,cf,names = _split_cell(cell, cf, names)\n if fast and same_inputs(v1,v2):\n if old_cf==0 and cf==0: return (v2 if trust_us else v1),cf,names,prev,added\n v1,v2 = (v2,v2) if trust_us else (v1,v1)\n res = []\n if old_cf == 0:\n added=True\n res.append(get_md_cell(f'`{conflicts[0]} {names[0]}`'))\n res.append(v1)\n if cf ==0:\n res.append(get_md_cell(f'`{conflicts[1]}`'))\n if prev is not None: res += prev\n res.append(v2)\n res.append(get_md_cell(f'`{conflicts[2]} {names[1]}`'))\n prev = None\n else: prev = [v2] if prev is None else prev + [v2]\n return '\\n'.join([r for r in res if len(r) > 0]),cf,names,prev,added", "_____no_output_____" ] ], [ [ "This is the main function used to walk through the cells of a notebook. `cell` is the cell we're at, `cf` the conflict state: `0` if we're not in any conflict, `1` if we are inside the first part of a conflict (between `<<<<<<<` and `=======`) and `2` for the second part of a conflict. `names` contains the names of the branches (they start at `[None,None]` and get updated as we pass along conflicts). `prev` contains a copy of what should be included at the start of the second version (if `cf=1` or `cf=2`). `added` starts at `False` and keeps track of whether we added any markdown cells (this flag allows us to know if a fast merge didn't leave any conflicts at the end). `fast` and `trust_us` are passed along by `fix_conflicts`: if `fast` is `True`, we don't point out conflict between cells if the inputs in the two versions are the same. Instead we merge using the local or remote branch, depending on `trust_us`.\n\nThe function then returns the updated text (with one or several cells, depending on the conflicts to solve), the updated `cf`, `names`, `prev` and `added`.", "_____no_output_____" ] ], [ [ "tst = '\\n'.join(['a', f'{conflicts[0]} HEAD', 'b', conflicts[1], 'c'])\nc,cf,names,prev,added = analyze_cell(tst, 0, [None,None], None, False,fast=False)\ntest_eq(c, get_md_cell('`<<<<<<< HEAD`')+'\\na\\nb')\ntest_eq(cf, 2)\ntest_eq(names, ['HEAD', None])\ntest_eq(prev, ['a\\nc'])\ntest_eq(added, True)", "_____no_output_____" ] ], [ [ "Here in this example, we were entering cell `tst` with no conflict state. At the end of the cells, we are still in the second part of the conflict, hence `cf=2`. The result returns a marker for the branch head, then the whole cell in version 1 (a + b). We save a (prior to the conflict hence common to the two versions) and c (only in version 2) for the next cell in `prev` (that should contain the resolution of this conflict).", "_____no_output_____" ], [ "## Main function", "_____no_output_____" ] ], [ [ "#export\ndef fix_conflicts(fname, fast=True, trust_us=True):\n \"Fix broken notebook in `fname`\"\n fname=Path(fname)\n shutil.copy(fname, fname.with_suffix('.ipynb.bak'))\n with open(fname, 'r') as f: raw_text = f.read()\n start,cells,end = extract_cells(raw_text)\n res = [start]\n cf,names,prev,added = 0,[None,None],None,False\n for cell in cells:\n c,cf,names,prev,added = analyze_cell(cell, cf, names, prev, added, fast=fast, trust_us=trust_us)\n res.append(c)\n if res[-1].endswith(','): res[-1] = res[-1][:-1]\n with open(f'{fname}', 'w') as f: f.write('\\n'.join([r for r in res+[end] if len(r) > 0]))\n if fast and not added: print(\"Succesfully merged conflicts!\")\n else: print(\"One or more conflict remains in the notebook, please inspect manually.\")", "_____no_output_____" ] ], [ [ "The function will begin by backing the notebook `fname` to `fname.bak` in case something goes wrong. Then it parses the broken json, solving conflicts in cells. If `fast=True`, every conflict that only involves metadata or outputs of cells will be solved automatically by using the local (`trust_us=True`) or the remote (`trust_us=False`) branch. Otherwise, or for conflicts involving the inputs of cells, the json will be repaired by including the two version of the conflicted cell(s) with markdown cells indicating the conflicts. You will be able to open the notebook again and search for the conflicts (look for `<<<<<<<`) then fix them as you wish.\n\nIf `fast=True`, the function will print a message indicating whether the notebook was fully merged or if conflicts remain.", "_____no_output_____" ], [ "## Export-", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.export import notebook2script\nnotebook2script()", "Converted 00_export.ipynb.\nConverted 01_sync.ipynb.\nConverted 02_showdoc.ipynb.\nConverted 03_export2html.ipynb.\nConverted 04_test.ipynb.\nConverted 05_merge.ipynb.\nConverted 06_cli.ipynb.\nConverted 07_clean.ipynb.\nConverted 08_flag_tests.ipynb.\nConverted 99_search.ipynb.\nConverted index.ipynb.\nConverted tutorial.ipynb.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
d030d8ab11d8b915b037ca79e7423a66cd70f866
236,056
ipynb
Jupyter Notebook
Processing.ipynb
Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection
0fa0dc0f158f933dfae3a5727e21e998b3b7a91e
[ "Apache-2.0" ]
null
null
null
Processing.ipynb
Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection
0fa0dc0f158f933dfae3a5727e21e998b3b7a91e
[ "Apache-2.0" ]
null
null
null
Processing.ipynb
Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection
0fa0dc0f158f933dfae3a5727e21e998b3b7a91e
[ "Apache-2.0" ]
null
null
null
266.128523
41,114
0.883752
[ [ [ "<a href=\"https://colab.research.google.com/github/Ivan-Nebogatikov/HumanActivityRecognitionOutliersDetection/blob/main/Processing.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "Скачиваем данные, преобразуем их в одну таблицу", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport json\nfrom datetime import datetime\nfrom datetime import date\nfrom math import sqrt\n\nfrom zipfile import ZipFile\nfrom os import listdir\nfrom os.path import isfile, join\n\nfilesDir = \"/content/drive/MyDrive/training_data\"\ncsvFiles = [join(filesDir, f) for f in listdir(filesDir) if (isfile(join(filesDir, f)) and 'csv' in f)]\n\ndata = pd.DataFrame()\nfor file in csvFiles:\n if 'acc' in file:\n with ZipFile(file, 'r') as zipObj:\n listOfFileNames = zipObj.namelist()\n for fileName in listOfFileNames:\n if 'chest' in fileName:\n with zipObj.open(fileName) as csvFile:\n newData = pd.read_csv(csvFile)\n newData['type'] = str(csvFile.name).replace('_',' ').replace('.',' ').split()[1]\n data = data.append(newData)\n # newData = pd.read_csv(csvFile)\n # newColumns = [col for col in newData.columns if col not in data.columns]\n # print(newColumns)\n # if data.empty or not newColumns:\n # newData['type'] = str(csvFile.name).replace('_',' ').replace('.',' ').split()[1]\n # data = data.append(newData)\n # else:\n # for index, newRow in newData.iterrows():\n # print(newRow['attr_time'])\n # print(data.iloc[[0]]['attr_time'])\n # print(len(data[data['attr_time'] < newRow['attr_time']]))\n # existingRow = data[data['attr_time'] <= newRow['attr_time']].iloc[-1]\n # existingRow[newColumns] = newRow[newColumns] \n # data = data.sort_values(by=['attr_time'])\n #print(data)\ndata = data.sort_values(by=['attr_time'])\nprint(data)\n\n# heart = pd.read_csv('https://raw.githubusercontent.com/Ivan-Nebogatikov/HumanActivityRecognition/master/datasets/2282_3888_bundle_archive/heart.csv')\n# heart['timestamp'] = heart['timestamp'].map(lambda x: datetime.strptime(x, \"%Y-%m-%d %H:%M:%S.%f\"))\n# heart = heart.sort_values(by='timestamp')\n\n# def getHeart(x):\n# dt = datetime.strptime(x, \"%Y-%m-%d %H:%M:%S.%f\")\n# f = heart[heart['timestamp'] < dt]\n# lastValue = f.iloc[[-1]]['values'].tolist()[0]\n# intValue = list(json.loads(lastValue.replace('\\'', '\"')))[0]\n# return intValue\n\n# acc = pd.read_csv('https://raw.githubusercontent.com/Ivan-Nebogatikov/HumanActivityRecognition/master/datasets/2282_3888_bundle_archive/acc.csv')\n# acc['heart'] = acc['timestamp'].map(lambda x: getHeart(x))\n# print(acc)\n\n# def change(x):\n# if x == 'Pause' or x == 'Movie':\n# x = 'Watching TV'\n# if x == 'Shop':\n# x = 'Walk'\n# if x == 'Football':\n# x = 'Running'\n# if x == 'Meeting' or x == 'Work' or x == 'Picnic ' or x == 'In vehicle' or x == 'In bus' :\n# x = 'Sitting'\n# if x == 'On bus stop':\n# x = 'Walk'\n# if x == 'Walking&party' or x == 'Shopping& wearing' or x == 'At home':\n# x = 'Walk'\n# return x\n# acc['act'] = acc['act'].map(lambda x: change(x))\n\n# labels = np.array(acc['act'])\n\n# arrays = acc['values'].map(lambda x: getValue(x))\n# x = getDiff(list(arrays.map(lambda x: np.double(x[0]))))\n# y = getDiff(list(arrays.map(lambda x: np.double(x[1]))))\n# z = getDiff(list(arrays.map(lambda x: np.double(x[2]))))\n# dist = list(map(lambda a, b, c: sqrt(a*a+b*b+c*c), x, y, z))", " id attr_time attr_x attr_y attr_z type\n0 1 1435990454117 0.565032 9.643246 1.301249 climbingup\n1 2 1435990454137 0.565630 9.632472 1.302446 climbingup\n2 3 1435990454157 0.560842 9.616910 1.315015 climbingup\n3 4 1435990454188 0.553659 9.599552 1.298256 climbingup\n4 5 1435990454208 0.553659 9.601946 1.293467 climbingup\n... ... ... ... ... ... ...\n31414 31415 1438191215897 -3.183091 8.975862 1.445499 lying\n31415 31416 1438191215923 -3.148974 8.924985 1.595735 lying\n31416 31417 1438191215941 -3.223793 8.966884 1.678335 lying\n31417 31418 1438191215959 -3.280655 8.953117 1.451485 lying\n31418 31419 1438191215981 -3.160945 8.998009 1.451485 lying\n\n[221613 rows x 6 columns]\n" ], [ "labels = np.array(data['type'])", "_____no_output_____" ] ], [ [ "", "_____no_output_____" ] ], [ [ "data['time_diff'] = data['attr_time'].diff()\n\nindMin = int(data[['time_diff']].idxmin())\nprint(indMin)\nt_j = data.iloc[indMin]['attr_time']\nprint(t_j)\nt_j1 = data.iloc[indMin+1]['attr_time']\n\ndiff = t_j1 - t_j\nprint(diff)\n\n# interpolated = []\ndata['attr_x_i'] = data.apply(lambda row: (t_j1 - row['attr_time']) * row['attr_x'] / diff + (row['attr_time'] - t_j) * row['attr_x'] / diff, axis=1) # !!! тут нужен +1 строка\ndata['attr_y_i'] = data.apply(lambda row: (t_j1 - row['attr_time']) * row['attr_y'] / diff + (row['attr_time'] - t_j) * row['attr_y'] / diff, axis=1)\ndata['attr_z_i'] = data.apply(lambda row: (t_j1 - row['attr_time']) * row['attr_z'] / diff + (row['attr_time'] - t_j) * row['attr_z'] / diff, axis=1)\n# # for i, row in data.iterrows():\n# # t_i = row['attr_time']\n# # def axis(value): (t_j1 - t_i) * value / (t_j1 - t_j) + (t_i + t_j) * value / (t_j1 + t_j)\n# # interpolated.append([row[\"id\"], row['attr_time'], axis(row['attr_x']), axis(row['attr_y']), axis(row['attr_z']), row['type'], row['time_diff']])\n\nprint(data)\n", "29\n1435990454718\n1\n id attr_time attr_x ... attr_x_i attr_y_i attr_z_i\n0 1 1435990454117 0.565032 ... 0.565032 9.643246 1.301249\n1 2 1435990454137 0.565630 ... 0.565630 9.632472 1.302446\n2 3 1435990454157 0.560842 ... 0.560842 9.616910 1.315015\n3 4 1435990454188 0.553659 ... 0.553659 9.599552 1.298256\n4 5 1435990454208 0.553659 ... 0.553659 9.601946 1.293468\n... ... ... ... ... ... ... ...\n31414 31415 1438191215897 -3.183091 ... -3.183091 8.975861 1.445499\n31415 31416 1438191215923 -3.148974 ... -3.148973 8.924984 1.595736\n31416 31417 1438191215941 -3.223793 ... -3.223792 8.966885 1.678335\n31417 31418 1438191215959 -3.280655 ... -3.280655 8.953117 1.451485\n31418 31419 1438191215981 -3.160945 ... -3.160945 8.998009 1.451485\n\n[221613 rows x 10 columns]\n" ], [ "data['g_x'] = data['attr_x_i'].rolling(window=5).mean()\ndata['g_y'] = data['attr_y_i'].rolling(window=5).mean()\ndata['g_z'] = data['attr_z_i'].rolling(window=5).mean()\nprint(data['g_x'])", "0 NaN\n1 NaN\n2 NaN\n3 NaN\n4 0.559764\n ... \n31414 -3.208829\n31415 -3.201048\n31416 -3.206913\n31417 -3.209786\n31418 -3.199491\nName: g_x, Length: 221613, dtype: float64\n" ], [ "data['g_x'] = data['attr_x_i'].rolling(window=5).mean()\ndata['g_y'] = data['attr_y_i'].rolling(window=5).mean()\ndata['g_z'] = data['attr_z_i'].rolling(window=5).mean()\nprint(data['g_x'])", "0 NaN\n1 NaN\n2 NaN\n3 NaN\n4 0.559764\n ... \n31414 -3.208829\n31415 -3.201048\n31416 -3.206913\n31417 -3.209786\n31418 -3.199491\nName: g_x, Length: 221613, dtype: float64\n" ], [ "import numpy as np\n\ndef acc(a, g):\n return np.cross(np.cross(a, g) / np.dot(g, g), g)\n\ndata['a_tv'] = data.apply(lambda row: acc([row.attr_x_i, row.attr_y_i, row.attr_z_i], [row.g_x, row.g_y, row.g_z]), axis=1)\ndata['a_th'] = data.apply(lambda row: [row.attr_x_i - row.a_tv[0], row.attr_y_i - row.a_tv[1], row.attr_z_i - row.a_tv[2]], axis=1)\n\nprint(data['a_tv'])", "0 [nan, nan, nan]\n1 [nan, nan, nan]\n2 [nan, nan, nan]\n3 [nan, nan, nan]\n4 [0.005057112819241918, -0.0011310265816110463,...\n ... \n31414 [-0.02069019868972204, -0.01710602083571396, 0...\n31415 [-0.04063326153831265, 0.00030805992402588127,...\n31416 [0.004154727972981805, 0.02379860076518528, -0...\n31417 [0.06656909388802254, 0.013670051238872064, 0....\n31418 [-0.04103426464249009, -0.02726753010378999, 0...\nName: a_tv, Length: 221613, dtype: object\n" ], [ "print(data['a_th'])", "0 [nan, nan, nan]\n1 [nan, nan, nan]\n2 [nan, nan, nan]\n3 [nan, nan, nan]\n4 [0.5486020271807942, 9.603077026582291, 1.2872...\n ... \n31414 [-3.162400964945532, 8.992966616538839, 1.3876...\n31415 [-3.108340203427508, 8.924675918347459, 1.6835...\n31416 [-3.2279468040838215, 8.943086012271925, 1.807...\n31417 [-3.347224001114585, 8.939447319366597, 1.3910...\n31418 [-3.119910674017178, 9.025276258131134, 1.3772...\nName: a_th, Length: 221613, dtype: object\n" ] ], [ [ "Вспомогательная функция для вывода результатов", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom scipy import interp\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.preprocessing import LabelBinarizer\n\ndef class_report(y_true, y_pred, y_score=None, average='micro'):\n if y_true.shape != y_pred.shape:\n print(\"Error! y_true %s is not the same shape as y_pred %s\" % (\n y_true.shape,\n y_pred.shape)\n )\n return\n accuracy = accuracy_score(y_true, y_pred)\n print(\"Accuracy:\", accuracy)\n\n lb = LabelBinarizer()\n\n if len(y_true.shape) == 1:\n lb.fit(y_true)\n\n #Value counts of predictions\n labels, cnt = np.unique(\n y_pred,\n return_counts=True)\n n_classes = 5\n pred_cnt = pd.Series(cnt, index=labels)\n\n metrics_summary = precision_recall_fscore_support(\n y_true=y_true,\n y_pred=y_pred,\n labels=labels)\n\n avg = list(precision_recall_fscore_support(\n y_true=y_true, \n y_pred=y_pred,\n average='weighted'))\n\n metrics_sum_index = ['precision', 'recall', 'f1-score', 'support']\n class_report_df = pd.DataFrame(\n list(metrics_summary),\n index=metrics_sum_index,\n columns=labels)\n\n support = class_report_df.loc['support']\n total = support.sum() \n class_report_df['avg / total'] = avg[:-1] + [total]\n\n class_report_df = class_report_df.T\n class_report_df['pred'] = pred_cnt\n class_report_df['pred'].iloc[-1] = total\n\n if not (y_score is None):\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for label_it, label in enumerate(labels):\n fpr[label], tpr[label], _ = roc_curve(\n (y_true == label).astype(int), \n y_score[:, label_it])\n\n roc_auc[label] = auc(fpr[label], tpr[label])\n\n if average == 'micro':\n if n_classes <= 2:\n fpr[\"avg / total\"], tpr[\"avg / total\"], _ = roc_curve(\n lb.transform(y_true).ravel(), \n y_score[:, 1].ravel())\n else:\n fpr[\"avg / total\"], tpr[\"avg / total\"], _ = roc_curve(\n lb.transform(y_true).ravel(), \n y_score.ravel())\n\n roc_auc[\"avg / total\"] = auc(\n fpr[\"avg / total\"], \n tpr[\"avg / total\"])\n\n elif average == 'macro':\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([\n fpr[i] for i in labels]\n ))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in labels:\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n # Finally average it and compute AUC\n mean_tpr /= n_classes\n\n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n\n roc_auc[\"avg / total\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n class_report_df['AUC'] = pd.Series(roc_auc)\n\n print(class_report_df)\n return accuracy", "_____no_output_____" ] ], [ [ "Определяем функции для предсказания с использованием классификатора и с использованием нескольких классификаторов", "_____no_output_____" ] ], [ [ "from sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn import metrics\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nimport pandas as pd\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import plot_confusion_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\n\ndef Predict(x, classifier = RandomForestClassifier(n_estimators = 400, random_state = 3, class_weight='balanced')):\n train_features, test_features, train_labels, test_labels = train_test_split(x, labels, test_size = 0.15, random_state = 242)\n print('Training Features Shape:', train_features.shape)\n print('Testing Features Shape:', test_features.shape)\n print(\"\\n\")\n\n classifier.fit(train_features, train_labels);\n\n x_shuffled, labels_shuffled = shuffle(np.array(x), np.array(labels))\n\n scores = cross_val_score(classifier, x_shuffled, labels_shuffled, cv=7)\n print(\"%f accuracy with a standard deviation of %f\" % (scores.mean(), scores.std()))\n\n predictions = list(classifier.predict(test_features))\n pred_prob = classifier.predict_proba(test_features)\n \n accuracy = class_report(\n y_true=test_labels,\n y_pred=np.asarray(predictions),\n y_score=pred_prob, average='micro')\n\n if hasattr(classifier, 'feature_importances_'):\n print(classifier.feature_importances_)\n\n plot_confusion_matrix(classifier, test_features, test_labels)\n plt.xticks(rotation = 90)\n plt.style.library['seaborn-darkgrid']\n plt.show()\n\n return [accuracy, scores.mean(), scores.std()]\n\ndef PredictWithClassifiers(data, classifiers):\n accuracies = {}\n for name, value in classifiers.items():\n accuracy = Predict(data, value)\n accuracies[name] = accuracy\n print(\"\\n\")\n df = pd.DataFrame({(k, v[0], v[1], v[2]) for k, v in accuracies.items()}, columns=[\"Method\", \"Accuracy\", \"Mean\", \"Std\"])\n print(df)", "_____no_output_____" ] ], [ [ "Определяем набор используемых классификаторов", "_____no_output_____" ] ], [ [ "from sklearn import svm\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.ensemble import AdaBoostClassifier\n\nmethods = {\n \"MLP\" : MLPClassifier(random_state=1, max_iter=300),\n \"K-neigh\" : KNeighborsClassifier(), # default k = 5\n \"Random Forest\" : RandomForestClassifier(n_estimators = 400, random_state = 3, class_weight='balanced'),\n \"Bayes\" : GaussianNB(),\n \"AdaBoost\" : AdaBoostClassifier(),\n \"SVM\" : svm.SVC(probability=True, class_weight='balanced')\n}", "_____no_output_____" ], [ "frame = pd.DataFrame(data['a_th'].to_list(), columns=['x','y','z']).fillna(0)\nprint(frame)\nfeature_list = list(frame.columns)\nprint(frame)\n\nPredictWithClassifiers(frame, methods)", " x y z\n0 0.000000 0.000000 0.000000\n1 0.000000 0.000000 0.000000\n2 0.000000 0.000000 0.000000\n3 0.000000 0.000000 0.000000\n4 0.548602 9.603077 1.287286\n... ... ... ...\n221608 -3.162401 8.992967 1.387654\n221609 -3.108340 8.924676 1.683505\n221610 -3.227947 8.943086 1.807846\n221611 -3.347224 8.939447 1.391044\n221612 -3.119911 9.025276 1.377277\n\n[221613 rows x 3 columns]\n x y z\n0 0.000000 0.000000 0.000000\n1 0.000000 0.000000 0.000000\n2 0.000000 0.000000 0.000000\n3 0.000000 0.000000 0.000000\n4 0.548602 9.603077 1.287286\n... ... ... ...\n221608 -3.162401 8.992967 1.387654\n221609 -3.108340 8.924676 1.683505\n221610 -3.227947 8.943086 1.807846\n221611 -3.347224 8.939447 1.391044\n221612 -3.119911 9.025276 1.377277\n\n[221613 rows x 3 columns]\nTraining Features Shape: (188371, 3)\nTesting Features Shape: (33242, 3)\n\n\n0.860793 accuracy with a standard deviation of 0.001170\nAccuracy: 0.8628542205643464\n precision recall f1-score support pred AUC\nclimbingdown 0.947478 0.963002 0.955177 3784.0 3846.0 0.998307\nclimbingup 0.730908 0.793458 0.760900 4861.0 5277.0 0.965126\njumping 0.736196 0.392799 0.512273 611.0 326.0 0.965964\nlying 0.996778 0.978082 0.987342 4745.0 4656.0 0.999438\nrunning 0.820877 0.712463 0.762837 4702.0 4081.0 0.956360\nsitting 0.936003 0.945902 0.940927 4917.0 4969.0 0.994198\nstanding 0.894068 0.930101 0.911728 4764.0 4956.0 0.994421\nwalking 0.754044 0.796418 0.774652 4858.0 5131.0 0.966664\navg / total 0.863435 0.862854 0.861296 33242.0 33242.0 0.987875\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d030ebabd28e2ebf77b3a0e3818d3f6981b90aed
31,951
ipynb
Jupyter Notebook
Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb
Kenneth-Macharia/Learning
0948dda73d94b25f96fad7e9ff3523782b0a407a
[ "MIT" ]
null
null
null
Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb
Kenneth-Macharia/Learning
0948dda73d94b25f96fad7e9ff3523782b0a407a
[ "MIT" ]
3
2020-07-26T19:17:23.000Z
2021-01-01T15:39:38.000Z
Python/data_science/data_analysis/04-Pandas-Exercises/02-SF Salaries Exercise - Solutions.ipynb
Kenneth-Macharia/Code-practise
3c94f1df1e874ea2e4dcf0e55ee11d09c0eeb16f
[ "MIT" ]
null
null
null
40.342172
4,721
0.478295
[ [ [ "# SF Salaries Exercise - Solutions\n\nWelcome to a quick exercise for you to practice your pandas skills! We will be using the [SF Salaries Dataset](https://www.kaggle.com/kaggle/sf-salaries) from Kaggle! Just follow along and complete the tasks outlined in bold below. The tasks will get harder and harder as you go along.", "_____no_output_____" ], [ "** Import pandas as pd.**", "_____no_output_____" ] ], [ [ "import pandas as pd", "_____no_output_____" ] ], [ [ "** Read Salaries.csv as a dataframe called sal.**", "_____no_output_____" ] ], [ [ "sal = pd.read_csv('Salaries.csv')", "_____no_output_____" ] ], [ [ "** Check the head of the DataFrame. **", "_____no_output_____" ] ], [ [ "sal.head()", "_____no_output_____" ] ], [ [ "** Use the .info() method to find out how many entries there are.**", "_____no_output_____" ] ], [ [ "sal.info() # 148654 Entries", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 148654 entries, 0 to 148653\nData columns (total 13 columns):\nId 148654 non-null int64\nEmployeeName 148654 non-null object\nJobTitle 148654 non-null object\nBasePay 148045 non-null float64\nOvertimePay 148650 non-null float64\nOtherPay 148650 non-null float64\nBenefits 112491 non-null float64\nTotalPay 148654 non-null float64\nTotalPayBenefits 148654 non-null float64\nYear 148654 non-null int64\nNotes 0 non-null float64\nAgency 148654 non-null object\nStatus 0 non-null float64\ndtypes: float64(8), int64(2), object(3)\nmemory usage: 14.7+ MB\n" ] ], [ [ "**What is the average BasePay ?**", "_____no_output_____" ] ], [ [ "sal['BasePay'].mean()", "_____no_output_____" ] ], [ [ "** What is the highest amount of OvertimePay in the dataset ? **", "_____no_output_____" ] ], [ [ "sal['OvertimePay'].max()", "_____no_output_____" ] ], [ [ "** What is the job title of JOSEPH DRISCOLL ? Note: Use all caps, otherwise you may get an answer that doesn't match up (there is also a lowercase Joseph Driscoll). **", "_____no_output_____" ] ], [ [ "sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['JobTitle']", "_____no_output_____" ] ], [ [ "** How much does JOSEPH DRISCOLL make (including benefits)? **", "_____no_output_____" ] ], [ [ "sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['TotalPayBenefits']", "_____no_output_____" ] ], [ [ "** What is the name of highest paid person (including benefits)?**", "_____no_output_____" ] ], [ [ "sal[sal['TotalPayBenefits']== sal['TotalPayBenefits'].max()] #['EmployeeName']\n# or\n# sal.loc[sal['TotalPayBenefits'].idxmax()]", "_____no_output_____" ] ], [ [ "** What is the name of lowest paid person (including benefits)? Do you notice something strange about how much he or she is paid?**", "_____no_output_____" ] ], [ [ "sal[sal['TotalPayBenefits']== sal['TotalPayBenefits'].min()] #['EmployeeName']\n# or\n# sal.loc[sal['TotalPayBenefits'].idxmax()]['EmployeeName']\n\n## ITS NEGATIVE!! VERY STRANGE", "_____no_output_____" ], [ "sal.groupby('Year')['BasePay'].mean()", "_____no_output_____" ] ], [ [ "** What was the average (mean) BasePay of all employees per year? (2011-2014) ? **", "_____no_output_____" ] ], [ [ "sal.groupby('Year').mean()['BasePay']", "_____no_output_____" ] ], [ [ "** How many unique job titles are there? **", "_____no_output_____" ] ], [ [ "sal['JobTitle'].nunique()", "_____no_output_____" ], [ "sal.head(0) # Get the col headers only", "_____no_output_____" ], [ "sal['JobTitle'].value_counts().head()", "_____no_output_____" ] ], [ [ "** What are the top 5 most common jobs? **", "_____no_output_____" ] ], [ [ "sal['JobTitle'].value_counts().head(5)", "_____no_output_____" ], [ "# sum(sal[sal['Year']==2013]['JobTitle'].value_counts() == 1)\n# sal[sal['Year']==2013sal['Year']==2013\nyr_cond = sal['Year']==2013 # Return a series of all rows in sal and whether they have 2013 in their 'Year' column\nyr_filtered_sal = sal[yr_cond] # Return sal filtered to only the rows that meet above criteria\njob_counts = yr_filtered_sal['JobTitle'].value_counts()\njob_counts_is_one = (job_counts == 1)\nsum(job_counts_is_one)", "_____no_output_____" ] ], [ [ "** How many Job Titles were represented by only one person in 2013? (e.g. Job Titles with only one occurence in 2013?) **", "_____no_output_____" ] ], [ [ "sum(sal[sal['Year']==2013]['JobTitle'].value_counts() == 1) # pretty tricky way to do this...", "_____no_output_____" ], [ "sal", "_____no_output_____" ], [ "def chief_check(title):\n if 'chief' in title.lower():\n return True\n else:\n return False\n\nsum(sal['JobTitle'].apply(lambda title: chief_check(title)))", "_____no_output_____" ] ], [ [ "** How many people have the word Chief in their job title? (This is pretty tricky) **", "_____no_output_____" ] ], [ [ "def chief_string(title):\n if 'chief' in title.lower():\n return True\n else:\n return False", "_____no_output_____" ], [ "sal['Title_len'] = sal['JobTitle'].apply(len)\nsal[['Title_len','TotalPayBenefits']].corr()", "_____no_output_____" ], [ "sum(sal['JobTitle'].apply(lambda x: chief_string(x)))", "_____no_output_____" ] ], [ [ "** Bonus: Is there a correlation between length of the Job Title string and Salary? **", "_____no_output_____" ] ], [ [ "sal['title_len'] = sal['JobTitle'].apply(len)", "_____no_output_____" ], [ "sal[['title_len','TotalPayBenefits']].corr() # No correlation.", "_____no_output_____" ] ], [ [ "# Great Job!", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
d0310bb026a9639297c199b05ec3a9a5a94aa7a7
16,785
ipynb
Jupyter Notebook
scripts/vqgan_clip_scratch.ipynb
ANaka/taming-transformers
c1e73d1f282ccc8c1b372ebdb3a7000feab9f383
[ "MIT" ]
null
null
null
scripts/vqgan_clip_scratch.ipynb
ANaka/taming-transformers
c1e73d1f282ccc8c1b372ebdb3a7000feab9f383
[ "MIT" ]
null
null
null
scripts/vqgan_clip_scratch.ipynb
ANaka/taming-transformers
c1e73d1f282ccc8c1b372ebdb3a7000feab9f383
[ "MIT" ]
null
null
null
78.802817
6,068
0.759249
[ [ [ "import argparse\nimport math\nfrom pathlib import Path\nimport sys\nfrom datetime import datetime\nimport os\nimport shutil\nsys.path.append('./taming-transformers')\nfrom IPython import display\nfrom base64 import b64encode\nfrom omegaconf import OmegaConf\nfrom PIL import Image\nfrom PIL.PngImagePlugin import PngInfo\nfrom taming.models import cond_transformer, vqgan\nimport torch\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torchvision import transforms\nfrom torchvision.transforms import functional as TF\nfrom tqdm.notebook import tqdm\n \nimport clip\nimport kornia.augmentation as K\nimport numpy as np\nimport imageio\nfrom PIL import ImageFile, Image\nimport taming\nimport json\nimport gc\n\n%load_ext autoreload\n%autoreload 2\n%config Completer.use_jedi = False\n\nfrom vqgan_clip import *", "The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n" ], [ "parameters = LatentSpacewalkParameters(\n initial_image=None,\n texts=['a minimalist watercolor painting of a red town'],\n target_images= [],\n seed= None,\n max_iterations= 50,\n learning_rate= 0.2,\n save_interval= 1,\n zoom_interval= None,\n display_interval= 3,\n)", "_____no_output_____" ], [ "parameters.prms", "_____no_output_____" ], [ "sw = Spacewalker(parameters=parameters, width=50, height=50)", "saved 20210823-180107_662441-9d17e-2e05e2 to s3://algorithmic-ink/current_nft_id\nWorking with z of shape (1, 256, 16, 16) = 65536 dimensions.\nloaded pretrained LPIPS loss from taming/modules/autoencoder/lpips/vgg.pth\nVQLPIPSWithDiscriminator running with hinge loss.\nRestored from /home/naka/code/side/taming-transformers/taming/models/vqgan_imagenet_f16_16384.ckpt\n" ], [ "empty_ram()", "_____no_output_____" ], [ "sw.run(parameters=parameters)", "i: 0, loss: 0.983403, losses: 0.983403\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
d0311142e19935adf7521b6f40ecfa3f72c736c2
3,547
ipynb
Jupyter Notebook
python-data-structures/interviews/goog-2021-02-03.ipynb
dimastatz/courses
663f19c53427552034e07f27ff0604b2d1d132ec
[ "MIT" ]
null
null
null
python-data-structures/interviews/goog-2021-02-03.ipynb
dimastatz/courses
663f19c53427552034e07f27ff0604b2d1d132ec
[ "MIT" ]
null
null
null
python-data-structures/interviews/goog-2021-02-03.ipynb
dimastatz/courses
663f19c53427552034e07f27ff0604b2d1d132ec
[ "MIT" ]
1
2022-03-24T01:16:12.000Z
2022-03-24T01:16:12.000Z
31.954955
465
0.54243
[ [ [ "# Sequence Reconstruction [PASSED]\nCheck whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.\n\n### Example 1\n- Input: org: [1,2,3], seqs: [[1,2],[1,3]]\n- Output: false\n- Explanation: [1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed.\n\n### Example 2\n- Input: org: [1,2,3], seqs: [[1,2]]\n- Output: false\n- Explanation: The reconstructed sequence can only be [1,2].\n\n### Example 3\n- Input: org: [1,2,3], seqs: [[1,2],[1,3],[2,3]]\n- Output: true\n- Explanation: The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct the original sequence [1,2,3].\n\n### Example 4:\n- Input: org: [4,1,5,2,6,3], seqs: [[5,2,6,3],[4,1,5,2]]\n- Output: true\n\n## Solution\n\n### Intuition\nTake the first numbers from each list. From the set of first numbers find the one that appears only in a first place. Add this number to result and delete it from all lists. Run until all input list are empty.\n\n### Implementation", "_____no_output_____" ] ], [ [ "def is_unique_first(x: int, seqs: list):\n return len([s for s in seqs if x in s[1:]]) == 0\n\n\ndef reconstruct(orgs: list, seqs: list) -> bool:\n res = []\n while seqs:\n first: set = set([lst[0] for lst in seqs if is_unique_first(lst[0], seqs)])\n if not first or len(first) > 2:\n return False\n else:\n elem = list(first)[0]\n res.append(elem)\n seqs = [[x for x in lst if x != elem] for lst in seqs]\n seqs = [s for s in seqs if s]\n return res == orgs\n\n\nreconstruct([1,2,3], [[1,2],[1,3]])\nreconstruct([1,2,3], [[1,2],[1,3],[2,3]])\nreconstruct([4,1,5,2,6,3], [[5,2,6,3],[4,1,5,2]])", "_____no_output_____" ] ], [ [ "Analysis:\n- Time Complexity: O(n^2)\n- Space Complexity: O(n)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ] ]
d031126f0da7d3ce45bcda70365c28110f09c183
293,225
ipynb
Jupyter Notebook
reading_assignments/5_Note-ML Methodology.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
ce14609327e5fa13f7af7b904a69da3aa3606f37
[ "MIT" ]
null
null
null
reading_assignments/5_Note-ML Methodology.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
ce14609327e5fa13f7af7b904a69da3aa3606f37
[ "MIT" ]
null
null
null
reading_assignments/5_Note-ML Methodology.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
ce14609327e5fa13f7af7b904a69da3aa3606f37
[ "MIT" ]
null
null
null
365.617207
98,268
0.931002
[ [ [ "$\\newcommand{\\xv}{\\mathbf{x}}\n \\newcommand{\\wv}{\\mathbf{w}}\n \\newcommand{\\yv}{\\mathbf{y}}\n \\newcommand{\\zv}{\\mathbf{z}}\n \\newcommand{\\uv}{\\mathbf{u}}\n \\newcommand{\\vv}{\\mathbf{v}}\n \\newcommand{\\Chi}{\\mathcal{X}}\n \\newcommand{\\R}{\\rm I\\!R}\n \\newcommand{\\sign}{\\text{sign}}\n \\newcommand{\\Tm}{\\mathbf{T}}\n \\newcommand{\\Xm}{\\mathbf{X}}\n \\newcommand{\\Zm}{\\mathbf{Z}}\n \\newcommand{\\Im}{\\mathbf{I}}\n \\newcommand{\\Um}{\\mathbf{U}}\n \\newcommand{\\Vm}{\\mathbf{V}} \n \\newcommand{\\muv}{\\boldsymbol\\mu}\n \\newcommand{\\Sigmav}{\\boldsymbol\\Sigma}\n \\newcommand{\\Lambdav}{\\boldsymbol\\Lambda}\n$\n\n# Machine Learning Methodology\n\nFor machine learning algorithms, we learned how to set goas to optimize and how to reach or approach the optimal solutions. Now, let us discuss how to evaluate the learned models. There will be many different aspects that we need to consider not simply accuracy, so we will further discuss techniques to make the machine learning models better. \n\n\n### Performance Measurement, Overfitting, Regularization, and Cross-Validation \n\nIn machine learning, *what is a good measure to assess the quality of a machine learning model?* Let us step back from what we have learned in class about ML techniques and think about this. \nIn previous lectures, we have discussed various measures such a `root mean square error (RMSE)`, `mean square error (MSE)`, `mean absolute error (MAE)` for **regression problems**, and `accuracy`, `confusion matrix`, `precision/recall`, `F1-score`, `receiver operating characteristic (ROC) curve`, and others for **classification**. \n\nFor your references, here are the list of references for diverse metrics for different categories of machine learning.\n* Regressions: https://arxiv.org/pdf/1809.03006.pdf\n* Classification: As we have a cheatsheet already, here is a comprehensive version from ICMLA tutorial. https://www.icmla-conference.org/icmla11/PE_Tutorial.pdf\n* Clustering: https://scikit-learn.org/stable/modules/clustering.html#clustering-performance-evaluation\n\nAnyway, are these measures good enough to say a specific model is better than the other? \n\nLet us take a look at following codes examples and think about something that we are missing.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom copy import deepcopy as copy", "_____no_output_____" ], [ "x = np.arange(3)\nt = copy(x)", "_____no_output_____" ], [ "def plot_data():\n plt.plot(x, t, \"o\", markersize=10)\n \nplot_data()", "_____no_output_____" ] ], [ [ "I know that it is silly to apply a linear regression on this obvious model, but let us try. :) ", "_____no_output_____" ] ], [ [ "## Least Square solution: Filled codes here to fit and plot as the instructor's output\nimport numpy as np \n\n# First creast X1 by adding 1's column to X\nN = x.shape[0]\nX1 = np.c_[np.ones((N, 1)), x]\n\n# Next, using inverse, solve, lstsq function to get w*\nw = np.linalg.inv(X1.transpose().dot(X1)).dot(X1.transpose()).dot(t)\n\n# print(w)\n\ny = X1.dot(w)\nplot_data()\nplt.plot(y)", "_____no_output_____" ] ], [ [ "Can we try a nonlinear model on this data? Why not? \nWe can make a nonlinear model by simply adding higher degree terms such square, cubic, quartic, and so on. \n\n$$ f(\\xv; \\wv) = w_0 + w_1 \\xv + w_2 \\xv^2 + w_3 \\xv^3 + \\cdots $$\n\nThis is called *polynomial regression* as we transform the input features to nonlinear by extending the features high dimensional with higher polynomial degree terms. For instance, your input feature $(1, x)$ is extended to $(1, x, x^2, x^3)$ for cubic polynomial regression model. After input transformation, you can simply use least squares or least mean squares to find the weights as the model is still linear with respect to the weight $\\wv$. \n\nLet us make the polynomial regression model and fit to the data above with lease squares.", "_____no_output_____" ] ], [ [ "# Polinomial regression\ndef poly_regress(x, d=3, t=None, **params):\n bnorm = params.pop('normalize', False)\n \n X_poly = []\n #######################################################################################\n # Transform input features: append polynomial terms (from bias when i=0) to degree d\n for i in range(d+1):\n X_poly.append(x**i)\n \n X_poly = np.vstack(X_poly).T\n \n # normalize \n if bnorm:\n mu, sd = np.mean(X_poly[:, 1:, None], axis=0), np.std(X_poly[:, 1:, None], axis=0)\n X_poly[:, 1:] = (X_poly[:, 1:] - mu.flat) / sd.flat\n \n # least sqaures\n if t is not None:\n # added least square solution here\n w = np.linalg.inv(X_poly.transpose().dot(X_poly)).dot(X_poly.transpose()).dot(t)\n \n if bnorm:\n return X_poly, mu, sd, w\n return X_poly, w\n \n if bnorm:\n return X_poly, mu, sd\n return X_poly", "_____no_output_____" ] ], [ [ "The poly_regress() function trains with the data when target input is given after transform the input x as the following example. The function also returns the transformed input X_poly. ", "_____no_output_____" ] ], [ [ "Xp, wp = poly_regress(x, 3, t)\nprint(wp.shape)\nprint(Xp.shape)\nyp = Xp @ wp\n\nplot_data()\nplt.plot(x, y)\nplt.plot(x, yp)", "(4,)\n(3, 4)\n" ] ], [ [ "Hmm... They both look good on this. Then, what is the difference? Let us take a look at how they change if I add the test data. If I compare the MSE, they are equivalent. Try to expand the data for test and see how different they are. \n\nHere, we use another usage of poly_regress() function without passing target, so we transform the target input to polynomial features. ", "_____no_output_____" ] ], [ [ "xtest = np.arange(11)-5\nXptest = poly_regress(xtest, 3)\nyptest = Xptest @ wp\n\nX1test = np.vstack((np.ones(len(xtest)), xtest)).T\nytest = X1test @ w\n\nplot_data()\nplt.plot(xtest, ytest)\nplt.plot(xtest, yptest)\n", "_____no_output_____" ] ], [ [ "Here the orange is th linear model and the green line is 3rd degree polynomial regression. \nWhich model looks better? What is your pick? \n\n<br/><br/><br/><br/><br/><br/>", "_____no_output_____" ], [ "## Learning Curve\n\nFrom the above example, we realized that the model evaluation we discussed so far is not enough. \n\nFirst, let us consider how well a learned model generalizes to new data with respect to the number of training samples. We assume that the test data are drawn from same distribution over example space as training data. \n\n", "_____no_output_____" ], [ "In this plot, we can compare the two learning algorithms and find which one generalizes better than the other. Also, during the training, we can access to the training error (or empirical loss). This may not look similar (mostly not) to the test error (generalization loss above). \n\nLet us take a look at the example in the Geron textbook. ", "_____no_output_____" ] ], [ [ "import os\nimport pandas as pd\nimport sklearn\n\ndef prepare_country_stats(oecd_bli, gdp_per_capita):\n oecd_bli = oecd_bli[oecd_bli[\"INEQUALITY\"]==\"TOT\"]\n oecd_bli = oecd_bli.pivot(index=\"Country\", columns=\"Indicator\", values=\"Value\")\n gdp_per_capita.rename(columns={\"2015\": \"GDP per capita\"}, inplace=True)\n gdp_per_capita.set_index(\"Country\", inplace=True)\n full_country_stats = pd.merge(left=oecd_bli, right=gdp_per_capita,\n left_index=True, right_index=True)\n full_country_stats.sort_values(by=\"GDP per capita\", inplace=True)\n remove_indices = [0, 1, 6, 8, 33, 34, 35]\n keep_indices = list(set(range(36)) - set(remove_indices))\n return full_country_stats[[\"GDP per capita\", 'Life satisfaction']].iloc[keep_indices], full_country_stats[[\"GDP per capita\", 'Life satisfaction']]", "_____no_output_____" ], [ "!curl https://raw.githubusercontent.com/ageron/handson-ml/master/datasets/lifesat/oecd_bli_2015.csv > oecd_bli_2015.csv", " % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 395k 100 395k 0 0 895k 0 --:--:-- --:--:-- --:--:-- 895k\n" ], [ "!curl https://raw.githubusercontent.com/ageron/handson-ml/master/datasets/lifesat/gdp_per_capita.csv > gdp_per_capita.csv", " % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 36323 100 36323 0 0 154k 0 --:--:-- --:--:-- --:--:-- 154k\n" ], [ "# Load the data\noecd_bli = pd.read_csv(\"oecd_bli_2015.csv\", thousands=',')\ngdp_per_capita = pd.read_csv(\"gdp_per_capita.csv\",thousands=',',delimiter='\\t',\n encoding='latin1', na_values=\"n/a\")\n\n\n# Prepare the data\ncountry_stats, full_country_stats = prepare_country_stats(oecd_bli, gdp_per_capita)\nX = np.c_[country_stats[\"GDP per capita\"]]\ny = np.c_[country_stats[\"Life satisfaction\"]]\n\n# Visualize the data\ncountry_stats.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(6.5,4))\nplt.axis([0, 60000, 0, 10])\nplt.show()", "_____no_output_____" ] ], [ [ "This looks like the data showing a linear trend. Now, let us extend the x-axis to further to 110K and see how it looks.", "_____no_output_____" ] ], [ [ "# Visualize the full data\n# Visualize the data\nfull_country_stats.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction', figsize=(12,4))\nplt.axis([0, 110000, 0, 10])\nplt.show()", "_____no_output_____" ] ], [ [ "Maybe a few outliers with high GDP do not follow the linear trend that we observed above.", "_____no_output_____" ] ], [ [ "# Data for training\nXfull = np.c_[full_country_stats[\"GDP per capita\"]]\nyfull = np.c_[full_country_stats[\"Life satisfaction\"]]\n\nprint(Xfull.shape, yfull.shape)", "(36, 1) (36, 1)\n" ] ], [ [ "We can better observe the trend by fitting polynomial regression models by changing the degrees. ", "_____no_output_____" ] ], [ [ "# polynomial model to this data\n\nfor deg in [1, 2, 5, 10, 30]:\n plt.figure();\n full_country_stats.plot(kind='scatter', x=\"GDP per capita\", y='Life satisfaction',\n figsize=(12,4));\n plt.axis([0, 110000, 3, 10]);\n Xp, mu, sd, wp = poly_regress(Xfull.flatten(), deg, yfull.flatten(), normalize=True)\n yp1 = Xp @ wp\n\n # plot curve \n plt.plot(Xfull, yp1, 'r-', label=deg);\n plt.title(\"degree: {}\".format(deg));\n\n", "_____no_output_____" ] ], [ [ "What degree do you think the data follow? What is your best pick? Do you see overfitting here? From which one do you see it? ", "_____no_output_____" ], [ "As the complexity of model grows, you may have small training errors. However, there is no guarantee that you have a good generalization (you may have very bad generalization error!). \nThis is called **Overfitting** problem in machine learning. From training data, once you learned the hypothesis *h* (or machine learning model), you can have training error $E_{train}(h)$ and testing error $E_{test}(h)$. Let us say that there is another model $h^\\prime$ for which\n\n$$ E_{train}(h) < E_{train}(h^\\prime) \\wedge E_{test}(h) > E_{test}(h^\\prime).$$\n\nThen, we say the hypothesis $h$ is \"overfitted.\" ", "_____no_output_____" ], [ "## Bias-Variance Tradeoff\n\nHere the bias refers an error from erroneous assumptions and the variance means an error from sensitivity to small variation in the data. Thus, high bias can cause an underfitted model and high variance can cause an overfitted model. Finding the sweet spot that have good generalization is on our hand. \n\nIn the same track of discussion, Scott summarizes the errors that we need to consider as follows: \n\n- high bias error: under-performing model that misses the important trends\n- high variance error: excessively sensitive to small variations in the training data\n- Irreducible error: genuine to the noise in the data. Need to clean up the data\n\n![](http://webpages.uncc.edu/mlee173/teach/itcs4156online/images/class/bias-and-variance.jpg)\n<center>From Understanding the Bias-Variance Tradeoff, by Scott Fortmann-Roe</center>", "_____no_output_____" ], [ "## Regularization\n\nWe reduce overfitting by addding a complexity penalty to the loss function. Here follows the loss function for the linear regression with $L2$-norm. \n\n$$\n\\begin{align*}\nE(\\wv) &= \\sum_i^N ( y_i - t_i)^2 + \\lambda \\lVert \\wv \\rVert_2^2 \\\\\n \\\\\n &= \\sum_i^N ( y_i - t_i)^2 + \\lambda \\sum_k^D w_k^2 \\\\\n \\\\\n &= (\\Xm \\wv - T)^\\top (\\Xm \\wv - T) + \\lambda \\wv^\\top \\wv \\\\\n \\\\\n &= \\wv^\\top \\Xm^\\top \\Xm \\wv - 2 \\Tm^\\top \\Xm \\wv + \\Tm^\\top \\Tm + \\lambda \\wv^\\top \\wv \n\\end{align*}\n$$\n\nRepeating the derivation as in linear regression, \n\n$$\n\\begin{align*}\n\\frac{\\partial E(\\wv)}{\\partial \\wv} &= \\frac{\\partial (\\Xm \\wv - \\Tm)^\\top (\\Xm \\wv - \\Tm)}{\\partial \\wv} + \\frac{\\partial \\lambda \\wv^\\top \\wv}{\\partial \\wv} \\\\\n \\\\\n &= 2 \\Xm^\\top \\Xm \\wv - 2 \\Xm^\\top \\Tm + 2 \\lambda \\wv\n\\end{align*}\n$$\n\nSetting the last term zero, we reach the solution of *ridge regression*: \n\n$$\n\\begin{align*}\n 2 \\Xm^\\top \\Xm \\wv - 2 \\Xm^\\top \\Tm + 2 \\lambda \\wv &= 0\\\\\n\\\\\n\\big(\\Xm^\\top \\Xm + \\lambda \\Im \\big) \\wv &= \\Xm^\\top \\Tm\\\\\n\\\\\n\\wv &= \\big(\\Xm^\\top \\Xm + \\lambda \\Im \\big)^{-1} \\Xm^\\top \\Tm.\n\\end{align*}\n$$\n", "_____no_output_____" ], [ "## Cross-Validation\n\nNow, let us select a model. Even with the regularization, we still need to pick $\\lambda$. For polynomial regression, we need to find the degree parameter. When we are mix-using multiple algorithms, we still need to know which model to choose. \nHere, remembe that we want a model that have good generalization. The idea is preparing one dataset (a validation set) by pretending that we cannot see the labels. After choosing a model parameter (or a model) and train it with training dataset, we test it on the validation data. \nComparing the validation error, we select the one that has the lowest validation error. Finally, we evaluate the model on testing data. \n\nHere follows the K-fold cross-validation that divides the data into K blocks for traing, validating and testing.\n\n### K-fold CV Procedure\n\n![image.png](attachment:image.png)", "_____no_output_____" ], [ "## Feature Selection\n\nAnother way to get a sparse (possibly good generalization) model is using small set of most relevant features. Weight analysis or some other tools can give us what is most relevant or irrelevant features w.r.t the training error. But it is still hard to tell the relevance to the generalization error. Thus, problems in choosing a minimally relevant set of features is NP-hard even with perfect estimation of generalization error. With inaccurate estimation that we have, it is much hard to find them. \n\nThus, we can simply use cross-validation to find features. \nWe can greedily add (forward selection) or delete (backward selection) features that decrease cross-validation error most. ", "_____no_output_____" ], [ "# Practice\n\nNow, try to write your own 5-fold cross validation code that follows the procedure above for ridge regression. Try 5 different $\\lambda$ values, [0, 0.01, 0.1, 1, 10], for this. ", "_____no_output_____" ] ], [ [ "# TODO: try to implement your own K-fold CV. \n# (This will be a part of next assignment (no solution will be provided.))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ] ]
d0311dbd4673f9aba0ba2a10f1d435d3fddb8451
430,276
ipynb
Jupyter Notebook
playstore analysis.ipynb
yazalipavan/Playstore_analysis
a823027b2abce48578b06045f7760e194d2a34cb
[ "MIT" ]
null
null
null
playstore analysis.ipynb
yazalipavan/Playstore_analysis
a823027b2abce48578b06045f7760e194d2a34cb
[ "MIT" ]
null
null
null
playstore analysis.ipynb
yazalipavan/Playstore_analysis
a823027b2abce48578b06045f7760e194d2a34cb
[ "MIT" ]
null
null
null
231.580194
175,144
0.895442
[ [ [ "# GOOGLE PLAYSTORE ANALYSIS", "_____no_output_____" ], [ "The dataset used in this analysis is taken from [kaggle datasets](https://www.kaggle.com/datasets)", "_____no_output_____" ], [ "In this analysis we took a raw data which is in csv format and then converted it into a dataframe.Performed some operations, cleaning of the data and finally visualizing some necessary conclusions obtained from it.", "_____no_output_____" ], [ "Let's import necessary libraries required for the analysis", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "Convert the csv file into dataframe using pandas", "_____no_output_____" ] ], [ [ "df=pd.read_csv('googleplaystore.csv')", "_____no_output_____" ], [ "df.head(5)", "_____no_output_____" ] ], [ [ "This is the data we obtained from the csv file.Let's see some info about this dataframe", "_____no_output_____" ] ], [ [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 10841 entries, 0 to 10840\nData columns (total 13 columns):\nApp 10841 non-null object\nCategory 10841 non-null object\nRating 9367 non-null float64\nReviews 10841 non-null object\nSize 10841 non-null object\nInstalls 10841 non-null object\nType 10840 non-null object\nPrice 10841 non-null object\nContent Rating 10840 non-null object\nGenres 10841 non-null object\nLast Updated 10841 non-null object\nCurrent Ver 10833 non-null object\nAndroid Ver 10838 non-null object\ndtypes: float64(1), object(12)\nmemory usage: 1.1+ MB\n" ] ], [ [ "This dataframe consists of 10841 entries ie information about 10841 apps.\nIt tells about the category to which the app belongs,rating given by the users,size of the app,number of reviews given,count of number of installs and some other information", "_____no_output_____" ], [ "# DATA CLEANING", "_____no_output_____" ], [ "Some columns have in-appropriate data,data types.This columns needed to be cleaned to perform the analysis.", "_____no_output_____" ], [ "##### SIZE : ", "_____no_output_____" ], [ "This column has in-appropriate data type.This needed to be converted into numeric type after converting every value into MB's", "_____no_output_____" ], [ "\nFor example, the size of the app is in “string” format. We need to convert it into a numeric value. If the size is “10M”, then ‘M’ was removed to get the numeric value of ‘10’. If the size is “512k”, which depicts app size in kilobytes, the first ‘k’ should be removed and the size should be converted to an equivalent of ‘megabytes’.", "_____no_output_____" ] ], [ [ "df['Size'] = df['Size'].map(lambda x: x.rstrip('M'))\ndf['Size'] = df['Size'].map(lambda x: str(round((float(x.rstrip('k'))/1024), 1)) if x[-1]=='k' else x)\ndf['Size'] = df['Size'].map(lambda x: np.nan if x.startswith('Varies') else x)", "_____no_output_____" ] ], [ [ "10472 has in-appropriate data in every column, may due to entry mistake.So we are removing that entry from the table", "_____no_output_____" ] ], [ [ "df.drop(10472,inplace=True)", "_____no_output_____" ] ], [ [ "By using pd.to_numeric command we are converting into numeric type", "_____no_output_____" ] ], [ [ "df['Size']=df['Size'].apply(pd.to_numeric)", "_____no_output_____" ] ], [ [ "##### Installs :", "_____no_output_____" ], [ "The value of installs is in “string” format. It contains numeric values with commas. It should be removed. And also, the ‘+’ sign should be removed from the end of each string.", "_____no_output_____" ] ], [ [ "df['Installs'] = df['Installs'].map(lambda x: x.rstrip('+'))\ndf['Installs'] = df['Installs'].map(lambda x: ''.join(x.split(',')))", "_____no_output_____" ] ], [ [ "By using pd.to_numeric command we are converting it into numeric data type", "_____no_output_____" ] ], [ [ "df['Installs']=df['Installs'].apply(pd.to_numeric)", "_____no_output_____" ] ], [ [ "##### Reviews :\nThe reviews column is in string format and we need to convert it into numeric type", "_____no_output_____" ] ], [ [ "df['Reviews']=df['Reviews'].apply(pd.to_numeric)", "_____no_output_____" ] ], [ [ "After cleaning some columns and rows we obtained the required format to perform the analysis", "_____no_output_____" ] ], [ [ "df.head(5)", "_____no_output_____" ] ], [ [ "# DATA VISUALIZATION", "_____no_output_____" ], [ "In this we are taking a parameter as reference and checking the trend of another parameter like whether there is a rise or fall,which category are more,what kinds are of more intrest and so on.", "_____no_output_____" ], [ "###### Basic pie chart to view distribution of apps across various categories", "_____no_output_____" ] ], [ [ "fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(aspect=\"equal\"))\nnumber_of_apps = df[\"Category\"].value_counts()\nlabels = number_of_apps.index\nsizes = number_of_apps.values\nax.pie(sizes,labeldistance=2,autopct='%1.1f%%')\nax.legend(labels=labels,loc=\"right\",bbox_to_anchor=(0.9, 0, 0.5, 1))\nax.axis(\"equal\")\nplt.show()", "_____no_output_____" ] ], [ [ "## App count for certain range of Ratings", "_____no_output_____" ], [ "In this we are finding the count of apps for each range from 0 to 5 ie how many apps have more rating,how many are less rated.", "_____no_output_____" ] ], [ [ "bins=pd.cut(df['Rating'],[0.0,1.0,2.0,3.0,4.0,5.0])\nrating_df=pd.DataFrame(df.groupby(bins)['App'].count())\nrating_df.reset_index(inplace=True)\nrating_df", "_____no_output_____" ], [ "plt.figure(figsize=(12, 6))\naxis=sns.barplot('Rating','App',data=rating_df);\naxis.set(ylabel= \"App count\",title='APP COUNT STATISTICS ACCORDING TO RATING');", "_____no_output_____" ] ], [ [ "We can see that most of the apps are with rating 4 and above and very less apps have rating below 2.", "_____no_output_____" ], [ "## Top5 Apps with highest review count ", "_____no_output_____" ], [ "In this we are retrieving the top5 apps with more number of reviews and seeing it visually how their review count is changing.", "_____no_output_____" ] ], [ [ "reviews_df=df.sort_values('Reviews').tail(15).drop_duplicates(subset='App')[['App','Reviews','Rating']]\nreviews_df", "_____no_output_____" ], [ "plt.figure(figsize=(12, 6))\naxis=sns.lineplot(x=\"App\",y=\"Reviews\",data=reviews_df)\naxis.set(title=\"Top 5 most Reviewed Apps\");\nsns.set_style('darkgrid')", "_____no_output_____" ] ], [ [ "Facebook has more reviews compared to other apps in the playstore", "_____no_output_____" ], [ "## Which content type Apps are more in playstore", "_____no_output_____" ], [ "In this we are grouping the apps according to their content type and visually observing the result", "_____no_output_____" ] ], [ [ "content_df=pd.DataFrame(df.groupby('Content Rating')['App'].count())\ncontent_df.reset_index(inplace=True)\ncontent_df", "_____no_output_____" ], [ "plt.figure(figsize=(12, 6))\nplt.bar(content_df['Content Rating'],content_df['App']);\nplt.xlabel('Content Rating')\nplt.ylabel('App count')\nplt.title('App count for different Contents');", "_____no_output_____" ] ], [ [ "Most of the apps in playstore can be used by everyone irrespective of the age.Only 3 apps are A rated", "_____no_output_____" ], [ "##### ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------", "_____no_output_____" ], [ "## Free vs Paid Apps", "_____no_output_____" ], [ "Let's see variations considering type of App ie paid and free apps", "_____no_output_____" ] ], [ [ "Type_df=df.groupby('Type')[['App']].count()\nType_df['Rating']=df.groupby('Type')['Rating'].mean()\n", "_____no_output_____" ], [ "Type_df.reset_index(inplace=True)\nType_df", "_____no_output_____" ] ], [ [ "We found the number of apps that are freely available and their average rating and also number of paid apps and their average rating.", "_____no_output_____" ] ], [ [ "fig, axes = plt.subplots(1, 2, figsize=(18, 6))\naxes[0].bar(Type_df.Type,Type_df.App)\naxes[0].set_title(\"Number of free and paid apps\")\naxes[0].set_ylabel('App count')\naxes[1].bar(Type_df.Type,Type_df.Rating)\naxes[1].set_title('Average Rating of free and paid apps')\naxes[1].set_ylabel('Average Rating');", "_____no_output_____" ] ], [ [ "#### Conclusion", "_____no_output_____" ], [ "Average rating of Paid Apps is more than Free apps.So,we can say that paid apps are trust worthy and we can invest in them", "_____no_output_____" ], [ "##### -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------", "_____no_output_____" ], [ "## Max Installs", "_____no_output_____" ], [ "In this we are finding the apps with more number of installs and as we dont have exact count of installs we got around 20 apps with 1B+ downloads\nFrom the 20 apps we will see some analysis of what types are more installed", "_____no_output_____" ] ], [ [ "max_installs=df.loc[df['Installs']==df.Installs.max()][['App','Category','Reviews','Rating','Installs','Content Rating']]", "_____no_output_____" ], [ "max_installs=max_installs.drop_duplicates(subset='App')\nmax_installs", "_____no_output_____" ] ], [ [ "These are the 20 apps which are with 1B+ downloads", "_____no_output_____" ], [ "### Which App has more rating and trend of 20 apps rating", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(12, 6))\nsns.barplot('Rating','App',data=max_installs);", "_____no_output_____" ] ], [ [ "We can see that Google photos,Instagram and Subway Surfers are the most rated Apps which have 1B+ downloads.\nThough the Apps are used by 1B+ users they have a good rating too", "_____no_output_____" ], [ "### Which content Apps are most Installed", "_____no_output_____" ], [ "We will group the most installed apps according to their content and see which content apps are most installed", "_____no_output_____" ] ], [ [ "content_max_df=pd.DataFrame(max_installs.groupby('Content Rating')['App'].count())\ncontent_max_df.reset_index(inplace=True)\ncontent_max_df", "_____no_output_____" ], [ "plt.figure(figsize=(12, 6))\naxis=sns.barplot('Content Rating','App',data=content_max_df);\naxis.set(ylabel= \"App count\",title='Max Installed APP COUNT STATISTICS ACCORDING TO Content RATING');", "_____no_output_____" ] ], [ [ "More than 10 apps are of type which can be used by any age group and about 8 apps are teen aged apps.Only 1 app is to used by person with age 10+", "_____no_output_____" ], [ "### Which category Apps are more Installed", "_____no_output_____" ], [ "In this we will group the most installed apps according to their category and see which category are on high demand", "_____no_output_____" ] ], [ [ "category_max_df=pd.DataFrame(max_installs.groupby('Category')['App'].count())\ncategory_max_df.reset_index(inplace=True)\ncategory_max_df", "_____no_output_____" ], [ "plt.figure(figsize=(12, 6))\naxis=sns.barplot('App','Category',data=category_max_df);\nplt.plot(category_max_df.App,category_max_df.Category,'o--r')\naxis.set(ylabel= \"App count\",title='Max Installed APP COUNT STATISTICS ACCORDING TO Category');", "_____no_output_____" ] ], [ [ "Communication Apps are mostly installed by people like facebook,whatsapp,instagram..and then social apps are in demand.", "_____no_output_____" ], [ "#### Conclusion", "_____no_output_____" ], [ "The most installed apps ie apps with downloads more than 1 Billion are mostly Communication related apps and can be used by any age group without any restriction and also have high user rating.", "_____no_output_____" ], [ "###### ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------", "_____no_output_____" ], [ "## Final Conclusion", "_____no_output_____" ], [ "This analysis is mostly based on the existing data in the dataset , how one parameter is changing with respect to another parameter,whether paid apps are trust worthy and intrests of people towards some particular categories. \n\nThis analysis can further be extended to predict the number of installs and ratings would be if a new app is launched by some Machine Learning algortihms and models.\n", "_____no_output_____" ], [ "##### -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------", "_____no_output_____" ], [ "### THANK YOU :) ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d0311e7ccab2bbfc6bc823da55201444052dbcf2
381,549
ipynb
Jupyter Notebook
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
coding-ss/DS-Unit-1-Sprint-3-Data-Storytelling
174df212cca746350ac54bf4fc18eb7b0967b6b4
[ "MIT" ]
1
2019-02-14T17:10:28.000Z
2019-02-14T17:10:28.000Z
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
ssingh1187/DS-Unit-1-Sprint-3-Data-Storytelling
174df212cca746350ac54bf4fc18eb7b0967b6b4
[ "MIT" ]
null
null
null
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
ssingh1187/DS-Unit-1-Sprint-3-Data-Storytelling
174df212cca746350ac54bf4fc18eb7b0967b6b4
[ "MIT" ]
null
null
null
78.298584
30,732
0.598592
[ [ [ "_Lambda School Data Science_\n\n# Make explanatory visualizations\n\n\n\n\nTody we will reproduce this [example by FiveThirtyEight:](https://fivethirtyeight.com/features/al-gores-new-movie-exposes-the-big-flaw-in-online-movie-ratings/)", "_____no_output_____" ] ], [ [ "from IPython.display import display, Image\n\nurl = 'https://fivethirtyeight.com/wp-content/uploads/2017/09/mehtahickey-inconvenient-0830-1.png'\nexample = Image(url=url, width=400)\n\ndisplay(example)", "_____no_output_____" ] ], [ [ "Using this data: https://github.com/fivethirtyeight/data/tree/master/inconvenient-sequel", "_____no_output_____" ], [ "Objectives\n- add emphasis and annotations to transform visualizations from exploratory to explanatory\n- remove clutter from visualizations\n\nLinks\n- [Strong Titles Are The Biggest Bang for Your Buck](http://stephanieevergreen.com/strong-titles/)\n- [Remove to improve (the data-ink ratio)](https://www.darkhorseanalytics.com/blog/data-looks-better-naked)\n- [How to Generate FiveThirtyEight Graphs in Python](https://www.dataquest.io/blog/making-538-plots/)", "_____no_output_____" ], [ "## Make prototypes\n\nThis helps us understand the problem", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\nplt.style.use('fivethirtyeight')\n\nfake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], \n index=range(1,11)) # index will start from 0 if not for this\n\nfake.plot.bar(color='C1', width=0.9);", "_____no_output_____" ], [ "fake2 = pd.Series(\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 2, 2, 2, \n 3, 3, 3,\n 4, 4,\n 5, 5, 5,\n 6, 6, 6, 6,\n 7, 7, 7, 7, 7,\n 8, 8, 8, 8,\n 9, 9, 9, 9, \n 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10])\n\nfake2.value_counts().sort_index().plot.bar(color='C1', width=0.9);", "_____no_output_____" ] ], [ [ "## Annotate with text", "_____no_output_____" ] ], [ [ "display(example)", "_____no_output_____" ], [ "plt.style.use('fivethirtyeight')\n\nfake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], \n index=range(1,11)) # index will start from 0 if not for this\n\nfake.plot.bar(color='C1', width=0.9);", "_____no_output_____" ], [ "# rotate x axis numbers\n\nplt.style.use('fivethirtyeight')\n\nfake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], \n index=range(1,11)) # index will start from 0 if not for this\n\nax = fake.plot.bar(color='C1', width=0.9)\n\nax.tick_params(labelrotation=0) #to unrotate or remove the rotation\n\nax.set(title=\"'An Incovenient Sequel: Truth to Power' is divisive\"); \n#or '\\'An Incovenient Sequel: Truth to Power\\' is divisive'\n\n", "_____no_output_____" ], [ "plt.style.use('fivethirtyeight')\n\nfake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], \n index=range(1,11)) # index will start from 0 if not for this\n\nax = fake.plot.bar(color='C1', width=0.9)\n\nax.tick_params(labelrotation=0) \n\nax.text(x=-2,y=48,s=\"'An Incovenient Sequel: Truth to Power' is divisive\",\n fontsize=16, fontweight='bold')\n\nax.text(x=-2,y=45, s='IMDb ratings for the film as of Aug. 29',\n fontsize=12)\n\nax.set(xlabel='Rating',\n ylabel='Percent of total votes',\n yticks=range(0,50,10)); \n#(start pt., end pt., increment)", "_____no_output_____" ] ], [ [ "## Reproduce with real data", "_____no_output_____" ] ], [ [ "df = pd.read_csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/inconvenient-sequel/ratings.csv')", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "width,height = df.shape\nwidth*height", "_____no_output_____" ], [ "pd.options.display.max_columns = 500\ndf.head()", "_____no_output_____" ], [ "df.sample(1).T", "_____no_output_____" ], [ "df.timestamp.describe()", "_____no_output_____" ], [ "# convert timestamp to date time\n\ndf.timestamp = pd.to_datetime(df.timestamp)", "_____no_output_____" ], [ "df.timestamp.describe()", "_____no_output_____" ], [ "# Making datetime index of your df\n\ndf = df.set_index('timestamp')", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df['2017-08-09']\n# everything from this date", "_____no_output_____" ], [ "df.category.value_counts()", "_____no_output_____" ] ], [ [ "####only interested in IMDb users", "_____no_output_____" ] ], [ [ "df.category == 'IMDb users'", "_____no_output_____" ], [ "# As a filter to select certain rows\n\ndf[df.category == 'IMDb users']", "_____no_output_____" ], [ "lastday = df['2017-08-09']", "_____no_output_____" ], [ "lastday.head(1)", "_____no_output_____" ], [ "lastday[lastday.category =='IMDb users'].tail()", "_____no_output_____" ], [ "lastday[lastday.category =='IMDb users'].respondents.plot();", "_____no_output_____" ], [ "final = df.tail(1)", "_____no_output_____" ], [ "#columns = ['1_pct','2_pct','3_pct','4_pct','5_pct','6_pct','7_pct','8_pct','9_pct','10_pct']\n\n#OR\n\ncolumns = [str(i) + '_pct' for i in range(1,11)]\nfinal[columns]\n\n#OR\n#data.index.str.replace('_pct', '')", "_____no_output_____" ], [ "data = final[columns].T", "_____no_output_____" ], [ "data", "_____no_output_____" ], [ "data.plot.bar()", "_____no_output_____" ], [ "plt.style.use('fivethirtyeight')\n\n\nax = data.plot.bar(color='C1', width=0.9)\n\nax.tick_params(labelrotation=0) \n\nax.text(x=-2,y=48,s=\"'An Incovenient Sequel: Truth to Power' is divisive\",\n fontsize=16, fontweight='bold')\n\nax.text(x=-2,y=44, s='IMDb ratings for the film as of Aug. 29',\n fontsize=12)\n\nax.set(xlabel='Rating',\n ylabel='Percent of total votes',\n yticks=range(0,50,10)); \n#(start pt., end pt., increment)", "_____no_output_____" ], [ "# to remove the timestamp texts in the center\n# to change the x axis texts\n\nplt.style.use('fivethirtyeight')\n\n\nax = data.plot.bar(color='C1', width=0.9, legend=False)\n\nax.tick_params(labelrotation=0) \n\nax.text(x=-2,y=48,s=\"'An Incovenient Sequel: Truth to Power' is divisive\",\n fontsize=16, fontweight='bold')\n\nax.text(x=-2,y=44, s='IMDb ratings for the film as of Aug. 29',\n fontsize=12)\n\nax.set(xlabel='Rating',\n ylabel='Percent of total votes',\n yticks=range(0,50,10)); \n", "_____no_output_____" ], [ "data.index = range(1,11)\n\ndata", "_____no_output_____" ], [ "plt.style.use('fivethirtyeight')\n\n\nax = data.plot.bar(color='C1', width=0.9, legend=False)\n\nax.tick_params(labelrotation=0) \n\nax.text(x=-2,y=48,s=\"'An Incovenient Sequel: Truth to Power' is divisive\",\n fontsize=16, fontweight='bold')\n\nax.text(x=-2,y=44, s='IMDb ratings for the film as of Aug. 29',\n fontsize=12)\n\nax.set(xlabel='Rating',\n ylabel='Percent of total votes',\n yticks=range(0,50,10))\n\nplt.xlabel('Rating', fontsize=14); ", "_____no_output_____" ] ], [ [ "# ASSIGNMENT\n\nReplicate the lesson code. I recommend that you [do not copy-paste](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit).\n\n# STRETCH OPTIONS\n\n#### Reproduce another example from [FiveThityEight's shared data repository](https://data.fivethirtyeight.com/).\n\nFor example:\n- [thanksgiving-2015](https://fivethirtyeight.com/features/heres-what-your-part-of-america-eats-on-thanksgiving/) (try the [`altair`](https://altair-viz.github.io/gallery/index.html#maps) library)\n- [candy-power-ranking](https://fivethirtyeight.com/features/the-ultimate-halloween-candy-power-ranking/) (try the [`statsmodels`](https://www.statsmodels.org/stable/index.html) library)\n- or another example of your choice!\n\n#### Make more charts!\n\nChoose a chart you want to make, from [FT's Visual Vocabulary poster](http://ft.com/vocabulary).\n\nFind the chart in an example gallery of a Python data visualization library:\n- [Seaborn](http://seaborn.pydata.org/examples/index.html)\n- [Altair](https://altair-viz.github.io/gallery/index.html)\n- [Matplotlib](https://matplotlib.org/gallery.html)\n- [Pandas](https://pandas.pydata.org/pandas-docs/stable/visualization.html)\n\nReproduce the chart. [Optionally, try the \"Ben Franklin Method.\"](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit) If you want, experiment and make changes.\n\nTake notes. Consider sharing your work with your cohort!\n\n\n\n\n\n\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
d031250dd00d3550f518e8e224c2e57b74b9ef4d
51,319
ipynb
Jupyter Notebook
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
15fd1c730b0ae2aec47d6156aaa448d3390efca6
[ "MIT" ]
null
null
null
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
15fd1c730b0ae2aec47d6156aaa448d3390efca6
[ "MIT" ]
null
null
null
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
15fd1c730b0ae2aec47d6156aaa448d3390efca6
[ "MIT" ]
null
null
null
38.355007
390
0.50987
[ [ [ "# Exam 2 - Gema Castillo García", "_____no_output_____" ] ], [ [ "%load_ext sql\n%config SqlMagic.autocommit=True\n%sql mysql+pymysql://root:root@127.0.0.1:3306/mysql", "_____no_output_____" ] ], [ [ "\n## Problem 1: Controls\n\nWrite a Python script that proves that the lines of data in Germplasm.tsv, and LocusGene are in the same sequence, based on the AGI Locus Code (ATxGxxxxxx). (hint: This will help you decide how to load the data into the database)", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport csv\n\ngp = pd.read_csv('Germplasm.tsv', sep='\\t')\nmatrix2 = gp[gp.columns[0]].to_numpy()\ngermplasm = matrix2.tolist()\n#print(germplasm) ##to see the first column (AGI Locus Codes) of Germplasm.tsv\n\nlg = pd.read_csv('LocusGene.tsv', sep='\\t')\nmatrix2 = lg[lg.columns[0]].to_numpy()\nlocus = matrix2.tolist()\n#print(locus) ##to see the first column (AGI Locus Codes) of LocusGene.tsv\n\n\nif (germplasm == locus):\n print(\"lines of data are in the same sequence\")\nelse:\n print(\"lines of data are not in the same sequence\")", "lines of data are in the same sequence\n" ] ], [ [ "**I have only compared the first columns because is where AGI Codes are (they are the same in the two tables).**", "_____no_output_____" ], [ "## Problem 2: Design and create the database. \n* It should have two tables - one for each of the two data files\n* The two tables should be linked in a 1:1 relationship\n* you may use either sqlMagic or pymysql to build the database\n\n\n", "_____no_output_____" ] ], [ [ "##creating a database called germplasm\n%sql create database germplasm;\n\n\n##showing the existing databases\n%sql show databases;", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n5 rows affected.\n" ], [ "##selecting the new database to interact with it\n%sql use germplasm;\n\n\n%sql show tables;\n##the database is empty (it has not tables as expected)", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n0 rows affected.\n * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n0 rows affected.\n" ], [ "##showing the structure of the tables I want to add to the germplasm database\ngermplasm_file = open(\"Germplasm.tsv\", \"r\")\nprint(germplasm_file.read())\n\nprint()\nprint()\n\nlocus_file = open(\"LocusGene.tsv\", \"r\")\nprint(locus_file.read())\n\ngermplasm_file.close() ##closing the Germplasm.tsv file\nlocus_file.close() ##closing the LocusGene.tsv file", "Locus\tgermplasm\tphenotype\tpubmed\nAT1G01040\tCS3828\tIncreased abundance of miRNA precursors.\t17369351\nAT1G01060\tlhy-101\tThe mutant plants are hypersensitive to both FRc and Rc light treatments in hypocotyl elongation and exhibits a small reciprocal enlargement in cotyledon area, albeit not statistically significant.\t16891401\nAT1G01140\tSALK_058629\thypersensitive to low potassium media\t17486125\nAT1G01220\tSALK_012400C\tfkgp-1 mutants have about 40 times more L-fucose than wild type Arabidopsis plants, but the levels of other monosaccharides do not appear to differ significantly in the mutants. No obvious phenotypic abnormalities were observed in the fkgp-1 mutants, nor were any differences in the sugar composition of cell wall polysaccharides detected.\t18199744\nAT2G03720\tSALK_042433\tMultiple straight hairs\t16367956\nAT2G03800\tgek1-1\tEthanol hypersensitivity.\t15215505\nAT2G04240\txerico\tResistant to exogenous ABA. Seeds contained lower amounts of endogenous ABA than wildtype.\t17933900\nAT2G05210\tpot1-1\tNo visible phenotype.\t17627276\nAT3G02130\trpk2-2\tThe homozygous progeny is indistinguishable from wild-type plants during vegetative growth but showed several morphological alterations after bolting. These plants displayed enhanced inflorescence branching and formed three times as many siliques and flowers as did wild-type plants.\t17419837\nAT3G02140\tafp4-1\tDecreased germination on high concentrations of glucose and sorbitol.\t18484180\nAT3G02230\trgp1-1\trgp1-1 mutants have significantly lower levels of UDP-L-arabinose mutase activity compared to wild-type plants and significantly lower levels of arabinose in their cell walls.\t21478444\nAT3G02260\ttir3-1 RGLG1:rglg1 rglg2\tThe triple homozygous progeny has low viability, accumulated anthocyanin, and all plants died before shoot emergence.\t17586653\nAT3G02310\tsep2-1\tNon-described subtle phenotype.\t10821278\nAT3G02680\tatnbs1-1\tSignificantly smaller when grown in the presence of methyl methanosulfonate (MMS) with root growth. Normal growth under standard growth conditions.\t17672843\nAT3G02850\tCS3816\tThe skor-1 mutant is sensitive to toxic cations in addition to K+ depletion.\t17568770\nAT3G02870\tvtc4-1\tascorbate deficient\t16595667\nAT3G03260\thdg8-1\tNo visible phenotype.\t16778018\nAT4G14790\tpdd17\tDefective pollen development.\t19237690\nAT4G15210\tbmy1-2\tPlants cold-shocked for 6h have an increased starch content compared to wildtype.\t16297066\nAT4G15560\tcla1-1\tMutant seeds grown on medium supplemented with non-phosphorylated synthetic 1-deoxy-D-xylulose (DX) develop green leaves.\t10982425\nAT4G15570\tmaa3\tHomozygotes are not recovered. Female gametophyte development is delayed and asynchronous. During fertilization, fusion of polar nuclei does not occur. Polar nuclei nucloeli are smaller than WT.\t18772186\nAT4G15802\tAthspb-2\tEarly flowering, reduced fertility, aborted seeds.\t20388662\nAT4G15880\tesd4-2\tDecreased mRNA levels of the floral repressors FLC and MAF4 and increased mRNA levels of the floral activators FT and SOC1.\t17513499\nAT4G16420\tprz1-1\tAltered response to auxin and cytokinin\t12747832\nAT4G16480\tatint4-2\tNo visible phenotype.\t16603666\nAT5G10480\tpas2-3\tSegregates 25% embryo lethal.\t18799749\nAT5G10510\tplt3-1\tShort roots and shortened root meristem.\t17960244\nAT5G11110\tkns2\tDefects are specific to pollen exine structure. Smaller mesh size in the exine structure. Increased number of baculae. Fully fertile.\t18779216\nAT5G11260\thy5-101\tUnder FRc conditions, the length mutant hypocotyls is increased compared to that of wild-type plants. Under Rc conditions, the hypocotyl length is also increased and the cotyledon area is smaller.\t16891401\nAT5G11510\tmyb3r4-1\tNo visible phenotype.\t17287251\nAT5G12200\tpyd2-2\tThe pyd2-2 mutant has a wild-type appearance under normal growth conditions. Pyrimidine nucleotide and uridine levels are not changed in the mutant, but uracil levels are increased. These mutants cannot grow normally when uracil is provided as a sole nitrogen source.\t19413687\nAT5G13290\tcrn-1\tIncreased meristem size. Vegetative meristems are are 30% larger than wild type. After bolting inflorescence meristems are enlarged and occasionally fasciated. Flowers occasionally produce extra organs in the first 3.\t12345678\n\n\n\nLocus\tGene\tProteinLength\nAT1G01040\tDCL1\t332\nAT1G01060\tLHY\t290\nAT1G01140\tCIPK9\t223\nAT1G01220\tFKGP\t190\nAT2G03720\tMRH6\t189\nAT2G03800\tGEK1\t196\nAT2G04240\tXERICO\t256\nAT2G05210\tPOT1A\t221\nAT3G02130\tRPK2\t284\nAT3G02140\tTMAC2\t300\nAT3G02230\tRGP1\t301\nAT3G02260\tBIG\t279\nAT3G02310\tSEP2\t175\nAT3G02680\tNBS1\t190\nAT3G02850\tSKOR\t234\nAT3G02870\tVTC4\t311\nAT3G03260\tHDG8\t194\nAT4G14790\tSUV3\t312\nAT4G15210\tBAM5\t313\nAT4G15560\tDXS\t219\nAT4G15570\tMAA3\t294\nAT4G15802\tHSBP\t254\nAT4G15880\tESD4\t265\nAT4G16420\tADA2B\t279\nAT4G16480\tINT4\t284\nAT5G10480\tPAS2\t301\nAT5G10510\tAIL6\t310\nAT5G11110\tSPS2\t232\nAT5G11260\tHY5\t221\nAT5G11510\tMYB3R-4\t336\nAT5G12200\tPYD2\t310\nAT5G13290\tCRN\t189\n\n" ], [ "##creating a table for Germplasm data\n%sql CREATE TABLE Germplasm_table(locus VARCHAR(10) NOT NULL PRIMARY KEY, germplasm VARCHAR(30) NOT NULL, phenotype VARCHAR(1000) NOT NULL, pubmed INTEGER NOT NULL);\n%sql DESCRIBE Germplasm_table;", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n0 rows affected.\n * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n4 rows affected.\n" ], [ "##creating a table for Locus data\n%sql CREATE TABLE Locus_table(locus VARCHAR(10) NOT NULL PRIMARY KEY, gene VARCHAR(10) NOT NULL, protein_lenght INTEGER NOT NULL);\n%sql DESCRIBE Locus_table;", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n0 rows affected.\n * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n3 rows affected.\n" ], [ "##showing the created tables\n%sql show tables;", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n2 rows affected.\n" ], [ "##showing all of the data linking the two tables in a 1:1 relationship (it is empty because I have not introduced the data yet)\n%sql SELECT Germplasm_table.locus, Germplasm_table.germplasm, Germplasm_table.phenotype, Germplasm_table.pubmed, Locus_table.gene, Locus_table.protein_lenght\\\nFROM Germplasm_table, Locus_table\\\nWHERE Germplasm_table.locus = Locus_table.locus;", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n0 rows affected.\n" ] ], [ [ "**- I have designed a database with two tables: Germplasm_table for Germplasm.tsv and Locus_table for LocusGene.tsv**\n\n**- The primary keys to link the two tables in a 1:1 relationship are in the 'locus' column of each table**", "_____no_output_____" ], [ "## Problem 3: Fill the database\nUsing pymysql, create a Python script that reads the data from these files, and fills the database. There are a variety of strategies to accomplish this. I will give all strategies equal credit - do whichever one you are most confident with.", "_____no_output_____" ] ], [ [ "import csv\nimport re\n\nwith open(\"Germplasm.tsv\", \"r\") as Germplasm_file:\n next(Germplasm_file) ##skipping the first row\n for line in Germplasm_file:\n line = line.rstrip() ##removing blank spaces created by the \\n (newline) character at the end of every line\n print(line, file=open('Germplasm_wo_header.tsv', 'a'))\n\nGermplasm_woh = open(\"Germplasm_wo_header.tsv\", \"r\")\n\n\n\nimport pymysql.cursors\n\n##connecting to the database (db) germplasm\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='root',\n db='germplasm',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\nconnection.autocommit(True)\n\n \ntry:\n with connection.cursor() as cursor:\n sql = \"INSERT INTO Germplasm_table (locus, germplasm, phenotype, pubmed) VALUES (%s, %s, %s, %s)\"\n for line in Germplasm_woh.readlines():\n field = line.split(\"\\t\") ##this splits the lines and inserts each field into a column\n fields = (field[0], field[1], field[2], field[3])\n cursor.execute(sql, fields) \n connection.commit()\nfinally:\n print(\"inserted\")\n #connection.close()", "inserted\n" ], [ "%sql SELECT * FROM Germplasm_table;", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n32 rows affected.\n" ], [ "import csv\nimport re\n\nwith open(\"LocusGene.tsv\", \"r\") as LocusGene_file:\n next(LocusGene_file) ##skipping the first row\n for line in LocusGene_file:\n line = line.rstrip() ##removing blank spaces created by the \\n (newline) character at the end of every line\n print(line, file=open('LocusGene_wo_header.tsv', 'a'))\n\nLocusGene_woh = open(\"LocusGene_wo_header.tsv\", \"r\")\n\n\n\nimport pymysql.cursors\n\n##connecting to the database (db) germplasm\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='root',\n db='germplasm',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\nconnection.autocommit(True)\n\n \ntry:\n with connection.cursor() as cursor:\n sql = \"INSERT INTO Locus_table (locus, gene, protein_lenght) VALUES (%s, %s, %s)\"\n for line in LocusGene_woh.readlines():\n field = line.split(\"\\t\") ##this splits the lines and inserts each field into a column\n fields = (field[0], field[1], field[2])\n cursor.execute(sql, fields) \n connection.commit()\nfinally:\n print(\"inserted\")\n #connection.close()", "inserted\n" ], [ "%sql SELECT * FROM Locus_table;", " * mysql+pymysql://root:***@127.0.0.1:3306/mysql\n32 rows affected.\n" ] ], [ [ "To do this exercise, I have asked Andrea Álvarez for some help because I did not understand well what you did in the suggested practice to fill databases.\n\n**As 'pubmed' and 'protein_length' columns are for INTEGERS, I have created new TSV files without the header (the first row gave me an error in those columns because of the header).**", "_____no_output_____" ], [ "## Problem 4: Create reports, written to a file\n\n1. Create a report that shows the full, joined, content of the two database tables (including a header line)\n\n2. Create a joined report that only includes the Genes SKOR and MAA3\n\n3. Create a report that counts the number of entries for each Chromosome (AT1Gxxxxxx to AT5Gxxxxxxx)\n\n4. Create a report that shows the average protein length for the genes on each Chromosome (AT1Gxxxxxx to AT5Gxxxxxxx)\n\nWhen creating reports 2 and 3, remember the \"Don't Repeat Yourself\" rule! \n\nAll reports should be written to **the same file**. You may name the file anything you wish.", "_____no_output_____" ] ], [ [ "##creating an empty text file in current directory\nreport = open('exam2_report.txt', 'x')", "_____no_output_____" ], [ "import pymysql.cursors\n\n##connecting to the database (db) germplasm\nconnection = pymysql.connect(host='localhost',\n user='root',\n password='root',\n db='germplasm',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\nconnection.autocommit(True)\n\nprint('Problem 4.1. Create a report that shows the full, joined, content of the two database tables (including a header line):', file=open('exam2_report.txt', 'a'))\ntry:\n with connection.cursor() as cursor:\n sql = \"SELECT 'locus' AS locus, 'germplasm' AS germplasm, 'phenotype' AS phenotype, 'pubmed' AS pubmed, 'gene' AS gene, 'protein_lenght' AS protein_lenght\\\n UNION ALL SELECT Germplasm_table.locus, Germplasm_table.germplasm, Germplasm_table.phenotype, Germplasm_table.pubmed, Locus_table.gene, Locus_table.protein_lenght\\\n FROM Germplasm_table, Locus_table\\\n WHERE Germplasm_table.locus = Locus_table.locus\"\n cursor.execute(sql)\n results = cursor.fetchall()\n for result in results:\n print(result['locus'],result['germplasm'], result['phenotype'], result['pubmed'], result['gene'], result['protein_lenght'], file=open('exam2_report.txt', 'a'))\n\nfinally:\n print(\"Problem 4.1 report written in exam2_report.txt file\")", "Problem 4.1 report written in exam2_report.txt file\n" ] ], [ [ "**I have omitted the locus column from the Locus_table in 4.1 and 4.2 for not repeating information.**", "_____no_output_____" ] ], [ [ "print('\\n\\nProblem 4.2. Create a joined report that only includes the Genes SKOR and MAA3:', file=open('exam2_report.txt', 'a'))\ntry:\n with connection.cursor() as cursor:\n sql = \"SELECT Germplasm_table.locus, Germplasm_table.germplasm, Germplasm_table.phenotype, Germplasm_table.pubmed, Locus_table.gene, Locus_table.protein_lenght\\\n FROM Germplasm_table, Locus_table\\\n WHERE Germplasm_table.locus = Locus_table.locus AND (Locus_table.gene = 'SKOR' OR Locus_table.gene = 'MAA3')\"\n cursor.execute(sql)\n results = cursor.fetchall()\n for result in results:\n print(result['locus'],result['germplasm'], result['phenotype'], result['pubmed'], result['gene'], result['protein_lenght'], file=open('exam2_report.txt', 'a'))\n\nfinally:\n print(\"Problem 4.2 report written in exam2_report.txt file\")", "Problem 4.2 report written in exam2_report.txt file\n" ], [ "print('\\n\\nProblem 4.3. Create a report that counts the number of entries for each Chromosome:', file=open('exam2_report.txt', 'a'))\ntry:\n with connection.cursor() as cursor:\n i = 1 ##marks the beginning of the loop (i.e., chromosome 1)\n while i < 6:\n sql = \"SELECT COUNT(*) AS 'Entries for each Chromosome' FROM Germplasm_table WHERE locus REGEXP 'AT\"+str(i)+\"G'\"\n cursor.execute(sql)\n results = cursor.fetchall()\n for result in results:\n print(\"- Chromosome\", i, \"has\", result['Entries for each Chromosome'], \"entries.\", file=open('exam2_report.txt', 'a'))\n i = i +1\nfinally:\n print(\"Problem 4.3 report written in exam2_report.txt file\")", "Problem 4.3 report written in exam2_report.txt file\n" ], [ "print('\\n\\nProblem 4.4. Create a report that shows the average protein length for the genes on each Chromosome:', file=open('exam2_report.txt', 'a'))\ntry:\n with connection.cursor() as cursor:\n i = 1 ##marks the beginning of the loop (i.e., chromosome 1)\n while i < 6:\n sql = \"SELECT AVG(protein_lenght) AS 'Average protein length for each Chromosome' FROM Locus_table WHERE locus REGEXP 'AT\"+str(i)+\"G'\"\n cursor.execute(sql)\n results = cursor.fetchall()\n for result in results:\n print(\"- Average protein length for chromosome\", i, \"genes is\", result['Average protein length for each Chromosome'], file=open('exam2_report.txt', 'a'))\n i = i +1\nfinally:\n print(\"Problem 4.4 report written in exam2_report.txt file\")\n\n\n##closing the report file with 'Problem 4' answers\nreport.close()", "Problem 4.4 report written in exam2_report.txt file\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d0313c9d3b7ff476952b6cde10add64678da5062
26,859
ipynb
Jupyter Notebook
Multiprocessing.ipynb
pawarbi/snippets
8ccec3a97ae69ad80c2a11a763c051849c094a3c
[ "Apache-2.0" ]
null
null
null
Multiprocessing.ipynb
pawarbi/snippets
8ccec3a97ae69ad80c2a11a763c051849c094a3c
[ "Apache-2.0" ]
null
null
null
Multiprocessing.ipynb
pawarbi/snippets
8ccec3a97ae69ad80c2a11a763c051849c094a3c
[ "Apache-2.0" ]
null
null
null
54.260606
16,232
0.774824
[ [ [ "# Quick Multi-Processing Tests", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport time\nimport numba\nimport pandas as pd\n\nimport pyspark\nfrom pyspark.sql import SparkSession", "_____no_output_____" ] ], [ [ "Defining a an arbitrary function for testing. The function doesn't mean anything.", "_____no_output_____" ] ], [ [ "def fun(x):\n return x * np.sin(10*x) + np.tan(34*x) + np.log(x)", "_____no_output_____" ], [ "#Calcluate a value for testing\nfun(10)", "_____no_output_____" ], [ "#Plot the function, for testing\nx = np.arange(0.1,10,0.5)\nplt.plot(x,fun(x));", "_____no_output_____" ] ], [ [ "### Benchmark \n\nWithout any parallelism, for comparison purposes", "_____no_output_____" ] ], [ [ "%%timeit\nn = int(1e7) ## Using a large number to iterate\n\ndef f(n):\n x = np.random.random(n)\n y = (x * np.sin(10*x) + np.tan(34*x) + np.log(x))\n \n \n return y\nf(n)", "652 ms ± 2.79 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ] ], [ [ "652 ms without parallel processing", "_____no_output_____" ], [ "### ProcessPool Execution", "_____no_output_____" ], [ "[ProcessPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html) uses executes the processes asynchronously by using the number of processors assigned, in parallel.", "_____no_output_____" ] ], [ [ "%%time\n\nwith ProcessPoolExecutor(max_workers=4) as executor:\n result = executor.map(f, [int(1e7) for i in range(10)])", "Wall time: 312 ms\n" ] ], [ [ "Execution time dropped from 652 ms to 312 ms! This can be further optimized by specifying the number of processors to use and the chunk size. I will skip that for now.", "_____no_output_____" ], [ "### ThreadPool Execution", "_____no_output_____" ], [ "Similar to `ProcessPool` but uses threads instead of CPU.", "_____no_output_____" ] ], [ [ "%%time\n\nwith ThreadPoolExecutor(max_workers=4) as texecute:\n result_t = texecute.map(f, [int(1e7) for i in range(10)])", "Wall time: 3.67 s\n" ] ], [ [ "Far worse than the benchmark and the `ProcessPool`. I am not entirely sure why, but most lilelt because the interpreter is allowing only 1 thread to run or is creating an I/O bottleneck. ", "_____no_output_____" ], [ "### Using NUMBA", "_____no_output_____" ], [ "I have used `numba` for JIT compilation for some of my programs for bootstrapping. ", "_____no_output_____" ] ], [ [ "%%time\n@numba.jit(nopython=True, parallel=True)\ndef f2(n):\n x = np.random.random(n)\n y = (x * np.sin(10*x) + np.tan(34*x) + np.log(x))\n \n \n return y\nf2(int(1e7))", "Wall time: 400 ms\n" ] ], [ [ "400 ms - so better than the bechmark but almost as good as the `ProcessPool` method", "_____no_output_____" ], [ "### Using Spark", "_____no_output_____" ] ], [ [ "spark=( SparkSession.builder.master(\"local\")\n .appName(\"processingtest\")\n .getOrCreate()\n )\n", "_____no_output_____" ], [ "from pyspark.sql.types import FloatType\nfrom pyspark.sql.functions import udf\n", "_____no_output_____" ], [ "n = int(1e7)\ndf = pd.DataFrame({\"x\":np.random.random(n)})", "_____no_output_____" ], [ "df.head(3)", "_____no_output_____" ], [ "def f3(x):\n return (x * np.sin(10*x) + np.tan(34*x) + np.log(x))\nfunc_udf = udf(lambda x: f3(x), FloatType())\n\ndf_spark = spark.createDataFrame(df)\n\ndf_spark.withColumn(\"udf\",func_udf(\"x\"))", "_____no_output_____" ] ], [ [ "Inspecting the Spark job shows execution time as 0.4s (400 ms), as good as numba and `ProcessPool`. Spark would be much more scalable. Th eonly challenge here is the data needs to be converted to a tabular/dataframe format first. For most business process modeling scenarios that's usually not required and is an added step.", "_____no_output_____" ] ], [ [ "spark.stop()", "_____no_output_____" ] ], [ [ "### References : \n\n1. https://medium.com/@nyomanpradipta120/why-you-should-use-threadpoolexecutor-instead-processpoolexecutor-based-on-ctf-challenge-f51e838df351\n\n2. https://docs.python.org/3/library/concurrent.futures.html\n\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d0313cb3c23f860057207d5ffd98f3f586dafa1b
695,489
ipynb
Jupyter Notebook
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
5dc580e7a24d0499722b41d23ace9158443d1ff5
[ "MIT" ]
null
null
null
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
5dc580e7a24d0499722b41d23ace9158443d1ff5
[ "MIT" ]
null
null
null
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
5dc580e7a24d0499722b41d23ace9158443d1ff5
[ "MIT" ]
null
null
null
388.541341
49,136
0.929151
[ [ [ "# Import the libraries\nimport numpy as np\nimport pandas as pd\nimport os\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport warnings\nimport numpy as np\nimport itertools\nimport statsmodels.api as sm\nimport matplotlib\nfrom textwrap import wrap\nfrom matplotlib import ticker\nfrom datetime import datetime\n\n\nwarnings.filterwarnings(\"ignore\")\nplt.style.use('fivethirtyeight')\n%matplotlib inline\n", "_____no_output_____" ] ], [ [ "## Importing the data\n\n", "_____no_output_____" ] ], [ [ "#print(os.listdir('../data'))\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv')\n#df = df.set_index('Date', append=False)\n#df['Date'] = df.apply(lambda x: datetime.strptime(x['Date'], '%d-%m-%Y').date(), axis=1) #convert the date\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\ndf['Date'] = pd.to_datetime(df['Date']) \ndf['date_delta'] = (df['Date'] - df['Date'].min()) / np.timedelta64(1,'D')\ndf.head()", "_____no_output_____" ], [ "#print(os.listdir('../data'))\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv')\n#df = df.set_index('Date', append=False)\n#df['Date'] = df.apply(lambda x: datetime.strptime(x['Date'], '%d-%m-%Y').date(), axis=1) #convert the date\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\ndf.head()", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ], [ "df.describe(include='O')", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "#print('Time period start: {}\\nTime period end: {}'.format(df.year.min(),df.year.max()))", "_____no_output_____" ] ], [ [ "## Visualizing the time series data\n\nWe are going to use matplotlib to visualise the dataset.", "_____no_output_____" ] ], [ [ "# Time series data source: fpp pacakge in R.\nimport matplotlib.pyplot as plt\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\n\n# Draw Plot\ndef plot_df(df, x, y, title=\"\", xlabel='Date', ylabel='Cases', dpi=100,angle=45):\n plt.figure(figsize=(8,4), dpi=dpi)\n plt.plot(x, y, color='tab:red')\n plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)\n plt.xticks(rotation=angle)\n plt.show()\n\nplot_df(df, x=df.Date, y=df.Cases, title='Dayly infiction') ", "_____no_output_____" ], [ "df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')\ndf['Date'].head()", "_____no_output_____" ], [ "df = df.set_index('Date')\ndf.index", "_____no_output_____" ], [ "from pandas import Series\nfrom matplotlib import pyplot\npyplot.figure(figsize=(6,8), dpi= 100)\npyplot.subplot(211)\ndf.Cases.hist()\npyplot.subplot(212)\ndf.Cases.plot(kind='kde')\npyplot.show()", "_____no_output_____" ], [ "from pylab import rcParams\n\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\ndf['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')\ndf = df.set_index('Date')\n\n\nrcParams['figure.figsize'] = 8,6\ndecomposition = sm.tsa.seasonal_decompose(df, model='multiplicative', freq=1)\nfig = decomposition.plot()\nplt.show()", "_____no_output_____" ], [ "df = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\n\nx = df['Date'].values\ny1 = df['Cases'].values\n\n# Plot\nfig, ax = plt.subplots(1, 1, figsize=(6,3), dpi= 120)\nplt.fill_between(x, y1=y1, y2=-y1, alpha=0.5, linewidth=2, color='seagreen')\nplt.ylim(-50, 50)\nplt.title('Dayly Infiction (Two Side View)', fontsize=16)\nplt.hlines(y=0, xmin=np.min(df.Date), xmax=np.max(df.Date), linewidth=.5)\nplt.xticks(rotation=45)\nplt.show()", "_____no_output_____" ] ], [ [ "## Boxplot of Month-wise (Seasonal) and Year-wise (trend) Distribution\n\nYou can group the data at seasonal intervals and see how the values are distributed within a given year or month and how it compares over time.\n\nThe boxplots make the year-wise and month-wise distributions evident. Also, in a month-wise boxplot, the months of December and January clearly has higher drug sales, which can be attributed to the holiday discounts season.\n\nSo far, we have seen the similarities to identify the pattern. Now, how to find out any deviations from the usual pattern?", "_____no_output_____" ] ], [ [ "# Importing the data\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\ndf.reset_index(inplace=True)\n\n# Prepare data\n#df['year'] = [d.year for d in df.Date]\ndf['month'] = [d.strftime('%b') for d in df.Date]\ndf['day']=df['Date'].dt.day\ndf['week']=df['Date'].dt.week\nmonths = df['month'].unique()\n\n# Plotting\nfig, axes = plt.subplots(3,1, figsize=(8,16), dpi= 80)\nsns.boxplot(x='month', y='Cases', data=df, ax=axes[0])\nsns.boxplot(x='week', y='Cases', data=df,ax=axes[1])\nsns.boxplot(x='day', y='Cases', data=df,ax=axes[2])\naxes[0].set_title('Month-wise Box Plot', fontsize=18); \naxes[1].set_title('Week-wise Box Plot', fontsize=18)\naxes[1].set_title('Day-wise Box Plot', fontsize=18)\n\nplt.show()", "_____no_output_____" ] ], [ [ "## Autocorrelation and partial autocorrelation\n\nAutocorrelation measures the relationship between a variable's current value and its past values.\n\nAutocorrelation is simply the correlation of a series with its own lags. If a series is significantly autocorrelated, that means, the previous values of the series (lags) may be helpful in predicting the current value.\n\nPartial Autocorrelation also conveys similar information but it conveys the pure correlation of a series and its lag, excluding the correlation contributions from the intermediate lags.", "_____no_output_____" ] ], [ [ "from statsmodels.graphics.tsaplots import plot_acf\nfrom statsmodels.graphics.tsaplots import plot_pacf\n\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\n\n\npyplot.figure(figsize=(6,8), dpi= 100)\npyplot.subplot(211)\nplot_acf(df.Cases, ax=pyplot.gca(), lags = len(df.Cases)-1)\npyplot.subplot(212)\nplot_pacf(df.Cases, ax=pyplot.gca(), lags = len(df.Cases)-1)\npyplot.show()", "_____no_output_____" ] ], [ [ "## Lag Plots\n\nA Lag plot is a scatter plot of a time series against a lag of itself. It is normally used to check for autocorrelation. If there is any pattern existing in the series like the one you see below, the series is autocorrelated. If there is no such pattern, the series is likely to be random white noise.", "_____no_output_____" ] ], [ [ "from pandas.plotting import lag_plot\nplt.rcParams.update({'ytick.left' : False, 'axes.titlepad':10})\n\n# Import\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\n\n# Plot\nfig, axes = plt.subplots(1, 4, figsize=(10,3), sharex=True, sharey=True, dpi=100)\nfor i, ax in enumerate(axes.flatten()[:4]):\n lag_plot(df.Cases, lag=i+1, ax=ax, c='firebrick')\n ax.set_title('Lag ' + str(i+1))\n fig.suptitle('Lag Plots of Sun Spots Area)', y=1.15) \n\n", "_____no_output_____" ] ], [ [ "## Estimating the forecastability\n\nThe more regular and repeatable patterns a time series has, the easier it is to forecast. Since we have a small dataset, we apply a Sample Entropy to examine that. Put in mind that, The higher the approximate entropy, the more difficult it is to forecast it.\n\n\n\n", "_____no_output_____" ] ], [ [ "# https://en.wikipedia.org/wiki/Sample_entropy\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\n\n\ndef SampEn(U, m, r):\n \"\"\"Compute Sample entropy\"\"\"\n def _maxdist(x_i, x_j):\n return max([abs(ua - va) for ua, va in zip(x_i, x_j)])\n\n def _phi(m):\n x = [[U[j] for j in range(i, i + m - 1 + 1)] for i in range(N - m + 1)]\n C = [len([1 for j in range(len(x)) if i != j and _maxdist(x[i], x[j]) <= r]) for i in range(len(x))]\n return sum(C)\n\n N = len(U)\n return -np.log(_phi(m+1) / _phi(m))\n\nprint(SampEn(df.Cases, m=2, r=0.2*np.std(df.Cases))) ", "0.21622310846963594\n" ] ], [ [ "### Plotting Rolling Statistics\n\nWe observe that the rolling mean and Standard deviation are not constant with respect to time (increasing trend)\n \nThe time series is hence not stationary\n\n", "_____no_output_____" ] ], [ [ "from statsmodels.tsa.stattools import adfuller\ndef test_stationarity(timeseries):\n \n #Determing rolling statistics\n rolmean = pd.Series(timeseries).rolling(window=12).std()\n rolstd = pd.Series(timeseries).rolling(window=12).mean()\n\n #Plot rolling statistics:\n orig = plt.plot(timeseries, color='blue',label='Original')\n mean = plt.plot(rolmean, color='red', label='Rolling Mean')\n std = plt.plot(rolstd, color='black', label = 'Rolling Std')\n plt.legend(loc='best')\n plt.title('Rolling Mean & Standard Deviation')\n plt.show(block=False)\n \n #Perform Dickey-Fuller test:\n print ('Results of Dickey-Fuller Test:')\n dftest = adfuller(timeseries, autolag='AIC')\n dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])\n for key,value in dftest[4].items():\n dfoutput['Critical Value (%s)'%key] = value\n print(dfoutput)", "_____no_output_____" ], [ "df = pd.read_csv('../data/NumberConfirmedOfCases.csv')\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\n\ntest_stationarity(df['Cases'])", "_____no_output_____" ] ], [ [ "The standard deviation and th mean are clearly increasing with time therefore, this is not a stationary series.", "_____no_output_____" ] ], [ [ "from pylab import rcParams\n\n\ndf = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date')\n\ndf = df.groupby('Date')['Cases'].sum().reset_index() #group the data\n\ndf['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')\n\ndf = df.set_index('Date')\n\n\n\n\nts_log = np.log(df)\nplt.plot(ts_log)", "_____no_output_____" ] ], [ [ "# Remove Trend - Smoothing", "_____no_output_____" ] ], [ [ "n = int(len(df.Cases)/2)\nmoving_avg = ts_log.rolling(n).mean()\nplt.plot(ts_log)\nplt.plot(moving_avg, color='red')", "_____no_output_____" ], [ "ts_log_moving_avg_diff = ts_log.Cases - moving_avg.Cases\nts_log_moving_avg_diff.head(n)", "_____no_output_____" ], [ "ts_log_moving_avg_diff.dropna(inplace=True)\ntest_stationarity(ts_log_moving_avg_diff)", "_____no_output_____" ], [ "expwighted_avg = ts_log.ewm(n).mean()\nplt.plot(ts_log)\nplt.plot(expwighted_avg, color='red')", "_____no_output_____" ], [ "ts_log_ewma_diff = ts_log.Cases - expwighted_avg.Cases\ntest_stationarity(ts_log_ewma_diff)", "_____no_output_____" ], [ "ts_log_diff = ts_log.Cases - ts_log.Cases.shift()\nplt.plot(ts_log_diff)", "_____no_output_____" ], [ "ts_log_diff.dropna(inplace=True)\ntest_stationarity(ts_log_diff)", "_____no_output_____" ] ], [ [ "## Autoregressive Integrated Moving Average (ARIMA)\n\nIn an ARIMA model there are 3 parameters that are used to help model the major aspects of a times series: seasonality, trend, and noise. These parameters are labeled p,d,and q.\n\nNumber of AR (Auto-Regressive) terms (p): p is the parameter associated with the auto-regressive aspect of the model, which incorporates past values i.e lags of dependent variable. For instance if p is 5, the predictors for x(t) will be x(t-1)….x(t-5).\n\nNumber of Differences (d): d is the parameter associated with the integrated part of the model, which effects the amount of differencing to apply to a time series.\n \nNumber of MA (Moving Average) terms (q): q is size of the moving average part window of the model i.e. lagged forecast errors in prediction equation. For instance if q is 5, the predictors for x(t) will be e(t-1)….e(t-5) where e(i) is the difference between the moving average at ith instant and actual value.\n\n\n", "_____no_output_____" ] ], [ [ "# ARMA example\nfrom statsmodels.tsa.arima_model import ARMA\nfrom random import random\n\n# fit model\nmodel = ARMA(ts_log_diff, order=(2, 1))\nmodel_fit = model.fit(disp=False)", "_____no_output_____" ], [ "model_fit.summary()", "_____no_output_____" ], [ "plt.plot(ts_log_diff)\nplt.plot(model_fit.fittedvalues, color='red')\nplt.title('RSS: %.4f'% np.nansum((model_fit.fittedvalues-ts_log_diff)**2))", "_____no_output_____" ], [ "ts = df.Cases - df.Cases.shift()\nts.dropna(inplace=True)\npyplot.figure()\npyplot.subplot(211)\nplot_acf(ts, ax=pyplot.gca(),lags=n)\npyplot.subplot(212)\nplot_pacf(ts, ax=pyplot.gca(),lags=n)\npyplot.show()", "_____no_output_____" ], [ "#divide into train and validation set\ntrain = df[:int(0.8*(len(df)))]\nvalid = df[int(0.8*(len(df))):]\n\n#plotting the data\ntrain['Cases'].plot()\nvalid['Cases'].plot()", "_____no_output_____" ], [ "#building the model\nfrom pmdarima.arima import auto_arima\nmodel = auto_arima(train, trace=True, error_action='ignore', suppress_warnings=True)\nmodel.fit(train)", "Performing stepwise search to minimize aic\nFit ARIMA: (2, 1, 2)x(0, 0, 0, 0) (constant=True); AIC=194.757, BIC=202.306, Time=0.446 seconds\nFit ARIMA: (0, 1, 0)x(0, 0, 0, 0) (constant=True); AIC=202.197, BIC=204.713, Time=0.036 seconds\nFit ARIMA: (1, 1, 0)x(0, 0, 0, 0) (constant=True); AIC=197.686, BIC=201.461, Time=0.078 seconds\nFit ARIMA: (0, 1, 1)x(0, 0, 0, 0) (constant=True); AIC=197.445, BIC=201.220, Time=0.143 seconds\nFit ARIMA: (0, 1, 0)x(0, 0, 0, 0) (constant=False); AIC=201.560, BIC=202.818, Time=0.007 seconds\nFit ARIMA: (1, 1, 2)x(0, 0, 0, 0) (constant=True); AIC=197.663, BIC=203.954, Time=0.326 seconds\nFit ARIMA: (2, 1, 1)x(0, 0, 0, 0) (constant=True); AIC=197.615, BIC=203.905, Time=0.148 seconds\nFit ARIMA: (3, 1, 2)x(0, 0, 0, 0) (constant=True); AIC=196.746, BIC=205.553, Time=0.345 seconds\nNear non-invertible roots for order (3, 1, 2)(0, 0, 0, 0); setting score to inf (at least one inverse root too close to the border of the unit circle: 0.999)\nFit ARIMA: (2, 1, 3)x(0, 0, 0, 0) (constant=True); AIC=196.742, BIC=205.549, Time=0.646 seconds\nNear non-invertible roots for order (2, 1, 3)(0, 0, 0, 0); setting score to inf (at least one inverse root too close to the border of the unit circle: 0.998)\nFit ARIMA: (1, 1, 1)x(0, 0, 0, 0) (constant=True); AIC=198.707, BIC=203.740, Time=0.079 seconds\nFit ARIMA: (1, 1, 3)x(0, 0, 0, 0) (constant=True); AIC=198.518, BIC=206.066, Time=0.392 seconds\nFit ARIMA: (3, 1, 1)x(0, 0, 0, 0) (constant=True); AIC=197.824, BIC=205.373, Time=0.190 seconds\nFit ARIMA: (3, 1, 3)x(0, 0, 0, 0) (constant=True); AIC=198.756, BIC=208.821, Time=0.543 seconds\nNear non-invertible roots for order (3, 1, 3)(0, 0, 0, 0); setting score to inf (at least one inverse root too close to the border of the unit circle: 0.998)\nTotal fit time: 3.406 seconds\n" ], [ "forecast = model.predict(n_periods=len(valid))\nforecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction'])\n\n#plot the predictions for validation set\nplt.plot(df.Cases, label='Train')\n#plt.plot(valid, label='Valid')\nplt.plot(forecast, label='Prediction')\nplt.show()", "_____no_output_____" ], [ "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error, median_absolute_error, mean_squared_log_error\ndef evaluate_forecast(y,pred):\n results = pd.DataFrame({'r2_score':r2_score(y, pred),\n }, index=[0])\n results['mean_absolute_error'] = mean_absolute_error(y, pred)\n results['median_absolute_error'] = median_absolute_error(y, pred)\n results['mse'] = mean_squared_error(y, pred)\n results['msle'] = mean_squared_log_error(y, pred)\n results['mape'] = mean_absolute_percentage_error(y, pred)\n results['rmse'] = np.sqrt(results['mse'])\n return results\nevaluate_forecast(valid, forecast)", "_____no_output_____" ], [ "train.head()", "_____no_output_____" ], [ "train_prophet = pd.DataFrame()\ntrain_prophet['ds'] = train.index\ntrain_prophet['y'] = train.Cases.values", "_____no_output_____" ], [ "train_prophet.head()", "_____no_output_____" ], [ "from fbprophet import Prophet\n\n#instantiate Prophet with only yearly seasonality as our data is monthly \nmodel = Prophet( yearly_seasonality=True, seasonality_mode = 'multiplicative')\nmodel.fit(train_prophet) #fit the model with your dataframe", "_____no_output_____" ], [ "# predict for five months in the furure and MS - month start is the frequency\nfuture = model.make_future_dataframe(periods = 36, freq = 'MS') \nfuture.tail()", "_____no_output_____" ], [ "forecast.columns", "_____no_output_____" ], [ "\n# now lets make the forecasts\nforecast = model.predict(future)\nforecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()\n", "_____no_output_____" ], [ "fig = model.plot(forecast)\n#plot the predictions for validation set\n\nplt.plot(valid, label='Valid', color = 'red', linewidth = 2)\n\nplt.show()", "_____no_output_____" ], [ "model.plot_components(forecast);", "_____no_output_____" ], [ "y_prophet = pd.DataFrame()\ny_prophet['ds'] = df.index\ny_prophet['y'] = df.Cases.values", "_____no_output_____" ], [ "y_prophet = y_prophet.set_index('ds')\nforecast_prophet = forecast.set_index('ds')", "_____no_output_____" ], [ "start_index =5\nend_index = 15\nevaluate_forecast(y_prophet.y[start_index:end_index], forecast_prophet.yhat[start_index:end_index])", "_____no_output_____" ], [ "from statsmodels.tsa.arima_model import ARIMA\n\nmodel = ARIMA(df['Cases'], order=(2, 1, 2)) \nresults_ARIMA = model.fit(disp=-1) \n#plt.plot(ts_log_diff)\nplt.plot(results_ARIMA.fittedvalues, color='red')\n#plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2))\n", "_____no_output_____" ] ] ]
[ "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" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d031684d517e0b0b258df691227bed9340802e6f
2,251
ipynb
Jupyter Notebook
04-Pandas/3/Activities/04-Stu_TedTalks/Unsolved/BinningTed.ipynb
madhavinamballa/datascience_Berkely
15f2987a0b012b344d209df70fdcf527f1c664b2
[ "ADSL" ]
null
null
null
04-Pandas/3/Activities/04-Stu_TedTalks/Unsolved/BinningTed.ipynb
madhavinamballa/datascience_Berkely
15f2987a0b012b344d209df70fdcf527f1c664b2
[ "ADSL" ]
null
null
null
04-Pandas/3/Activities/04-Stu_TedTalks/Unsolved/BinningTed.ipynb
madhavinamballa/datascience_Berkely
15f2987a0b012b344d209df70fdcf527f1c664b2
[ "ADSL" ]
null
null
null
19.405172
73
0.535762
[ [ [ "# Import Dependencies\nimport pandas as pd", "_____no_output_____" ], [ "# Create a path to the csv and read it into a Pandas DataFrame\ncsv_path = \"Resources/ted_talks.csv\"\nted_df = pd.read_csv(csv_path)\n\nted_df.head()", "_____no_output_____" ], [ "# Figure out the minimum and maximum views for a TED Talk", "_____no_output_____" ], [ "# Create bins in which to place values based upon TED Talk views\n\n# Create labels for these bins", "_____no_output_____" ], [ "# Slice the data and place it into bins", "_____no_output_____" ], [ "# Place the data series into a new column inside of the DataFrame", "_____no_output_____" ], [ "# Create a GroupBy object based upon \"View Group\"\n\n\n# Find how many rows fall into each bin\n\n\n# Get the average of each column within the GroupBy object", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d0317261f7daa14db7427ae8f3911b4f302b1644
3,776
ipynb
Jupyter Notebook
mnist_dataset_60mil_examples.ipynb
AlestanAlves/KerasAndTensorFlow1
975ebc4d9d4cdd654bf88873fa5197d85753df1e
[ "MIT" ]
null
null
null
mnist_dataset_60mil_examples.ipynb
AlestanAlves/KerasAndTensorFlow1
975ebc4d9d4cdd654bf88873fa5197d85753df1e
[ "MIT" ]
null
null
null
mnist_dataset_60mil_examples.ipynb
AlestanAlves/KerasAndTensorFlow1
975ebc4d9d4cdd654bf88873fa5197d85753df1e
[ "MIT" ]
null
null
null
41.043478
1,194
0.616261
[ [ [ "#modulos\nfrom keras.datasets import mnist\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import Sequencial\nfrom keras.layers import Dense\nfrom keras.utils import np_utils", "Using TensorFlow backend.\n" ], [ "#carregando o mnist\n(x_train , y_train), (x_test, y_test) = mnist.load_data()\n\n#como é pixels divide por 255 que é o maximo de pixels em uma tela\n\nnum_pix = X_train.shape[1] * X_train.shape[2]\n\nX_train = X_train.reshape(X_train.shape[0], num_pix).astype('float')\nX_test = X_test.reshape(X_test.shape[0], num_pix).astype('float')\n\nx_train = X_train / 255\nx_test = X_test / 255 \n\ny_train = np.utils.to_categorical(Y_train)\ny_test = np.utils.to_categorical(Y_test)\n\nclasses = y_test.shape[1]\n\nmodel = Sequencial()\nmodel.add(Dense(num_pix, input_dim=num_pix, activation='relu'))\nmodel.add(Dense(classes, activation='softmax'))\nmodel.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['acc'])\nmodel.fit(X_train, y_train, epochs=10, batch_size=100)#batch size é feito para evitar overfitting\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
d03176a4f251770577e0db313788a60c16c81b28
742,610
ipynb
Jupyter Notebook
02-bayesian-rb-example-hierarchical.ipynb
pdc-quantum/qiskit-advocates-bayes-RB
eca82f2525e3fc25404714fdfa5bac45ceb6b71a
[ "Apache-2.0" ]
null
null
null
02-bayesian-rb-example-hierarchical.ipynb
pdc-quantum/qiskit-advocates-bayes-RB
eca82f2525e3fc25404714fdfa5bac45ceb6b71a
[ "Apache-2.0" ]
null
null
null
02-bayesian-rb-example-hierarchical.ipynb
pdc-quantum/qiskit-advocates-bayes-RB
eca82f2525e3fc25404714fdfa5bac45ceb6b71a
[ "Apache-2.0" ]
1
2021-08-09T19:53:00.000Z
2021-08-09T19:53:00.000Z
1,077.808418
362,796
0.94973
[ [ [ "# Bayesian Randomized Benchmarking Demo\n\nThis is a bayesian pyMC3 implementation on top of frequentist interleaved RB from qiskit experiments\n\nBased on this [WIP tutorial](https://github.com/Qiskit/qiskit-experiments/blob/main/docs/tutorials/rb_example.ipynb) \non july 10 2021\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport copy\nimport qiskit_experiments as qe\nimport qiskit.circuit.library as circuits\nrb = qe.randomized_benchmarking\n\n# for retrieving gate calibration\nfrom datetime import datetime\nimport qiskit.providers.aer.noise.device as dv\n\n# import the bayesian packages\nimport pymc3 as pm\nimport arviz as az\nimport bayesian_fitter as bf", "_____no_output_____" ], [ "simulation = True # make your choice here\nif simulation:\n from qiskit.providers.aer import AerSimulator\n from qiskit.test.mock import FakeParis\n backend = AerSimulator.from_backend(FakeParis())\nelse:\n from qiskit import IBMQ\n IBMQ.load_account()\n provider = IBMQ.get_provider(hub='ibm-q')\n backend = provider.get_backend('ibmq_lima') # type here hardware backend ", "_____no_output_____" ], [ "import importlib\nimportlib.reload(bf)", "_____no_output_____" ] ], [ [ "# Running 1-qubit RB", "_____no_output_____" ] ], [ [ "lengths = np.arange(1, 1000, 100)\nnum_samples = 10\nseed = 1010\nqubits = [0]\n# Run an RB experiment on qubit 0\nexp1 = rb.StandardRB(qubits, lengths, num_samples=num_samples, seed=seed)\nexpdata1 = exp1.run(backend)\n\n# View result data\nprint(expdata1)", "---------------------------------------------------\nExperiment: StandardRB\nExperiment ID: 3051d86c-2fd3-4559-a767-3310080b487b\nStatus: DONE\nCircuits: 100\nAnalysis Results: 1\n---------------------------------------------------\nLast Analysis Result\n- a: 0.47740811449053433 ± 0.010108659378860563\n- alpha: 0.9957298638759341 ± 0.0003428385567477714\n- b: 0.5058163655018323 ± 0.00971472975879595\n- analysis_type: RBAnalysis\n- reduced_chisq: 0.09368628885182677\n- dof: 7\n- xrange: [1.0, 901.0]\n- EPC: 0.002135068062032952\n- EPC_err: 0.00017215440110094376\n- EPG: {0: {'rz': 0.0, 'sx': 0.0004322490834099537, 'x': 0.0004322490834099537}}\n- success: True\n" ], [ "physical_qubits = [0]\nnQ = len(qubits)\nscale = (2 ** nQ - 1) / 2 ** nQ\ninterleaved_gate =''", "_____no_output_____" ], [ "# retrieve from the frequentist model (fm) analysis\n# some values,including priors, for the bayesian analysis\nperr_fm, popt_fm, epc_est_fm, epc_est_fm_err, experiment_type = bf.retrieve_from_lsf(expdata1)\nEPG_dic = expdata1._analysis_results[0]['EPG'][qubits[0]]\n# get count data\nY = bf.get_GSP_counts(expdata1._data, len(lengths),range(num_samples))\nshots = bf.guess_shots(Y)", "_____no_output_____" ] ], [ [ "### Pooled model", "_____no_output_____" ] ], [ [ "#build model\npooled_model = bf.get_bayesian_model(model_type=\"pooled\",Y=Y,shots=shots,m_gates=lengths,\n mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]],\n alpha_ref=popt_fm[1],\n alpha_lower=popt_fm[1]-6*perr_fm[1],\n alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]))\npm.model_to_graphviz(pooled_model)", "_____no_output_____" ], [ "trace_p = bf.get_trace(pooled_model, target_accept = 0.95)", "Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nMultiprocess sampling (4 chains in 4 jobs)\nNUTS: [AB, alpha]\n" ], [ "# backend's recorded EPG\nprint(rb.RBUtils.get_error_dict_from_backend(backend, qubits))", "{((0,), 'id'): 0.0004432101747785104, ((0,), 'rz'): 0, ((0,), 'sx'): 0.0004432101747785104, ((0,), 'x'): 0.0004432101747785104}\n" ], [ "bf.RB_bayesian_results(pooled_model, trace_p, lengths,\n epc_est_fm, epc_est_fm_err, experiment_type, scale, \n num_samples, Y, shots, physical_qubits, interleaved_gate, backend,\n EPG_dic = EPG_dic)", " mean sd hdi_3% hdi_97%\nalpha 0.995688 0.000099 0.995500 0.995870\nAB[0] 0.476342 0.003614 0.469744 0.483336\nAB[1] 0.506909 0.003476 0.500081 0.513033 \n\nModel: Frequentist Bayesian\n_______________________________________\nEPC 2.135e-03 2.156e-03 \n± sigma ± 1.722e-04 ± 4.950e-05 \nEPG rz 0.000e+00 0.000e+00\nEPG sx 4.322e-04 4.365e-04\nEPG x 4.322e-04 4.365e-04\n" ] ], [ [ "### Hierarchical model", "_____no_output_____" ] ], [ [ "#build model\noriginal_model = bf.get_bayesian_model(model_type=\"h_sigma\",Y=Y,shots=shots,m_gates=lengths,\n mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]],\n alpha_ref=popt_fm[1],\n alpha_lower=popt_fm[1]-6*perr_fm[1],\n alpha_upper=min(1.-1.E-6,popt_fm[1]+6*perr_fm[1]),\n sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015)\npm.model_to_graphviz(original_model)", "_____no_output_____" ], [ "trace_o = bf.get_trace(original_model, target_accept = 0.95)", "Auto-assigning NUTS sampler...\nInitializing NUTS using jitter+adapt_diag...\nMultiprocess sampling (4 chains in 4 jobs)\nNUTS: [GSP, sigma_t, AB, alpha]\n" ], [ "# backend's recorded EPG\nprint(rb.RBUtils.get_error_dict_from_backend(backend, qubits))", "{((0,), 'id'): 0.0004432101747785104, ((0,), 'rz'): 0, ((0,), 'sx'): 0.0004432101747785104, ((0,), 'x'): 0.0004432101747785104}\n" ], [ "bf.RB_bayesian_results(original_model, trace_o, lengths,\n epc_est_fm, epc_est_fm_err, experiment_type, scale, \n num_samples, Y, shots, physical_qubits, interleaved_gate, backend,\n EPG_dic = EPG_dic)", " mean sd hdi_3% hdi_97%\nalpha 0.995677 0.000103 0.995476 0.995860\nAB[0] 0.476004 0.003727 0.469408 0.483239\nAB[1] 0.507318 0.003578 0.500497 0.513866\nsigma_t 0.001005 0.000290 0.000500 0.001439\nGSP[0] 0.981185 0.001334 0.978472 0.983521\nGSP[1] 0.814874 0.002270 0.810739 0.819283\nGSP[2] 0.706736 0.002638 0.701747 0.711649\nGSP[3] 0.636268 0.002425 0.631594 0.640623\nGSP[4] 0.591258 0.002131 0.587351 0.595196\nGSP[5] 0.561619 0.002015 0.557831 0.565306\nGSP[6] 0.543046 0.002158 0.538801 0.546921\nGSP[7] 0.530202 0.002393 0.525753 0.534719\nGSP[8] 0.522240 0.002650 0.517287 0.527240\nGSP[9] 0.516811 0.002883 0.511258 0.522020 \n\nModel: Frequentist Bayesian\n_______________________________________\nEPC 2.135e-03 2.161e-03 \n± sigma ± 1.722e-04 ± 5.150e-05 \nEPG rz 0.000e+00 0.000e+00\nEPG sx 4.322e-04 4.376e-04\nEPG x 4.322e-04 4.376e-04\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d03177f122774ff1143d238f1746388d553f05db
906,910
ipynb
Jupyter Notebook
unconditional/main_cifar_rl_bs8k_stdlearnscale_15_run3.ipynb
minhtannguyen/ffjord
f3418249eaa4647f4339aea8d814cf2ce33be141
[ "MIT" ]
null
null
null
unconditional/main_cifar_rl_bs8k_stdlearnscale_15_run3.ipynb
minhtannguyen/ffjord
f3418249eaa4647f4339aea8d814cf2ce33be141
[ "MIT" ]
null
null
null
unconditional/main_cifar_rl_bs8k_stdlearnscale_15_run3.ipynb
minhtannguyen/ffjord
f3418249eaa4647f4339aea8d814cf2ce33be141
[ "MIT" ]
null
null
null
100.012131
2,424
0.540947
[ [ [ "%run -p ../train_cnf_disentangle_rl.py --data cifar10 --dims 64,64,64 --strides 1,1,1,1 --num_blocks 2 --layer_type concat --multiscale True --rademacher True --batch_size 8000 --test_batch_size 5000 --save ../experiments_published/cnf_cifar10_bs8K_rl_stdlearnscale_15_run3 --resume ../experiments_published/cnf_cifar10_bs8K_rl_stdlearnscale_15_run3/epoch_178_checkpt.pth --seed 3 --conditional False --lr 0.001 --warmup_iters 1000 --atol 1e-4 --rtol 1e-4 --scale_fac 1.0 --gate cnn2 --scale_std 15.0 --max_grad_norm 20.0\n#", "/tancode/repos/tan-ffjord/train_cnf_disentangle_rl.py\nimport argparse\nimport os\nimport time\nimport numpy as np\n\nimport torch\nimport torch.optim as optim\nimport torchvision.datasets as dset\nimport torchvision.transforms as tforms\nfrom torchvision.utils import save_image\n\nimport torch.utils.data as data\nfrom torch.utils.data import Dataset\n\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.dpi'] = 300\n\nfrom PIL import Image\nimport os.path\nimport errno\nimport codecs\n\nimport lib.layers as layers\nimport lib.utils as utils\nimport lib.multiscale_parallel as multiscale_parallel\nimport lib.modules as modules\nimport lib.thops as thops\n\nfrom train_misc import standard_normal_logprob\nfrom train_misc import set_cnf_options, count_nfe, count_parameters, count_total_time, count_nfe_gate\nfrom train_misc import add_spectral_norm, spectral_norm_power_iteration\nfrom train_misc import create_regularization_fns, get_regularization, append_regularization_to_log\n\nfrom tensorboardX import SummaryWriter\n\n# go fast boi!!\ntorch.backends.cudnn.benchmark = True\nSOLVERS = [\"dopri5\", \"bdf\", \"rk4\", \"midpoint\", 'adams', 'explicit_adams']\nGATES = [\"cnn1\", \"cnn2\", \"rnn\"]\n\nparser = argparse.ArgumentParser(\"Continuous Normalizing Flow\")\nparser.add_argument(\"--data\", choices=[\"mnist\", \"colormnist\", \"svhn\", \"cifar10\", 'lsun_church'], type=str, default=\"mnist\")\nparser.add_argument(\"--dims\", type=str, default=\"8,32,32,8\")\nparser.add_argument(\"--strides\", type=str, default=\"2,2,1,-2,-2\")\nparser.add_argument(\"--num_blocks\", type=int, default=1, help='Number of stacked CNFs.')\n\nparser.add_argument(\"--conv\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\n \"--layer_type\", type=str, default=\"ignore\",\n choices=[\"ignore\", \"concat\", \"concat_v2\", \"squash\", \"concatsquash\", \"concatcoord\", \"hyper\", \"blend\"]\n)\nparser.add_argument(\"--divergence_fn\", type=str, default=\"approximate\", choices=[\"brute_force\", \"approximate\"])\nparser.add_argument(\n \"--nonlinearity\", type=str, default=\"softplus\", choices=[\"tanh\", \"relu\", \"softplus\", \"elu\", \"swish\"]\n)\n\nparser.add_argument(\"--seed\", type=int, default=0)\n\nparser.add_argument('--solver', type=str, default='dopri5', choices=SOLVERS)\nparser.add_argument('--atol', type=float, default=1e-5)\nparser.add_argument('--rtol', type=float, default=1e-5)\nparser.add_argument(\"--step_size\", type=float, default=None, help=\"Optional fixed step size.\")\n\nparser.add_argument('--gate', type=str, default='cnn1', choices=GATES)\nparser.add_argument('--scale', type=float, default=1.0)\nparser.add_argument('--scale_fac', type=float, default=1.0)\nparser.add_argument('--scale_std', type=float, default=1.0)\nparser.add_argument('--eta', default=0.1, type=float,\n help='tuning parameter that allows us to trade-off the competing goals of' \n 'minimizing the prediction loss and maximizing the gate rewards ')\nparser.add_argument('--rl-weight', default=0.01, type=float,\n help='rl weight')\n\nparser.add_argument('--gamma', default=0.99, type=float,\n help='discount factor, default: (0.99)')\n\nparser.add_argument('--test_solver', type=str, default=None, choices=SOLVERS + [None])\nparser.add_argument('--test_atol', type=float, default=None)\nparser.add_argument('--test_rtol', type=float, default=None)\n\nparser.add_argument(\"--imagesize\", type=int, default=None)\nparser.add_argument(\"--alpha\", type=float, default=1e-6)\nparser.add_argument('--time_length', type=float, default=1.0)\nparser.add_argument('--train_T', type=eval, default=True)\n\nparser.add_argument(\"--num_epochs\", type=int, default=500)\nparser.add_argument(\"--batch_size\", type=int, default=200)\nparser.add_argument(\n \"--batch_size_schedule\", type=str, default=\"\", help=\"Increases the batchsize at every given epoch, dash separated.\"\n)\nparser.add_argument(\"--test_batch_size\", type=int, default=200)\nparser.add_argument(\"--lr\", type=float, default=1e-3)\nparser.add_argument(\"--warmup_iters\", type=float, default=1000)\nparser.add_argument(\"--weight_decay\", type=float, default=0.0)\nparser.add_argument(\"--spectral_norm_niter\", type=int, default=10)\nparser.add_argument(\"--weight_y\", type=float, default=0.5)\nparser.add_argument(\"--annealing_std\", type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--y_class\", type=int, default=10)\nparser.add_argument(\"--y_color\", type=int, default=10)\n\nparser.add_argument(\"--add_noise\", type=eval, default=True, choices=[True, False])\nparser.add_argument(\"--batch_norm\", type=eval, default=False, choices=[True, False])\nparser.add_argument('--residual', type=eval, default=False, choices=[True, False])\nparser.add_argument('--autoencode', type=eval, default=False, choices=[True, False])\nparser.add_argument('--rademacher', type=eval, default=True, choices=[True, False])\nparser.add_argument('--spectral_norm', type=eval, default=False, choices=[True, False])\nparser.add_argument('--multiscale', type=eval, default=False, choices=[True, False])\nparser.add_argument('--parallel', type=eval, default=False, choices=[True, False])\nparser.add_argument('--conditional', type=eval, default=False, choices=[True, False])\nparser.add_argument('--controlled_tol', type=eval, default=False, choices=[True, False])\nparser.add_argument(\"--train_mode\", choices=[\"semisup\", \"sup\", \"unsup\"], type=str, default=\"semisup\")\nparser.add_argument(\"--condition_ratio\", type=float, default=0.5)\nparser.add_argument(\"--dropout_rate\", type=float, default=0.0)\n\n\n# Regularizations\nparser.add_argument('--l1int', type=float, default=None, help=\"int_t ||f||_1\")\nparser.add_argument('--l2int', type=float, default=None, help=\"int_t ||f||_2\")\nparser.add_argument('--dl2int', type=float, default=None, help=\"int_t ||f^T df/dt||_2\")\nparser.add_argument('--JFrobint', type=float, default=None, help=\"int_t ||df/dx||_F\")\nparser.add_argument('--JdiagFrobint', type=float, default=None, help=\"int_t ||df_i/dx_i||_F\")\nparser.add_argument('--JoffdiagFrobint', type=float, default=None, help=\"int_t ||df/dx - df_i/dx_i||_F\")\n\nparser.add_argument(\"--time_penalty\", type=float, default=0, help=\"Regularization on the end_time.\")\nparser.add_argument(\n \"--max_grad_norm\", type=float, default=1e10,\n help=\"Max norm of graidents (default is just stupidly high to avoid any clipping)\"\n)\n\nparser.add_argument(\"--begin_epoch\", type=int, default=1)\nparser.add_argument(\"--resume\", type=str, default=None)\nparser.add_argument(\"--save\", type=str, default=\"experiments/cnf\")\nparser.add_argument(\"--val_freq\", type=int, default=1)\nparser.add_argument(\"--log_freq\", type=int, default=1)\n\nargs = parser.parse_args()\n\nimport lib.odenvp_conditional_rl as odenvp\n \n# set seed\ntorch.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\n# logger\nutils.makedirs(args.save)\nlogger = utils.get_logger(logpath=os.path.join(args.save, 'logs'), filepath=os.path.abspath(__file__)) # write to log file\nwriter = SummaryWriter(os.path.join(args.save, 'tensorboard')) # write to tensorboard\n\nif args.layer_type == \"blend\":\n logger.info(\"!! Setting time_length from None to 1.0 due to use of Blend layers.\")\n args.time_length = 1.0\n\nlogger.info(args)\n\nclass ColorMNIST(data.Dataset):\n \"\"\"\n ColorMNIST\n \"\"\"\n urls = [\n 'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz',\n 'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz',\n ]\n raw_folder = 'raw'\n processed_folder = 'processed'\n training_file = 'training.pt'\n test_file = 'test.pt'\n\n def __init__(self, root, train=True, transform=None, target_transform=None, download=False):\n self.root = os.path.expanduser(root)\n self.transform = transform\n self.target_transform = target_transform\n self.train = train # training set or test set\n\n if download:\n self.download()\n\n if not self._check_exists():\n raise RuntimeError('Dataset not found.' +\n ' You can use download=True to download it')\n\n if self.train:\n self.train_data, self.train_labels = torch.load(\n os.path.join(self.root, self.processed_folder, self.training_file))\n \n self.train_data = np.tile(self.train_data[:, :, :, np.newaxis], 3)\n else:\n self.test_data, self.test_labels = torch.load(\n os.path.join(self.root, self.processed_folder, self.test_file))\n \n self.test_data = np.tile(self.test_data[:, :, :, np.newaxis], 3)\n \n self.pallette = [[31, 119, 180],\n [255, 127, 14],\n [44, 160, 44],\n [214, 39, 40],\n [148, 103, 189],\n [140, 86, 75],\n [227, 119, 194],\n [127, 127, 127],\n [188, 189, 34],\n [23, 190, 207]]\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n if self.train:\n img, target = self.train_data[index].copy(), self.train_labels[index]\n else:\n img, target = self.test_data[index].copy(), self.test_labels[index]\n \n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n y_color_digit = np.random.randint(0, args.y_color)\n c_digit = self.pallette[y_color_digit]\n \n img[:, :, 0] = img[:, :, 0] / 255 * c_digit[0]\n img[:, :, 1] = img[:, :, 1] / 255 * c_digit[1]\n img[:, :, 2] = img[:, :, 2] / 255 * c_digit[2]\n \n img = Image.fromarray(img)\n\n if self.transform is not None:\n img = self.transform(img)\n\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n return img, [target,torch.from_numpy(np.array(y_color_digit))]\n\n def __len__(self):\n if self.train:\n return len(self.train_data)\n else:\n return len(self.test_data)\n\n def _check_exists(self):\n return os.path.exists(os.path.join(self.root, self.processed_folder, self.training_file)) and \\\n os.path.exists(os.path.join(self.root, self.processed_folder, self.test_file))\n\n def download(self):\n \"\"\"Download the MNIST data if it doesn't exist in processed_folder already.\"\"\"\n from six.moves import urllib\n import gzip\n\n if self._check_exists():\n return\n\n # download files\n try:\n os.makedirs(os.path.join(self.root, self.raw_folder))\n os.makedirs(os.path.join(self.root, self.processed_folder))\n except OSError as e:\n if e.errno == errno.EEXIST:\n pass\n else:\n raise\n\n for url in self.urls:\n print('Downloading ' + url)\n data = urllib.request.urlopen(url)\n filename = url.rpartition('/')[2]\n file_path = os.path.join(self.root, self.raw_folder, filename)\n with open(file_path, 'wb') as f:\n f.write(data.read())\n with open(file_path.replace('.gz', ''), 'wb') as out_f, \\\n gzip.GzipFile(file_path) as zip_f:\n out_f.write(zip_f.read())\n os.unlink(file_path)\n\n # process and save as torch files\n print('Processing...')\n\n training_set = (\n read_image_file(os.path.join(self.root, self.raw_folder, 'train-images-idx3-ubyte')),\n read_label_file(os.path.join(self.root, self.raw_folder, 'train-labels-idx1-ubyte'))\n )\n test_set = (\n read_image_file(os.path.join(self.root, self.raw_folder, 't10k-images-idx3-ubyte')),\n read_label_file(os.path.join(self.root, self.raw_folder, 't10k-labels-idx1-ubyte'))\n )\n with open(os.path.join(self.root, self.processed_folder, self.training_file), 'wb') as f:\n torch.save(training_set, f)\n with open(os.path.join(self.root, self.processed_folder, self.test_file), 'wb') as f:\n torch.save(test_set, f)\n\n print('Done!')\n\n def __repr__(self):\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\n tmp = 'train' if self.train is True else 'test'\n fmt_str += ' Split: {}\\n'.format(tmp)\n fmt_str += ' Root Location: {}\\n'.format(self.root)\n tmp = ' Transforms (if any): '\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n tmp = ' Target Transforms (if any): '\n fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\n return fmt_str\n\ndef add_noise(x):\n \"\"\"\n [0, 1] -> [0, 255] -> add noise -> [0, 1]\n \"\"\"\n if args.add_noise:\n noise = x.new().resize_as_(x).uniform_()\n x = x * 255 + noise\n x = x / 256\n return x\n\n\ndef update_lr(optimizer, itr):\n iter_frac = min(float(itr + 1) / max(args.warmup_iters, 1), 1.0)\n lr = args.lr * iter_frac\n for param_group in optimizer.param_groups:\n param_group[\"lr\"] = lr\n\n \ndef update_scale_std(model, epoch):\n epoch_frac = 1.0 - float(epoch - 1) / max(args.num_epochs + 1, 1)\n scale_std = args.scale_std * epoch_frac\n model.set_scale_std(scale_std)\n\n\ndef get_train_loader(train_set, epoch):\n if args.batch_size_schedule != \"\":\n epochs = [0] + list(map(int, args.batch_size_schedule.split(\"-\")))\n n_passed = sum(np.array(epochs) <= epoch)\n current_batch_size = int(args.batch_size * n_passed)\n else:\n current_batch_size = args.batch_size\n train_loader = torch.utils.data.DataLoader(\n dataset=train_set, batch_size=current_batch_size, shuffle=True, drop_last=True, pin_memory=True\n )\n logger.info(\"===> Using batch size {}. Total {} iterations/epoch.\".format(current_batch_size, len(train_loader)))\n return train_loader\n\n\ndef get_dataset(args):\n trans = lambda im_size: tforms.Compose([tforms.Resize(im_size), tforms.ToTensor(), add_noise])\n\n if args.data == \"mnist\":\n im_dim = 1\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = dset.MNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = dset.MNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"colormnist\":\n im_dim = 3\n im_size = 28 if args.imagesize is None else args.imagesize\n train_set = ColorMNIST(root=\"../data\", train=True, transform=trans(im_size), download=True)\n test_set = ColorMNIST(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == \"svhn\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.SVHN(root=\"../data\", split=\"train\", transform=trans(im_size), download=True)\n test_set = dset.SVHN(root=\"../data\", split=\"test\", transform=trans(im_size), download=True)\n elif args.data == \"cifar10\":\n im_dim = 3\n im_size = 32 if args.imagesize is None else args.imagesize\n train_set = dset.CIFAR10(\n root=\"../data\", train=True, transform=tforms.Compose([\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ]), download=True\n )\n test_set = dset.CIFAR10(root=\"../data\", train=False, transform=trans(im_size), download=True)\n elif args.data == 'celeba':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.CelebA(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.CelebA(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n elif args.data == 'lsun_church':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.LSUN(\n '../data', ['church_outdoor_train'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.LSUN(\n '../data', ['church_outdoor_val'], transform=tforms.Compose([\n tforms.Resize(96),\n tforms.RandomCrop(64),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n ) \n elif args.data == 'imagenet_64':\n im_dim = 3\n im_size = 64 if args.imagesize is None else args.imagesize\n train_set = dset.ImageFolder(\n train=True, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.RandomHorizontalFlip(),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n test_set = dset.ImageFolder(\n train=False, transform=tforms.Compose([\n tforms.ToPILImage(),\n tforms.Resize(im_size),\n tforms.ToTensor(),\n add_noise,\n ])\n )\n \n data_shape = (im_dim, im_size, im_size)\n if not args.conv:\n data_shape = (im_dim * im_size * im_size,)\n\n test_loader = torch.utils.data.DataLoader(\n dataset=test_set, batch_size=args.test_batch_size, shuffle=False, drop_last=True\n )\n return train_set, test_loader, data_shape\n\n\ndef compute_bits_per_dim(x, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n\n logpz = standard_normal_logprob(z).view(z.shape[0], -1).sum(1, keepdim=True) # logp(z)\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n\n return bits_per_dim, atol, rtol, logp_actions, nfe\n\ndef compute_bits_per_dim_conditional(x, y, model):\n zero = torch.zeros(x.shape[0], 1).to(x)\n y_onehot = thops.onehot(y, num_classes=model.module.y_class).to(x)\n\n # Don't use data parallelize if batch size is small.\n # if x.shape[0] < 200:\n # model = model.module\n \n z, delta_logp, atol, rtol, logp_actions, nfe = model(x, zero) # run model forward\n \n dim_sup = int(args.condition_ratio * np.prod(z.size()[1:]))\n \n # prior\n mean, logs = model.module._prior(y_onehot)\n\n logpz_sup = modules.GaussianDiag.logp(mean, logs, z[:, 0:dim_sup]).view(-1,1) # logp(z)_sup\n logpz_unsup = standard_normal_logprob(z[:, dim_sup:]).view(z.shape[0], -1).sum(1, keepdim=True)\n logpz = logpz_sup + logpz_unsup\n logpx = logpz - delta_logp\n\n logpx_per_dim = torch.sum(logpx) / x.nelement() # averaged over batches\n bits_per_dim = -(logpx_per_dim - np.log(256)) / np.log(2)\n \n # dropout\n if args.dropout_rate > 0:\n zsup = model.module.dropout(z[:, 0:dim_sup])\n else:\n zsup = z[:, 0:dim_sup]\n \n # compute xentropy loss\n y_logits = model.module.project_class(zsup)\n loss_xent = model.module.loss_class(y_logits, y.to(x.get_device()))\n y_predicted = np.argmax(y_logits.cpu().detach().numpy(), axis=1)\n\n return bits_per_dim, loss_xent, y_predicted, atol, rtol, logp_actions, nfe\n\ndef create_model(args, data_shape, regularization_fns):\n hidden_dims = tuple(map(int, args.dims.split(\",\")))\n strides = tuple(map(int, args.strides.split(\",\")))\n\n if args.multiscale:\n model = odenvp.ODENVP(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n nonlinearity=args.nonlinearity,\n alpha=args.alpha,\n cnf_kwargs={\"T\": args.time_length, \"train_T\": args.train_T, \"regularization_fns\": regularization_fns, \"solver\": args.solver, \"atol\": args.atol, \"rtol\": args.rtol, \"scale\": args.scale, \"scale_fac\": args.scale_fac, \"scale_std\": args.scale_std, \"gate\": args.gate},\n condition_ratio=args.condition_ratio,\n dropout_rate=args.dropout_rate,\n y_class = args.y_class)\n elif args.parallel:\n model = multiscale_parallel.MultiscaleParallelCNF(\n (args.batch_size, *data_shape),\n n_blocks=args.num_blocks,\n intermediate_dims=hidden_dims,\n alpha=args.alpha,\n time_length=args.time_length,\n )\n else:\n if args.autoencode:\n\n def build_cnf():\n autoencoder_diffeq = layers.AutoencoderDiffEqNet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.AutoencoderODEfunc(\n autoencoder_diffeq=autoencoder_diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n else:\n\n def build_cnf():\n diffeq = layers.ODEnet(\n hidden_dims=hidden_dims,\n input_shape=data_shape,\n strides=strides,\n conv=args.conv,\n layer_type=args.layer_type,\n nonlinearity=args.nonlinearity,\n )\n odefunc = layers.ODEfunc(\n diffeq=diffeq,\n divergence_fn=args.divergence_fn,\n residual=args.residual,\n rademacher=args.rademacher,\n )\n cnf = layers.CNF(\n odefunc=odefunc,\n T=args.time_length,\n train_T=args.train_T,\n regularization_fns=regularization_fns,\n solver=args.solver,\n )\n return cnf\n\n chain = [layers.LogitTransform(alpha=args.alpha)] if args.alpha > 0 else [layers.ZeroMeanTransform()]\n chain = chain + [build_cnf() for _ in range(args.num_blocks)]\n if args.batch_norm:\n chain.append(layers.MovingBatchNorm2d(data_shape[0]))\n model = layers.SequentialFlow(chain)\n return model\n\n\nif __name__ == \"__main__\":\n\n # get deivce\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n cvt = lambda x: x.type(torch.float32).to(device, non_blocking=True)\n\n # load dataset\n train_set, test_loader, data_shape = get_dataset(args)\n\n # build model\n regularization_fns, regularization_coeffs = create_regularization_fns(args)\n model = create_model(args, data_shape, regularization_fns)\n\n if args.spectral_norm: add_spectral_norm(model, logger)\n set_cnf_options(args, model)\n\n logger.info(model)\n logger.info(\"Number of trainable parameters: {}\".format(count_parameters(model)))\n \n writer.add_text('info', \"Number of trainable parameters: {}\".format(count_parameters(model)))\n\n # optimizer\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n \n # set initial iter\n itr = 1\n \n # set the meters\n time_epoch_meter = utils.RunningAverageMeter(0.97)\n time_meter = utils.RunningAverageMeter(0.97)\n loss_meter = utils.RunningAverageMeter(0.97) # track total loss\n nll_meter = utils.RunningAverageMeter(0.97) # track negative log-likelihood\n xent_meter = utils.RunningAverageMeter(0.97) # track xentropy score\n error_meter = utils.RunningAverageMeter(0.97) # track error score\n steps_meter = utils.RunningAverageMeter(0.97)\n grad_meter = utils.RunningAverageMeter(0.97)\n tt_meter = utils.RunningAverageMeter(0.97)\n\n # restore parameters\n if args.resume is not None:\n checkpt = torch.load(args.resume, map_location=lambda storage, loc: storage)\n model.load_state_dict(checkpt[\"state_dict\"])\n if \"optim_state_dict\" in checkpt.keys():\n optimizer.load_state_dict(checkpt[\"optim_state_dict\"])\n # Manually move optimizer state to device.\n for state in optimizer.state.values():\n for k, v in state.items():\n if torch.is_tensor(v):\n state[k] = cvt(v)\n args.begin_epoch = checkpt['epoch'] + 1\n itr = checkpt['iter'] + 1\n time_epoch_meter.set(checkpt['epoch_time_avg'])\n time_meter.set(checkpt['time_train'])\n loss_meter.set(checkpt['loss_train'])\n nll_meter.set(checkpt['bits_per_dim_train'])\n xent_meter.set(checkpt['xent_train'])\n error_meter.set(checkpt['error_train'])\n steps_meter.set(checkpt['nfe_train'])\n grad_meter.set(checkpt['grad_train'])\n tt_meter.set(checkpt['total_time_train'])\n\n if torch.cuda.is_available():\n model = torch.nn.DataParallel(model).cuda()\n\n # For visualization.\n if args.conditional:\n dim_unsup = int((1.0 - args.condition_ratio) * np.prod(data_shape))\n fixed_y = torch.from_numpy(np.arange(model.module.y_class)).repeat(model.module.y_class).type(torch.long).to(device, non_blocking=True)\n fixed_y_onehot = thops.onehot(fixed_y, num_classes=model.module.y_class)\n with torch.no_grad():\n mean, logs = model.module._prior(fixed_y_onehot)\n fixed_z_sup = modules.GaussianDiag.sample(mean, logs)\n fixed_z_unsup = cvt(torch.randn(model.module.y_class**2, dim_unsup))\n fixed_z = torch.cat((fixed_z_sup, fixed_z_unsup),1)\n else:\n fixed_z = cvt(torch.randn(100, *data_shape))\n \n\n if args.spectral_norm and not args.resume: spectral_norm_power_iteration(model, 500)\n\n best_loss_nll = float(\"inf\")\n best_error_score = float(\"inf\")\n \n for epoch in range(args.begin_epoch, args.num_epochs + 1):\n start_epoch = time.time()\n model.train()\n if args.annealing_std:\n update_scale_std(model.module, epoch)\n \n train_loader = get_train_loader(train_set, epoch)\n for _, (x, y) in enumerate(train_loader):\n if args.data == \"colormnist\":\n y = y[0]\n \n start = time.time()\n update_lr(optimizer, itr)\n optimizer.zero_grad()\n\n if not args.conv:\n x = x.view(x.shape[0], -1)\n\n # cast data and move to device\n x = cvt(x)\n \n # compute loss\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n error_score = 1. - np.mean(y_predicted.astype(int) == y.numpy()) \n \n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent, error_score = loss, 0., 0.\n \n if regularization_coeffs:\n reg_states = get_regularization(model, regularization_coeffs)\n reg_loss = sum(\n reg_state * coeff for reg_state, coeff in zip(reg_states, regularization_coeffs) if coeff != 0\n )\n loss = loss + reg_loss\n total_time = count_total_time(model)\n loss = loss + total_time * args.time_penalty\n\n # re-weight the gate rewards\n normalized_eta = args.eta / len(logp_actions)\n \n # collect cumulative future rewards\n R = - loss\n cum_rewards = []\n for r in nfe[::-1]:\n R = -normalized_eta * r.view(-1,1) + args.gamma * R\n cum_rewards.insert(0,R)\n \n # apply REINFORCE\n rl_loss = 0\n for lpa, r in zip(logp_actions, cum_rewards):\n rl_loss = rl_loss - lpa.view(-1,1) * args.rl_weight * r\n \n loss = loss + rl_loss.mean()\n \n loss.backward()\n \n grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\n\n optimizer.step()\n\n if args.spectral_norm: spectral_norm_power_iteration(model, args.spectral_norm_niter)\n \n time_meter.update(time.time() - start)\n loss_meter.update(loss.item())\n nll_meter.update(loss_nll.item())\n if args.conditional:\n xent_meter.update(loss_xent.item())\n else:\n xent_meter.update(loss_xent)\n error_meter.update(error_score)\n steps_meter.update(count_nfe_gate(model))\n grad_meter.update(grad_norm)\n tt_meter.update(total_time)\n \n for idx in range(len(model.module.transforms)):\n for layer in model.module.transforms[idx].chain:\n if hasattr(layer, 'atol'):\n layer.odefunc.after_odeint()\n \n # write to tensorboard\n writer.add_scalars('time', {'train_iter': time_meter.val}, itr)\n writer.add_scalars('loss', {'train_iter': loss_meter.val}, itr)\n writer.add_scalars('bits_per_dim', {'train_iter': nll_meter.val}, itr)\n writer.add_scalars('xent', {'train_iter': xent_meter.val}, itr)\n writer.add_scalars('error', {'train_iter': error_meter.val}, itr)\n writer.add_scalars('nfe', {'train_iter': steps_meter.val}, itr)\n writer.add_scalars('grad', {'train_iter': grad_meter.val}, itr)\n writer.add_scalars('total_time', {'train_iter': tt_meter.val}, itr)\n\n if itr % args.log_freq == 0:\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'train': atol[tol_indx].mean()}, itr)\n writer.add_scalars('rtol_%i'%tol_indx, {'train': rtol[tol_indx].mean()}, itr)\n \n log_message = (\n \"Iter {:04d} | Time {:.4f}({:.4f}) | Bit/dim {:.4f}({:.4f}) | Xent {:.4f}({:.4f}) | Loss {:.4f}({:.4f}) | Error {:.4f}({:.4f}) \"\n \"Steps {:.0f}({:.2f}) | Grad Norm {:.4f}({:.4f}) | Total Time {:.2f}({:.2f})\".format(\n itr, time_meter.val, time_meter.avg, nll_meter.val, nll_meter.avg, xent_meter.val, xent_meter.avg, loss_meter.val, loss_meter.avg, error_meter.val, error_meter.avg, steps_meter.val, steps_meter.avg, grad_meter.val, grad_meter.avg, tt_meter.val, tt_meter.avg\n )\n )\n if regularization_coeffs:\n log_message = append_regularization_to_log(log_message, regularization_fns, reg_states)\n logger.info(log_message)\n writer.add_text('info', log_message, itr)\n\n itr += 1\n \n if args.data == \"colormnist\":\n # print train images\n xall = []\n ximg = x[0:40].cpu().numpy().transpose((0,2,3,1))\n for i in range(ximg.shape[0]):\n xall.append(ximg[i])\n \n xall = np.hstack(xall)\n\n plt.imshow(xall)\n plt.axis('off')\n plt.show()\n \n # compute test loss\n model.eval()\n if epoch % args.val_freq == 0:\n with torch.no_grad():\n # write to tensorboard\n writer.add_scalars('time', {'train_epoch': time_meter.avg}, epoch)\n writer.add_scalars('loss', {'train_epoch': loss_meter.avg}, epoch)\n writer.add_scalars('bits_per_dim', {'train_epoch': nll_meter.avg}, epoch)\n writer.add_scalars('xent', {'train_epoch': xent_meter.avg}, epoch)\n writer.add_scalars('error', {'train_epoch': error_meter.avg}, epoch)\n writer.add_scalars('nfe', {'train_epoch': steps_meter.avg}, epoch)\n writer.add_scalars('grad', {'train_epoch': grad_meter.avg}, epoch)\n writer.add_scalars('total_time', {'train_epoch': tt_meter.avg}, epoch)\n \n start = time.time()\n logger.info(\"validating...\")\n writer.add_text('info', \"validating...\", epoch)\n losses_nll = []; losses_xent = []; losses = []\n total_correct = 0\n \n for (x, y) in test_loader:\n if args.data == \"colormnist\":\n y = y[0]\n \n if not args.conv:\n x = x.view(x.shape[0], -1)\n x = cvt(x)\n if args.conditional:\n loss_nll, loss_xent, y_predicted, atol, rtol, logp_actions, nfe = compute_bits_per_dim_conditional(x, y, model)\n if args.train_mode == \"semisup\":\n loss = loss_nll + args.weight_y * loss_xent\n elif args.train_mode == \"sup\":\n loss = loss_xent\n elif args.train_mode == \"unsup\":\n loss = loss_nll\n else:\n raise ValueError('Choose supported train_mode: semisup, sup, unsup')\n total_correct += np.sum(y_predicted.astype(int) == y.numpy())\n else:\n loss, atol, rtol, logp_actions, nfe = compute_bits_per_dim(x, model)\n loss_nll, loss_xent = loss, 0.\n losses_nll.append(loss_nll.cpu().numpy()); losses.append(loss.cpu().numpy())\n if args.conditional: \n losses_xent.append(loss_xent.cpu().numpy())\n else:\n losses_xent.append(loss_xent)\n \n if args.data == \"colormnist\":\n # print test images\n xall = []\n ximg = x[0:40].cpu().numpy().transpose((0,2,3,1))\n for i in range(ximg.shape[0]):\n xall.append(ximg[i])\n\n xall = np.hstack(xall)\n\n plt.imshow(xall)\n plt.axis('off')\n plt.show()\n \n loss_nll = np.mean(losses_nll); loss_xent = np.mean(losses_xent); loss = np.mean(losses)\n error_score = 1. - total_correct / len(test_loader.dataset)\n time_epoch_meter.update(time.time() - start_epoch)\n \n # write to tensorboard\n test_time_spent = time.time() - start\n writer.add_scalars('time', {'validation': test_time_spent}, epoch)\n writer.add_scalars('epoch_time', {'validation': time_epoch_meter.val}, epoch)\n writer.add_scalars('bits_per_dim', {'validation': loss_nll}, epoch)\n writer.add_scalars('xent', {'validation': loss_xent}, epoch)\n writer.add_scalars('loss', {'validation': loss}, epoch)\n writer.add_scalars('error', {'validation': error_score}, epoch)\n \n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n \n log_message = \"Epoch {:04d} | Time {:.4f}, Epoch Time {:.4f}({:.4f}), Bit/dim {:.4f}(best: {:.4f}), Xent {:.4f}, Loss {:.4f}, Error {:.4f}(best: {:.4f})\".format(epoch, time.time() - start, time_epoch_meter.val, time_epoch_meter.avg, loss_nll, best_loss_nll, loss_xent, loss, error_score, best_error_score)\n logger.info(log_message)\n writer.add_text('info', log_message, epoch)\n \n for name, param in model.named_parameters():\n writer.add_histogram(name, param.clone().cpu().data.numpy(), epoch)\n \n \n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"epoch_%i_checkpt.pth\"%epoch))\n \n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"current_checkpt.pth\"))\n \n if loss_nll < best_loss_nll:\n best_loss_nll = loss_nll\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_nll_checkpt.pth\"))\n \n if args.conditional:\n if error_score < best_error_score:\n best_error_score = error_score\n utils.makedirs(args.save)\n torch.save({\n \"args\": args,\n \"state_dict\": model.module.state_dict() if torch.cuda.is_available() else model.state_dict(),\n \"optim_state_dict\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"iter\": itr-1,\n \"error\": error_score,\n \"loss\": loss,\n \"xent\": loss_xent,\n \"bits_per_dim\": loss_nll,\n \"best_bits_per_dim\": best_loss_nll,\n \"best_error_score\": best_error_score,\n \"epoch_time\": time_epoch_meter.val,\n \"epoch_time_avg\": time_epoch_meter.avg,\n \"time\": test_time_spent,\n \"error_train\": error_meter.avg,\n \"loss_train\": loss_meter.avg,\n \"xent_train\": xent_meter.avg,\n \"bits_per_dim_train\": nll_meter.avg,\n \"total_time_train\": tt_meter.avg,\n \"time_train\": time_meter.avg,\n \"nfe_train\": steps_meter.avg,\n \"grad_train\": grad_meter.avg,\n }, os.path.join(args.save, \"best_error_checkpt.pth\"))\n \n\n # visualize samples and density\n with torch.no_grad():\n fig_filename = os.path.join(args.save, \"figs\", \"{:04d}.jpg\".format(epoch))\n utils.makedirs(os.path.dirname(fig_filename))\n generated_samples, atol, rtol, logp_actions, nfe = model(fixed_z, reverse=True)\n generated_samples = generated_samples.view(-1, *data_shape)\n for tol_indx in range(len(atol)):\n writer.add_scalars('atol_gen_%i'%tol_indx, {'validation': atol[tol_indx].mean()}, epoch)\n writer.add_scalars('rtol_gen_%i'%tol_indx, {'validation': rtol[tol_indx].mean()}, epoch)\n save_image(generated_samples, fig_filename, nrow=10)\n if args.data == \"mnist\":\n writer.add_images('generated_images', generated_samples.repeat(1,3,1,1), epoch)\n else:\n writer.add_images('generated_images', generated_samples.repeat(1,1,1,1), epoch)\nNamespace(JFrobint=None, JdiagFrobint=None, JoffdiagFrobint=None, add_noise=True, alpha=1e-06, annealing_std=False, atol=0.0001, autoencode=False, batch_norm=False, batch_size=8000, batch_size_schedule='', begin_epoch=1, condition_ratio=0.5, conditional=False, controlled_tol=False, conv=True, data='cifar10', dims='64,64,64', divergence_fn='approximate', dl2int=None, dropout_rate=0.0, eta=0.1, gamma=0.99, gate='cnn2', imagesize=None, l1int=None, l2int=None, layer_type='concat', log_freq=1, lr=0.001, max_grad_norm=20.0, multiscale=True, nonlinearity='softplus', num_blocks=2, num_epochs=500, parallel=False, rademacher=True, residual=False, resume='../experiments_published/cnf_cifar10_bs8K_rl_stdlearnscale_15_run3/epoch_178_checkpt.pth', rl_weight=0.01, rtol=0.0001, save='../experiments_published/cnf_cifar10_bs8K_rl_stdlearnscale_15_run3', scale=1.0, scale_fac=1.0, scale_std=15.0, seed=3, solver='dopri5', spectral_norm=False, spectral_norm_niter=10, step_size=None, strides='1,1,1,1', test_atol=None, test_batch_size=5000, test_rtol=None, test_solver=None, time_length=1.0, time_penalty=0, train_T=True, train_mode='semisup', val_freq=1, warmup_iters=1000.0, weight_decay=0.0, weight_y=0.5, y_class=10, y_color=10)\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
d0317e4ffb61cf3c5c23b69393bbe158ba34e0a2
373,625
ipynb
Jupyter Notebook
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
569dda896767ea270fd63c8c1afc17caeec8e815
[ "MIT" ]
null
null
null
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
569dda896767ea270fd63c8c1afc17caeec8e815
[ "MIT" ]
null
null
null
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
569dda896767ea270fd63c8c1afc17caeec8e815
[ "MIT" ]
null
null
null
256.786942
96,882
0.8932
[ [ [ "<a href=\"https://colab.research.google.com/github/DSNortsev/CSE-694-Case-Studies-in-Deep-Learning/blob/master/HW2/HW2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom pandas.plotting import parallel_coordinates\n\ndata = sns.load_dataset(\"iris\")", "_____no_output_____" ] ], [ [ "## **Task 1.\tBrief description on its value and possible applications.**\n\nThe IRIS dataset has the following characteristics:\n* 150 examples of Iris flowers \n* The first four fields are features that are the characteristics of flower examples. All these fields hold float numbers representing flower measurements. \n* The last column is the label which represents the Iris species. * Balance class distribution meaning that each category has even amount of instances \n* Has no missing values \n\nOne example of possible application is for botanists to find an automated way to categorize each Iris flower they find. For instance, to classify based on photographs, or in our case based on the length and width measurements of their sepals and petals.", "_____no_output_____" ] ], [ [ "data", "_____no_output_____" ], [ "print(f'CLASS DISTRIBUTION:\\n{data.groupby(\"species\").size()}')\nprint(f'\\nSHAPE: {data.shape}')\nprint(f'\\nTOTAL MISSING VALUES:\\n{data.isnull().sum()}\\n')", "CLASS DISTRIBUTION:\nspecies\nsetosa 50\nversicolor 50\nvirginica 50\ndtype: int64\n\nSHAPE: (150, 5)\n\nTOTAL MISSING VALUES:\nsepal_length 0\nsepal_width 0\npetal_length 0\npetal_width 0\nspecies 0\ndtype: int64\n\n" ] ], [ [ "_________", "_____no_output_____" ], [ "## **Task 2. Summarize and visually report on the Size of this data set including labeling or non-labeled status**\n\n", "_____no_output_____" ], [ "For all three species, the respective values of the mean and median of its features are found to be pretty close. This indicates that data is nearly symmetrically distributed with very less presence of outliers.", "_____no_output_____" ] ], [ [ "data.groupby('species').agg(['mean', 'median'])", "_____no_output_____" ] ], [ [ "Standard deviation (or variance) is an indication of how widely the data is spread about the mean.", "_____no_output_____" ] ], [ [ "data.groupby('species').std()", "_____no_output_____" ] ], [ [ "The isolated points for each feature that can be seen in the box-plots below are the outliers in the data. Since these are very few in number, it wouldn't have any significant impact on our analysis.", "_____no_output_____" ] ], [ [ "sns.set(style=\"ticks\") \nplt.figure(figsize=(12,10))\nplt.subplot(2,2,1)\nsns.boxplot(x='species',y='sepal_length',data=data)\nplt.subplot(2,2,2)\nsns.boxplot(x='species',y='sepal_width',data=data)\nplt.subplot(2,2,3)\nsns.boxplot(x='species',y='petal_length',data=data)\nplt.subplot(2,2,4)\nsns.boxplot(x='species',y='petal_width',data=data)\nplt.show()", "_____no_output_____" ] ], [ [ "Scatter plot helps to analyze the relationship between 2 features on the x and y ", "_____no_output_____" ] ], [ [ "sns.pairplot(data)", "_____no_output_____" ] ], [ [ "Next, we can make a correlation matrix to see how these features are correlated to each other using a heatmap in the seaborn library. It can be observed that petal measurements are highly correlated, while the sepal one are uncorrelated. Also we can see that petal length is highly correlated with speal length, but not with sepal width. ", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,11))\nsns.heatmap(data.corr(),annot=True, square = True)\nplt.plot()", "_____no_output_____" ] ], [ [ "Another way to visualize the data is by parallel coordinate plot, which represents each row as a line. As we have seen below, petal measurements can separate species better than the sepal ones.", "_____no_output_____" ] ], [ [ "parallel_coordinates(data, \"species\", color = ['blue', 'red', 'green']);", "_____no_output_____" ] ], [ [ "Now, we can plot a scatter plot between the sepal length and the sepal width to visualise the iris dataset. We can observe that the blue dots(setosa) are quite clear separated from red(versicolor) and green dots(virginica), while separation between red dots and green dots might be a very difficult task given the two features available. ", "_____no_output_____" ] ], [ [ "labels_names = { 'setosa': 'blue',\n 'versicolor': 'red',\n 'virginica': 'green'}\n\nfor species, color in labels_names.items():\n x = data.loc[data['species'] == species]['sepal_length']\n y = data.loc[data['species'] == species]['sepal_width']\n plt.scatter(x, y, c=color)\nplt.legend(labels_names.keys())\nplt.xlabel('sepal_length')\nplt.ylabel('sepal_width')\nplt.show()", "_____no_output_____" ] ], [ [ "We can also visualise the data on different features such as petal width and petal length. In this case, the decision boundary between blue, green and red dots can be easily determined, which indicates that using all features for training is a good choice. ", "_____no_output_____" ] ], [ [ "labels_names = { 'setosa': 'blue',\n 'versicolor': 'red',\n 'virginica': 'green'}\n\nfor species, color in labels_names.items():\n x = data.loc[data['species'] == species]['petal_length']\n y = data.loc[data['species'] == species]['petal_width']\n plt.scatter(x, y, c=color)\nplt.legend(labels_names.keys())\nplt.xlabel('petal_length')\nplt.ylabel('petal_width')\nplt.show()", "_____no_output_____" ] ], [ [ "___________\n## **3.\tPropose and perform Deep Learning using this data set.**\nReport on your implementation as follows:\n* Justify your selection of techniques and platform\n* Explain your results and their applicability\n", "_____no_output_____" ], [ "&nbsp;&nbsp;&nbsp;&nbsp;In our project we are using python language. There are two well-known libraries for deep learning such as PyTorch and Tensorflow. Each library has its own API implementation for example, Keras is high level API for Tensorflow, while fastai is an API for PyTorch.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;The Iris classification problem is an example of supervised machine learning: the model is trained from examples that contain labels and for our model we are planning to use Keras wrapper for Tensor flow.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;The Deep Learning would be performed in the following steps:\n * Data preprocessing\n * Model Building\n * Model Selection<br> \n\n&nbsp;&nbsp;&nbsp;&nbsp;In the **Data preprocessing**, we need to create data frames for features and labels, normalize the feature data by converting all values in a range between 0 and 1, convert species labels to numerical representation and then to binary string. Then, the data needs to be split into train and test data sets. ", "_____no_output_____" ], [ "# **Phase 1: Data Preprocessing**\n### Step 1: Create Dataframes for features and lables", "_____no_output_____" ] ], [ [ "import pandas as pd\nfrom sklearn.preprocessing import LabelBinarizer, LabelEncoder\n\n\nencoder = LabelBinarizer()\nle=LabelEncoder() \nseed = 42\n\ndata = sns.load_dataset(\"iris\")\n# Create X variable with four features\nX = data.drop(['species'],axis=1)\n# Convert species to int\nY_int = le.fit_transform(data['species'])\n# Convert species int to binary representation\nY_binary = encoder.fit_transform(Y_int)\ntarget_names = data['species'].unique()\nY = pd.DataFrame(data=Y_binary, columns=target_names) \n\nprint(f'\\nNormalized X_test values:\\n{X[:5]}')\nprint(f'\\nEncoded Y_test:\\n{Y[:5]}')", "\nNormalized X_test values:\n sepal_length sepal_width petal_length petal_width\n0 5.1 3.5 1.4 0.2\n1 4.9 3.0 1.4 0.2\n2 4.7 3.2 1.3 0.2\n3 4.6 3.1 1.5 0.2\n4 5.0 3.6 1.4 0.2\n\nEncoded Y_test:\n setosa versicolor virginica\n0 1 0 0\n1 1 0 0\n2 1 0 0\n3 1 0 0\n4 1 0 0\n" ] ], [ [ "### Step 2: Create training and testing datasets", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\n\n# Split data in train and test with percentage proportion 70%/30%\nX_train,X_test,y_train,y_test = train_test_split(X, Y, test_size=0.30,random_state=seed)\n\nprint(f'X_train: {X_train.shape}, y_train: {y_train.shape}')\nprint(f'X_test : {X_test.shape}, y_test : {y_test.shape}')", "X_train: (105, 4), y_train: (105, 3)\nX_test : (45, 4), y_test : (45, 3)\n" ] ], [ [ "### Step 3: Normalize the feature data, all values should be in a range from 0 to 1", "_____no_output_____" ] ], [ [ " import pandas as pd\n from sklearn import preprocessing\n \n# Normalize X features, make all values between 0 and 1\nX_train = pd.DataFrame(preprocessing.normalize(X_train),\n columns=X_train.columns,\n index=X_train.index)\nX_test = pd.DataFrame(preprocessing.normalize(X_test),\n columns=X_test.columns,\n index=X_test.index)\n\nprint(f'Train sample:\\n{X_train.head(4)},\\nShape: {X_train.shape}')\nprint(f'\\nTest sample:\\n{X_test.head(4)},\\nShape: {X_test.shape}')", "Train sample:\n sepal_length sepal_width petal_length petal_width\n81 0.772429 0.337060 0.519634 0.140442\n133 0.723660 0.321627 0.585820 0.172300\n137 0.698048 0.338117 0.599885 0.196326\n75 0.767857 0.349026 0.511905 0.162879,\nShape: (105, 4)\n\nTest sample:\n sepal_length sepal_width petal_length petal_width\n73 0.736599 0.338111 0.567543 0.144905\n18 0.806828 0.537885 0.240633 0.042465\n118 0.706006 0.238392 0.632655 0.210885\n78 0.733509 0.354530 0.550132 0.183377,\nShape: (45, 4)\n" ] ], [ [ "# **Phase 2: Model Building**\n### Step 1: Build model\n&nbsp;&nbsp;&nbsp;&nbsp;The IRIS is a classification problem, we need to classify if an Iris flower is setosa, versicolor or virginia. Softmax activation function is commonly used in multi classification problems in the output layer, that would return the label with the highest probability.<br> \n&nbsp;&nbsp;&nbsp;&nbsp;The **tf.keras.Sequential** model is a linear stack of layers. Its constructor takes a list of layer instances, in this case, one tf.keras.layers.Dense layer with 8 nodes, two layers with 10 nodes, and an output layer with 3 nodes representing our label predictions. The first layer’s input_shape parameter corresponds to the number of features from the dataset which is equal 4. <br>\n&nbsp;&nbsp;&nbsp;&nbsp;The **activation** function determines the output shape of each node in the layer. These non linearities are important, without them the model would be equivalent to a single layer. There are many tf.keras.activations such as tanh, like sigmoid or relu. In our two models we have decided to use \"tahn\" and \"relu\" and compare the performance.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;The ideal number of hidden layers and neurons depends on the problem and the dataset. Like many aspects of machine learning, picking the best shape of the neural network requires a mixture of knowledge and experimentation. As a rule of thumb, increasing the number of hidden layers and neurons typically creates a more powerful model, which requires more data to train effectively. For our illustration we have used two models with 3 and 4 layers. Our expectation that the model with many layers should give a better result.\n", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras.layers import Dense\n\ndef model_with_3_layers():\n model = Sequential()\n model.add(Dense(27, input_dim=4, activation='relu', name='input_layer'))\n model.add(Dense(9, activation='relu', name='layer_1'))\n model.add(Dense(3, activation='softmax', name='output_layer'))\n\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n return model", "_____no_output_____" ], [ "\n\ndef model_with_4_layers():\n \"\"\"build the Keras model callback\"\"\"\n model = Sequential()\n model.add(Dense(8, input_dim=4, activation='tanh', name='layer_1'))\n model.add(Dense(10, activation='tanh', name='layer_2'))\n model.add(Dense(10, activation='tanh', name='layer_3'))\n model.add(Dense(3, activation='softmax', name='output_layer'))\n \n model.compile(loss=\"categorical_crossentropy\",\n optimizer=\"adam\",\n metrics=['accuracy'])\n return model", "_____no_output_____" ] ], [ [ "### Step 2: Create estimator\n\n&nbsp;&nbsp;&nbsp;&nbsp;We can also pass arguments in the construction of the KerasClassifier class that will be passed on to the fit() function internally used to train the neural network. Here, we pass the number of epochs as 200 and batch size as 20 to use when training the model. ", "_____no_output_____" ] ], [ [ "from keras.wrappers.scikit_learn import KerasClassifier\n\nestimator = KerasClassifier(\n build_fn=model_with_4_layers,\n epochs=200, batch_size=20,\n verbose=0)", "_____no_output_____" ] ], [ [ "### Step 3: Evaluate The Model with k-Fold Cross Validation\n\n&nbsp;&nbsp;&nbsp;&nbsp;Now, the neural network model can be evaluated on a training dataset. The scikit-learn has excellent capability to evaluate models using a suite of techniques. The gold standard for evaluating machine learning models is k-fold cross validation.Since the dataset is quite small, we can pass 5 fold for cross validation.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nimport tensorflow as tf\n\n# Suppress Tensorflow warning\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nestimator = KerasClassifier(\n build_fn=model_with_3_layers,\n epochs=200, batch_size=20,\n verbose=0)\n\nkfold = KFold(n_splits=5, shuffle=True, random_state=seed)\nresults = cross_val_score(estimator, X_train, y_train, cv=kfold)\nprint(f'Model Performance:\\nmean: {results.mean()*100:.2f}\\\n \\nstd: {results.std()*100:.2f}') ", "Model Performance:\nmean: 98.10 \nstd: 2.33\n" ], [ "from sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\n\nestimator = KerasClassifier(\n build_fn=model_with_4_layers,\n epochs=200, batch_size=20,\n verbose=0)\n\nkfold = KFold(n_splits=5, shuffle=True, random_state=seed)\nresults = cross_val_score(estimator, X_train, y_train, cv=kfold)\nprint(f'Model Performance:\\nmean: {results.mean()*100:.2f}\\\n \\nstd: {results.std()*100:.2f}') ", "Model Performance:\nmean: 98.10 \nstd: 2.33\n" ] ], [ [ "### Phase 3 : Model Selection\n\n&nbsp;&nbsp;&nbsp;&nbsp; For our illustration, two models have been used. One with 3 layers and another with 4 layers. We can observe that the accuracy are almost the same, but the loss value is much lower in the model with 4 layers. It can be concluded that by adding more layers, it improves the accuracy and lost and at the same time requires more computational power. ", "_____no_output_____" ] ], [ [ "md1 = model_with_3_layers()\nmd1.fit(X_train,\n y_train,\n epochs=200,\n shuffle=True, # shuffle data randomly.\n verbose=0 # this will tell keras to print more detailed info\n )\n\n# Validate the model with test dateset\ntest_error_rate = md1.evaluate(X_test, y_test, verbose=0)\nprint(f'{md1.metrics_names[1]}: {test_error_rate[1]*100:.2f}')\nprint(f'{md1.metrics_names[0]}: {test_error_rate[0]*100:.2f}')", "accuracy: 95.56\nloss: 23.09\n" ], [ "md2 = model_with_4_layers()\nmd2.fit(X_train,\n y_train,\n epochs=200,\n shuffle=True, # shuffle data randomly.\n verbose=0 # this will tell keras to print more detailed info\n )\n\n# Validate the model with test dateset\ntest_error_rate = md2.evaluate(X_test, y_test, verbose=0)\nprint(f'{md2.metrics_names[1]}: {test_error_rate[1]*100:.2f}')\nprint(f'{md2.metrics_names[0]}: {test_error_rate[0]*100:.2f}')", "accuracy: 95.56\nloss: 11.00\n" ] ], [ [ "### STEP 4: Evaluate model performs on the test data", "_____no_output_____" ] ], [ [ "from sklearn.metrics import confusion_matrix\n\n\ndef evaluate_performace(actual, expected):\n \"\"\"\n Function accepts two lists with actual and expected lables\n \"\"\"\n flowers = {0:'setosa',\n 1:'versicolor',\n 2:'virginica'}\n print(f'Flowers in test set: \\nSetosa={y_test[\"setosa\"].sum()}\\\n \\nVersicolor={y_test[\"versicolor\"].sum()}\\\n \\nVirginica={y_test[\"virginica\"].sum()}')\n \n for act,exp in zip(actual, expected):\n if act != exp:\n print(f'ERROR: {flowers[exp]} predicted as {flowers[act]}')\n\n\nfor i,model in enumerate((md1, md2), 1):\n print(f'\\nEVALUATION OF MODEL {i}')\n predicted_targets = model.predict_classes(X_test)\n true_targets = encoder.inverse_transform(y_test.values)\n evaluate_performace(predicted_targets, true_targets)\n # Calculate the confusion matrix using sklearn.metrics\n fig, ax =plt.subplots(1,1)\n conf_matrix = confusion_matrix(true_targets, predicted_targets)\n sns.heatmap(conf_matrix, annot=True, cmap='Blues', xticklabels=target_names,yticklabels=target_names)\n print('\\n')\n", "\nEVALUATION OF MODEL 1\nFlowers in test set: \nSetosa=19 \nVersicolor=13 \nVirginica=13\nERROR: versicolor predicted as virginica\nERROR: virginica predicted as versicolor\n\n\n\nEVALUATION OF MODEL 2\nFlowers in test set: \nSetosa=19 \nVersicolor=13 \nVirginica=13\nERROR: versicolor predicted as virginica\nERROR: virginica predicted as versicolor\n\n\n" ] ], [ [ "&nbsp;&nbsp;&nbsp;&nbsp;From the confusion matrix above we can see that the second model with 4 layers outperformed the model with 3 layers and the prediction was wrong only once for versicolor species. ", "_____no_output_____" ], [ "___\n## **4.\tFind a publication or report that uses this same data set and compare it’s methodology and results to what you did**\n&nbsp;&nbsp;&nbsp;&nbsp;In the last assignment, we would like to analyze the approach that has been suggested by TensorFlow in \"Custom Training: walkthrough\" report [1]. The same deep learning framework has been used. Feature and labels are stored in tf.Tensor structure, where in my model all data was stored in pandas.DataFrame. Label data is converted to numerical representation, where in our side we have decided to use binary string representation. The Author decided to not normalize the feature data, to be more specific to represent in the range from 0 to 1. It is a preferable approach, because it allows the model to learn faster.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;Suggested model is using a Sequential model which is a linear stack of layers. The stack is built with 4 layers, input and output layers and two Dense layers with 10 nodes each can be simply represented as 4/10/10/3. One of our models that showed better accuracy and loss contains 5 layers which can be represented as follows: 4/8/10/10/3. The relu activation function has been chosen for inner layers, that outputs 0 if input is negative or 0, and returns the value when it is positive. Both models are using **SparseCategoricalCrossentropy** function which calculates the loss value by taking the model's class probability predictions and the desired labels, and returns the average loss across all examples. To minimize the loss the Stochastic gradient algorithm has been chosen with learning rate 0.01, in contrast our model is built with Adam which is an extension to stochastic gradient descent algorithm.<br>\n&nbsp;&nbsp;&nbsp;&nbsp;Both models are run with almost the same number of epochs. It can be observed that both models return almost the same accuracy and loss.\n&nbsp;&nbsp;&nbsp;&nbsp;To summarize, we can see that both models performed similarly, but in our approach to the same result can be achieved by adding the new inner layer that does help to improve the model but it might be very resource-intensive.<br>\n\n**References:**<br>\n[1] - \"Custom training: walkthrough\", https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/customization/custom_training_walkthrough.ipynb#scrollTo=rwxGnsA92emp, Accessed 2018, The TensorFlow Authors", "_____no_output_____" ] ], [ [ "# To convert colab notebook to pdf\n!apt-get install texlive texlive-xetex texlive-latex-extra pandoc >/dev/null\n!pip install pypandoc >/dev/null", "Extracting templates from packages: 100%\n" ], [ "from google.colab import drive\ndrive.mount('/content/drive')\n!cp drive/My\\ Drive/Colab\\ Notebooks/HW2.ipynb ./", "Mounted at /content/drive\n" ], [ "!jupyter nbconvert --to PDF \"HW2.ipynb\" 2>/dev/null\n!cp ./HW2.pdf drive/My\\ Drive/Colab\\ Notebooks/", "_____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", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
d0318005068a948be3e7e1dab7edbfed6fd5b5aa
972,575
ipynb
Jupyter Notebook
notebooks/metric_gradient.ipynb
SalishSeaCast/analysis-james
a50b0cf666babf8cb5dd3b1cc808475ae09fdc5d
[ "Apache-2.0" ]
null
null
null
notebooks/metric_gradient.ipynb
SalishSeaCast/analysis-james
a50b0cf666babf8cb5dd3b1cc808475ae09fdc5d
[ "Apache-2.0" ]
null
null
null
notebooks/metric_gradient.ipynb
SalishSeaCast/analysis-james
a50b0cf666babf8cb5dd3b1cc808475ae09fdc5d
[ "Apache-2.0" ]
null
null
null
672.596819
455,872
0.917062
[ [ [ "import numpy as np\nimport xarray as xr\nimport math\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nimport os\nimport f90nml\nfrom salishsea_tools import metric_tools_5x5 as met\n\n%matplotlib inline\nplt.rcParams['image.cmap'] = 'jet'\nplt.rc('xtick', labelsize=20) \nplt.rc('ytick', labelsize=20) ", "_____no_output_____" ], [ "reference_namelist_file = '/data/jpetrie/MEOPAR/SS-run-sets/SS-SMELT/namelists/namelist_pisces_cfg_5x5_NewIC'\nreference_bio_params = f90nml.read(reference_namelist_file)", "_____no_output_____" ], [ "tracer_file = 'SS5x5_1h_20150201_20150501_ptrc_T.nc'\n\nparam_metrics = pd.DataFrame()\n\nbatch_directories = [\n #'/data/jpetrie/MEOPAR/SalishSea/results/nampiszoo_june_14/',\n '/data/jpetrie/MEOPAR/SalishSea/results/nampisopt_june_14/',\n #'/data/jpetrie/MEOPAR/SalishSea/results/nampismes_june_14/',\n #'/data/jpetrie/MEOPAR/SalishSea/results/nampissink_june_17/',\n #'/data/jpetrie/MEOPAR/SalishSea/results/nampisprod_june_16/',\n #'/data/jpetrie/MEOPAR/SalishSea/results/nampismort_june_17/',\n #'/data/jpetrie/MEOPAR/SalishSea/results/nampisrem_june_17/',\n #'/data/jpetrie/MEOPAR/SalishSea/results/nampismezo_june_20/',\n]\n\nmetric_func_list = [\n met.mean_NH4_at_depth,\n met.mean_NO3_at_depth,\n met.mean_DON_at_depth,\n met.mean_PON_at_depth,\n met.time_of_peak_PHY2,\n met.time_surface_NO3_drops_below_4,\n met.peak_3_day_biomass,\n]\n\nfor batch_dir in batch_directories:\n for file in os.listdir(batch_dir):\n if os.path.isfile(batch_dir + '/' + file + '/' + tracer_file) and 'zz_frac_waste' not in file:\n last_underscore = file.rfind('_')\n first_underscore = file.find('_')\n param_section = file[:first_underscore]\n param_name = file[(first_underscore+1):last_underscore]\n param_val = float(file[(last_underscore+1):])\n param_desc = param_section + ' ' + param_name\n \n original_val = reference_bio_params[param_section][param_name]\n \n if type(original_val) is list:\n param_scale = round(param_val/original_val[0], 3)\n else:\n param_scale = round(param_val/original_val, 3)\n \n grid_t = xr.open_dataset(batch_dir + '/' + file +'/' + tracer_file)\n \n for metric_func in metric_func_list:\n metric_val = metric_func(grid_t)\n metric_name = metric_func.__name__\n # inefficient to keep appending, but much less expensive than other parts of the loop so it doesn't matter\n param_metrics = param_metrics.append(pd.DataFrame({\"PARAM_SECTION\":[param_section],\n \"PARAM_NAME\":[param_name],\n \"PARAM_DESC\":[param_desc],\n \"PARAM_VAL\":[param_val],\n \"PARAM_SCALE\":[param_scale],\n \"METRIC_NAME\":[metric_name],\n \"METRIC_VAL\": [metric_val]}))\n", "_____no_output_____" ], [ "sns.set(font_scale = 2)\nplt.rcParams['image.cmap'] = 'jet'\n\nparam_metrics = param_metrics.sort_values([\"PARAM_SCALE\", \"PARAM_DESC\"])\n\nfg = sns.FacetGrid(data=param_metrics.query(\"PARAM_SCALE < 10\"), col = \"METRIC_NAME\", hue = \"PARAM_DESC\", sharex=False, sharey=False, col_wrap = 2, size = 10)\nfg.map(plt.scatter, \"PARAM_SCALE\", \"METRIC_VAL\", s = 80)\nfg.map(plt.plot, \"PARAM_SCALE\", \"METRIC_VAL\")\nfg.add_legend()\nfg.set_titles(\"{col_name}\")", "_____no_output_____" ], [ "param_metrics[\"PARAM_SCALE\"] = \"PARAM_SCALE_\" + param_metrics[\"PARAM_SCALE\"].astype(str)\nwide_format_metrics = pd.pivot_table(param_metrics, values='METRIC_VAL', index=['PARAM_SECTION','PARAM_NAME', 'PARAM_DESC', 'METRIC_NAME'], columns=['PARAM_SCALE'])\nwide_format_metrics.reset_index(inplace=True)\nwide_format_metrics[\"SLOPE\"] = (wide_format_metrics[\"PARAM_SCALE_1.1\"] - wide_format_metrics[\"PARAM_SCALE_0.9\"])/0.2", "_____no_output_____" ], [ "wide_format_metrics", "_____no_output_____" ], [ "cmap = plt.get_cmap('Set2')\nfor metric_name in np.unique(wide_format_metrics[\"METRIC_NAME\"]):\n x = wide_format_metrics.query(\"METRIC_NAME == @metric_name\")\n \n categories = np.unique(x[\"PARAM_SECTION\"])\n colors = np.linspace(0, 1, len(categories))\n colordict = dict(zip(categories, colors)) \n x[\"COLOR\"] = x[\"PARAM_SECTION\"].apply(lambda x: colordict[x])\n \n x.plot.barh(\"PARAM_DESC\", \"SLOPE\", figsize = (7,0.6*len(x[\"SLOPE\"])), color = cmap(x.COLOR), title = metric_name)", "/home/jpetrie/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:8: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d0318788bc8c837e23b6005d1ef9a6ac8cf8759b
1,604
ipynb
Jupyter Notebook
HolaGitHub.ipynb
andresrivera125/colab-books
1a922bd3051355031d88b6d9f8a6df6b4af96370
[ "MIT" ]
null
null
null
HolaGitHub.ipynb
andresrivera125/colab-books
1a922bd3051355031d88b6d9f8a6df6b4af96370
[ "MIT" ]
null
null
null
HolaGitHub.ipynb
andresrivera125/colab-books
1a922bd3051355031d88b6d9f8a6df6b4af96370
[ "MIT" ]
null
null
null
22.914286
234
0.436409
[ [ [ "<a href=\"https://colab.research.google.com/github/andresrivera125/colab-books/blob/main/HolaGitHub.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "list = [1, 2, 3, 4, 5, 6]\n\nfor element in list:\n print(element)\n", "1\n2\n3\n4\n5\n6\n" ] ], [ [ "# Hola mundo en markup\n\n## Esto es una subsección", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ] ]
d0318d71fa4351f1dca4c25fc8e3d76588d7d440
101,269
ipynb
Jupyter Notebook
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
4546900fd24ac1a884e5d9dc79b64063acb85000
[ "MIT" ]
null
null
null
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
4546900fd24ac1a884e5d9dc79b64063acb85000
[ "MIT" ]
null
null
null
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
4546900fd24ac1a884e5d9dc79b64063acb85000
[ "MIT" ]
null
null
null
38.622807
1,359
0.51698
[ [ [ "# Plagiarism Detection, Feature Engineering\n\nIn this project, you will be tasked with building a plagiarism detector that examines an answer text file and performs binary classification; labeling that file as either plagiarized or not, depending on how similar that text file is to a provided, source text. \n\nYour first task will be to create some features that can then be used to train a classification model. This task will be broken down into a few discrete steps:\n\n* Clean and pre-process the data.\n* Define features for comparing the similarity of an answer text and a source text, and extract similarity features.\n* Select \"good\" features, by analyzing the correlations between different features.\n* Create train/test `.csv` files that hold the relevant features and class labels for train/test data points.\n\nIn the _next_ notebook, Notebook 3, you'll use the features and `.csv` files you create in _this_ notebook to train a binary classification model in a SageMaker notebook instance.\n\nYou'll be defining a few different similarity features, as outlined in [this paper](https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c412841_developing-a-corpus-of-plagiarised-short-answers/developing-a-corpus-of-plagiarised-short-answers.pdf), which should help you build a robust plagiarism detector!\n\nTo complete this notebook, you'll have to complete all given exercises and answer all the questions in this notebook.\n> All your tasks will be clearly labeled **EXERCISE** and questions as **QUESTION**.\n\nIt will be up to you to decide on the features to include in your final training and test data.\n\n---", "_____no_output_____" ], [ "## Read in the Data\n\nThe cell below will download the necessary, project data and extract the files into the folder `data/`.\n\nThis data is a slightly modified version of a dataset created by Paul Clough (Information Studies) and Mark Stevenson (Computer Science), at the University of Sheffield. You can read all about the data collection and corpus, at [their university webpage](https://ir.shef.ac.uk/cloughie/resources/plagiarism_corpus.html). \n\n> **Citation for data**: Clough, P. and Stevenson, M. Developing A Corpus of Plagiarised Short Answers, Language Resources and Evaluation: Special Issue on Plagiarism and Authorship Analysis, In Press. [Download]", "_____no_output_____" ] ], [ [ "# NOTE:\n# you only need to run this cell if you have not yet downloaded the data\n# otherwise you may skip this cell or comment it out\n\n#!wget https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c4147f9_data/data.zip\n#!unzip data", "_____no_output_____" ], [ "# import libraries\nimport pandas as pd\nimport numpy as np\nimport os", "_____no_output_____" ] ], [ [ "This plagiarism dataset is made of multiple text files; each of these files has characteristics that are is summarized in a `.csv` file named `file_information.csv`, which we can read in using `pandas`.", "_____no_output_____" ] ], [ [ "csv_file = 'data/file_information.csv'\nplagiarism_df = pd.read_csv(csv_file)\n\n# print out the first few rows of data info\nplagiarism_df.head()", "_____no_output_____" ] ], [ [ "## Types of Plagiarism\n\nEach text file is associated with one **Task** (task A-E) and one **Category** of plagiarism, which you can see in the above DataFrame.\n\n### Tasks, A-E\n\nEach text file contains an answer to one short question; these questions are labeled as tasks A-E. For example, Task A asks the question: \"What is inheritance in object oriented programming?\"\n\n### Categories of plagiarism \n\nEach text file has an associated plagiarism label/category:\n\n**1. Plagiarized categories: `cut`, `light`, and `heavy`.**\n* These categories represent different levels of plagiarized answer texts. `cut` answers copy directly from a source text, `light` answers are based on the source text but include some light rephrasing, and `heavy` answers are based on the source text, but *heavily* rephrased (and will likely be the most challenging kind of plagiarism to detect).\n \n**2. Non-plagiarized category: `non`.** \n* `non` indicates that an answer is not plagiarized; the Wikipedia source text is not used to create this answer.\n \n**3. Special, source text category: `orig`.**\n* This is a specific category for the original, Wikipedia source text. We will use these files only for comparison purposes.", "_____no_output_____" ], [ "---\n## Pre-Process the Data\n\nIn the next few cells, you'll be tasked with creating a new DataFrame of desired information about all of the files in the `data/` directory. This will prepare the data for feature extraction and for training a binary, plagiarism classifier.", "_____no_output_____" ], [ "### EXERCISE: Convert categorical to numerical data\n\nYou'll notice that the `Category` column in the data, contains string or categorical values, and to prepare these for feature extraction, we'll want to convert these into numerical values. Additionally, our goal is to create a binary classifier and so we'll need a binary class label that indicates whether an answer text is plagiarized (1) or not (0). Complete the below function `numerical_dataframe` that reads in a `file_information.csv` file by name, and returns a *new* DataFrame with a numerical `Category` column and a new `Class` column that labels each answer as plagiarized or not. \n\nYour function should return a new DataFrame with the following properties:\n\n* 4 columns: `File`, `Task`, `Category`, `Class`. The `File` and `Task` columns can remain unchanged from the original `.csv` file.\n* Convert all `Category` labels to numerical labels according to the following rules (a higher value indicates a higher degree of plagiarism):\n * 0 = `non`\n * 1 = `heavy`\n * 2 = `light`\n * 3 = `cut`\n * -1 = `orig`, this is a special value that indicates an original file.\n* For the new `Class` column\n * Any answer text that is not plagiarized (`non`) should have the class label `0`. \n * Any plagiarized answer texts should have the class label `1`. \n * And any `orig` texts will have a special label `-1`. \n\n### Expected output\n\nAfter running your function, you should get a DataFrame with rows that looks like the following: \n```\n\n File\t Task Category Class\n0\tg0pA_taska.txt\ta\t 0 \t0\n1\tg0pA_taskb.txt\tb\t 3 \t1\n2\tg0pA_taskc.txt\tc\t 2 \t1\n3\tg0pA_taskd.txt\td\t 1 \t1\n4\tg0pA_taske.txt\te\t 0\t 0\n...\n...\n99 orig_taske.txt e -1 -1\n\n```", "_____no_output_____" ] ], [ [ "# Read in a csv file and return a transformed dataframe\ndef numerical_dataframe(csv_file='data/file_information.csv'):\n '''Reads in a csv file which is assumed to have `File`, `Category` and `Task` columns.\n This function does two things: \n 1) converts `Category` column values to numerical values \n 2) Adds a new, numerical `Class` label column.\n The `Class` column will label plagiarized answers as 1 and non-plagiarized as 0.\n Source texts have a special label, -1.\n :param csv_file: The directory for the file_information.csv file\n :return: A dataframe with numerical categories and a new `Class` label column'''\n \n orig_df = pd.read_csv(csv_file)\n new_df = orig_df[['File', 'Task']]\n new_df['Category'] = [0 if x == 'non' else 1 if x == 'heavy' else 2 if x == 'light' else 3 if x == 'cut' else -1 for x in orig_df['Category']]\n new_df['Class'] = [0 if x == 0 else 1 if x > 0 else -1 for x in new_df['Category']]\n return new_df\n\nnumerical_dataframe().head(100)", "_____no_output_____" ] ], [ [ "### Test cells\n\nBelow are a couple of test cells. The first is an informal test where you can check that your code is working as expected by calling your function and printing out the returned result.\n\nThe **second** cell below is a more rigorous test cell. The goal of a cell like this is to ensure that your code is working as expected, and to form any variables that might be used in _later_ tests/code, in this case, the data frame, `transformed_df`.\n\n> The cells in this notebook should be run in chronological order (the order they appear in the notebook). This is especially important for test cells.\n\nOften, later cells rely on the functions, imports, or variables defined in earlier cells. For example, some tests rely on previous tests to work.\n\nThese tests do not test all cases, but they are a great way to check that you are on the right track!", "_____no_output_____" ] ], [ [ "# informal testing, print out the results of a called function\n# create new `transformed_df`\ntransformed_df = numerical_dataframe(csv_file ='data/file_information.csv')\n\n# check work\n# check that all categories of plagiarism have a class label = 1\ntransformed_df.head(20)", "_____no_output_____" ], [ "# test cell that creates `transformed_df`, if tests are passed\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n\n# importing tests\nimport problem_unittests as tests\n\n# test numerical_dataframe function\ntests.test_numerical_df(numerical_dataframe)\n\n# if above test is passed, create NEW `transformed_df`\ntransformed_df = numerical_dataframe(csv_file ='data/file_information.csv')\n\n# check work\nprint('\\nExample data: ')\ntransformed_df.head()", "Tests Passed!\n\nExample data: \n" ] ], [ [ "## Text Processing & Splitting Data\n\nRecall that the goal of this project is to build a plagiarism classifier. At it's heart, this task is a comparison text; one that looks at a given answer and a source text, compares them and predicts whether an answer has plagiarized from the source. To effectively do this comparison, and train a classifier we'll need to do a few more things: pre-process all of our text data and prepare the text files (in this case, the 95 answer files and 5 original source files) to be easily compared, and split our data into a `train` and `test` set that can be used to train a classifier and evaluate it, respectively. \n\nTo this end, you've been provided code that adds additional information to your `transformed_df` from above. The next two cells need not be changed; they add two additional columns to the `transformed_df`:\n\n1. A `Text` column; this holds all the lowercase text for a `File`, with extraneous punctuation removed.\n2. A `Datatype` column; this is a string value `train`, `test`, or `orig` that labels a data point as part of our train or test set\n\nThe details of how these additional columns are created can be found in the `helpers.py` file in the project directory. You're encouraged to read through that file to see exactly how text is processed and how data is split.\n\nRun the cells below to get a `complete_df` that has all the information you need to proceed with plagiarism detection and feature engineering.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport helpers \n\n# create a text column \ntext_df = helpers.create_text_column(transformed_df)\ntext_df.head()", "_____no_output_____" ], [ "# after running the cell above\n# check out the processed text for a single file, by row index\nrow_idx = 0 # feel free to change this index\n\nsample_text = text_df.iloc[0]['Text']\n\nprint('Sample processed text:\\n\\n', sample_text)", "Sample processed text:\n\n inheritance is a basic concept of object oriented programming where the basic idea is to create new classes that add extra detail to existing classes this is done by allowing the new classes to reuse the methods and variables of the existing classes and new methods and classes are added to specialise the new class inheritance models the is kind of relationship between entities or objects for example postgraduates and undergraduates are both kinds of student this kind of relationship can be visualised as a tree structure where student would be the more general root node and both postgraduate and undergraduate would be more specialised extensions of the student node or the child nodes in this relationship student would be known as the superclass or parent class whereas postgraduate would be known as the subclass or child class because the postgraduate class extends the student class inheritance can occur on several layers where if visualised would display a larger tree structure for example we could further extend the postgraduate node by adding two extra extended classes to it called msc student and phd student as both these types of student are kinds of postgraduate student this would mean that both the msc student and phd student classes would inherit methods and variables from both the postgraduate and student classes \n" ] ], [ [ "## Split data into training and test sets\n\nThe next cell will add a `Datatype` column to a given DataFrame to indicate if the record is: \n* `train` - Training data, for model training.\n* `test` - Testing data, for model evaluation.\n* `orig` - The task's original answer from wikipedia.\n\n### Stratified sampling\n\nThe given code uses a helper function which you can view in the `helpers.py` file in the main project directory. This implements [stratified random sampling](https://en.wikipedia.org/wiki/Stratified_sampling) to randomly split data by task & plagiarism amount. Stratified sampling ensures that we get training and test data that is fairly evenly distributed across task & plagiarism combinations. Approximately 26% of the data is held out for testing and 74% of the data is used for training.\n\nThe function **train_test_dataframe** takes in a DataFrame that it assumes has `Task` and `Category` columns, and, returns a modified frame that indicates which `Datatype` (train, test, or orig) a file falls into. This sampling will change slightly based on a passed in *random_seed*. Due to a small sample size, this stratified random sampling will provide more stable results for a binary plagiarism classifier. Stability here is smaller *variance* in the accuracy of classifier, given a random seed.", "_____no_output_____" ] ], [ [ "random_seed = 1 # can change; set for reproducibility\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport helpers\n\n# create new df with Datatype (train, test, orig) column\n# pass in `text_df` from above to create a complete dataframe, with all the information you need\ncomplete_df = helpers.train_test_dataframe(text_df, random_seed=random_seed)\n\n# check results\ncomplete_df.head()", "_____no_output_____" ] ], [ [ "# Determining Plagiarism\n\nNow that you've prepared this data and created a `complete_df` of information, including the text and class associated with each file, you can move on to the task of extracting similarity features that will be useful for plagiarism classification. \n\n> Note: The following code exercises, assume that the `complete_df` as it exists now, will **not** have its existing columns modified. \n\nThe `complete_df` should always include the columns: `['File', 'Task', 'Category', 'Class', 'Text', 'Datatype']`. You can add additional columns, and you can create any new DataFrames you need by copying the parts of the `complete_df` as long as you do not modify the existing values, directly.\n\n---", "_____no_output_____" ], [ "\n# Similarity Features \n\nOne of the ways we might go about detecting plagiarism, is by computing **similarity features** that measure how similar a given answer text is as compared to the original wikipedia source text (for a specific task, a-e). The similarity features you will use are informed by [this paper on plagiarism detection](https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c412841_developing-a-corpus-of-plagiarised-short-answers/developing-a-corpus-of-plagiarised-short-answers.pdf). \n> In this paper, researchers created features called **containment** and **longest common subsequence**. \n\nUsing these features as input, you will train a model to distinguish between plagiarized and not-plagiarized text files.\n\n## Feature Engineering\n\nLet's talk a bit more about the features we want to include in a plagiarism detection model and how to calculate such features. In the following explanations, I'll refer to a submitted text file as a **Student Answer Text (A)** and the original, wikipedia source file (that we want to compare that answer to) as the **Wikipedia Source Text (S)**.\n\n### Containment\n\nYour first task will be to create **containment features**. To understand containment, let's first revisit a definition of [n-grams](https://en.wikipedia.org/wiki/N-gram). An *n-gram* is a sequential word grouping. For example, in a line like \"bayes rule gives us a way to combine prior knowledge with new information,\" a 1-gram is just one word, like \"bayes.\" A 2-gram might be \"bayes rule\" and a 3-gram might be \"combine prior knowledge.\"\n\n> Containment is defined as the **intersection** of the n-gram word count of the Wikipedia Source Text (S) with the n-gram word count of the Student Answer Text (S) *divided* by the n-gram word count of the Student Answer Text.\n\n$$ \\frac{\\sum{count(\\text{ngram}_{A}) \\cap count(\\text{ngram}_{S})}}{\\sum{count(\\text{ngram}_{A})}} $$\n\nIf the two texts have no n-grams in common, the containment will be 0, but if _all_ their n-grams intersect then the containment will be 1. Intuitively, you can see how having longer n-gram's in common, might be an indication of cut-and-paste plagiarism. In this project, it will be up to you to decide on the appropriate `n` or several `n`'s to use in your final model.\n\n### EXERCISE: Create containment features\n\nGiven the `complete_df` that you've created, you should have all the information you need to compare any Student Answer Text (A) with its appropriate Wikipedia Source Text (S). An answer for task A should be compared to the source text for task A, just as answers to tasks B, C, D, and E should be compared to the corresponding original source text.\n\nIn this exercise, you'll complete the function, `calculate_containment` which calculates containment based upon the following parameters:\n* A given DataFrame, `df` (which is assumed to be the `complete_df` from above)\n* An `answer_filename`, such as 'g0pB_taskd.txt' \n* An n-gram length, `n`\n\n### Containment calculation\n\nThe general steps to complete this function are as follows:\n1. From *all* of the text files in a given `df`, create an array of n-gram counts; it is suggested that you use a [CountVectorizer](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html) for this purpose.\n2. Get the processed answer and source texts for the given `answer_filename`.\n3. Calculate the containment between an answer and source text according to the following equation.\n\n >$$ \\frac{\\sum{count(\\text{ngram}_{A}) \\cap count(\\text{ngram}_{S})}}{\\sum{count(\\text{ngram}_{A})}} $$\n \n4. Return that containment value.\n\nYou are encouraged to write any helper functions that you need to complete the function below.", "_____no_output_____" ] ], [ [ "complete_df[complete_df['File'] == 'g0pA_taska.txt'].iloc[0]['Text']\n'g0pA_taska.txt'.replace('g0pA','orig')\ns = 'g0pA_taska.txt'\n'orig' + s[4:]", "_____no_output_____" ], [ "from sklearn.feature_extraction.text import CountVectorizer\n\ndef get_texts(df, filename):\n answer = df[df['File'] == filename].iloc[0]['Text']\n orig_filename = 'orig' + filename[4:]\n orig = df[df['File'] == orig_filename].iloc[0]['Text']\n #print(filename)\n #print(orig_filename)\n return answer, orig\n\n\n# Calculate the ngram containment for one answer file/source file pair in a df\ndef calculate_containment(df, n, answer_filename):\n '''Calculates the containment between a given answer text and its associated source text.\n This function creates a count of ngrams (of a size, n) for each text file in our data.\n Then calculates the containment by finding the ngram count for a given answer text, \n and its associated source text, and calculating the normalized intersection of those counts.\n :param df: A dataframe with columns,\n 'File', 'Task', 'Category', 'Class', 'Text', and 'Datatype'\n :param n: An integer that defines the ngram size\n :param answer_filename: A filename for an answer text in the df, ex. 'g0pB_taskd.txt'\n :return: A single containment value that represents the similarity\n between an answer text and its source text.\n '''\n a_text, s_text = get_texts(df, answer_filename)\n \n # instantiate an ngram counter\n counts = CountVectorizer(analyzer='word', ngram_range=(n,n))\n ngrams = counts.fit_transform([a_text, s_text])\n ngram_array = ngrams.toarray()\n return sum(np.amin(ngram_array,axis=0))/sum(ngram_array[0])\n", "_____no_output_____" ] ], [ [ "### Test cells\n\nAfter you've implemented the containment function, you can test out its behavior. \n\nThe cell below iterates through the first few files, and calculates the original category _and_ containment values for a specified n and file.\n\n>If you've implemented this correctly, you should see that the non-plagiarized have low or close to 0 containment values and that plagiarized examples have higher containment values, closer to 1.\n\nNote what happens when you change the value of n. I recommend applying your code to multiple files and comparing the resultant containment values. You should see that the highest containment values correspond to files with the highest category (`cut`) of plagiarism level.", "_____no_output_____" ] ], [ [ "# select a value for n\nn = 1\n\n# indices for first few files\ntest_indices = range(4)\n\n# iterate through files and calculate containment\ncategory_vals = []\ncontainment_vals = []\nfor i in test_indices:\n # get level of plagiarism for a given file index\n category_vals.append(complete_df.loc[i, 'Category'])\n # calculate containment for given file and n\n filename = complete_df.loc[i, 'File']\n print(filename)\n c = calculate_containment(complete_df, n, filename)\n containment_vals.append(c)\n\n# print out result, does it make sense?\nprint('Original category values: \\n', category_vals)\nprint()\nprint(str(n)+'-gram containment values: \\n', containment_vals)\nngram_1 = [0.39814814814814814, 1.0, 0.86936936936936937, 0.5935828877005348]\nprint('Expected values: \\n', ngram_1)\nassert all(np.isclose(containment_vals, ngram_1, rtol=1e-04)), \\\n 'n=1 calculations are incorrect. Double check the intersection calculation.'", "g0pA_taska.txt\ng0pA_taskb.txt\ng0pA_taskc.txt\ng0pA_taskd.txt\nOriginal category values: \n [0, 3, 2, 1]\n\n1-gram containment values: \n [0.39814814814814814, 1.0, 0.8693693693693694, 0.5935828877005348]\nExpected values: \n [0.39814814814814814, 1.0, 0.8693693693693694, 0.5935828877005348]\n" ], [ "# run this test cell\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# test containment calculation\n# params: complete_df from before, and containment function\nimport problem_unittests as tests\ntests.test_containment(complete_df, calculate_containment)", "Tests Passed!\n" ] ], [ [ "### QUESTION 1: Why can we calculate containment features across *all* data (training & test), prior to splitting the DataFrame for modeling? That is, what about the containment calculation means that the test and training data do not influence each other?", "_____no_output_____" ], [ "**Answer:**\nBit ambiguous lengthy question. But I think, since containment value is just one feature or one variable for our data, and it is not we are changing origin data or running prediction, in other words it is a pre-step before running actual trainnning. So we can calculate it for all data at this stage. ", "_____no_output_____" ], [ "---\n## Longest Common Subsequence\n\nContainment a good way to find overlap in word usage between two documents; it may help identify cases of cut-and-paste as well as paraphrased levels of plagiarism. Since plagiarism is a fairly complex task with varying levels, it's often useful to include other measures of similarity. The paper also discusses a feature called **longest common subsequence**.\n\n> The longest common subsequence is the longest string of words (or letters) that are *the same* between the Wikipedia Source Text (S) and the Student Answer Text (A). This value is also normalized by dividing by the total number of words (or letters) in the Student Answer Text. \n\nIn this exercise, we'll ask you to calculate the longest common subsequence of words between two texts.\n\n### EXERCISE: Calculate the longest common subsequence\n\nComplete the function `lcs_norm_word`; this should calculate the *longest common subsequence* of words between a Student Answer Text and corresponding Wikipedia Source Text. \n\nIt may be helpful to think of this in a concrete example. A Longest Common Subsequence (LCS) problem may look as follows:\n* Given two texts: text A (answer text) of length n, and string S (original source text) of length m. Our goal is to produce their longest common subsequence of words: the longest sequence of words that appear left-to-right in both texts (though the words don't have to be in continuous order).\n* Consider:\n * A = \"i think pagerank is a link analysis algorithm used by google that uses a system of weights attached to each element of a hyperlinked set of documents\"\n * S = \"pagerank is a link analysis algorithm used by the google internet search engine that assigns a numerical weighting to each element of a hyperlinked set of documents\"\n\n* In this case, we can see that the start of each sentence of fairly similar, having overlap in the sequence of words, \"pagerank is a link analysis algorithm used by\" before diverging slightly. Then we **continue moving left -to-right along both texts** until we see the next common sequence; in this case it is only one word, \"google\". Next we find \"that\" and \"a\" and finally the same ending \"to each element of a hyperlinked set of documents\".\n* Below, is a clear visual of how these sequences were found, sequentially, in each text.\n\n<img src='notebook_ims/common_subseq_words.png' width=40% />\n\n* Now, those words appear in left-to-right order in each document, sequentially, and even though there are some words in between, we count this as the longest common subsequence between the two texts. \n* If I count up each word that I found in common I get the value 20. **So, LCS has length 20**. \n* Next, to normalize this value, divide by the total length of the student answer; in this example that length is only 27. **So, the function `lcs_norm_word` should return the value `20/27` or about `0.7408`.**\n\nIn this way, LCS is a great indicator of cut-and-paste plagiarism or if someone has referenced the same source text multiple times in an answer.", "_____no_output_____" ], [ "### LCS, dynamic programming\n\nIf you read through the scenario above, you can see that this algorithm depends on looking at two texts and comparing them word by word. You can solve this problem in multiple ways. First, it may be useful to `.split()` each text into lists of comma separated words to compare. Then, you can iterate through each word in the texts and compare them, adding to your value for LCS as you go. \n\nThe method I recommend for implementing an efficient LCS algorithm is: using a matrix and dynamic programming. **Dynamic programming** is all about breaking a larger problem into a smaller set of subproblems, and building up a complete result without having to repeat any subproblems. \n\nThis approach assumes that you can split up a large LCS task into a combination of smaller LCS tasks. Let's look at a simple example that compares letters:\n\n* A = \"ABCD\"\n* S = \"BD\"\n\nWe can see right away that the longest subsequence of _letters_ here is 2 (B and D are in sequence in both strings). And we can calculate this by looking at relationships between each letter in the two strings, A and S.\n\nHere, I have a matrix with the letters of A on top and the letters of S on the left side:\n\n<img src='notebook_ims/matrix_1.png' width=40% />\n\nThis starts out as a matrix that has as many columns and rows as letters in the strings S and O **+1** additional row and column, filled with zeros on the top and left sides. So, in this case, instead of a 2x4 matrix it is a 3x5.\n\nNow, we can fill this matrix up by breaking it into smaller LCS problems. For example, let's first look at the shortest substrings: the starting letter of A and S. We'll first ask, what is the Longest Common Subsequence between these two letters \"A\" and \"B\"? \n\n**Here, the answer is zero and we fill in the corresponding grid cell with that value.**\n\n<img src='notebook_ims/matrix_2.png' width=30% />\n\nThen, we ask the next question, what is the LCS between \"AB\" and \"B\"?\n\n**Here, we have a match, and can fill in the appropriate value 1**.\n\n<img src='notebook_ims/matrix_3_match.png' width=25% />\n\nIf we continue, we get to a final matrix that looks as follows, with a **2** in the bottom right corner.\n\n<img src='notebook_ims/matrix_6_complete.png' width=25% />\n\nThe final LCS will be that value **2** *normalized* by the number of n-grams in A. So, our normalized value is 2/4 = **0.5**.\n\n### The matrix rules\n\nOne thing to notice here is that, you can efficiently fill up this matrix one cell at a time. Each grid cell only depends on the values in the grid cells that are directly on top and to the left of it, or on the diagonal/top-left. The rules are as follows:\n* Start with a matrix that has one extra row and column of zeros.\n* As you traverse your string:\n * If there is a match, fill that grid cell with the value to the top-left of that cell *plus* one. So, in our case, when we found a matching B-B, we added +1 to the value in the top-left of the matching cell, 0.\n * If there is not a match, take the *maximum* value from either directly to the left or the top cell, and carry that value over to the non-match cell.\n\n<img src='notebook_ims/matrix_rules.png' width=50% />\n\nAfter completely filling the matrix, **the bottom-right cell will hold the non-normalized LCS value**.\n\nThis matrix treatment can be applied to a set of words instead of letters. Your function should apply this to the words in two texts and return the normalized LCS value.", "_____no_output_____" ] ], [ [ "ss = \"aas\"\nfor i in range(1,len(ss)+1):\n print(ss[i-1])\n \nd = np.zeros((2, 2))\nd[0][0] = 1\nd", "a\na\ns\n" ], [ "import re\n\ndef clean_text(sentence):\n return [re.sub(r'\\W+', '', c) for c in sentence.split()]\n\n# Compute the normalized LCS given an answer text and a source text\ndef lcs_norm_word(answer_text, source_text):\n '''Computes the longest common subsequence of words in two texts; returns a normalized value.\n :param answer_text: The pre-processed text for an answer text\n :param source_text: The pre-processed text for an answer's associated source text\n :return: A normalized LCS value'''\n \n answer_words = clean_text(answer_text)\n source_words = clean_text(source_text)\n lcs = 0\n la = len(answer_words)\n ls = len(source_words)\n table = np.zeros((la+1, ls+1))\n for i in range(1,la+1):\n for j in range(1,ls+1):\n o = max(table[i-1][j], table[i][j-1])\n if (answer_words[i-1] == source_words[j-1]):\n o = table[i-1][j-1] + 1\n table[i][j] = o\n lcs = o\n \n return lcs/la\n", "_____no_output_____" ] ], [ [ "### Test cells\n\nLet's start by testing out your code on the example given in the initial description.\n\nIn the below cell, we have specified strings A (answer text) and S (original source text). We know that these texts have 20 words in common and the submitted answer is 27 words long, so the normalized, longest common subsequence should be 20/27.\n", "_____no_output_____" ] ], [ [ "# Run the test scenario from above\n# does your function return the expected value?\n\nA = \"i think pagerank is a link analysis algorithm used by google that uses a system of weights attached to each element of a hyperlinked set of documents\"\nS = \"pagerank is a link analysis algorithm used by the google internet search engine that assigns a numerical weighting to each element of a hyperlinked set of documents\"\n\n# calculate LCS\nlcs = lcs_norm_word(A, S)\nprint('LCS = ', lcs)\n\n\n# expected value test\nassert lcs==20/27., \"Incorrect LCS value, expected about 0.7408, got \"+str(lcs)\n\nprint('Test passed!')", "LCS = 0.7407407407407407\nTest passed!\n" ] ], [ [ "This next cell runs a more rigorous test.", "_____no_output_____" ] ], [ [ "# run test cell\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# test lcs implementation\n# params: complete_df from before, and lcs_norm_word function\ntests.test_lcs(complete_df, lcs_norm_word)", "Tests Passed!\n" ] ], [ [ "Finally, take a look at a few resultant values for `lcs_norm_word`. Just like before, you should see that higher values correspond to higher levels of plagiarism.", "_____no_output_____" ] ], [ [ "# test on your own\ntest_indices = range(5) # look at first few files\n\ncategory_vals = []\nlcs_norm_vals = []\n# iterate through first few docs and calculate LCS\nfor i in test_indices:\n category_vals.append(complete_df.loc[i, 'Category'])\n # get texts to compare\n answer_text = complete_df.loc[i, 'Text'] \n task = complete_df.loc[i, 'Task']\n # we know that source texts have Class = -1\n orig_rows = complete_df[(complete_df['Class'] == -1)]\n orig_row = orig_rows[(orig_rows['Task'] == task)]\n source_text = orig_row['Text'].values[0]\n \n # calculate lcs\n lcs_val = lcs_norm_word(answer_text, source_text)\n lcs_norm_vals.append(lcs_val)\n\n# print out result, does it make sense?\nprint('Original category values: \\n', category_vals)\nprint()\nprint('Normalized LCS values: \\n', lcs_norm_vals)", "Original category values: \n [0, 3, 2, 1, 0]\n\nNormalized LCS values: \n [0.1917808219178082, 0.8207547169811321, 0.8464912280701754, 0.3160621761658031, 0.24257425742574257]\n" ] ], [ [ "---\n# Create All Features\n\nNow that you've completed the feature calculation functions, it's time to actually create multiple features and decide on which ones to use in your final model! In the below cells, you're provided two helper functions to help you create multiple features and store those in a DataFrame, `features_df`.\n\n### Creating multiple containment features\n\nYour completed `calculate_containment` function will be called in the next cell, which defines the helper function `create_containment_features`. \n\n> This function returns a list of containment features, calculated for a given `n` and for *all* files in a df (assumed to the the `complete_df`).\n\nFor our original files, the containment value is set to a special value, -1.\n\nThis function gives you the ability to easily create several containment features, of different n-gram lengths, for each of our text files.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# Function returns a list of containment features, calculated for a given n \n# Should return a list of length 100 for all files in a complete_df\ndef create_containment_features(df, n, column_name=None):\n \n containment_values = []\n \n if(column_name==None):\n column_name = 'c_'+str(n) # c_1, c_2, .. c_n\n \n # iterates through dataframe rows\n for i in df.index:\n file = df.loc[i, 'File']\n # Computes features using calculate_containment function\n if df.loc[i,'Category'] > -1:\n c = calculate_containment(df, n, file)\n containment_values.append(c)\n # Sets value to -1 for original tasks \n else:\n containment_values.append(-1)\n \n print(str(n)+'-gram containment features created!')\n return containment_values\n", "_____no_output_____" ] ], [ [ "### Creating LCS features\n\nBelow, your complete `lcs_norm_word` function is used to create a list of LCS features for all the answer files in a given DataFrame (again, this assumes you are passing in the `complete_df`. It assigns a special value for our original, source files, -1.\n", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# Function creates lcs feature and add it to the dataframe\ndef create_lcs_features(df, column_name='lcs_word'):\n \n lcs_values = []\n \n # iterate through files in dataframe\n for i in df.index:\n # Computes LCS_norm words feature using function above for answer tasks\n if df.loc[i,'Category'] > -1:\n # get texts to compare\n answer_text = df.loc[i, 'Text'] \n task = df.loc[i, 'Task']\n # we know that source texts have Class = -1\n orig_rows = df[(df['Class'] == -1)]\n orig_row = orig_rows[(orig_rows['Task'] == task)]\n source_text = orig_row['Text'].values[0]\n\n # calculate lcs\n lcs = lcs_norm_word(answer_text, source_text)\n lcs_values.append(lcs)\n # Sets to -1 for original tasks \n else:\n lcs_values.append(-1)\n\n print('LCS features created!')\n return lcs_values\n ", "_____no_output_____" ] ], [ [ "## EXERCISE: Create a features DataFrame by selecting an `ngram_range`\n\nThe paper suggests calculating the following features: containment *1-gram to 5-gram* and *longest common subsequence*. \n> In this exercise, you can choose to create even more features, for example from *1-gram to 7-gram* containment features and *longest common subsequence*. \n\nYou'll want to create at least 6 features to choose from as you think about which to give to your final, classification model. Defining and comparing at least 6 different features allows you to discard any features that seem redundant, and choose to use the best features for your final model!\n\nIn the below cell **define an n-gram range**; these will be the n's you use to create n-gram containment features. The rest of the feature creation code is provided.", "_____no_output_____" ] ], [ [ "# Define an ngram range\nngram_range = range(1,7)\n\n\n# The following code may take a minute to run, depending on your ngram_range\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nfeatures_list = []\n\n# Create features in a features_df\nall_features = np.zeros((len(ngram_range)+1, len(complete_df)))\n\n# Calculate features for containment for ngrams in range\ni=0\nfor n in ngram_range:\n column_name = 'c_'+str(n)\n features_list.append(column_name)\n # create containment features\n all_features[i]=np.squeeze(create_containment_features(complete_df, n))\n i+=1\n\n# Calculate features for LCS_Norm Words \nfeatures_list.append('lcs_word')\nall_features[i]= np.squeeze(create_lcs_features(complete_df))\n\n# create a features dataframe\nfeatures_df = pd.DataFrame(np.transpose(all_features), columns=features_list)\n\n# Print all features/columns\nprint()\nprint('Features: ', features_list)\nprint()", "1-gram containment features created!\n2-gram containment features created!\n3-gram containment features created!\n4-gram containment features created!\n5-gram containment features created!\n6-gram containment features created!\nLCS features created!\n\nFeatures: ['c_1', 'c_2', 'c_3', 'c_4', 'c_5', 'c_6', 'lcs_word']\n\n" ], [ "# print some results \nfeatures_df.head(10)", "_____no_output_____" ] ], [ [ "## Correlated Features\n\nYou should use feature correlation across the *entire* dataset to determine which features are ***too*** **highly-correlated** with each other to include both features in a single model. For this analysis, you can use the *entire* dataset due to the small sample size we have. \n\nAll of our features try to measure the similarity between two texts. Since our features are designed to measure similarity, it is expected that these features will be highly-correlated. Many classification models, for example a Naive Bayes classifier, rely on the assumption that features are *not* highly correlated; highly-correlated features may over-inflate the importance of a single feature. \n\nSo, you'll want to choose your features based on which pairings have the lowest correlation. These correlation values range between 0 and 1; from low to high correlation, and are displayed in a [correlation matrix](https://www.displayr.com/what-is-a-correlation-matrix/), below.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n# Create correlation matrix for just Features to determine different models to test\ncorr_matrix = features_df.corr().abs().round(2)\n\n# display shows all of a dataframe\ndisplay(corr_matrix)", "_____no_output_____" ] ], [ [ "## EXERCISE: Create selected train/test data\n\nComplete the `train_test_data` function below. This function should take in the following parameters:\n* `complete_df`: A DataFrame that contains all of our processed text data, file info, datatypes, and class labels\n* `features_df`: A DataFrame of all calculated features, such as containment for ngrams, n= 1-5, and lcs values for each text file listed in the `complete_df` (this was created in the above cells)\n* `selected_features`: A list of feature column names, ex. `['c_1', 'lcs_word']`, which will be used to select the final features in creating train/test sets of data.\n\nIt should return two tuples:\n* `(train_x, train_y)`, selected training features and their corresponding class labels (0/1)\n* `(test_x, test_y)`, selected training features and their corresponding class labels (0/1)\n\n** Note: x and y should be arrays of feature values and numerical class labels, respectively; not DataFrames.**\n\nLooking at the above correlation matrix, you should decide on a **cutoff** correlation value, less than 1.0, to determine which sets of features are *too* highly-correlated to be included in the final training and test data. If you cannot find features that are less correlated than some cutoff value, it is suggested that you increase the number of features (longer n-grams) to choose from or use *only one or two* features in your final model to avoid introducing highly-correlated features.\n\nRecall that the `complete_df` has a `Datatype` column that indicates whether data should be `train` or `test` data; this should help you split the data appropriately.", "_____no_output_____" ] ], [ [ "# Takes in dataframes and a list of selected features (column names) \n# and returns (train_x, train_y), (test_x, test_y)\ndef train_test_data(complete_df, features_df, selected_features):\n '''Gets selected training and test features from given dataframes, and \n returns tuples for training and test features and their corresponding class labels.\n :param complete_df: A dataframe with all of our processed text data, datatypes, and labels\n :param features_df: A dataframe of all computed, similarity features\n :param selected_features: An array of selected features that correspond to certain columns in `features_df`\n :return: training and test features and labels: (train_x, train_y), (test_x, test_y)'''\n \n # get the training features\n train_x = features_df[complete_df['Datatype'] == 'train'][selected_features].to_numpy()\n # And training class labels (0 or 1)\n train_y = complete_df[complete_df['Datatype'] == 'train']['Class'].to_numpy()\n \n # get the test features and labels\n test_x = features_df[complete_df['Datatype'] == 'test'][selected_features].to_numpy()\n test_y = complete_df[complete_df['Datatype'] == 'test']['Class'].to_numpy()\n \n return (train_x, train_y), (test_x, test_y)\n ", "_____no_output_____" ] ], [ [ "### Test cells\n\nBelow, test out your implementation and create the final train/test data.", "_____no_output_____" ] ], [ [ "#complete_df.loc(list(features_df)[:2])\n[list(features_df)[:2]]\nfeatures_df[list(features_df)[:2]]\nfeatures_df[complete_df['Datatype'] == 'train'][list(features_df)[:2]].to_numpy()\n#list(complete_df[complete_df['Datatype'] == 'train']['Class'])\nfeatures_df", "_____no_output_____" ], [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntest_selection = list(features_df)[:2] # first couple columns as a test\n# test that the correct train/test data is created\n(train_x, train_y), (test_x, test_y) = train_test_data(complete_df, features_df, test_selection)\n\n# params: generated train/test data\ntests.test_data_split(train_x, train_y, test_x, test_y)", "Tests Passed!\n" ] ], [ [ "## EXERCISE: Select \"good\" features\n\nIf you passed the test above, you can create your own train/test data, below. \n\nDefine a list of features you'd like to include in your final mode, `selected_features`; this is a list of the features names you want to include.", "_____no_output_____" ] ], [ [ "# Select your list of features, this should be column names from features_df\n# ex. ['c_1', 'lcs_word']\nselected_features = ['c_1', 'c_5', 'lcs_word']\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n\n(train_x, train_y), (test_x, test_y) = train_test_data(complete_df, features_df, selected_features)\n\n# check that division of samples seems correct\n# these should add up to 95 (100 - 5 original files)\nprint('Training size: ', len(train_x))\nprint('Test size: ', len(test_x))\nprint()\nprint('Training df sample: \\n', train_x[:10])", "Training size: 70\nTest size: 25\n\nTraining df sample: \n [[0.39814815 0. 0.19178082]\n [0.86936937 0.44954128 0.84649123]\n [0.59358289 0.08196721 0.31606218]\n [0.54450262 0. 0.24257426]\n [0.32950192 0. 0.16117216]\n [0.59030837 0. 0.30165289]\n [0.75977654 0.24571429 0.48430493]\n [0.51612903 0. 0.27083333]\n [0.44086022 0. 0.22395833]\n [0.97945205 0.78873239 0.9 ]]\n" ], [ "from numpy import cov\n\ncov(features_df['c_1'].to_numpy(), features_df['c_2'].to_numpy())\n#features_df['c_1'].to_numpy()\nless_corr = 1\nless_corr_a=0\nless_corr_b=0\nfor i in range(1,6):\n for j in range(1,6):\n if less_corr > features_df['c_'+str(i)].corr(features_df['c_'+str(j)]):\n less_corr = features_df['c_'+str(i)].corr(features_df['c_'+str(j)])\n less_corr_a = i\n less_corr_b = j\n\nprint(less_corr)\nprint(less_corr_a)\nprint(less_corr_b)", "0.8809022697353123\n1\n5\n" ] ], [ [ "\n\n### Question 2: How did you decide on which features to include in your final model? ", "_____no_output_____" ], [ "**Answer:**\nI run correlation analysis between each pair of features, and result shows that c_1 and c_5 are least correlated, therefore I chose them", "_____no_output_____" ], [ "---\n## Creating Final Data Files\n\nNow, you are almost ready to move on to training a model in SageMaker!\n\nYou'll want to access your train and test data in SageMaker and upload it to S3. In this project, SageMaker will expect the following format for your train/test data:\n* Training and test data should be saved in one `.csv` file each, ex `train.csv` and `test.csv`\n* These files should have class labels in the first column and features in the rest of the columns\n\nThis format follows the practice, outlined in the [SageMaker documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html), which reads: \"Amazon SageMaker requires that a CSV file doesn't have a header record and that the target variable [class label] is in the first column.\"\n\n## EXERCISE: Create csv files\n\nDefine a function that takes in x (features) and y (labels) and saves them to one `.csv` file at the path `data_dir/filename`.\n\nIt may be useful to use pandas to merge your features and labels into one DataFrame and then convert that into a csv file. You can make sure to get rid of any incomplete rows, in a DataFrame, by using `dropna`.", "_____no_output_____" ] ], [ [ "fake_x = [ [0.39814815, 0.0001, 0.19178082], \n [0.86936937, 0.44954128, 0.84649123], \n [0.44086022, 0., 0.22395833] ]\n\nfake_y = [0, 1, 1]\na=np.array(fake_x)\nb=np.array(fake_y).reshape(3,1)\n\nnp.concatenate((a,b),axis=1)", "_____no_output_____" ], [ "def make_csv(x, y, filename, data_dir):\n '''Merges features and labels and converts them into one csv file with labels in the first column.\n :param x: Data features\n :param y: Data labels\n :param file_name: Name of csv file, ex. 'train.csv'\n :param data_dir: The directory where files will be saved\n '''\n # make data dir, if it does not exist\n if not os.path.exists(data_dir):\n os.makedirs(data_dir)\n \n \n # your code here\n a = np.array(x)\n b = np.array(y).reshape(len(y),1)\n c = np.concatenate((b,a),axis=1)\n \n np.savetxt(str(data_dir)+'/'+str(filename), c, delimiter=\",\")\n \n # nothing is returned, but a print statement indicates that the function has run\n print('Path created: '+str(data_dir)+'/'+str(filename))", "_____no_output_____" ] ], [ [ "### Test cells\n\nTest that your code produces the correct format for a `.csv` file, given some text features and labels.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nfake_x = [ [0.39814815, 0.0001, 0.19178082], \n [0.86936937, 0.44954128, 0.84649123], \n [0.44086022, 0., 0.22395833] ]\n\nfake_y = [0, 1, 1]\n\nmake_csv(fake_x, fake_y, filename='to_delete.csv', data_dir='test_csv')\n\n# read in and test dimensions\nfake_df = pd.read_csv('test_csv/to_delete.csv', header=None)\n\n# check shape\nassert fake_df.shape==(3, 4), \\\n 'The file should have as many rows as data_points and as many columns as features+1 (for indices).'\n# check that first column = labels\nassert np.all(fake_df.iloc[:,0].values==fake_y), 'First column is not equal to the labels, fake_y.'\nprint('Tests passed!')", "Path created: test_csv/to_delete.csv\nTests passed!\n" ], [ "# delete the test csv file, generated above\n! rm -rf test_csv", "_____no_output_____" ] ], [ [ "If you've passed the tests above, run the following cell to create `train.csv` and `test.csv` files in a directory that you specify! This will save the data in a local directory. Remember the name of this directory because you will reference it again when uploading this data to S3.", "_____no_output_____" ] ], [ [ "# can change directory, if you want\ndata_dir = 'plagiarism_data'\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n\nmake_csv(train_x, train_y, filename='train.csv', data_dir=data_dir)\nmake_csv(test_x, test_y, filename='test.csv', data_dir=data_dir)", "Path created: plagiarism_data/train.csv\nPath created: plagiarism_data/test.csv\n" ] ], [ [ "## Up Next\n\nNow that you've done some feature engineering and created some training and test data, you are ready to train and deploy a plagiarism classification model. The next notebook will utilize SageMaker resources to train and test a model that you design.", "_____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" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
d0319fc0764449a219741a378edeb7b0de771170
103,826
ipynb
Jupyter Notebook
notebooks/dngo_example.ipynb
hssandriss/pybnn
e878553a24ce9ebdde9088f285c7f292e4ee8885
[ "BSD-3-Clause" ]
null
null
null
notebooks/dngo_example.ipynb
hssandriss/pybnn
e878553a24ce9ebdde9088f285c7f292e4ee8885
[ "BSD-3-Clause" ]
null
null
null
notebooks/dngo_example.ipynb
hssandriss/pybnn
e878553a24ce9ebdde9088f285c7f292e4ee8885
[ "BSD-3-Clause" ]
null
null
null
447.525862
53,252
0.941489
[ [ [ "import numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\n\nfrom pybnn import DNGO\nfrom pybnn.util.normalization import zero_mean_unit_var_normalization, zero_mean_unit_var_denormalization\n\n%matplotlib inline\n\n# plt.rc('text', usetex=True)\n# plt.rc('font', size=15.0, family='serif')\n# plt.rcParams['figure.figsize'] = (12.0, 8.0)\n# plt.rcParams['text.latex.preamble'] = [r\"\\usepackage{amsmath}\"]", "_____no_output_____" ], [ "def my_data(x_min, x_max, n, train=True):\n x = np.linspace(x_min, x_max, n)\n# x = np.expand_dims(x, -1)\n sigma = 3 * np.ones_like(x) if train else np.zeros_like(x)\n y = x**3 + np.random.normal(0, sigma)\n return x, y\n\n\ndef my_data_2_intervals(inter_1: tuple, inter_2: tuple, n, train=True):\n x_min, x_max = inter_1\n x_0 = np.linspace(x_min, x_max, n // 2)\n# x_0 = np.expand_dims(x_0, -1)\n x_min, x_max = inter_2\n x_1 = np.linspace(x_min, x_max, n // 2)\n# x_1 = np.expand_dims(x_1, -1)\n x = np.concatenate((x_0, x_1), 0)\n sigma = 3 * np.ones_like(x) if train else np.zeros_like(x)\n y = x**3 + np.random.normal(0, sigma)\n return x, y", "_____no_output_____" ], [ "\n\nx, y = my_data_2_intervals((-4, 1), (4, 5), 500, train=True)\n\ngrid, fvals = my_data(-7, 7, 500, train=False)\n\nplt.plot(grid, fvals, \"k--\")\nplt.plot(x, y, \"ro\")\nplt.grid()\nplt.xlim(-7, 7)\n\nplt.show()", "_____no_output_____" ], [ "y.shape", "_____no_output_____" ], [ "model = DNGO(do_mcmc=True)\nmodel.train(x[:, None], y, do_optimize=True)", "c:\\users\\tdrishs\\working_dir\\venv\\lib\\site-packages\\emcee\\moves\\red_blue.py:99: RuntimeWarning: invalid value encountered in double_scalars\n lnpdiff = f + nlp - state.log_prob[j]\nc:\\users\\tdrishs\\working_dir\\venv\\lib\\site-packages\\pybnn\\dngo.py:306: RuntimeWarning: invalid value encountered in log\n mll -= 0.5 * np.log(np.linalg.det(K) + 1e-10)\n" ], [ "x_test_norm = zero_mean_unit_var_normalization(grid[:, None], model.X_mean, model.X_std)[0]\n\n# Get basis functions from the network\nbasis_funcs = model.network.basis_funcs(torch.Tensor(x_test_norm)).data.numpy()\n\nfor i in range(min(50, model.n_units_3)):\n plt.plot(grid, basis_funcs[:, i])\nplt.grid()\nplt.xlabel(\"Input\")\nplt.ylabel(\"Basisfunction\")\nplt.show()", "_____no_output_____" ], [ "m, v = model.predict(grid[:, None])\n\nplt.plot(x, y, \"x\")\nplt.grid()\nplt.plot(grid, fvals, \"k--\")\nplt.plot(grid, m, \"blue\")\nplt.fill_between(grid, m + np.sqrt(v), m - np.sqrt(v), color=\"orange\", alpha=0.8)\nplt.fill_between(grid, m + 2 * np.sqrt(v), m - 2 * np.sqrt(v), color=\"orange\", alpha=0.6)\nplt.fill_between(grid, m + 3 * np.sqrt(v), m - 3 * np.sqrt(v), color=\"orange\", alpha=0.4)\nplt.xlim(-7, 7)\nplt.ylim(-250,250)\nplt.xlabel(\"Input x\")\nplt.ylabel(\"Output f(x)\")\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
d031b90ea0fe1534db1187f86c832dd72731aac7
5,968
ipynb
Jupyter Notebook
Convexity/OPT_HW3.ipynb
QuantumGorilla/Optimization
ed7dc755cb1346d208f5f33fc4814e3931c9b44d
[ "MIT" ]
null
null
null
Convexity/OPT_HW3.ipynb
QuantumGorilla/Optimization
ed7dc755cb1346d208f5f33fc4814e3931c9b44d
[ "MIT" ]
null
null
null
Convexity/OPT_HW3.ipynb
QuantumGorilla/Optimization
ed7dc755cb1346d208f5f33fc4814e3931c9b44d
[ "MIT" ]
null
null
null
5,968
5,968
0.59065
[ [ [ "# **Optimización - Actividad 3**\n![researchgate-logo.png](https://www.uninorte.edu.co/Uninorte/images/topbar_un/headerlogo_un.png)", "_____no_output_____" ], [ "\n\n* Estudiante: Alejandro Jesús Manotas Marmolejo\n* Código: 200108289\n\n", "_____no_output_____" ], [ "# **Pregunta 1.**", "_____no_output_____" ], [ "Considere $N$ funciones convexas $f_i(x):\\Re\\Rightarrow \\Re$, para $1 \\le i \\le N$, demuestre que su suma\n\\begin{eqnarray}\n\\sum_{i=1}^{N} f_i(x)\\,,\n\\end{eqnarray}\nes convexa.", "_____no_output_____" ], [ "**Respuesta.**", "_____no_output_____" ], [ "\\begin{equation}\n\\begin{split}\n& x_1, x_2 \\in \\Re\\\\\n& z = \\alpha x_1 + (1-\\alpha)x_2\\\\\n& f(z) = g(\\alpha x_1 + (1-\\alpha)x_2)\\\\\n& g(x) = \\sum_{i=1}^{N} f_i(x)\\\\\n& = \\sum_{i=1}^{N} f_i(z)\\\\\n& = \\sum_{i=1}^{N} f(\\alpha x_1 + (1-\\alpha)x_2)\\\\\n& = \\sum_{i=1}^{N} \\alpha f_i(x_1) + (1-\\alpha)f_i(x_2)\\\\\n& = \\sum_{i=1}^{N} \\alpha f_i(x_1) + \\sum_{i=1}^{N} (1-\\alpha)f_i(x_2)\\\\\n& = \\alpha \\sum_{i=1}^{N} f_i(x_1) + (1-\\alpha)\\sum_{i=1}^{N} f_i(x_2)\\\\\n& = \\alpha g(x_1) + (1-\\alpha) g(x_2) \n\\end{split}\n\\end{equation}\n\n", "_____no_output_____" ], [ "\n\n---\n\n", "_____no_output_____" ], [ "# **Pregunta 2**", "_____no_output_____" ], [ "Demuestre que $g(x) = a\\cdot f(x) +b$ es convexa, en donde $a,b\\ge 0$ y $f(x):\\Re\\Rightarrow \\Re$ es una función convexa.", "_____no_output_____" ], [ "**Respuesta.**", "_____no_output_____" ], [ "\\begin{equation}\n\\begin{split}\n& x_1, x_2 \\in \\Re\\\\\n& z = \\alpha x_1 + (1-\\alpha)x_2\\\\\n& f(z) = g(\\alpha x_1 + (1-\\alpha)x_2)\\\\\n& g(x) = a \\cdot f(x) + b\\\\\n& = a \\cdot f(z) + b \\\\\n& = a \\cdot (f(\\alpha x_1 + (1-\\alpha)x_2)) + b\\\\\n& = a \\cdot (\\alpha f(x_1) + (1-\\alpha) f(x_2)) + b\\\\\n& = a\\alpha f(x_1) + (1-\\alpha)af(x_2) + b \\\\\n& = a\\alpha f(x_1) + (1-\\alpha)af(x_2) + b + \\alpha b - \\alpha b\\\\\n& = a\\alpha f(x_1) + \\alpha b + (1-\\alpha)af(x_2) + b - \\alpha b\\\\\n& = \\alpha (a f(x_1) + b) + (1-\\alpha)af(x_2) + b (1 - \\alpha)\\\\\n& = \\alpha (a f(x_1) + b) + (1-\\alpha)af(x_2) + b (1 - \\alpha)\\\\ \n& = \\alpha [a f(x_1) + b] + (1-\\alpha) [af(x_2) + b]\\\\ \n& = \\alpha g(x_1) + (1-\\alpha) g(x_2)\n\\end{split}\n\\end{equation}", "_____no_output_____" ], [ "\n\n---\n\n", "_____no_output_____" ], [ "# **Pregunta 3**", "_____no_output_____" ], [ "Demuestre que, si $f(x):\\Re \\Rightarrow \\Re$ es convexa, entonces $g(x) = f(a\\cdot x +b)$ es convexa también, en donde $a,b \\ge 0$.", "_____no_output_____" ], [ "**Respuesta.**", "_____no_output_____" ], [ "\\begin{equation}\n\\begin{split}\n& x_1, x_2 \\in \\Re \\\\\n& z = \\alpha x_1 + (1-\\alpha) x_2\\\\\n& f(z) = g(\\alpha x_1 + (1-\\alpha)x_2)\\\\\n& g(x) = f(a \\cdot x + b)\\\\\n& = f(a \\cdot (\\alpha x_1 + (1-\\alpha)x_2) + b)\\\\\n& = f(a \\alpha x_1 + (1-\\alpha)ax_2 + b)\\\\\n& = f(a \\alpha x_1 + (1-\\alpha)ax_2 + b + \\alpha b - \\alpha b)\\\\\n& = f(a \\alpha x_1 + \\alpha b + (1-\\alpha)ax_2 + b - \\alpha b)\\\\\n& = f(\\alpha [a x_1 + b] + (1-\\alpha)ax_2 + b [1- \\alpha])\\\\\n& = f(\\alpha [a x_1 + b] + (1-\\alpha) [ax_2 + b])\\\\\n& = \\alpha f([a x_1 + b]) + (1-\\alpha) f(ax_2 + b)\\\\\n& = \\alpha g(x_1) + (1-\\alpha) g(x_2)\\\\\n\\end{split}\n\\end{equation}", "_____no_output_____" ], [ "\n\n---\n\n", "_____no_output_____" ], [ "**Recuerde:** En este curso no se tolerará el plagio. Sin excepción, en caso de presentarse esta situación, a los estudiantes involucrados se les iniciará proceso de investigación, y se actuará en conformidad con el Reglamento de Estudiantes de la Universidad del Norte. El plagio incluye: usar contenidos sin la debida referencia, de manera literal o con mínimos cambios que no alteren el espíritu del texto/código; adquirir con o sin intención, trabajos de terceros y presentarlos parcial o totalmente como propios; presentar trabajos en grupo donde alguno de los integrantes no trabajó o donde no se hubo trabajo en equipo demostrable; entre otras situaciones definidas en el manual de fraude académico de la Universidad del Norte:\n\n(https://guayacan.uninorte.edu.co/normatividad_interna/upload/File/Guia_Prevencion_Fraude%20estudiantes(5).pdf )", "_____no_output_____" ], [ "**Isaías 40:31.** pero los que esperan a Jehová tendrán nuevas fuerzas; levantarán alas como las águilas; correrán, y no se cansarán; caminarán, y no se fatigarán.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
d031bcb4918dc324970cb27ee8c5594f2b37efc3
3,723
ipynb
Jupyter Notebook
notebooks_AR/Module1_unit4/0_Start_here.ipynb
LaurenZ-IHE/WAPOROCW
7e1357f23a142ea4394404f4462ed7ceb1f47009
[ "CC0-1.0" ]
7
2020-10-08T21:09:06.000Z
2022-02-08T08:48:31.000Z
notebooks_AR/Module1_unit4/0_Start_here.ipynb
LaurenZ-IHE/WAPOROCW
7e1357f23a142ea4394404f4462ed7ceb1f47009
[ "CC0-1.0" ]
9
2020-10-03T04:26:57.000Z
2022-03-01T10:56:01.000Z
notebooks_AR/Module1_unit4/0_Start_here.ipynb
LaurenZ-IHE/WAPOROCW
7e1357f23a142ea4394404f4462ed7ceb1f47009
[ "CC0-1.0" ]
5
2020-09-30T05:45:21.000Z
2022-02-08T08:48:38.000Z
26.034965
266
0.532904
[ [ [ "<div dir=\"rtl\">\n \n# يرجى القراءة \n\n</div>\n\n<div dir=\"rtl\">\nالدفتر التالي هو مثال عن كيفية استخدام Python لتحميل، معالجة وتحليل WaPOR data:\n</div>\n\n<div dir=\"rtl\">\n \n* [1 تحميل بيانات WaPOR بالجملة](1_Bulk_download_WaPOR_data.ipynb)\n* [2 معالجة بيانات WaPOR المحملة](2_Preprocess_WaPOR_data.ipynb)\n* [3 تحليل بيانات WaPOR](3_Analyse_WaPOR_data.ipynb)\n\n</div>\n\n<div dir=\"rtl\">\nتحتاج إلى تحميل الحزم التالية لبدء تشغيل الدفتر:\n</div>\n\n<div dir=\"rtl\">\n \n* requests\n* gdal\n* numpy\n* pandas\n* matplotlib\n* pyshp (shapefile)\n\n</div>\n\n<div dir=\"rtl\">\nتفقد إن تم تحميل الحزم التالية من خلال بدء تشغيل الكود التالي.\n</div>", "_____no_output_____" ] ], [ [ "import requests\nimport numpy\nimport pandas\nimport matplotlib\nimport shapefile\nimport gdal\nimport osr\nimport ogr", "_____no_output_____" ] ], [ [ "<div dir=\"rtl\">\nإن لم تحصل في الخلية على أية مخرجات، هذا يعني أن الحزم قد تحملت بشكل صحيح. إن لم يتم التحميل بشكل صحيح، سوف يظهر الخطأ على شكل كود كالتالي\n</div>", "_____no_output_____" ] ], [ [ "import notinstalledpackage", "_____no_output_____" ] ], [ [ "<div dir=\"rtl\">\n \n[في هذه الحالة، يمكن تجربة الخيارات التالية لتحميل الحزم](https://ocw.un-ihe.org/mod/book/view.php?id=6539&chapterid=680) \n\n### ملاحظات:\n- تم الحصول على osr و **ogr** بمجرد تحميل **gdal** \n \n</div>", "_____no_output_____" ], [ "<div dir=\"rtl\">\n\n# الحصول على رمز API\n\nفي بعض الدفاتر سوف تحتاج إلى رمز الAPI الخاص بك من WaPOR. وهو المفتاح الخاص بك لتتمكن من الجخول على مخدم WaPOR باستخدام حسابك وكلمة المرور الشخصية. يمكنك توليد الرمز من خلال بوابة WaPOR - profile page\n\n</div>\n\n![fig1](../img/fig1_get_api_key.gif)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d031be7ee86b55536ca4064c94edc20bf4b5d5b0
100,885
ipynb
Jupyter Notebook
notebooks/Correlation between app size and app quality.ipynb
jpzhangvincent/MobileAppRecommendSys
7c426c8c9586a8bad786d1f0d49b7f470590208f
[ "MIT" ]
null
null
null
notebooks/Correlation between app size and app quality.ipynb
jpzhangvincent/MobileAppRecommendSys
7c426c8c9586a8bad786d1f0d49b7f470590208f
[ "MIT" ]
null
null
null
notebooks/Correlation between app size and app quality.ipynb
jpzhangvincent/MobileAppRecommendSys
7c426c8c9586a8bad786d1f0d49b7f470590208f
[ "MIT" ]
null
null
null
216.027837
52,000
0.870903
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "app = pd.read_pickle('/Users/krystal/Desktop/app_cleaned.pickle')\napp.head()", "_____no_output_____" ], [ "app = app.drop_duplicates()", "_____no_output_____" ], [ "for i in range(0,len(app)):\n unit = app['size'][i][-2:]\n if unit == 'GB':\n app['size'][i] = float(app['size'][i][:-3])*1000\n else:\n app['size'][i] = float(app['size'][i][:-3])\n", "_____no_output_____" ] ], [ [ "<p> Convert unit of app size from GB into KB.</p>", "_____no_output_____" ] ], [ [ "rating_df = app[[\"name\",\"size\",\"overall_rating\", \"current_rating\", 'num_current_rating', \"num_overall_rating\"]].dropna()", "_____no_output_____" ], [ "rating_cleaned = {'1 star':1, \"1 and a half stars\": 1.5, '2 stars': 2, '2 and a half stars':2.5, \"3 stars\":3, \"3 and a half stars\":3.5, \"4 stars\": 4,\n '4 and a half stars': 4.5, \"5 stars\": 5}", "_____no_output_____" ], [ "rating_df.overall_rating = rating_df.overall_rating.replace(rating_cleaned)", "_____no_output_____" ], [ "rating_df['weighted_rating'] = np.divide(rating_df['num_current_rating'],rating_df['num_overall_rating'])*rating_df['current_rating']+(1-np.divide(rating_df['num_current_rating'],rating_df['num_overall_rating']))*rating_df['overall_rating']", "_____no_output_____" ] ], [ [ "<p>Add variable weighted rating as app's quality into data set.</p>", "_____no_output_____" ] ], [ [ "plt.scatter(rating_df['size'], rating_df['weighted_rating'])\nplt.xlabel('Size of app')\nplt.ylabel('Quality of app')\nplt.title('Relationship between app size and quality')\nplt.show()", "_____no_output_____" ], [ "rating_df_2 = rating_df[rating_df['size'] <= 500]", "_____no_output_____" ], [ "plt.scatter(rating_df_2['size'], rating_df_2['weighted_rating'])\nplt.xlabel('Size of app')\nplt.ylabel('Quality of app')\nplt.title('Relationship between app size(less than 500) and quality')\nplt.show()", "_____no_output_____" ] ], [ [ "<p>I plot scatter plot for app size and overall rating of app. The second plot only contains app with size less than 500KB. I find that there is a positive association between app size and app overall rating. Further analysis is still needed.</p>", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ] ]
d031c30a8ff3aaae6a6e3665af8524c8145dd010
6,199
ipynb
Jupyter Notebook
makefig.ipynb
computational-sediment-hyd/2DH_Python
38acbf615d48c8a8b8817cffc9869b678d318f69
[ "MIT" ]
null
null
null
makefig.ipynb
computational-sediment-hyd/2DH_Python
38acbf615d48c8a8b8817cffc9869b678d318f69
[ "MIT" ]
null
null
null
makefig.ipynb
computational-sediment-hyd/2DH_Python
38acbf615d48c8a8b8817cffc9869b678d318f69
[ "MIT" ]
null
null
null
22.460145
114
0.498629
[ [ [ "import numpy as np\nimport xarray as xr\nimport hvplot.xarray\nimport glob\nimport holoviews as hv\nhv.extension('bokeh')", "_____no_output_____" ] ], [ [ "# environment(on conda)", "_____no_output_____" ], [ "```bash\nconda create -y -n holo python=3.7\nconda activate holo\n# https://xarray.pydata.org/en/stable/getting-started-guide/installing.html#instructions\nconda install -y -c conda-forge xarray dask netCDF4 bottleneck\nconda install -y -c conda-forge hvplot\nconda install -y -c conda-forge selenium\nconda install -y -c conda-forge firefox geckodriver\nconda install -y -c conda-forge jupyter\n```", "_____no_output_____" ], [ "# make html & png", "_____no_output_____" ], [ "## read", "_____no_output_____" ] ], [ [ "fs = glob.glob('out0*.nc')\nfs.sort()\ndd = []\nfor f in fs:\n ds = xr.open_dataset(f)\n U = ds['u'].values\n V = ds['v'].values\n Vmag = np.sqrt( U**2 + V**2) + 0.00000001\n angle = (np.pi/2.) - np.arctan2(U/Vmag, V/Vmag)\n ds['Vmag'] = (['t','x','y'], Vmag)\n ds['angle'] =(['t','x','y'], angle)\n ds = ds.drop(['u','v'])\n dd.append(ds)\n \ndss = xr.concat(dd, dim=\"t\")", "_____no_output_____" ], [ "with open('obst.dat', mode='r', encoding='utf-8') as response:\n l = next(response)\n l = next(response)\n\nll = l.replace('\\n','').split(',')\ni1,i2,j1,j2 = np.array(ll, dtype=int)\n\nx1 = dss['x'].values[i1]\nx2 = dss['x'].values[i2]\ny1 = dss['y'].values[j1]\ny2 = dss['y'].values[j2]\n\nfPoly = hv.Polygons(np.array([[x1,y1],[x2,y1],[x2,y2],[x1,y2]])).options(fill_color='green')", "_____no_output_____" ] ], [ [ "## make html graph", "_____no_output_____" ] ], [ [ "fVec = dss.hvplot.vectorfield(x='x', y='y', groupby='t', angle='angle', mag='Vmag',hover=False)\nfVor = dss['vortex'].hvplot(frame_height=220, frame_width=600, x='x', y='y', cmap='bwr', clim=(-10,10)) \ng = fVor * fVec * fPoly", "_____no_output_____" ], [ "g", "_____no_output_____" ] ], [ [ "### Thinning out for github", "_____no_output_____" ] ], [ [ "dssp = dss.isel( t=range(0,int(dss.dims['t']/2),10) )", "_____no_output_____" ], [ "fVec = dssp.hvplot.vectorfield(x='x', y='y', groupby='t', angle='angle', mag='Vmag',hover=False)\nfVor = dssp['vortex'].hvplot(frame_height=220, frame_width=600, x='x', y='y', cmap='bwr', clim=(-10,10)) \ng = fVor * fVec * fPoly", "_____no_output_____" ] ], [ [ "### export html", "_____no_output_____" ] ], [ [ "d = hvplot.save(g,'out.html')\ndel d", "_____no_output_____" ] ], [ [ "### export png", "_____no_output_____" ] ], [ [ "%%time\nfor i, t in enumerate( dssp['t'].values ):\n gp = g[t].options(title=str(np.round(t,3)) + ' sec', toolbar=None)\n d = hvplot.save(gp,'png'+str(i).zfill(8) +'.png')\ndel d", "_____no_output_____" ] ], [ [ "# make gif ", "_____no_output_____" ] ], [ [ "from PIL import Image", "_____no_output_____" ], [ "fs = glob.glob(\"*.png\")\nimgs = [Image.open(f) for f in fs]\n# imgs = imgs[0:501:2]\n# appendした画像配列をGIFにする。durationで持続時間、loopでループ数を指定可能。\nd= imgs[0].save('out.gif',\n save_all=True, append_images=imgs[1:], optimize=False, duration=0.5, loop=0)\ndel d", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
d031c398bacbff795dd513c6a7ed8ba28877b542
29,171
ipynb
Jupyter Notebook
misc/deep_learning_notes/Ch4_Recurrent_Networks/001_Optimization_Algorithms_and_Hyper-parameter_Search/Higher_Dimentional_Convolutions.ipynb
tmjnow/MoocX
52c8450ff7ecc8450a8adc2457233d5777a3d5bb
[ "MIT" ]
7
2017-06-13T05:24:15.000Z
2022-01-09T01:10:28.000Z
misc/deep_learning_notes/Ch4_Recurrent_Networks/001_Optimization_Algorithms_and_Hyper-parameter_Search/Higher_Dimentional_Convolutions.ipynb
tmjnow/MoocX
52c8450ff7ecc8450a8adc2457233d5777a3d5bb
[ "MIT" ]
11
2017-05-08T23:30:50.000Z
2017-06-24T21:57:42.000Z
misc/deep_learning_notes/Ch4_Recurrent_Networks/001_Optimization_Algorithms_and_Hyper-parameter_Search/Higher_Dimentional_Convolutions.ipynb
kinshuk4/MoocX
52c8450ff7ecc8450a8adc2457233d5777a3d5bb
[ "MIT" ]
4
2017-10-05T12:56:53.000Z
2020-06-14T17:01:32.000Z
117.625
16,018
0.856604
[ [ [ "import numpy as np\nfrom scipy import signal\n\n%matplotlib inline\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## 1D convolution", "_____no_output_____" ] ], [ [ "b = np.random.random(4)\na = np.random.random(10)\nnp.convolve(a, b)", "_____no_output_____" ], [ "def convolve(a, b):\n \n if a.shape[0] < b.shape[0]: \n a, b = b, a\n \n return np.array([\n # important to remember the [::-1]\n np.matmul(a[i:i+b.shape[0]], b[::-1]) # \\equiv dot().sum()\n for i in range(a.shape[0] - b.shape[0] + 1)\n ])\n\nplt.plot(convolve(a, b))\nplt.plot(signal.convolve(a, b, mode=\"valid\"))\nplt.show()\n# print(convolve(a, b), signal.convolve(a, b, mode=\"valid\"))", "_____no_output_____" ] ], [ [ "## 2D convolution", "_____no_output_____" ] ], [ [ "a = np.random.random((3, 6))\nb = np.random.random((2, 2))", "_____no_output_____" ], [ "# 2D convolution\ndef convolve2d(a, b):\n #a_f = a.flatten().reshape((a.size, 1))\n #b_f = b.flatten().reshape((1, b.size))\n \n return np.array(\n [\n [\n (a[i:i+b.shape[0], j:j+b.shape[1]]* b[::-1,::-1]).sum()\n for j in range(a.shape[1] - b.shape[1] + 1)\n ]\n for i in range(a.shape[0] - b.shape[0] + 1)\n ])\n\nprint(convolve2d(a,b) - signal.convolve2d(a,b,mode='valid'))\nplt.figure(figsize=(12,5))\nplt.subplot(131)\nplt.imshow(a, interpolation=\"none\")\nplt.subplot(132)\nplt.imshow(convolve2d(a, b), interpolation=\"none\")\nplt.subplot(133)\nplt.imshow(convolve2d(a, b)-signal.convolve2d(a, b, mode='valid'), interpolation=\"none\")\nplt.show()", "[[ 0.00000000e+00 1.11022302e-16 0.00000000e+00 0.00000000e+00\n 0.00000000e+00]\n [ 0.00000000e+00 0.00000000e+00 0.00000000e+00 2.22044605e-16\n 2.22044605e-16]]\n" ] ], [ [ "results in the difference are from floating point imprecision. ", "_____no_output_____" ], [ "## 3D convolution (for video applications)", "_____no_output_____" ] ], [ [ "a = np.random.random((3, 6, 4))\nb = np.random.random((2, 2, 3))", "_____no_output_____" ], [ "# 2D convolution\ndef convolve3d(a, b):\n #a_f = a.flatten().reshape((a.size, 1))\n #b_f = b.flatten().reshape((1, b.size))\n \n return np.array(\n [\n [\n [\n (a[i:i+b.shape[0], j:j+b.shape[1], k:k+b.shape[2]]* b[::-1, ::-1, ::-1]).sum()\n for k in range(a.shape[2] - b.shape[2] + 1)\n ]\n for j in range(a.shape[1] - b.shape[1] + 1)\n ]\n for i in range(a.shape[0] - b.shape[0] + 1)\n ])", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
d031d48e36fe250914019f1441045d8483751631
10,980
ipynb
Jupyter Notebook
notebooks/ROI/03_ClimateChange/S5_SLR_ENSO/01_12_Climate_Emulator.ipynb
teslakit/teslak
3f3dda08c5c5998cb2a7debbf22f2be675a4ff8b
[ "MIT" ]
12
2019-11-14T22:19:12.000Z
2022-03-04T01:25:33.000Z
notebooks/ROI/03_ClimateChange/S5_SLR_ENSO/01_12_Climate_Emulator.ipynb
anderdyl/teslaCoSMoS
1495bfa2364ddbacb802d145b456a35213abfb7c
[ "MIT" ]
5
2020-03-24T18:21:41.000Z
2021-08-23T20:39:43.000Z
notebooks/ROI/03_ClimateChange/S5_SLR_ENSO/01_12_Climate_Emulator.ipynb
anderdyl/teslaCoSMoS
1495bfa2364ddbacb802d145b456a35213abfb7c
[ "MIT" ]
2
2021-03-06T07:54:41.000Z
2021-06-30T14:33:22.000Z
26.845966
139
0.494353
[ [ [ "\n... ***CURRENTLY UNDER DEVELOPMENT*** ...\n", "_____no_output_____" ], [ "## Obtain synthetic waves and water level timeseries under a climate change scenario (future AWTs occurrence probability)\n\ninputs required: \n * Historical DWTs (for plotting)\n * Historical wave families (for plotting)\n * Synthetic DWTs climate change\n * Historical intradaily hydrograph parameters \n * TCs waves\n * Fitted multivariate extreme model for the waves associated to each DWT\n\n \nin this notebook:\n * Generate synthetic time series of wave conditions \n \n", "_____no_output_____" ] ], [ [ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# common\nimport os\nimport os.path as op\n\n# pip\nimport numpy as np\nimport xarray as xr\nimport pandas as pd\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\n# DEV: override installed teslakit\nimport sys\nsys.path.insert(0, op.join(os.path.abspath(''), '..', '..','..', '..'))\n\n# teslakit\nfrom teslakit.database import Database\nfrom teslakit.climate_emulator import Climate_Emulator\nfrom teslakit.waves import AWL, Aggregate_WavesFamilies\n\nfrom teslakit.plotting.outputs import Plot_FitSim_Histograms\nfrom teslakit.plotting.extremes import Plot_FitSim_AnnualMax, Plot_FitSim_GevFit, Plot_Fit_QQ\n\nfrom teslakit.plotting.waves import Plot_Waves_Histogram_FitSim\n", "_____no_output_____" ] ], [ [ "\n## Database and Site parameters", "_____no_output_____" ] ], [ [ "# --------------------------------------\n# Teslakit database\n\np_data = r'/Users/anacrueda/Documents/Proyectos/TESLA/data'\n\n# offshore\ndb = Database(p_data)\ndb.SetSite('ROI')\n\n# climate change - S5\ndb_S5 = Database(p_data)\ndb_S5.SetSite('ROI_CC_S5')\n\n\n# climate emulator simulation modified path\np_S5_CE_sims = op.join(db_S5.paths.site.EXTREMES.climate_emulator, 'Simulations')\n", "_____no_output_____" ], [ "# --------------------------------------\n# Load data for climate emulator simulation climate change: ESTELA DWT and TCs (MU, TAU) \n\nDWTs_sim = db_S5.Load_ESTELA_DWT_sim() # DWTs climate change\n\nTCs_params = db.Load_TCs_r2_sim_params() # TCs parameters (copula generated) \nTCs_RBFs = db.Load_TCs_sim_r2_rbf_output() # TCs numerical_IH-RBFs_interpolation output\n\nprobs_TCs = db.Load_TCs_probs_synth() # TCs synthetic probabilities\npchange_TCs = probs_TCs['category_change_cumsum'].values[:]\n\nl_mutau_wt = db.Load_MU_TAU_hydrograms() # MU - TAU intradaily hidrographs for each DWT\nMU_WT = np.array([x.MU.values[:] for x in l_mutau_wt]) # MU and TAU numpy arrays\nTAU_WT = np.array([x.TAU.values[:] for x in l_mutau_wt])\n\n", "_____no_output_____" ], [ "# solve first 10 DWTs simulations\n\nDWTs_sim = DWTs_sim.isel(n_sim=slice(0, 10))\n#DWTs_sim = DWTs_sim.isel(time=slice(0,365*40+10), n_sim=slice(0,1))\n\nprint(DWTs_sim)\n", "<xarray.Dataset>\nDimensions: (n_sim: 10, time: 365244)\nCoordinates:\n * time (time) object 2000-01-01 00:00:00 ... 3000-01-01 00:00:00\nDimensions without coordinates: n_sim\nData variables:\n evbmus_sims (time, n_sim) float32 ...\nAttributes:\n source: teslakit_v0.9.1\n" ] ], [ [ "\n## Climate Emulator - Simulation", "_____no_output_____" ] ], [ [ "# --------------------------------------\n# Climate Emulator extremes model fitting\n\n# Load Climate Emulator\nCE = Climate_Emulator(db.paths.site.EXTREMES.climate_emulator)\nCE.Load()\n\n# set a new path for S5 simulations\nCE.Set_Simulation_Folder(p_S5_CE_sims, copy_WAVES_noTCs = False) # climate change waves (no TCs) not simulated, DWTs have changed\n\n\n \n# optional: list variables to override distribution to empirical\n#CE.sim_icdf_empirical_override = ['sea_Hs_31',\n# 'swell_1_Hs_1','swell_1_Tp_1',\n# 'swell_1_Hs_2','swell_1_Tp_2',]\n\n# set simulated waves min-max filter\nCE.sim_waves_filter.update({\n 'hs': (0, 8),\n 'tp': (2, 25),\n 'ws': (0, 0.06),\n})\n", "_____no_output_____" ], [ "# --------------------------------------\n#  Climate Emulator simulation\n\n# each DWT series will generate a different set of waves\nfor n in DWTs_sim.n_sim:\n print('- Sim: {0} -'.format(int(n)+1))\n \n # Select DWTs simulation\n DWTs = DWTs_sim.sel(n_sim=n)\n\n # Simulate waves\n n_ce = 1 # (one CE sim. for each DWT sim.)\n WVS_sim = CE.Simulate_Waves(DWTs, n_ce, filters={'hs':True, 'tp':True, 'ws':True})\n\n # Simulate TCs and update simulated waves\n TCs_sim, WVS_upd = CE.Simulate_TCs(DWTs, WVS_sim, TCs_params, TCs_RBFs, pchange_TCs, MU_WT, TAU_WT)\n \n # store simulation data\n CE.SaveSim(WVS_sim, TCs_sim, WVS_upd, int(n))\n \n ", "- Sim: 1 -\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d031d5e9617d10a642344ada83ed455558bcbf3b
26,016
ipynb
Jupyter Notebook
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
92939a83803b464208f15f785d4e093aaa795e0b
[ "MIT" ]
null
null
null
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
92939a83803b464208f15f785d4e093aaa795e0b
[ "MIT" ]
null
null
null
Day_00/02_Strings_and_FileIO/00 Strings in Python.ipynb
saudijack/unfpyboot
92939a83803b464208f15f785d4e093aaa795e0b
[ "MIT" ]
null
null
null
19.157585
327
0.518796
[ [ [ "# Strings in Python", "_____no_output_____" ], [ "## What is a string?", "_____no_output_____" ], [ "A \"string\" is a series of characters of arbitrary length.\nStrings are immutable - they cannot be changed once created. When you modify a string, you automatically make a copy and modify the copy.", "_____no_output_____" ] ], [ [ "s1 = 'Godzilla'\nprint s1, s1.upper(), s1", "_____no_output_____" ] ], [ [ "## String literals", "_____no_output_____" ], [ "A \"literal\" is essentially a string constant, already spelled out for you. Python uses either on output, but that's just for formatting simplicity.", "_____no_output_____" ] ], [ [ "\"Godzilla\"", "_____no_output_____" ] ], [ [ "### Single and double quotes", "_____no_output_____" ], [ "Generally, a string literal can be in single ('), double (\"), or triple (''') quotes. Single and double quotes are equivalent - use whichever you prefer (but be consistent). If you need to have a single or double quote in your literal, surround your literal with the other type, or use the backslash to escape the quote.", "_____no_output_____" ] ], [ [ "\"Godzilla's a kaiju.\"", "_____no_output_____" ], [ "'Godzilla\\'s a kaiju.'", "_____no_output_____" ], [ "'We call him... \"Godzilla\".'", "_____no_output_____" ] ], [ [ "### Triple quotes (''')", "_____no_output_____" ], [ "Triple quotes are a special form of quoting used for documenting your Python files (docstrings). We won't discuss that type here.", "_____no_output_____" ], [ "### Raw strings", "_____no_output_____" ], [ "Raw strings don't use any escape character interpretation. Use them when you have a complicated string that you don't want to clutter with lots of backslashes. Python puts them in for you.", "_____no_output_____" ] ], [ [ "print('This is a\\ncomplicated string with newline escapes in it.')", "_____no_output_____" ], [ "print(r'This is a\\ncomplicated string with newline escapes in it.')", "_____no_output_____" ] ], [ [ "## Strings and numbers", "_____no_output_____" ] ], [ [ "x=int('122', 3)\nx+1", "_____no_output_____" ] ], [ [ "### String objects", "_____no_output_____" ], [ "String objects are just the string variables you create in Python.", "_____no_output_____" ] ], [ [ "kaiju = 'Godzilla'\nprint(kaiju)", "_____no_output_____" ], [ "kaiju", "_____no_output_____" ] ], [ [ "Note the print() call shows no quotes, while the simple variable name did. That is a Python output convention. Just entering the name will call the repr() method, which displays the value of the argument as Python would see it when it reads it in, not as the user wants it.", "_____no_output_____" ] ], [ [ "repr(kaiju)", "_____no_output_____" ], [ "print(repr(kaiju))", "_____no_output_____" ] ], [ [ "### String operators", "_____no_output_____" ], [ "When you read text from a file, it's just that - text. No matter what the data represents, it's still text. To use it as a number, you have to explicitly convert it to a number.", "_____no_output_____" ] ], [ [ "one = 1\ntwo = '2'\nprint one, two, one + two", "_____no_output_____" ], [ "one = 1\ntwo = int('2')\nprint one, two, one + two", "_____no_output_____" ], [ "num1 = 1.1\nnum2 = float('2.2')\nprint num1, num2, num1 + num2", "_____no_output_____" ] ], [ [ "You can also do this with hexadecimal and octal numbers, or any other base, for that matter.", "_____no_output_____" ] ], [ [ "print int('FF', 16)\nprint int('0xff', 16)\nprint int('777', 8)\nprint int('0777', 8)\nprint int('222', 7)\nprint int('110111001', 2)", "_____no_output_____" ] ], [ [ "If the conversion cannot be done, an exception is thrown.", "_____no_output_____" ] ], [ [ "print int('0xGG', 16)", "_____no_output_____" ] ], [ [ "#### Concatenation", "_____no_output_____" ] ], [ [ "kaiju1 = 'Godzilla'\nkaiju2 = 'Mothra'\nkaiju1 + ' versus ' + kaiju2", "_____no_output_____" ] ], [ [ "#### Repetition", "_____no_output_____" ] ], [ [ "'Run away! ' * 3", "_____no_output_____" ] ], [ [ "### String keywords", "_____no_output_____" ], [ "#### in()", "_____no_output_____" ], [ "NOTE: This _particular_ statement is false regardless of how the statement is evaluated! :^)", "_____no_output_____" ] ], [ [ "'Godzilla' in 'Godzilla vs Gamera'", "_____no_output_____" ] ], [ [ "### String functions", "_____no_output_____" ], [ "#### len()", "_____no_output_____" ] ], [ [ "len(kaiju)", "_____no_output_____" ] ], [ [ "### String methods", "_____no_output_____" ], [ "Remember - methods are functions attached to objects, accessed via the 'dot' notation.", "_____no_output_____" ], [ "#### Basic formatting and manipulation", "_____no_output_____" ], [ "##### capitalize()/lower()/upper()/swapcase()/title()", "_____no_output_____" ] ], [ [ "kaiju.capitalize()", "_____no_output_____" ], [ "kaiju.lower()", "_____no_output_____" ], [ "kaiju.upper()", "_____no_output_____" ], [ "kaiju.swapcase()", "_____no_output_____" ], [ "'godzilla, king of the monsters'.title()", "_____no_output_____" ] ], [ [ "##### center()/ljust()/rjust()", "_____no_output_____" ] ], [ [ "kaiju.center(20, '*')", "_____no_output_____" ], [ "kaiju.ljust(20, '*')", "_____no_output_____" ], [ "kaiju.rjust(20, '*')", "_____no_output_____" ] ], [ [ "##### expandtabs()", "_____no_output_____" ] ], [ [ "tabbed_kaiju = '\\tGodzilla'\nprint('[' + tabbed_kaiju + ']')", "_____no_output_____" ], [ "print('[' + tabbed_kaiju.expandtabs(16) + ']')", "_____no_output_____" ] ], [ [ "##### join()", "_____no_output_____" ] ], [ [ "' vs '.join(['Godzilla', 'Hedorah'])", "_____no_output_____" ], [ "','.join(['Godzilla', 'Mothra', 'King Ghidorah'])", "_____no_output_____" ] ], [ [ "##### strip()/lstrip()/rstrip()", "_____no_output_____" ] ], [ [ "' Godzilla '.strip()", "_____no_output_____" ], [ "'xxxGodzillayyy'.strip('xy')", "_____no_output_____" ], [ "' Godzilla '.lstrip()", "_____no_output_____" ], [ "' Godzilla '.rstrip()", "_____no_output_____" ] ], [ [ "##### partition()/rpartition()", "_____no_output_____" ] ], [ [ "battle = 'Godzilla x Gigan'\nbattle.partition(' x ')", "_____no_output_____" ], [ "battle = 'Godzilla and Jet Jaguar vs. Gigan and Megalon'\nbattle.partition(' vs. ')", "_____no_output_____" ], [ "battle = 'Godzilla vs Megalon vs Jet Jaguar'\nbattle.partition('vs')", "_____no_output_____" ], [ "battle = 'Godzilla vs Megalon vs Jet Jaguar'\nbattle.rpartition('vs')", "_____no_output_____" ] ], [ [ "##### replace()", "_____no_output_____" ] ], [ [ "battle = 'Godzilla vs Mothra'\nbattle.replace('Mothra', 'Anguiras')", "_____no_output_____" ], [ "battle = 'Godzilla vs a monster and another monster'\nbattle.replace('monster', 'kaiju', 2)", "_____no_output_____" ], [ "battle = 'Godzilla vs a monster and another monster and yet another monster'\nbattle.replace('monster', 'kaiju', 2)", "_____no_output_____" ] ], [ [ "##### split()/rsplit()", "_____no_output_____" ] ], [ [ "battle = 'Godzilla vs King Ghidorah vs Mothra'\nbattle.split(' vs ')", "_____no_output_____" ], [ "kaijus = 'Godzilla,Mothra,King Ghidorah'\nkaijus.split(',')", "_____no_output_____" ], [ "kaijus = 'Godzilla Mothra King Ghidorah'\nkaijus.split()", "_____no_output_____" ], [ "kaijus = 'Godzilla,Mothra,King Ghidorah,Megalon'\nkaijus.rsplit(',', 2)", "_____no_output_____" ] ], [ [ "##### splitlines()", "_____no_output_____" ] ], [ [ "kaijus_in_lines = 'Godzilla\\nMothra\\nKing Ghidorah\\nEbirah'\nprint(kaijus_in_lines)", "_____no_output_____" ], [ "kaijus_in_lines.splitlines()", "_____no_output_____" ], [ "kaijus_in_lines.splitlines(True)", "_____no_output_____" ] ], [ [ "##### zfill()", "_____no_output_____" ] ], [ [ "age_of_Godzilla = 60\nage_string = str(age_of_Godzilla)\nprint(age_string, age_string.zfill(5))", "_____no_output_____" ] ], [ [ "#### String information", "_____no_output_____" ], [ "##### isXXX()", "_____no_output_____" ] ], [ [ "print('Godzilla'.isalnum())\nprint('*Godzilla*'.isalnum())\nprint('Godzilla123'.isalnum())", "_____no_output_____" ], [ "print('Godzilla'.isalpha())\nprint('Godzilla123'.isalpha())", "_____no_output_____" ], [ "print('Godzilla'.isdigit())\nprint('60'.isdigit())", "_____no_output_____" ], [ "print('SpaceGodzilla'.isspace())\nprint(' '.isspace())", "_____no_output_____" ], [ "print('Godzilla'.islower())\nprint('godzilla'.islower())", "_____no_output_____" ], [ "print('Godzilla'.isupper())\nprint('GODZILLA'.isupper())", "_____no_output_____" ], [ "print('Godzilla vs Mothra'.istitle())\nprint('Godzilla X Mothra'.istitle())", "_____no_output_____" ] ], [ [ "##### count()", "_____no_output_____" ] ], [ [ "monsters = 'Godzilla and Space Godzilla and MechaGodzilla'\nprint 'There are ', monsters.count('Godzilla'), ' Godzillas.'\nprint 'There are ', monsters.count('Godzilla', len('Godzilla')), ' pseudo-Godzillas.'", "_____no_output_____" ] ], [ [ "##### startswith()/endswith()", "_____no_output_____" ] ], [ [ "king_kaiju = 'Godzilla'\nprint king_kaiju.startswith('God')\nprint king_kaiju.endswith('lla')\nprint king_kaiju.startswith('G')\nprint king_kaiju.endswith('amera')", "_____no_output_____" ] ], [ [ "##### find()/index()/rfind()/rindex()", "_____no_output_____" ] ], [ [ "kaiju_string = 'Godzilla,Gamera,Gorgo,Space Godzilla'\nprint 'The first Godz is at position', kaiju_string.find('Godz')\nprint 'The second Godz is at position', kaiju_string.find('Godz', len('Godz'))", "_____no_output_____" ], [ "kaiju_string.index('Minilla')", "_____no_output_____" ], [ "kaiju_string.rindex('Godzilla')", "_____no_output_____" ] ], [ [ "#### Advanced features", "_____no_output_____" ], [ "##### decode()/encode()/translate()", "_____no_output_____" ], [ "Used to convert strings to/from Unicode and other systems. Rarely used in science code.", "_____no_output_____" ], [ "##### String formatting", "_____no_output_____" ], [ "Similar to formatting in C, FORTRAN, etc.. There is a _lot_ more to this than I am showing here.", "_____no_output_____" ] ], [ [ "kaiju = 'Godzilla'\nage = 60\nprint '%s is %d years old.' % (kaiju, age)", "_____no_output_____" ] ], [ [ "## The _string_ module", "_____no_output_____" ], [ "The _string_ module is the Python equivalent of \"junk DNA\" in living organisms. It's been around since the beginning, but many of its functions have been superseded by evolution. But some ancient code still relies on it, so they leave the old parts in....\n\nFor modern code, the _string_ module does have some useful constants and functions.", "_____no_output_____" ] ], [ [ "import string", "_____no_output_____" ], [ "print string.ascii_letters\nprint string.ascii_lowercase\nprint string.ascii_uppercase", "_____no_output_____" ], [ "print string.digits\nprint string.hexdigits\nprint string.octdigits", "_____no_output_____" ], [ "print string.letters\nprint string.lowercase\nprint string.uppercase", "_____no_output_____" ], [ "print string.printable\nprint string.punctuation\nprint string.whitespace", "_____no_output_____" ] ], [ [ "The _string_ module also provides the _Formatter_ class, which can be useful for sophisticated text formatting.", "_____no_output_____" ], [ "## Regular Expressions", "_____no_output_____" ], [ "### What is a regular expression?", "_____no_output_____" ], [ "Regular expressions ('regexps') are essentially a mini-language for describing string operations. Everything shown above with string methods and operators can be done with regular expressions. Most of the time, the regular expression verrsion is more concise. But not always more readable....\n\nTo use regular expressions, you have to import the 're' module.", "_____no_output_____" ] ], [ [ "import re", "_____no_output_____" ] ], [ [ "### A very short, whirlwind tour of regular expressions", "_____no_output_____" ], [ "#### Scanning", "_____no_output_____" ] ], [ [ "kaiju_truth = 'Godzilla is the King of the Monsters. Ebirah is also a monster, but looks like a giant lobster.'\nre.findall('Godz', kaiju_truth)", "_____no_output_____" ], [ "print re.findall('(^.+) is the King', kaiju_truth)", "_____no_output_____" ] ], [ [ "For simple searches like this, using in() is typically easier.\nRegexps are by default case-sensitive.", "_____no_output_____" ] ], [ [ "print re.findall('\\. (.+) is also', kaiju_truth)", "_____no_output_____" ], [ "print re.findall('(.+) is also a (.+)', kaiju_truth)[0]\nprint re.findall('\\. (.+) is also a (.+),', kaiju_truth)[0]", "_____no_output_____" ] ], [ [ "#### Changing", "_____no_output_____" ] ], [ [ "some_kaiju = 'Godzilla, Space Godzilla, Mechagodzilla'\nprint re.sub('Godzilla', 'Gamera', some_kaiju)\nprint re.sub('(?i)Godzilla', 'Gamera', some_kaiju)", "_____no_output_____" ] ], [ [ "#### And so much more...", "_____no_output_____" ], [ "You could spend a whole day (or more) just learning about regular expressions. But they are incredibly useful and powerful, especially in the all-to-frequent drudgery of munging files from one format to another.\n\nRegular expressions can be internally compiled for speed.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d031d86cedb54e1f04702001b24f871558d216df
18,925
ipynb
Jupyter Notebook
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
fa34efcaeffbb7289ca986eafd9c1fad0439c3fb
[ "MIT" ]
null
null
null
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
fa34efcaeffbb7289ca986eafd9c1fad0439c3fb
[ "MIT" ]
null
null
null
DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/11_Intel_Distribution_for_GDB/gdb_oneapi.ipynb
krisrak/oneAPI-samples
fa34efcaeffbb7289ca986eafd9c1fad0439c3fb
[ "MIT" ]
null
null
null
44.320843
496
0.609141
[ [ [ "# Intel® Distribution for GDB*", "_____no_output_____" ], [ "In this notebook, we will cover using the Intel® Distribution for GDB* to debug oneAPI applications on the GPU.\n\n##### Sections\n- [Intel Distribution for GDB Overview](#Intel-Distribution-for-GDB-Overview)\n- [How does the Intel Distribution for GDB debug GPUs?](#How-does-Intel-Distribution-for-GDB-debug-GPUs?)\n- [GDB Commands](#GDB-Commands)\n- [Debug an Application](#Debug-an-Application)\n- [Multi-Device Debugging](#Multi-Device-Debugging)\n\nNote: Unlike other modules in the oneAPI Essentials series, this notebook is designed for the DevCloud and cannot be run in a local environment. This is because when GDB pauses the GPU execution, display rendering is also interrupted.", "_____no_output_____" ], [ "## Learning Objectives\nThe goal of this notebook is to show how the Intel® Distribution for GDB* can help you debug GPU kernels. At the end of module, you will be able to:\n<ul>\n <li>Run the Intel Distribution for GDB.</li>\n <li>Understand inferiors, threads, and SIMD lanes as shown in GDB.</li>\n <li>Use different methods to examine local variables for different threads and lanes.</li>\n</ul>", "_____no_output_____" ], [ "## Intel Distribution for GDB Overview\n\nIntel® Distribution for GDB* (*gdb-oneapi* executable) is part of the Intel® oneAPI Base Toolkit. It can be used to debug oneAPI applications written in several different languages targeting various different accelerator devices.\n\n<img src=\"assets/gdb_overview.jpg\">\n\n### Major Features\n* Multi-target: The debugger can orchestrate multiple targets for different architectures. This feature allows you to debug the \"host\" portion and the \"kernel\" of a DPC++ program in the same GDB* session.\n* Auto-attach: The debugger automatically creates an inferior that attaches itself to the Intel® Graphics Technology target to be able to receive events and control the GPU for debugging.\n* Thread and SIMD lanes: The debugger displays SIMD lane information for the GPU threads on the command line interface. You can switch among active threads and lanes.\n* Support for debugging a kernel offloaded to a CPU, GPU, or FPGA-emulation device.\n\n\n## How does the Intel Distribution for GDB debug GPUs?\n\n\n### Compilation and Execution for Debug\nWhen debugging oneAPI applications with gdb-oneapi, debug information for the GPU needs to be generated and embedded in the application. The compilation and execution process looks like the following.\n\n<img src=\"assets/gpu_debug.jpg\">\n\n1. Source code is compiled. Host code is compiled normally while kernel code is compiled with debug info into SPIR-V intermediate representation format embedded in the host binary.\n * Use -g (generate debug info) and -O0 (disable optimization) compiler options to debug source.\n * May use -O2 to debug optimized code at assembly level.\n * Use same optimization level when linking, if compiling and linking separately.\n * Ahead-of-time (AOT) compilation also works with GPU debug and can be utilize to avoid JIT compilation everytime application is run.\n2. Launch appliction with `gdb-oneapi`\n * `gdb-oneapi <your_app>`\n3. Application runtime compiles SPIR-V and debug info into ELF and DWARF formats.\n4. GPU kernel code is executed and debugged.\n\n### Inferiors for GPUs\n\nGDB creates objects called *inferior*s to represent the state of each program execution. An inferior usually corresponds to a debugee process. For oneAPI applications, GDB will create one inferior for the native host target and additional inferiors for each GPU or GPU tile. When a GPU application is debugged, the debugger, by default, automatically launches a `gdbserver-gt` process to listen to GPU debug events. The `gdbserver-gt` target is then added to the debugger as an inferior.\n\n<img src=\"assets/gdb_gpu_inferior.jpg\">\n\nTo see information about the inferiors while debugging. Use the `info inferiors` GDB command.\n\n### Debugging Threaded GPU SIMD Code\n\nGPU kernel code is written for a single work-item. When executing, the code is implicitly threaded and widened to vectors of work-items. In the Intel Distribution for GDB, variable locations are expressed as functions of the SIMD lane. The lane field is added to the thread representation in the form of `<inferior>.<thread>:<lane>`.\n\nUsers can use the `info threads` command to see information about the various active threads. The `thread` command can be used to switching among active threads and SIMD lanes. The `thread apply <thread>:<lane> <cmd>` command can be used to apply the specified command to the specified lanes.\n\nSIMD Lanes Support:\n\n * Only enabled SIMD lanes are displayed\n * SIMD width is not fixed\n * User can switch between enabled SIMD lanes\n * After a stop, GDB switches to an enabled SIMD lane", "_____no_output_____" ], [ "## GDB Commands\n\nThe following table lists some common GDB commands. If a command has special functionality for GPU debugging, description will be shown in orange. You may also consult the [Intel Distribution for GDB Reference Sheet](https://software.intel.com/content/www/us/en/develop/download/gdb-reference-sheet.html).\n\n| Command | Description |\n| ---: | :--- |\n| help \\<cmd> | Print help information. |\n| run [arg1, ... argN] | Start the program, optionally with arguments. |\n| break \\<file>:\\<line> | Define a breakpoint at a specified line. |\n| info break | Show defined breakpoints. |\n| delete \\<N> | Remove Nth breakpoint. |\n| step / next | Single-step a source line, stepping into / over function calls. |\n| info args/locals | Show the arguments/local variables of the current function. |\n| print \\<exp> | Print value of expression. |\n| x/\\<format> \\<addr> | Examine the memory at \\<addr>. |\n| up, down | Go one level up/down the function call stack |\n| disassemble | Disassemble the current function. <font color='orange'> If inside a GPU kernel, GPU instructions will be shown. </font> |\n| backtrace | Shown the function call stack. |\n| info inferiors | Display information about the inferiors. <font color='orange'> GPU debugging will display additional inferior(s) (gdbserver-gt). </font> |\n| info threads \\<thread> | Display information about threads, including their <font color='orange'> active SIMD lanes. </font> |\n| thread \\<thread>:\\<lane> | Switch context to the <font color='orange'> SIMD lane of the specified thread. <font> |\n| thread apply \\<thread>:\\<lane> \\<cmd> | Apply \\<cmd> to specified lane of the thread. |\n| set scheduler-locking on/step/off | Lock the thread scheduler. Keep other threads stopped while current thread is stepping (step) or resumed (on) to avoid interference. Default (off). |\n| set nonstop on/off | Enable/disable nonstop mode. Set before program starts. <br> (off) : When a thread stops, all other threads stop. Default. <br> (on) : When a thread stops, other threads keep running. |\n| print/t $emask | Inspect the execution mask to show active SIMD lanes. | ", "_____no_output_____" ], [ "## Debug an Application\nThe kernel we're going to debug is a simple array transform function where the kernel adds 100 to even elements of the array and sets the odd elements to be -1. Below is the kernel code, the entire source code is [here](src/array-transform.cpp).\n``` cpp\n54 h.parallel_for(data_range, [=](id<1> index) {\n55 size_t id0 = GetDim(index, 0);\n56 int element = in[index]; // breakpoint-here\n57 int result = element + 50;\n58 if (id0 % 2 == 0) {\n59 result = result + 50; // then-branch\n60 } else {\n61 result = -1; // else-branch\n62 }\n63 out[index] = result;\n64 });\n```\n\n### Compile the Code\nExecute the following cell to compile the code. Notice the compiler options used to disable optimization and enable debug information.", "_____no_output_____" ] ], [ [ "! dpcpp -O0 -g src/array-transform.cpp -o bin/array-transform", "_____no_output_____" ] ], [ [ "### Create a debug script\nTo debug on the GPU, we're going to write the GDB debug commands to a file and then submit the execution of the debugger to a node with GPUs.\n\nIn our first script, we'll get take a look at how inferiors, threads, and SIMD lanes are represented. Our debug script will perform the following tasks. \n1. Set a temporary breakpoint in the DPCPP kernel at line 59.\n2. Run the application in the debugger.\n3. Display information about the active inferiors once the breakpoint is encountered.\n4. Display information about the active threads and SIMD lanes.\n5. Display the execution mask showing which SIMD lanes are active.\n6. Remove breakpoint.\n7. Continue running.\n\nExecute the following cell to write the debug commands to file.", "_____no_output_____" ] ], [ [ "%%writefile lab/array-transform.gdb\n#Set Breakpoint in the Kernel\necho ================= (1) tbreak 59 ===============\\n\ntbreak 59\n\n# Run the application on the GPU\necho ================= (2) run gpu ===============\\n\nrun gpu\n\necho ================= (3) info inferiors ============\\n\ninfo inferiors\n\necho ================= (4) info threads ============\\n\ninfo threads\n\n# Show execution mask that show active SIMD lanes.\necho ================= (5) print/t $emask ============\\n\nprint/t $emask\n\necho ================= (6) c ==========================\\n\nc ", "_____no_output_____" ] ], [ [ "### Start the Debugger\nThe [run_debug.sh](run_debug.sh) script runs the *gdb-oneapi* executable with our debug script on the compiled application.\n\nExecute the following cell to submit the debug job to a node with a GPU.", "_____no_output_____" ] ], [ [ "! chmod 755 q; chmod 755 run_debug.sh; if [ -x \"$(command -v qsub)\" ]; then ./q run_debug.sh; else ./run_debug.sh; fi", "_____no_output_____" ] ], [ [ "#### Explanation of Output\n1. You should see breakpoint 1 created at line 59.\n2. Application is run with the *gpu* argument to execute on the GPU device. Program should stop at the kernel breakpoint.\n3. With context now automatically switched to the device. The *info inferiors* command will show the active GDB inferior(s). Here, you should see two, one corresponds to the host portion, another, the active one, for gdbserver-gt which is debugging the GPU kernel. \n4. The *info threads* command allows you to examine the active threads and SIMD lanes. There should be 8 threads active. Notice that only even SIMD lanes are active, this is because only the even work-items encounter the breakpoint at line 59.\n5. Printing the $emask execution mask also shows the even lanes being active.\n6. Continue running the program.", "_____no_output_____" ], [ "## Debug the Application Again\n\nNow, we will debug the application again. This time, we'll switch threads, use the scheduler-locking feature, and print local variables.\nRun the following cell to write new GDB commands to array-transform.gdb.", "_____no_output_____" ] ], [ [ "%%writefile lab/array-transform.gdb\n#Set Breakpoint in the Kernel\necho ================= (1) break 59 ===============\\n\nbreak 59\necho ================= (2) break 61 ===============\\n\nbreak 61\n\n# Run the application on the GPU\necho ================= (3) run gpu ===============\\n\nrun gpu\n\n# Keep other threads stopped while current thread is stepped\necho ================= (4) set scheduler-locking step ===============\\n\nset scheduler-locking step \n\necho ================= (5) next ===============\\n\nnext \n\necho ================= (6) info threads 2.* ===============\\n\ninfo threads 2.*\n\necho ================= (7) Print element ============\\n\nprint element\n\n# Switch thread\necho ================= (8) thread 2.1:5 =======================\\n\nthread 2.1:4\n\necho ================= (9) Print element ============\\n\nprint element\n\necho ================= (10) thread apply 2.1:* print element =======================\\n\nthread apply 2.1:* print element\n\n# Inspect vector of a local variable, 8 elements, integer word\necho ================= (11) x/8dw &result =======================\\n\nx /8dw &result\n\necho ================= (12) d 1 =======================\\n\nd 1\necho ================= (13) d 2 =======================\\n\nd 2\necho ================= (14) c ==========================\\n\nc ", "_____no_output_____" ] ], [ [ "### Start Debugger Again To Examine Variables, Memories\nRun the following cell to run the debugger for the second time.", "_____no_output_____" ] ], [ [ "! chmod 755 q; chmod 755 run_debug.sh; if [ -x \"$(command -v qsub)\" ]; then ./q run_debug.sh; else ./run_debug.sh; fi", "_____no_output_____" ] ], [ [ "### Explanation of Output\n1. Set Breakpoint at line 59 for the even lanes.\n2. Set Breakpoint at line 61 for the odd lanes.\n3. Start the application, it will stop at breakpoint 2. At this point all the threads should be stopped and active for the odd SIMD lanes.\n4. Set schedule-locking so that when the current thread is stepped all other threads remain stopped.\n5. Step the current thread (thread 2.1), breakpoint at line 59 is encountered only for current thread.\n6. Show the threads and where each thread is stopped. Notice the current thread is stopped and active at the even SIMD lanes.\n7. Print local variable element.\n8. Switch to a different lane.\n9. Print local variable element again, this time you should see a different value.\n10. Use thread apply to print element for all lanes of the 2.1 thread.\n11. Print vectorized result.\n12. Delete breakpoint.\n13. Delete breakpoint.\n14. Run until the end.", "_____no_output_____" ], [ "## Multi-Device Debugging\n\nThe Intel Distribution for GDB can debug applications that offload a kernel to multiple GPU devices. Each GPU device appear as a separate inferior within the debugger. Users can switch to the context of a thread that corresponds to a particular GPU or CPU using the `inferior <id>` command. Threads of the GPUs can be independently resumed and the thread state can be individually examined.", "_____no_output_____" ], [ "## References\n* [Intel Distribution for GDB Landing Page](https://software.intel.com/content/www/us/en/develop/tools/oneapi/components/distribution-for-gdb.html)\n* [Intel Distribution for GDB Release Notes](https://software.intel.com/content/www/us/en/develop/articles/gdb-release-notes.html)\n* [Intel Distribution for GDB Reference Sheet](https://software.intel.com/content/www/us/en/develop/download/gdb-reference-sheet.html)", "_____no_output_____" ], [ "## Summary\n\n * Used Intel Distribution for GDB to debug a GPU application.\n * Used various-GPU related GDB commands.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
d0320045bb4a121ff1974a794d7f843a96f13dbb
99,941
ipynb
Jupyter Notebook
AbstractR function build.ipynb
bryantchambers/AbstractR
313d0c2a9f1430e57bacc5b29b35f2d6b0e980ae
[ "MIT" ]
null
null
null
AbstractR function build.ipynb
bryantchambers/AbstractR
313d0c2a9f1430e57bacc5b29b35f2d6b0e980ae
[ "MIT" ]
null
null
null
AbstractR function build.ipynb
bryantchambers/AbstractR
313d0c2a9f1430e57bacc5b29b35f2d6b0e980ae
[ "MIT" ]
null
null
null
59.136686
652
0.47523
[ [ [ "# RefAssig V0.0", "_____no_output_____" ], [ "this is my faster simple version of the PMI and Abstract gene count scoring system.\nImprovements: \n* rapid access\n* streamlined function calls\n* clean data output\n* xml abstract data parsing", "_____no_output_____" ], [ "---\n## 1.0 Libraries and input\n\nThe work flow looks like this:\n\n1. read in a list of chemicals as a csv with a column named chemicals and all chemicals examined in this study\n2. read in a query map as a csv\n * a query map is a relationship map between all query phrases and all classifiers\n * three columns are used:\n * A general class/super class for a query\n * a direction: 'pos' or 'neg' refereing to positive or negative\n * the search phrase surrounded by quotes, e.g., ' \"dna damage\" '\n \nThe work flow will automatically construction all wanted querries between chemicals and search phrases from these list. In later steps the results can be reduced to a meaningfull level by knowing if search phrases are addative for the target or subtractive e.g., metal stresss vs chelator. Here, a high number of chelator hits and metal stress hits might indicate that although the chemical might have a significant response for metal stress it also is likely related tagentially to the overall function. Think about what queries you are supplying to ensure they are meaningful.", "_____no_output_____" ], [ "---\n# RAPID QUERY FUNCTION", "_____no_output_____" ] ], [ [ "#This function reads csv with a list of chemical names and a query map and returns a list of dataframes for all combinations of queries in the data set\n#this result can be input to two functions: ```PMI_matrix``` which will give you information about the information or strength of the search phrase relative to the total \n\nquery_result = function(chemical.list.path, query.map.path = NULL, limit_input_to = NULL, output.path) {\n\n \n\n #Libraries\n suppressMessages(library(tidyverse))\n suppressMessages(library(easyPubMed))\n suppressMessages(library(kableExtra))\n suppressMessages(library(parallel))\n\n #testingpaths\n chemical.list.path = \"input/chemical-list-LINCS-2021.07.23.csv\"\n query.map.path = \"input/query.map-build.csv\"\n #query.map.path = NULL\n limit_input_to = NULL\n\nif(!is.null(query.map.path)) { \n ######################\n #SEARCH WITH QUERY MAP\n \n #read chemical list\n chems = suppressMessages(read_csv(paste0(chemical.list.path)))\n #read query map\n q.map = suppressMessages(read_csv(paste0(query.map.path))) %>%\n mutate(phrase.q = paste0('\"',phrase,'\"'))\n \n #cutchems\n if(is.null(limit_input_to)) {chems = chems$chemicals[1:length(chems$chemicals)]} else {chems = chems$chemicals[1:limit_input_to]}\n\n #build partial search vectors\n chems.search = paste0('\"', chems,'\" AND ')\n searchterms.search = q.map$phrase.q\n\n #controlable and bindable search grid with directions\n search.combinations = expand.grid(chems.search, searchterms.search, stringsAsFactors = FALSE) %>%\n setNames(c('chemical', 'phrase.q')) %>% \n left_join(q.map, by = \"phrase.q\") %>%\n mutate(query = paste(chemical, phrase.q)) %>%\n select(SRP, direction, query)\n\n #acutal query list\n search.query = search.combinations$query %>% as.list()\n \n } else {\n ####################### \n #SEARCH WITH ONLY CHEMS\n \n #read chemical list \n chems = suppressMessages(read_csv(paste0(chemical.list.path)))\n \n #cutchems\n if(is.null(limit_input_to)) {chems = chems$chemicals[1:length(chems$chemicals)]} else {chems = chems$chemicals[1:limit_input_to]}\n\n #build partial search vectors\n chems.search = paste0('\"', chems,'\"')\n \n #actual query list\n search.query = chems.search\n }\n\n #build output object\n query.result = vector(length = 3, mode = \"list\")\n\n #query\n query.result[[1]] = mclapply(seq_along(search.query), function(x){\n \n Sys.sleep(time = 2) \n \n get_pubmed_ids(search.query[[x]], api_key = 'b3accc43abfb376d63b0c2d2f7d8f984de09') %>%\n {if(class(.) == 'try-error') 'TRY-FAILED-increase sys sleep' else\n {if(as.numeric(.$Count) > 0) fetch_pubmed_data(., retstart = 0, retmax = 100000) %>%\n articles_to_list() %>%\n lapply(., article_to_df, max_chars = 100000, getAuthors = FALSE) %>%\n do.call(rbind, .) else 'EMPTY' }}\n \n }, mc.cores = 10) %>% setNames(search.query)\n \n\n #clean out empty hits\n query.result[[1]] = query.result[[1]][query.result[[1]] != 'EMPTY']\n\n #save additional mapping information if a map was used\n if(is.null(query.map.path)) {query.result[[2]] = 'NO MAP USED'} else {query.result[[2]] = search.combinations}\n if(is.null(query.map.path)) {query.result[[3]] = 'NO MAP USED'} else {query.result[[3]] = q.map}\n\n \n #save result\n base::save(query.result, file = paste0(\"../AbstractR-projects/LINCS/output/query.result_LINCS_\", Sys.Date(),\".RData\"))\n\n \n\n return(query.result)\n\n \n}", "_____no_output_____" ] ], [ [ "---\n# ABSTRACT GENE COUNT PARSING FINAL FUNCTION\n\n[ ] update prioritization of chemical over abstract for gene parsing line 54 - change outter apply to MC and inner to lapply\n\n'''#isolate genes from all abstracts\n abstracts.genes.filtered = lapply(seq_along(abstracts), function(y)\n mclapply(1:nrow(abstracts[[y]]), function(x) abstracts[[y]][x,2] %>%\n remove.punc() %>% match.genes(mouse.rat.vec), mc.cores = 32) %>% unlist()) %>% setNames(names(abstracts))`''", "_____no_output_____" ] ], [ [ "#This function reads csv with a list of chemical names and a query map and returns a list of dataframes for all combinations of queries in the data set\n#this result can be input to two functions: ```PMI_matrix``` which will give you information about the information or strength of the search phrase relative to the total \n\nabstract_gene_counts = function(query_result_object) { \n\n #Libraries\n suppressMessages(library(tidyverse))\n library(parallel)\n\n #helper functions\n remove.punc = function(x) {\n string.1 = gsub(\"(?!\\\\.)[[:punct:]]\", \"\", x, perl=TRUE)\n string.2 = substr(string.1,1,nchar(string.1)-1) #%>% tolower()\n string.3 = str_split(string.2, \" \") %>% unlist()\n return(string.3)\n }\n\n match.genes <- function(sentence, genelist) {\n gene.matches = sentence[sentence %in% genelist]\n return(gene.matches)\n }\n\n #testingpaths\n #query_result_object = \"../AbstractR-projects/LINCS/output/query.result_LINCS_2021-07-29.RData\"\n \n #read query result\n load(paste0(query_result_object))\n\n #set up genes dictionary - improve this in the future, allow for a list of homolouges in a csv from bioMart - for now use your H-M-R set up\n #read in coding genes\n #also a data dir or lib is needed\n gene.list = suppressMessages(suppressWarnings(read_tsv(\"data/proteincodinggenesHGNC.txt\"))) %>%\n pull(symbol) %>% unique()\n \n #read in non human gene lists homolouge lists\n nh.gene.list <- suppressMessages(read_csv(\"data/genes.list_h.m.r.csv\")) %>% filter(human %in% gene.list) %>% distinct(`.keep_all` = FALSE)\n \n #comparative lists\n mouse.rat.vec = c(nh.gene.list$human, nh.gene.list$mouse, nh.gene.list$rat) %>% unique()\n\n #filter some bad gene names\n bad.genes.q = c('a')\n mouse.rat.vec = mouse.rat.vec[!mouse.rat.vec %in% bad.genes.q]\n\n #take only pmids and abstract from the query resul\n abstracts = mclapply(seq_along(query.result[[1]]), function(x) {\n query.result[[1]][[x]] %>%\n select(pmid, abstract)\n }, mc.cores = 32) %>% setNames(names(query.result[[1]]))\n\n #isolate genes from all abstracts\n abstracts.genes.filtered = mclapply(seq_along(abstracts), function(y)\n lapply(1:nrow(abstracts[[y]]), function(x) abstracts[[y]][x,2] %>%\n remove.punc() %>% match.genes(mouse.rat.vec)) %>% unlist() %>% na.omit, mc.cores = 32) %>% setNames(names(abstracts))\n\n \n\n \n #remove empty gene matches\n abstracts.genes.filtered = abstracts.genes.filtered[names(lapply(abstracts.genes.filtered, length)[lapply(abstracts.genes.filtered, length) > 0])]\n\n #count the genes for all queried chemicals with genes mentioned in abstracts\n query.result.gene.counts = mclapply(seq_along(abstracts.genes.filtered), function(x) {\n abstracts.genes.filtered[[x]] %>%\n table() %>%\n data.frame() %>%\n setNames(c('gene', 'count')) %>%\n mutate(gene = as.character(gene)) %>%\n mutate(rat = nh.gene.list$human[match(gene, nh.gene.list$rat)], mouse = nh.gene.list$human[match(gene, nh.gene.list$mouse)]) %>%\n mutate(gene = ifelse(is.na(rat), gene, rat), gene = ifelse(is.na(mouse), gene, mouse)) %>%\n select(gene, count) %>%\n group_by(gene) %>%\n summarise(count = sum(count)) %>%\n arrange(desc(count))}, mc.cores = 32) %>% setNames(names(abstracts.genes.filtered))\n\n #calulate the final counts matrixs for all fo the samples\n abstract.gene.count.matrix = query.result.gene.counts %>% reduce(full_join, by = \"gene\") %>%\n arrange(gene) %>%\n column_to_rownames('gene') %>%\n t() %>%\n as.data.frame() %>%\n replace(is.na(.), 0) %>%\n rownames_to_column('sample') %>%\n select(-sample) %>%\n mutate(chemical = names(query.result.gene.counts)) %>%\n column_to_rownames('chemical')\n\nreturn(abstract.gene.count.matrix)\n\n}", "_____no_output_____" ], [ "abstract.gene.count.matrix %>% rownames_to_column('chemicals') %>% write_csv(., path = \"output/LINCS-chemical.no.map-abstract-gene-counts-2021.09.17.csv\" )", "_____no_output_____" ], [ "save(abstract.gene.count.matrix, file = \"../AbstractR-projects/LINCS/output/gene.counts.matrix-2021.09.17-stress.only.RData\")", "_____no_output_____" ] ], [ [ "---\n# PMI calculation", "_____no_output_____" ] ], [ [ "#This function reads a ```query_object``` output by the ```query_result``` function. The result is a list of \n#parwise mututal information scores resulting from \n\nPMI_query_combinations = function(query_result_object, chemical.list.path, search.min = 0, search.max = 100000, num.cores = 1) {\n\n #Libraries\n library(tidyverse)\n library(parallel)\n library(magrittr)\n\n #testingpaths\n # query_result_object = \"input/build/pmi.testing.query.object.RData\"\n # chemical.list.path = \"input/build/pmi.testing.chem.list.csv\"\n # search.min = 5\n # search.max = 100000\n # num.cores = 15\n\n #read query result\n load(paste0(query_result_object))\n chems.data = suppressMessages(read_csv(paste0(chemical.list.path))) %>%\n mutate(q.chemical = paste0('\"',chemicals,'\"'))\n\n#take only pmids and abstract from the query result and parse by/ aggregate by SRP/query\nsearch_matrix.i = mclapply(seq_along(query.result[[1]]), function(x) { query.result[[1]][[x]] %>%\n select(pmid) %>% distinct() %>% setNames(c(\"pmid\")) %>% mutate(query = names(query.result[[1]][x]))}, mc.cores = num.cores) %>%\n do.call(rbind, .) %>%\n left_join(query.result[[2]], 'query') %>%\n mutate(search = query) %>%\n separate(col = search, into = c('q.chemical', 'search'), sep = ' AND ') %>%\n left_join(chems.data, 'q.chemical') %>%\n mutate(search = gsub('\\\\\"','', search)) %>%\n group_split(SRP)\n\n # aggregate by SRP and chemcial name to remove non-inique PMIDs and remove negative query phrases\n\nsearch_matrix = mclapply(seq_along(search_matrix.i), function(y){\n search_matrix.i[[y]] %>% ungroup() %>%\n group_by(SRP, chemicals, pmid) %>%\n summarise(dir.tot = direction %>% unique %>% sort %>% paste(collapse = \", \")) %>% #gets rid of negative querried PMIDs\n filter(!grepl(pattern = \"neg\", x = dir.tot)) %>%\n ungroup() %>%\n group_by(SRP, chemicals) %>%\n summarise(count = pmid %>% unique() %>% length) %>% #takes the unqiue PMID vector length as n unique searches\n ungroup()\n}, mc.cores = num.cores) %>%\n do.call(rbind, .) %>%\n pivot_wider(names_from = SRP, values_from = count, values_fill = 0) %>%\n filter(!is.na(chemicals)) %>%\n column_to_rownames(\"chemicals\") %>%\n mutate(rsum = rowSums(across(where(is.numeric))))\n\n \n \n\n\n\n #filter based on search returns\n search_matrix.wide.f = search_matrix %>%\n filter(rsum >= search.min & rsum <= search.max) %>%\n select(-rsum)\n\n\n #build a result matrix\n search_PMI = matrix(nrow = nrow(search_matrix.wide.f), ncol = ncol(search_matrix.wide.f)) %>%\n magrittr::set_rownames(rownames(search_matrix.wide.f)) %>%\n magrittr::set_colnames(colnames(search_matrix.wide.f))\n\n #Calculate PMI\n for (i in 1:nrow(search_matrix.wide.f)) {\n for (j in 1:ncol(search_matrix.wide.f)){\n search_PMI[i, j] <- (log2(sum(search_matrix.wide.f[i,])/sum(search_matrix.wide.f))\n + log2(sum(search_matrix.wide.f[,j])/sum(search_matrix.wide.f))\n -log2(search_matrix.wide.f[i,j]/sum(search_matrix.wide.f))) *-1\n }\n }\n \n\n #clean up infs\n search_PMI = search_PMI %>%\n replace(is.infinite(.), 0)\n\n \n return(search_PMI)\n \n}", "_____no_output_____" ], [ "PMI_query_combinations()", "_____no_output_____" ] ], [ [ "base::save(search_PMI, file = \"../AbstractR-projects/LINCS/output/PMI_table_0t100000_2021.07.29.RData\")", "_____no_output_____" ] ], [ [ "---\n# select.highest\n", "_____no_output_____" ], [ "---\n# search hits table", "_____no_output_____" ] ], [ [ "#This function reads a ```query_object``` output by the ```query_result``` function. The result is a list of \n#parwise mututal information scores resulting from \n\nsearch_query_combinations = function(query_result_object, chemical.list.path, search.min = 0, search.max = 100000) {\n\n #Libraries\n library(tidyverse)\n library(parallel)\n library(magrittr)\n\n #testingpaths\n# query_result_object = \"../AbstractR-projects/LINCS/output/query.result_LINCS_2021-07-29.RData\"\n# chemical.list.path = \"input/chemical-list-LINCS-2021.07.23.csv\"\n# search.min = 5\n# search.max = 100000\n \n\n #read query result\n load(paste0(query_result_object))\n chems.data = suppressMessages(read_csv(paste0(chemical.list.path))) %>%\n mutate(q.chemical = paste0('\"',chemicals,'\"'))\n\n#take only pmids and abstract from the query result and calc number results\nsearch_matrix = mclapply(seq_along(query.result[[1]]), function(x) { query.result[[1]][[x]] %>%\n pull(pmid) %>% unique() %>% length() }, mc.cores = 10) %>% setNames(names(query.result[[1]])) %>% unlist() %>%\n as.data.frame() %>%\n setNames('search_results') %>%\n rownames_to_column('query') %>%\n left_join(query.result[[2]], 'query') %>%\n mutate(search = query) %>%\n separate(col = search, into = c('q.chemical', 'search'), sep = ' AND ') %>%\n left_join(chems.data, 'q.chemical') %>%\n mutate(search = gsub('\\\\\"','', search)) %>%\n select(chemicals, SRP, search, direction, search_results)\n\n #make a wide form matrix\n search_matrix.wide = search_matrix %>%\n select(chemicals, search, search_results) %>%\n pivot_wider(id_cols = chemicals, names_from = search, values_from = search_results) %>%\n replace(is.na(.), 0) %>%\n mutate(rsum = rowSums(across(where(is.numeric))))\n\n #filter based on search returns\n search_matrix.wide.f = search_matrix.wide %>%\n filter(rsum >= search.min & rsum <= search.max) %>%\n select(-rsum) %>%\n column_to_rownames('chemicals')\n\n\n\n \n return(search_matrix.wide.f)\n \n}", "_____no_output_____" ], [ "#This function takes a numeric matrix resulting from PMI, GSEA (connectivity), or some other metric and \n#' returns that same matrix with two additional columns: the name of the highest scoring column for each row and\n#' the corresponding score\n\nselect.highest = function(score.matrix) {\n\n #Libraries\n suppressMessages(library(tidyverse))\n \n #testingpaths\n #score.matrix = score.matrix\n \n\n #maxcolumn and value\n score.matrix.highest = data.frame(max_column = colnames(score.matrix)[apply(score.matrix, 1, which.max)], stringsAsFactors = FALSE) %>%\n cbind(score.matrix %>% apply(1, max) %>% as.data.frame() %>% setNames(\"max_value\") %>%\n rownames_to_column(var = \"row\"), .) %>%\n left_join(score.matrix %>% as.data.frame() %>% rownames_to_column('row'), by = 'row') %>%\n column_to_rownames('row')\n\nreturn(score.matrix.highest)\n}", "_____no_output_____" ] ], [ [ "---\n# WORK FLOW\n---", "_____no_output_____" ] ], [ [ "suppressMessages(R.utils::sourceDirectory(\"lib/\", modifiedOnly = FALSE, recursive = TRUE))", "_____no_output_____" ], [ "query.result = query_result(chemical.list.path = \"input/chemical-list-LINCS-2021.07.23.csv\", query.map.path = \"input/query.map.csv\", limit_input_to = 10)", "_____no_output_____" ], [ "load(\"input/build/pmi.testing.query.object.RData\")", "_____no_output_____" ], [ "query.result[[3]]", "_____no_output_____" ], [ "#save(query.result, file = \"input/pmi.testing.query.object.RData\")", "_____no_output_____" ], [ "count.matrix = abstract_gene_counts(query_result_object = \"input/build/pmi.testing.query.object.RData\")", "_____no_output_____" ], [ "count.matrix", "_____no_output_____" ], [ "PMI_matrix = PMI_query_combinations(query_result_object = \"input/build/pmi.testing.query.object.RData\", chemical.list.path = \"input/chemical-list-LINCS-2021.07.23.csv\", search.min = 0, search.max = 100000)", "_____no_output_____" ], [ "PMI_matrix", "_____no_output_____" ], [ "PMI_matrix_best = select.highest(score.matrix = PMI_matrix)", "_____no_output_____" ], [ "PMI_matrix_best", "_____no_output_____" ] ], [ [ "accuracy rank", "_____no_output_____" ] ], [ [ "#this function takes a matrix of measures for a sample set, along side a validated columns, and measures the weighted accuracy of each assignment\nfunction(score.matrix, val.col, measures.cols){\n matrix = score.matrix\n\n \n}", "_____no_output_____" ] ], [ [ "---\nSTRACTH and LEARNING", "_____no_output_____" ] ], [ [ "---\n#### 0.0 Build input variables - *masked because this would be a different step*", "_____no_output_____" ], [ "#Load libraries\nsuppressMessages(library(tidyverse))\nlibrary(cmapR)", "_____no_output_____" ], [ "we are using stress response system abrevations follows below. As of this version we have the following categories: ", "_____no_output_____" ], [ "#set stress cats of interests\nSRPs <- c(\"DDR\", # dna damage response\n \"UPR\", # unfolded protein response\n \"HSR\", # heatshock or proteolytic response\n \"HPX\", # hypoxic response\n \"MTL\", # response to metals\n \"OSR\" # oxidative stress response\n )\n\n#set key directory points\nphase1 <- '/share/projects/HTTr/HTTr_pipeline_dev/HumanWT_v1/Analysis/Bundy/cmap_explore/input/phase_1/'\nphase2 <- '/share/projects/HTTr/HTTr_pipeline_dev/HumanWT_v1/Analysis/Bundy/cmap_explore/input/phase_2/'\n\n#set phase GSE identifiers\nGSEp1=\"GSE92742\"\nGSEp2=\"GSE70138\"\n\n#build a list of the phases to iterate\nphases <- list(phase1, phase2)\nGSEs <- list(GSEp1, GSEp2)\n\n#build a list of all chemicals in LINCS\n#pull all chemical\nexperimentaldb <- lapply(seq_along(phases), function(x) suppressMessages(suppressWarnings(read_tsv(file= paste0(phases[[x]],GSEs[[x]],'_Broad_LINCS_sig_info.txt')))) %>%\n select(pert_id, pert_iname, pert_type, cell_id, pert_idose, pert_itime) %>%\n filter(pert_type == \"trt_cp\") %>%\n select(pert_id, pert_iname)\n )\n#make a single df\ntotalchems <- do.call(rbind, experimentaldb) %>% distinct()\n\n#filter for those that do not have a BRD- id inplace of chem name\nfilterchems0 <- totalchems[!grepl(pattern = 'BRD-', x = totalchems$pert_iname, ignore.case = TRUE),] %>% \n mutate(original.pert_iname = pert_iname, pert_iname = gsub(pattern = \"\\\\\\'\", replacement = \"\", x = pert_iname)) #clean up the miss annotated \" \\' \"\n\nfilterchems = filterchems0 %>% distinct(pert_iname) %>%\n left_join(totalchems, 'pert_iname') %>%\n arrange(pert_iname)\n\nchems = filterchems$pert_iname %>% unique()\n\n\n\n#define seearch phrases\nsearchchemicals = filterchems$pert_iname %>% unique() %>% sort() #chems\nsearchterms = c(\"dna damage\",\n \"unfolded protein response\",\n \"er stress\",\n \"heat shock\",\n \"hypoxia\",\n \"metal stress\",\n \"chelator\",\n \"oxidative stress\",\n \"antioxidant\"\n )", "_____no_output_____" ], [ "write.csv(chems, \"chemical-list-LINCS-2021.07.23.csv\")", "_____no_output_____" ], [ "### 1.1 libraries", "_____no_output_____" ], [ "library(tidyverse)\nlibrary(easyPubMed)\nlibrary(kableExtra)", "_____no_output_____" ], [ "### 1.2 read in data\n\nStart by reading in the chemical list of interest", "_____no_output_____" ], [ "#read chemical list\nchems = read_csv(file = \"chemical-list-LINCS-2021.07.23.csv\")", "_____no_output_____" ], [ "chems %>% head()", "_____no_output_____" ], [ "chems.short = chems$chemicals[1:10]", "_____no_output_____" ], [ "next read in the query map", "_____no_output_____" ], [ "#read in query map\nq.map = read_csv(\"query.map.csv\")", "_____no_output_____" ], [ "q.map", "_____no_output_____" ], [ "---\n## 2. Perpare for data for query", "_____no_output_____" ], [ "#build partial search vectors\nchems.search = paste0('\"', chems.short, '\" AND')\nsearchterms.search = q.map$phrase", "_____no_output_____" ], [ "#controlable and bindable search grid with directions\nsearch.grid = expand.grid(chems.search, searchterms.search, stringsAsFactors = FALSE) %>%\n setNames(c('chemical', 'phrase')) %>% \n left_join(q.map, by = \"phrase\") %>%\n mutate(query = paste(chemical, phrase)) %>%\n select(SRP, direction, query)\n\n#acutal query list\nsearch.query = search.grid$query", "_____no_output_____" ], [ "# now pass this to the new version of ezPubMed and get XML dataframe back with PID, Abstract, then summate it and get search result as an second query ... this lets you parse abstracts imediately as a single data object!!!!!", "_____no_output_____" ], [ "so you will have to reduce the # of rows etc to re-extract search information but you can save the object once!!!", "_____no_output_____" ], [ "# Get a query result object", "_____no_output_____" ], [ "lapply(seq_along(search.quick), function(x) get_pubmed_ids(search.quick[[1]], api_key = 'b3accc43abfb376d63b0c2d2f7d8f984de09') %>%\n fetch_pubmed_data() %>%\n articles_to_list() %>%\n lapply(., article_to_df, max_chars = -1, getAuthors = FALSE) %>%\n do.call(rbind, .)\n )", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "raw", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "raw" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "raw" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw", "raw" ] ]
d0320b170ee082330aa13545f4fcbb5aec5f678f
608
ipynb
Jupyter Notebook
20170114/20140114.ipynb
JaeGyu/PythonEx_1
e67053db6ca7431c3dd66351c190c53229e3f141
[ "MIT" ]
null
null
null
20170114/20140114.ipynb
JaeGyu/PythonEx_1
e67053db6ca7431c3dd66351c190c53229e3f141
[ "MIT" ]
null
null
null
20170114/20140114.ipynb
JaeGyu/PythonEx_1
e67053db6ca7431c3dd66351c190c53229e3f141
[ "MIT" ]
null
null
null
16.888889
34
0.514803
[ [ [ "print(\"-\"*60)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
d032116a9036c826073609c336487eb6a0b38cf0
180,417
ipynb
Jupyter Notebook
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
e040693001941079b2e0acc12e0c3ee5c917671c
[ "MIT" ]
3
2019-03-27T05:22:34.000Z
2021-01-27T10:49:13.000Z
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
e040693001941079b2e0acc12e0c3ee5c917671c
[ "MIT" ]
null
null
null
topics/initial-value-problems/Cyclical Example.ipynb
jomorodi/NumericalMethods
e040693001941079b2e0acc12e0c3ee5c917671c
[ "MIT" ]
7
2019-12-29T23:31:56.000Z
2021-12-28T19:04:10.000Z
43.286228
209
0.481667
[ [ [ "# Cyclical Systems: An Example of the Crank-Nicolson Method\n## CH EN 2450 - Numerical Methods\n**Prof. Tony Saad (<a>www.tsaad.net</a>) <br/>Department of Chemical Engineering <br/>University of Utah**\n<hr/>", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom numpy import *\n# %matplotlib notebook\n# %matplotlib nbagg\n%matplotlib inline\n%config InlineBackend.figure_format = 'svg'\n\n# %matplotlib qt\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import fsolve\nfrom scipy.integrate import odeint", "_____no_output_____" ], [ "def forward_euler(rhs, f0, tend, dt):\n ''' Computes the forward_euler method '''\n nsteps = int(tend/dt)\n f = np.zeros(nsteps)\n f[0] = f0\n time = np.linspace(0,tend,nsteps)\n for n in np.arange(nsteps-1):\n f[n+1] = f[n] + dt * rhs(f[n], time[n])\n return time, f\n\ndef forward_euler_system(rhsvec, f0vec, tend, dt):\n '''\n Solves a system of ODEs using the Forward Euler method\n '''\n nsteps = int(tend/dt)\n neqs = len(f0vec)\n f = np.zeros( (neqs, nsteps) )\n f[:,0] = f0vec\n time = np.linspace(0,tend,nsteps)\n for n in np.arange(nsteps-1):\n t = time[n]\n f[:,n+1] = f[:,n] + dt * rhsvec(f[:,n], t)\n return time, f\n\ndef be_residual(fnp1, rhs, fn, dt, tnp1):\n '''\n Nonlinear residual function for the backward Euler implicit time integrator\n ''' \n return fnp1 - fn - dt * rhs(fnp1, tnp1)\n\ndef backward_euler(rhs, f0, tend, dt):\n ''' \n Computes the backward euler method \n :param rhs: an rhs function\n '''\n nsteps = int(tend/dt)\n f = np.zeros(nsteps)\n f[0] = f0\n time = np.linspace(0,tend,nsteps)\n for n in np.arange(nsteps-1):\n fn = f[n]\n tnp1 = time[n+1]\n fnew = fsolve(be_residual, fn, (rhs, fn, dt, tnp1))\n f[n+1] = fnew\n return time, f\n\ndef cn_residual(fnp1, rhs, fn, dt, tnp1, tn):\n '''\n Nonlinear residual function for the Crank-Nicolson implicit time integrator\n '''\n return fnp1 - fn - 0.5 * dt * ( rhs(fnp1, tnp1) + rhs(fn, tn) )\n\ndef crank_nicolson(rhs,f0,tend,dt):\n nsteps = int(tend/dt)\n f = np.zeros(nsteps)\n f[0] = f0\n time = np.linspace(0,tend,nsteps)\n for n in np.arange(nsteps-1):\n fn = f[n]\n tnp1 = time[n+1]\n tn = time[n]\n fnew = fsolve(cn_residual, fn, (rhs, fn, dt, tnp1, tn))\n f[n+1] = fnew\n return time, f", "_____no_output_____" ] ], [ [ "# Sharp Transient\nSolve the ODE:\n\\begin{equation}\n\\frac{\\text{d}y}{\\text{d}t} = -1000 y + 3000 - 2000 e^{-t};\\quad y(0) = 0\n\\end{equation}\nThe analytical solution is \n\\begin{equation}\ny(t) = 3 - 0.998 e^{-1000t} - 2.002 e^{-t}\n\\end{equation}\n\n", "_____no_output_____" ], [ "We first plot the analytical solution", "_____no_output_____" ] ], [ [ "y = lambda t : 3 - 0.998*exp(-1000*t) - 2.002*exp(-t)\nt = np.linspace(0,1,500)\nplt.plot(t,y(t))\nplt.grid()", "_____no_output_____" ] ], [ [ "Now let's solve this numerically. We first define the RHS for this function", "_____no_output_____" ] ], [ [ "def rhs_sharp_transient(f,t):\n return 3000 - 1000 * f - 2000* np.exp(-t)", "_____no_output_____" ] ], [ [ "Let's solve this using forward euler and backward euler", "_____no_output_____" ] ], [ [ "y0 = 0\ntend = 0.03\ndt = 0.001\nt,yfe = forward_euler(rhs_sharp_transient,y0,tend,dt)\nt,ybe = backward_euler(rhs_sharp_transient,y0,tend,dt)\nt,ycn = crank_nicolson(rhs_sharp_transient,y0,tend,dt)\n\nplt.plot(t,y(t),label='Exact')\n# plt.plot(t,yfe,'r.-',markevery=1,markersize=10,label='Forward Euler')\nplt.plot(t,ybe,'k*-',markevery=2,markersize=10,label='Backward Euler')\nplt.plot(t,ycn,'o-',markevery=2,markersize=2,label='Crank Nicholson')\nplt.grid()\nplt.legend()", "_____no_output_____" ] ], [ [ "# Oscillatory Systems\nSolve the ODE:\nSolve the ODE:\n\\begin{equation}\n\\frac{\\text{d}y}{\\text{d}t} = r \\omega \\sin(\\omega t)\n\\end{equation}\nThe analytical solution is \n\\begin{equation}\ny(t) = r - r \\cos(\\omega t)\n\\end{equation}\n\n\n", "_____no_output_____" ], [ "First plot the analytical solution", "_____no_output_____" ] ], [ [ "r = 0.5\nω = 0.02\ny = lambda t : r - r * cos(ω*t)\nt = np.linspace(0,100*pi)\nplt.clf()\nplt.plot(t,y(t))\nplt.grid()", "_____no_output_____" ] ], [ [ "Let's solve this numerically", "_____no_output_____" ] ], [ [ "def rhs_oscillatory(f,t):\n r = 0.5\n ω = 0.02\n return r * ω * sin(ω*t)", "_____no_output_____" ], [ "y0 = 0\ntend = 100*pi\ndt = 10\nt,yfe = forward_euler(rhs_oscillatory,y0,tend,dt)\nt,ybe = backward_euler(rhs_oscillatory,y0,tend,dt)\nt,ycn = crank_nicolson(rhs_oscillatory,y0,tend,dt)\nplt.plot(t,y(t),label='Exact')\nplt.plot(t,yfe,'r.-',markevery=1,markersize=10,label='Forward Euler')\nplt.plot(t,ybe,'k*-',markevery=2,markersize=10,label='Backward Euler')\nplt.plot(t,ycn,'o-',markevery=2,markersize=2,label='Crank Nicholson')\nplt.grid()\nplt.legend()\nplt.savefig('cyclical-system-example.pdf')", "_____no_output_____" ], [ "import urllib\nimport requests\nfrom IPython.core.display import HTML\ndef css_styling():\n styles = requests.get(\"https://raw.githubusercontent.com/saadtony/NumericalMethods/master/styles/custom.css\")\n return HTML(styles.text)\ncss_styling()\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d03211a4e02f23335bb8e6e1412a1ec54d97cf11
397,265
ipynb
Jupyter Notebook
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
50818001acc3e47ba46deac466bd7f4ee5da2043
[ "MIT" ]
null
null
null
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
50818001acc3e47ba46deac466bd7f4ee5da2043
[ "MIT" ]
null
null
null
code/UnsupervisedNeuralComputation.ipynb
caxenie/basecamp-winterschool-2017
50818001acc3e47ba46deac466bd7f4ee5da2043
[ "MIT" ]
null
null
null
150.081224
106,484
0.847346
[ [ [ "# Unsupervised neural computation - Practical\n\nDependencies:\n- Python (>= 2.6 or >= 3.3)\n- NumPy (>= 1.6.1)\n- SciPy (>= 0.12)\n- SciKit Learn (>=0.18.1)\n\nJust as there are different ways in which we ourselves learn from our own surrounding environments, so it is with neural networks. In a broad sense, we may categorize the learning processes through which neural networks function as follows: learning with a teacher and learning without a teacher. \n\nThese different forms of learning as performed on neural networks parallel those of human learning. Learning with a teacher is also referred to as supervised learning. In conceptual terms, we may think of the teacher as having knowledge of the environment, with that knowledge being represented by a set of input - output examples. Unsupervised learning does not require target vectors for the outputs. \n\nWithout input-output training pairs as external teachers, unsupervised learning is self-organized to produce consistent output vectors by modifying weights. That is to say, there are no labelled examples of the function to be learned by the network. \n\nFor a specific task-independent measure, once the network has become tuned to the statistical regularities of the input data, the network develops the ability to discover internal structure for encoding features of the input or compress the input data, and thereby to create new classes automatically.", "_____no_output_____" ], [ "## Radial Basis Functions and Radial Basis Function Networks - Semi-supervised Learning\n\n### combining supervised and unsupervised learning", "_____no_output_____" ], [ "In machine learning, the radial basis function kernel, or RBF kernel, is a popular kernel function (typically Gaussian) used in various kernelized learning algorithms.", "_____no_output_____" ] ], [ [ "# Class implementing the basic RBF parametrization\n# based on code from https://github.com/jeffheaton/aifh\nimport numpy as np\n\nclass RbfFunction(object):\n def __init__(self, dimensions, params, index):\n self.dimensions = dimensions\n self.params = params\n self.index = index\n\n @property\n def width(self):\n return self.params[self.index]\n\n @width.setter\n def width(self, value):\n self.params[self.index] = value\n\n def set_center(self, index, value):\n self.params[self.index + index + 1] = value\n\n def get_center(self, index):\n return self.params[self.index + index + 1]", "_____no_output_____" ] ], [ [ "RBFs can take various shapes: quadratic, multi-quadratic, inverse multi-quadratic, mexican hat. Yet the most used is the Gaussian.", "_____no_output_____" ] ], [ [ "# Class implementing a Gaussian RBF\nclass RbfGaussian(RbfFunction):\n def evaluate(self, x):\n value = 0\n width = self.width\n\n for i in range(self.dimensions):\n center = self.get_center(i)\n value += ((x[i] - center) ** 2) / (2.0 * width * width)\n return np.exp(-value)", "_____no_output_____" ] ], [ [ "A RBF network is an advanced machine learning algorithm that uses a series of RBF functions to perform regression. It can also perform classification by means of one-of-n encoding. The long term memory of a RBF network is made up of the widths and centers of the RBF functions, as well as input and output weighting.", "_____no_output_____" ] ], [ [ "# Class implementing a Gaussian RBF Network\nclass RbfNetwork(object):\n\n def __init__(self, input_count, rbf_count, output_count):\n \"\"\" Create an RBF network with the specified shape.\n @param input_count: The input count.\n @param rbf_count: The RBF function count.\n @param output_count: The output count.\n \"\"\"\n self.input_count = input_count\n self.output_count = output_count\n\n # calculate input and output weight counts\n # add 1 to output to account for an extra bias node\n input_weight_count = input_count * rbf_count\n output_weight_count = (rbf_count + 1) * output_count\n rbf_params = (input_count + 1) * rbf_count\n self.long_term_memory = np.zeros((input_weight_count + output_weight_count + rbf_params), dtype=float)\n\n self.index_input_weights = 0\n self.index_output_weights = input_weight_count + rbf_params\n\n self.rbf = {}\n\n # default the Rbf's to gaussian\n for i in range(0, rbf_count):\n rbf_index = input_weight_count + ((input_count + 1) * i)\n self.rbf[i] = RbfGaussian(input_count, self.long_term_memory, rbf_index)\n\n\n def compute_regression(self, input):\n \"\"\" Compute the output for the network.\n @param input: The input pattern.\n @return: The output pattern.\n \"\"\"\n # first, compute the output values of each of the RBFs\n # Add in one additional RBF output for bias (always set to one).\n rbf_output = [0] * (len(self.rbf) + 1)\n # bias\n rbf_output[len(rbf_output) - 1] = 1.0\n\n for rbfIndex in range(0, len(self.rbf)):\n # weight the input\n weighted_input = [0] * len(input)\n\n for inputIndex in range(0, len(input)):\n memory_index = self.index_input_weights + (rbfIndex * self.input_count) + inputIndex\n weighted_input[inputIndex] = input[inputIndex] * self.long_term_memory[memory_index]\n\n # calculate the rbf\n rbf_output[rbfIndex] = self.rbf[rbfIndex].evaluate(weighted_input)\n\n # Second, calculate the output, which is the result of the weighted result of the RBF's.\n result = [0] * self.output_count\n\n for outputIndex in range(0, len(result)):\n sum_value = 0\n for rbfIndex in range(0, len(rbf_output)):\n # add 1 to rbf length for bias\n memory_index = self.index_output_weights + (outputIndex * (len(self.rbf) + 1)) + rbfIndex\n sum_value += rbf_output[rbfIndex] * self.long_term_memory[memory_index]\n result[outputIndex] = sum_value\n\n # finally, return the result.\n return result\n\n def reset(self):\n \"\"\"\n Reset the network to a random state.\n \"\"\"\n for i in range(0, len(self.long_term_memory)):\n self.long_term_memory[i] = np.random.uniform(0, 1)\n\n def compute_classification(self, input):\n \"\"\" Compute the output and return the index of the output with the largest value. This is the class that\n the network recognized.\n @param input: The input pattern.\n @return:\n \"\"\"\n output = self.compute_regression(input)\n return output.index(max(output))\n\n def copy_memory(self, source):\n \"\"\" Copy the specified vector into the long term memory of the network.\n @param source: The source vector.\n \"\"\"\n for i in range(0, len(source)):\n self.long_term_memory[i] = source[i]", "_____no_output_____" ] ], [ [ "The Iris dataset is a traditional benchmark in classification problems in ML. The data set consists of 50 samples from each of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). Four features were measured from each sample: the length and the width of the sepals and petals, in centimetres. Based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other.\n\nThe Iris flower data set or Fisher's Iris data set is a multivariate data set introduced by Ronald Fisher in his 1936 paper \"The use of multiple measurements in taxonomic problems\" as an example of linear discriminant analysis. It is sometimes called Anderson's Iris data set because Edgar Anderson collected the data to quantify the morphologic variation of Iris flowers of three related species. Based on Fisher's linear discriminant model, this data set became a typical test case for many statistical classification techniques in machine learning such as support vector machines.\n\nIn the following we will use simulated annealing to fit an RBF network to the Iris data set, to classifiy the iris species correctly.\n\nSimulated annealing is a probabilistic technique for approximating the global optimum of a given function. Specifically, it is a metaheuristic to approximate global optimization in a large search space.", "_____no_output_____" ] ], [ [ "# Find the dataset\nimport os\nimport sys\nfrom normalize import Normalize\nfrom error import ErrorCalculation\nfrom train import TrainAnneal\nimport numpy as np\n\nirisFile = os.path.abspath(\"./data/iris.csv\")\n\n# Read the Iris data set\nprint('Reading CSV file: ' + irisFile)\nnorm = Normalize()\niris_work = norm.load_csv(irisFile)\n\n# Extract the original iris species so we can display during the final validation\nideal_species = [row[4] for row in iris_work]\n\n# Setup the first four fields to \"range normalize\" between -1 and 1.\nfor i in range(0, 4):\n norm.make_col_numeric(iris_work, i)\n norm.norm_col_range(iris_work, i, 0, 1)\n\n# Discover all of the classes for column #4, the iris species.\nclasses = norm.build_class_map(iris_work, 4)\ninv_classes = {v: k for k, v in classes.items()}\n\n# Normalize iris species using one-of-n.\n# We could have used equilateral as well. For an example of equilateral, see the example_nm_iris example.\nnorm.norm_col_one_of_n(iris_work, 4, classes, 0, 1)\n\n# Prepare training data. Separate into input and ideal.\ntraining = np.array(iris_work)\ntraining_input = training[:, 0:4]\ntraining_ideal = training[:, 4:7]", "Reading CSV file: /media/data_warehouse/Dropbox/Public/sandbox/teaching/Basecamp.ai_Lectures/code/data/iris.csv\n" ], [ "# Define the score of the training process of the network\ndef score_funct(x):\n \"\"\"\n The score function for Iris anneal.\n @param x:\n @return:\n \"\"\"\n global best_score\n global input_data\n global output_data\n # Update the network's long term memory to the vector we need to score.\n network.copy_memory(x)\n # Loop over the training set and calculate the output for each.\n actual_output = []\n for input_data in training_input:\n output_data = network.compute_regression(input_data)\n actual_output.append(output_data)\n # Calculate the error with MSE.\n result = ErrorCalculation.mse(np.array(actual_output), training_ideal)\n return result", "_____no_output_____" ], [ "# Create an RBF network. There are four inputs and two outputs.\n# There are also five RBF functions used internally.\n# You can experiment with different numbers of internal RBF functions.\n# However, the input and output must match the data set.\ninputs = 4\nrbfs = 4\noutputs = 3\nnetwork = RbfNetwork(inputs, rbfs, outputs)\nnetwork.reset()\n\n# Create a copy of the long-term memory. This becomes the initial state.\nx0 = list(network.long_term_memory)\n\n# Perform the annealing\n\n# Train a Machine Learning Algorithm using Simulated Annealing. Simulated Annealing is a Monte Carlo algorithm\n# that is based on annealing in metallurgy, a technique involving heating and controlled cooling of a\n# material to increase the size of its crystals and reduce their defects, both are attributes of the material\n# that depend on its thermodynamic free energy.\n \ntrain = TrainAnneal()\ntrain.display_iteration = True\ntrain.train(x0, score_funct)\n\n# Display the final validation. We show all of the iris data as well as the predicted species.\nfor i in range(0, len(training_input)):\n input_data = training_input[i]\n # Compute the output from the RBF network\n output_data = network.compute_regression(input_data)\n ideal_data = training_ideal[i]\n # Decode the three output neurons into a class number.\n class_id = norm.denorm_one_of_n(output_data)\n print(str(input_data) + \" -> \" + inv_classes[class_id] + \", Ideal: \" + ideal_species[i])", "_____no_output_____" ] ], [ [ "It is often used when the search space is discrete (e.g., all tours that visit a given set of cities). For problems where finding an approximate global optimum is more important than finding a precise local optimum in a fixed amount of time, simulated annealing may be preferable to alternatives such as gradient descent.", "_____no_output_____" ], [ "## Assignments", "_____no_output_____" ], [ "Given the RBFN API please follow the next steps to train a RBF to clssify the Iris dataset.", "_____no_output_____" ] ], [ [ "# Perform the simmulated annealing.\n# Display the final validation. We show all of the iris data as well as the predicted species.\n# Compute the output from the RBF network\n# Decode the three output neurons into a class number and print it ", "_____no_output_____" ] ], [ [ "# Vector Quantization", "_____no_output_____" ], [ "Vector quantization (VQ) is a form of competitive learning. Such an algorithm is able to discover structure in the input data. Generally speaking, vector quantization is a form of lossy data compression—lossy in the sense that some information contained in the input data is lost as a result of the compression.\n![title](img/vq_alg.png)\nAn input data point belongs to a certain class if its position (in the 2D space) is closest to the class prototype, fulfilling the Voronoi partitioning (i.e. partitioning of a plane into regions based on distance to points in a specific subset of the plane.\n![title](img/vq.png)\nIn a typical scenario, such behavior can be implemented with a neural network that consists of two layers—an input layer and a competitive layer with lateral inhibition. The input layer receives the available data. The competitive layer consists of neurons that compete with each other.\n![title](img/vq_net.png)\nThe classic image processing example, Lena, an 8-bit grayscale bit-depth, 512 x 512 sized image, is used here to illustrate how `k`-means is used for vector quantization.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nfrom sklearn import cluster\nfrom sklearn.utils.testing import SkipTest\nfrom sklearn.utils.fixes import sp_version\n\ntry:\n face = sp.face(gray=True)\nexcept AttributeError:\n # Newer versions of scipy have face in misc\n from scipy import misc\n face = misc.face(gray=True)\n\nn_clusters = 5\nnp.random.seed(0)\n\nX = face.reshape((-1, 1)) # We need an (n_sample, n_feature) array\nk_means = cluster.KMeans(n_clusters=n_clusters, n_init=4)\nk_means.fit(X)\nvalues = k_means.cluster_centers_.squeeze()\nlabels = k_means.labels_\n\n# create an array from labels and values\nface_compressed = np.choose(labels, values)\nface_compressed.shape = face.shape\n\nvmin = face.min()\nvmax = face.max()", "_____no_output_____" ] ], [ [ "Plot the results of the clutering and plot the original, quatized, and histogram.", "_____no_output_____" ] ], [ [ "# original face\nplt.figure(1, figsize=(3, 2.2))\nplt.imshow(face, cmap=plt.cm.gray, vmin=vmin, vmax=256)\n\n# compressed face\nplt.figure(2, figsize=(3, 2.2))\nplt.imshow(face_compressed, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)\n\n# equal bins face\nregular_values = np.linspace(0, 256, n_clusters + 1)\nregular_labels = np.searchsorted(regular_values, face) - 1\nregular_values = .5 * (regular_values[1:] + regular_values[:-1]) # mean\nregular_face = np.choose(regular_labels.ravel(), regular_values, mode=\"clip\")\nregular_face.shape = face.shape\nplt.figure(3, figsize=(3, 2.2))\nplt.imshow(regular_face, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)\n\n# histogram\nplt.figure(4, figsize=(3, 2.2))\nplt.clf()\nplt.axes([.01, .01, .98, .98])\nplt.hist(X, bins=256, color='.5', edgecolor='.5')\nplt.yticks(())\nplt.xticks(regular_values)\nvalues = np.sort(values)\nfor center_1, center_2 in zip(values[:-1], values[1:]):\n plt.axvline(.5 * (center_1 + center_2), color='b')\n\nfor center_1, center_2 in zip(regular_values[:-1], regular_values[1:]):\n plt.axvline(.5 * (center_1 + center_2), color='b', linestyle='--')\n\nplt.show()", "_____no_output_____" ] ], [ [ "## Assignments", "_____no_output_____" ], [ "In this problem you should group 2d input points (x,y) into clusters and determine the center of each cluster. The number of required clusters is provided as integer number on the first line. Following, the system provides an unknown number of 2d input data points (x, y), one per line. Continue reading until your program obtains no more data. You can safely assume to read less than 1000 points. After reading, you should run the Vector Quantization algorithm to find the center(s) of input data, and finally report the center position as x, y coordinate. Present one such center position per output line. The order of center points output does not matter.", "_____no_output_____" ], [ "3 cluster VQ\n![title](img/vq_3clust.png)", "_____no_output_____" ] ], [ [ "# load the datasets for training and testing \nimport numpy as np\nimport csv \nwith open('./data/vq_3clust_in.txt') as inputfile:\n train_data = list(csv.reader(inputfile))\nwith open('./data/vq_3clust_out.txt') as inputfile:\n test_data = list(csv.reader(inputfile))\n \n# add network code here", "_____no_output_____" ] ], [ [ "6 cluster VQ\n![title](img/vq_3clust.png)", "_____no_output_____" ] ], [ [ "# load the datasets for training and testing for the 6 cluster example\nimport numpy as np\nimport csv \nwith open('./data/vq_6clust_in.txt') as inputfile:\n train_data = list(csv.reader(inputfile))\nwith open('./data/vq_6clust_out.txt') as inputfile:\n test_data = list(csv.reader(inputfile))\n \n# add network code here", "_____no_output_____" ] ], [ [ "# Self-Organizing Maps", "_____no_output_____" ], [ "In neurobiology, during neural growth, synapses are strengthened or weakened, in a process usually modelled as a competition for resources. In such a learning process, there is a competition between the neurons to fire. More precisely, neurons compete with each other (in accordance with a learning rule) for the “opportunity” to respond to features contained in the input data. \n![title](img/som.png)\nIn its simplest form, such behaviour describes a “winner-takes-all” strategy. In such a strategy, the neuron with the greatest total input “wins” the competition and turns on; all the other neurons in the network then switch off. The aim of such learning mechanisms is to cluster the data.\n![title](img/som_tr.png)\nKohonen’s self-organizing map (SOM) is one of the most popular unsupervised neural network models. Developed for an associative memory model, it is an unsupervised learning algorithm with a simple structure and computational form, and is motivated by the retina-cortex mapping. The SOM can provide topologically preserved mapping from input to output spaces, such that “nearby” sensory stimuli are represented in “nearby” regions.\n![title](img/som_alg.png)", "_____no_output_____" ] ], [ [ "# Class implementing a basic SOM\nimport scipy.spatial\nimport numpy as np\nimport scipy as sp\nimport sys\n\n\nclass SelfOrganizingMap:\n \"\"\"\n The weights of the output neurons base on the input from the input\n neurons.\n \"\"\"\n\n def __init__(self, input_count, output_count):\n \"\"\"\n The constructor.\n :param input_count: Number of input neurons\n :param output_count: Number of output neurons\n :return:\n \"\"\"\n self.input_count = input_count\n self.output_count = output_count\n self.weights = np.zeros([self.output_count, self.input_count])\n\n self.distance = sp.spatial.distance.euclidean\n\n def calculate_error(self, data):\n bmu = BestMatchingUnit(self)\n\n bmu.reset()\n\n # Determine the BMU for each training element.\n for input in data:\n bmu.calculate_bmu(input)\n\n # update the error\n return bmu.worst_distance / 100.0\n\n def classify(self, input):\n if len(input) > self.input_count:\n raise Exception(\"Can't classify SOM with input size of {} \"\n \"with input data of count {}\".format(self.input_count, len(input)))\n\n min_dist = sys.maxfloat\n result = -1\n\n for i in range(self.output_count):\n dist = self.distance.calculate(input, self.weights[i])\n if dist < min_dist:\n min_dist = dist\n result = i\n\n return result\n\n def reset(self):\n self.weights = (np.random.rand(self.weights.shape[0], self.weights.shape[1]) * 2.0) - 1", "_____no_output_____" ] ], [ [ "The \"Best Matching Unit\" or BMU is a very important concept in the training for a SOM. The BMU is the output neuron that has weight connections to the input neurons that most closely match the current input vector. This neuron (and its \"neighborhood\") are the neurons that will receive training.", "_____no_output_____" ] ], [ [ "# Class implementing the competition stage in SOM, finding the best matching unit.\nclass BestMatchingUnit:\n \"\"\"\n This class also tracks the worst distance (of all BMU's). This gives some\n indication of how well the network is trained, and thus becomes the \"error\"\n of the entire network.\n \"\"\"\n\n def __init__(self, som):\n \"\"\"\n Construct a BestMatchingUnit class. The training class must be provided.\n :param som: The SOM to evaluate.\n \"\"\"\n # The owner of this class.\n self.som = som\n\n # What is the worst BMU distance so far, this becomes the error for the\n # entire SOM.\n self.worst_distance = 0\n\n def calculate_bmu(self, input):\n \"\"\"\n Calculate the best matching unit (BMU). This is the output neuron that\n has the lowest Euclidean distance to the input vector.\n :param input: The input vector.\n :return: The output neuron number that is the BMU.\n \"\"\"\n result = 0\n\n if len(input) > self.som.input_count:\n raise Exception(\n \"Can't train SOM with input size of {} with input data of count {}.\".format(self.som.input_count,\n len(input)))\n\n # Track the lowest distance so far.\n lowest_distance = float(\"inf\")\n\n for i in range(self.som.output_count):\n distance = self.calculate_euclidean_distance(self.som.weights, input, i)\n\n # Track the lowest distance, this is the BMU.\n if distance < lowest_distance:\n lowest_distance = distance\n result = i\n\n # Track the worst distance, this is the error for the entire network.\n if lowest_distance > self.worst_distance:\n self.worst_distance = lowest_distance\n\n return result\n\n def calculate_euclidean_distance(self, matrix, input, output_neuron):\n \"\"\"\n Calculate the Euclidean distance for the specified output neuron and the\n input vector. This is the square root of the squares of the differences\n between the weight and input vectors.\n :param matrix: The matrix to get the weights from.\n :param input: The input vector.\n :param outputNeuron: The neuron we are calculating the distance for.\n :return: The Euclidean distance.\n \"\"\"\n result = 0\n\n # Loop over all input data.\n diff = input - matrix[output_neuron]\n return np.sqrt(sum(diff*diff))", "_____no_output_____" ] ], [ [ "In the next section we analyze competitive training, which would be used in a winner-take-all neural network, such as the self organizing map (SOM). This is an unsupervised training method, no ideal data is needed on the training set. If ideal data is provided, it will be ignored. Training is done by looping over all of the training elements and calculating a \"best matching unit\" (BMU). This BMU output neuron is then adjusted to better \"learn\" this pattern. Additionally, this training may be applied to other \"nearby\" output neurons. The degree to which nearby neurons are update is defined by the neighborhood function.\n\nA neighborhood function is required to determine the degree to which neighboring neurons (to the winning neuron) are updated by each training iteration. Because this is unsupervised training, calculating an error to measure progress by is difficult. The error is defined to be the \"worst\", or longest, Euclidean distance of any of the BMU's. This value should be minimized, as learning progresses.", "_____no_output_____" ] ], [ [ "# Class implementing the basic training algorithm for a SOM\nclass BasicTrainSOM:\n \"\"\"\n Because only the BMU neuron and its close neighbors are updated, you can end\n up with some output neurons that learn nothing. By default these neurons are\n not forced to win patterns that are not represented well. This spreads out\n the workload among all output neurons. This feature is not used by default,\n but can be enabled by setting the \"forceWinner\" property.\n \"\"\"\n\n def __init__(self, network, learning_rate, training, neighborhood):\n\n # The neighborhood function to use to determine to what degree a neuron\n # should be \"trained\".\n self.neighborhood = neighborhood\n\n # The learning rate. To what degree should changes be applied.\n self.learning_rate = learning_rate\n\n # The network being trained.\n self.network = network\n\n # How many neurons in the input layer.\n self.input_neuron_count = network.input_count\n\n # How many neurons in the output layer.\n self.output_neuron_count = network.output_count\n\n # Utility class used to determine the BMU.\n self.bmu_util = BestMatchingUnit(network)\n\n # Correction matrix.\n self.correction_matrix = np.zeros([network.output_count, network.input_count])\n\n # True is a winner is to be forced, see class description, or forceWinners\n # method. By default, this is true.\n self.force_winner = False\n\n # When used with autodecay, this is the starting learning rate.\n self.start_rate = 0\n\n # When used with autodecay, this is the ending learning rate.\n self.end_rate = 0\n\n # When used with autodecay, this is the starting radius.\n self.start_radius = 0\n\n # When used with autodecay, this is the ending radius.\n self.end_radius = 0\n\n # This is the current autodecay learning rate.\n self.auto_decay_rate = 0\n\n # This is the current autodecay radius.\n self.auto_decay_radius = 0\n\n # The current radius.\n self.radius = 0\n\n # Training data.\n self.training = training\n\n def _apply_correction(self):\n \"\"\"\n Loop over the synapses to be trained and apply any corrections that were\n determined by this training iteration.\n \"\"\"\n np.copyto(self.network.weights, self.correction_matrix)\n\n def auto_decay(self):\n \"\"\"\n Should be called each iteration if autodecay is desired.\n \"\"\"\n if self.radius > self.end_radius:\n self.radius += self.auto_decay_radius\n\n if self.learning_rate > self.end_rate:\n self.learning_rate += self.auto_decay_rate\n\n self.neighborhood.radius = self.radius\n\n def copy_input_pattern(self, matrix, output_neuron, input):\n \"\"\"\n Copy the specified input pattern to the weight matrix. This causes an\n output neuron to learn this pattern \"exactly\". This is useful when a\n winner is to be forced.\n :param matrix: The matrix that is the target of the copy.\n :param output_neuron: The output neuron to set.\n :param input: The input pattern to copy.\n \"\"\"\n matrix[output_neuron, :] = input\n\n def decay(self, decay_rate, decay_radius):\n \"\"\"\n Decay the learning rate and radius by the specified amount.\n :param decay_rate: The percent to decay the learning rate by.\n :param decay_radius: The percent to decay the radius by.\n \"\"\"\n self.radius *= (1.0 - decay_radius)\n self.learning_rate *= (1.0 - decay_rate)\n self.neighborhood.radius = self.radius\n\n def _determine_new_weight(self, weight, input, currentNeuron, bmu):\n \"\"\"\n Determine the weight adjustment for a single neuron during a training\n iteration.\n :param weight: The starting weight.\n :param input: The input to this neuron.\n :param currentNeuron: The neuron who's weight is being updated.\n :param bmu: The neuron that \"won\", the best matching unit.\n :return: The new weight value.\n \"\"\"\n return weight \\\n + (self.neighborhood.fn(currentNeuron, bmu) \\\n * self.learning_rate * (input - weight))\n\n def _force_winners(self, matrix, won, least_represented):\n \"\"\"\n Force any neurons that did not win to off-load patterns from overworked\n neurons.\n :param matrix: An array that specifies how many times each output neuron has \"won\".\n :param won: The training pattern that is the least represented by this neural network.\n :param least_represented: The synapse to modify.\n :return: True if a winner was forced.\n \"\"\"\n max_activation = float(\"-inf\")\n max_activation_neuron = -1\n\n output = self.compute(self.network, self.least_represented)\n\n # Loop over all of the output neurons. Consider any neurons that were\n # not the BMU (winner) for any pattern. Track which of these\n # non-winning neurons had the highest activation.\n for output_neuron in range(len(won)):\n # Only consider neurons that did not \"win\".\n if won[output_neuron] == 0:\n if (max_activation_neuron == -1) \\\n or (output[output_neuron] > max_activation):\n max_activation = output[output_neuron]\n max_activation_neuron = output_neuron\n\n # If a neurons was found that did not activate for any patterns, then\n # force it to \"win\" the least represented pattern.\n if max_activation_neuron != -1:\n self.copy_input_pattern(matrix, max_activation_neuron, least_represented)\n return True\n else:\n return False\n\n def iteration(self):\n \"\"\"\n Perform one training iteration.\n \"\"\"\n # Reset the BMU and begin this iteration.\n self.bmu_util.reset()\n won = [0] * self.output_neuron_count\n least_represented_activation = float(\"inf\")\n least_represented = None\n\n # Reset the correction matrix for this synapse and iteration.\n self.correctionMatrix.clear()\n\n # Determine the BMU for each training element.\n for input in self.training:\n bmu = self.bmu_util.calculate_bmu(input)\n won[bmu] += 1\n\n # If we are to force a winner each time, then track how many\n # times each output neuron becomes the BMU (winner).\n if self.force_winner:\n # Get the \"output\" from the network for this pattern. This\n # gets the activation level of the BMU.\n output = self.compute(self.network, input)\n\n # Track which training entry produces the least BMU. This\n # pattern is the least represented by the network.\n if output[bmu] < least_represented_activation:\n least_represented_activation = output[bmu]\n least_represented = input.getInput()\n\n self.train(bmu, self.network.getWeights(), input.getInput())\n\n if self.force_winner:\n # force any non-winning neurons to share the burden somewhat\n if not self.force_winners(self.network.weights, won, least_represented):\n self.apply_correction()\n else:\n self.apply_correction()\n\n def set_auto_decay(self, planned_iterations, start_rate, end_rate, start_radius, end_radius):\n \"\"\"\n Setup autodecay. This will decrease the radius and learning rate from the\n start values to the end values.\n :param planned_iterations: The number of iterations that are planned. This allows the\n decay rate to be determined.\n :param start_rate: The starting learning rate.\n :param end_rate: The ending learning rate.\n :param start_radius: The starting radius.\n :param end_radius: The ending radius.\n \"\"\"\n self.start_rate = start_rate\n self.end_rate = end_rate\n self.start_radius = start_radius\n self.end_radius = end_radius\n self.auto_decay_radius = (end_radius - start_radius) / planned_iterations\n self.auto_decay_rate = (end_rate - start_rate) / planned_iterations\n self.set_params(self.start_rate, self.start_radius)\n\n def set_params(self, rate, radius):\n \"\"\"\n Set the learning rate and radius.\n :param rate: The new learning rate.\n :param radius:\n :return: The new radius.\n \"\"\"\n self.radius = radius\n self.learning_rate = rate\n self.neighborhood.radius = radius\n\n def get_status(self):\n \"\"\"\n :return: A string display of the status.\n \"\"\"\n result = \"Rate=\"\n result += str(self.learning_rate)\n result += \", Radius=\"\n result += str(self.radius)\n return result\n\n def _train(self, bmu, matrix, input):\n \"\"\"\n Train for the specified synapse and BMU.\n :param bmu: The best matching unit for this input.\n :param matrix: The synapse to train.\n :param input: The input to train for.\n :return:\n \"\"\"\n # adjust the weight for the BMU and its neighborhood\n for output_neuron in range(self.output_neuron_count):\n self._train_pattern(matrix, input, output_neuron, bmu)\n\n def _train_pattern(self, matrix, input, current, bmu):\n \"\"\"\n Train for the specified pattern.\n :param matrix: The synapse to train.\n :param input: The input pattern to train for.\n :param current: The current output neuron being trained.\n :param bmu: The best matching unit, or winning output neuron.\n \"\"\"\n\n for input_neuron in range(self.input_neuron_count):\n current_weight = matrix[current][input_neuron]\n input_value = input[input_neuron]\n\n new_weight = self._determine_new_weight(current_weight,\n input_value, current, bmu)\n\n self.correction_matrix[current][input_neuron] = new_weight\n\n def train_single_pattern(self, pattern):\n \"\"\"\n Train the specified pattern. Find a winning neuron and adjust all neurons\n according to the neighborhood function.\n :param pattern: The pattern to train.\n \"\"\"\n bmu = self.bmu_util.calculate_bmu(pattern)\n self._train(bmu, self.network.weights, pattern)\n self._apply_correction()\n\n def compute(self, som, input):\n \"\"\"\n Calculate the output of the SOM, for each output neuron. Typically,\n you will use the classify method instead of calling this method.\n :param som: The input pattern.\n :param input: The output activation of each output neuron.\n :return:\n \"\"\"\n\n result = np.zeros(som.output_count)\n\n for i in range(som.output_count):\n optr = som.weights[i]\n\n matrix_a = np.zeros([input.length,1])\n for j in range(len(input)):\n matrix_a[0][j] = input[j]\n\n matrix_b = np.zeros(1,input.length)\n for j in range(len(optr)):\n matrix_b[0][j] = optr[j]\n\n result[i] = np.dot(matrix_a, matrix_b)\n\n return result", "_____no_output_____" ] ], [ [ "A common example used to help teach the principals behind SOMs is the mapping of colours from their three dimensional components - red, green and blue, into two dimensions.The colours are presented to the network as 3D vectors - one dimension for each of the colour components (RGB encoding) - and the network learns to represent them in the 2D space we can see. Notice that in addition to clustering the colours into distinct regions, regions of similar properties are usually found adjacent to each other.", "_____no_output_____" ] ], [ [ "import os\nimport sys\nfrom Tkinter import *\nimport numpy as np\nfrom neighborhood import *\n\nTILES_WIDTH = 50\nTILES_HEIGHT = 50\nTILE_SCREEN_SIZE = 10\n\nclass DisplayColors:\n def __init__(self,root,samples):\n # Build the grid display\n canvas_width = TILES_WIDTH * TILE_SCREEN_SIZE\n canvas_height = TILES_HEIGHT * TILE_SCREEN_SIZE\n\n self.samples = samples\n self.root = root\n self.c = Canvas(self.root,width=canvas_width, height=canvas_height)\n self.c.pack()\n\n self.grid_rects = [[None for j in range(TILES_WIDTH)]\n for i in range(TILES_HEIGHT)]\n\n for row in range(TILES_HEIGHT):\n for col in range(TILES_WIDTH):\n x = col * TILE_SCREEN_SIZE\n y = row * TILE_SCREEN_SIZE\n r = self.c.create_rectangle(x, y, x+TILE_SCREEN_SIZE,y+TILE_SCREEN_SIZE, fill=\"white\")\n self.grid_rects[row][col] = r\n\n self.som = SelfOrganizingMap(3,TILES_WIDTH * TILES_HEIGHT)\n self.som.reset()\n\n self.gaussian = NeighborhoodRBF(NeighborhoodRBF.TYPE_GAUSSIAN,[TILES_WIDTH,TILES_HEIGHT])\n self.train = BasicTrainSOM(self.som, 0.01, None, self.gaussian)\n self.train.force_winner = False\n self.train.set_auto_decay(1000, 0.8, 0.003, 30, 5)\n self.iteration = 1\n\n def RGBToHTMLColor(self, rgb_tuple):\n hexcolor = '#%02x%02x%02x' % rgb_tuple\n return hexcolor\n\n def convert_color(self, d):\n result = 128*d\n result+= 128\n result = min(result, 255)\n result = max(result, 0)\n return result\n\n def update(self, som):\n for row in range(TILES_HEIGHT):\n for col in range(TILES_WIDTH):\n index = (row*TILES_WIDTH)+col\n color = (\n self.convert_color(som.weights[index][0]),\n self.convert_color(som.weights[index][1]),\n self.convert_color(som.weights[index][2]))\n r = self.grid_rects[row][col]\n self.c.itemconfig(r, fill=self.RGBToHTMLColor(color))\n self.c.itemconfig(r, outline=self.RGBToHTMLColor(color))\n\n def update_clock(self):\n idx = np.random.randint(len(samples))\n c = self.samples[idx]\n\n self.train.train_single_pattern(c)\n self.train.auto_decay()\n self.update(self.som)\n print(\"Iteration {}, {}\".format(self.iteration,self.train.get_status()))\n self.iteration+=1\n if self.iteration<=1000:\n self.root.after(1, self.update_clock)\n\n\n\n\nsamples = np.zeros([15,3])\nfor i in range(15):\n samples[i][0] = np.random.uniform(-1,1)\n samples[i][1] = np.random.uniform(-1,1)\n samples[i][2] = np.random.uniform(-1,1)\n\nroot = Tk()\ndisplay = DisplayColors(root, samples)\ndisplay.update_clock()\nroot.mainloop()", "Iteration 1, Rate=0.799203, Radius=29\nIteration 2, Rate=0.798406, Radius=28\nIteration 3, Rate=0.797609, Radius=27\nIteration 4, Rate=0.796812, Radius=26\nIteration 5, Rate=0.796015, Radius=25\nIteration 6, Rate=0.795218, Radius=24\nIteration 7, Rate=0.794421, Radius=23\nIteration 8, Rate=0.793624, Radius=22\nIteration 9, Rate=0.792827, Radius=21\nIteration 10, Rate=0.79203, Radius=20\nIteration 11, Rate=0.791233, Radius=19\nIteration 12, Rate=0.790436, Radius=18\nIteration 13, Rate=0.789639, Radius=17\nIteration 14, Rate=0.788842, Radius=16\nIteration 15, Rate=0.788045, Radius=15\nIteration 16, Rate=0.787248, Radius=14\nIteration 17, Rate=0.786451, Radius=13\nIteration 18, Rate=0.785654, Radius=12\nIteration 19, Rate=0.784857, Radius=11\nIteration 20, Rate=0.78406, Radius=10\nIteration 21, Rate=0.783263, Radius=9\nIteration 22, Rate=0.782466, Radius=8\nIteration 23, Rate=0.781669, Radius=7\nIteration 24, Rate=0.780872, Radius=6\nIteration 25, Rate=0.780075, Radius=5\nIteration 26, Rate=0.779278, Radius=5\nIteration 27, Rate=0.778481, Radius=5\nIteration 28, Rate=0.777684, Radius=5\nIteration 29, Rate=0.776887, Radius=5\nIteration 30, Rate=0.77609, Radius=5\nIteration 31, Rate=0.775293, Radius=5\nIteration 32, Rate=0.774496, Radius=5\nIteration 33, Rate=0.773699, Radius=5\nIteration 34, Rate=0.772902, Radius=5\nIteration 35, Rate=0.772105, Radius=5\nIteration 36, Rate=0.771308, Radius=5\nIteration 37, Rate=0.770511, Radius=5\nIteration 38, Rate=0.769714, Radius=5\nIteration 39, Rate=0.768917, Radius=5\nIteration 40, Rate=0.76812, Radius=5\nIteration 41, Rate=0.767323, Radius=5\nIteration 42, Rate=0.766526, Radius=5\nIteration 43, Rate=0.765729, Radius=5\nIteration 44, Rate=0.764932, Radius=5\nIteration 45, Rate=0.764135, Radius=5\nIteration 46, Rate=0.763338, Radius=5\nIteration 47, Rate=0.762541, Radius=5\nIteration 48, Rate=0.761744, Radius=5\nIteration 49, Rate=0.760947, Radius=5\nIteration 50, Rate=0.76015, Radius=5\nIteration 51, Rate=0.759353, Radius=5\nIteration 52, Rate=0.758556, Radius=5\nIteration 53, Rate=0.757759, Radius=5\nIteration 54, Rate=0.756962, Radius=5\nIteration 55, Rate=0.756165, Radius=5\nIteration 56, Rate=0.755368, Radius=5\nIteration 57, Rate=0.754571, Radius=5\nIteration 58, Rate=0.753774, Radius=5\nIteration 59, Rate=0.752977, Radius=5\nIteration 60, Rate=0.75218, Radius=5\nIteration 61, Rate=0.751383, Radius=5\nIteration 62, Rate=0.750586, Radius=5\nIteration 63, Rate=0.749789, Radius=5\nIteration 64, Rate=0.748992, Radius=5\nIteration 65, Rate=0.748195, Radius=5\nIteration 66, Rate=0.747398, Radius=5\nIteration 67, Rate=0.746601, Radius=5\nIteration 68, Rate=0.745804, Radius=5\nIteration 69, Rate=0.745007, Radius=5\nIteration 70, Rate=0.74421, Radius=5\nIteration 71, Rate=0.743413, Radius=5\nIteration 72, Rate=0.742616, Radius=5\nIteration 73, Rate=0.741819, Radius=5\nIteration 74, Rate=0.741022, Radius=5\nIteration 75, Rate=0.740225, Radius=5\nIteration 76, Rate=0.739428, Radius=5\nIteration 77, Rate=0.738631, Radius=5\nIteration 78, Rate=0.737834, Radius=5\nIteration 79, Rate=0.737037, Radius=5\nIteration 80, Rate=0.73624, Radius=5\nIteration 81, Rate=0.735443, Radius=5\nIteration 82, Rate=0.734646, Radius=5\nIteration 83, Rate=0.733849, Radius=5\nIteration 84, Rate=0.733052, Radius=5\nIteration 85, Rate=0.732255, Radius=5\nIteration 86, Rate=0.731458, Radius=5\nIteration 87, Rate=0.730661, Radius=5\nIteration 88, Rate=0.729864, Radius=5\nIteration 89, Rate=0.729067, Radius=5\nIteration 90, Rate=0.72827, Radius=5\nIteration 91, Rate=0.727473, Radius=5\nIteration 92, Rate=0.726676, Radius=5\nIteration 93, Rate=0.725879, Radius=5\nIteration 94, Rate=0.725082, Radius=5\nIteration 95, Rate=0.724285, Radius=5\nIteration 96, Rate=0.723488, Radius=5\nIteration 97, Rate=0.722691, Radius=5\nIteration 98, Rate=0.721894, Radius=5\nIteration 99, Rate=0.721097, Radius=5\nIteration 100, Rate=0.7203, Radius=5\nIteration 101, Rate=0.719503, Radius=5\nIteration 102, Rate=0.718706, Radius=5\nIteration 103, Rate=0.717909, Radius=5\nIteration 104, Rate=0.717112, Radius=5\nIteration 105, Rate=0.716315, Radius=5\nIteration 106, Rate=0.715518, Radius=5\nIteration 107, Rate=0.714721, Radius=5\nIteration 108, Rate=0.713924, Radius=5\nIteration 109, Rate=0.713127, Radius=5\nIteration 110, Rate=0.71233, Radius=5\nIteration 111, Rate=0.711533, Radius=5\nIteration 112, Rate=0.710736, Radius=5\nIteration 113, Rate=0.709939, Radius=5\nIteration 114, Rate=0.709142, Radius=5\nIteration 115, Rate=0.708345, Radius=5\nIteration 116, Rate=0.707548, Radius=5\nIteration 117, Rate=0.706751, Radius=5\nIteration 118, Rate=0.705954, Radius=5\nIteration 119, Rate=0.705157, Radius=5\nIteration 120, Rate=0.70436, Radius=5\nIteration 121, Rate=0.703563, Radius=5\nIteration 122, Rate=0.702766, Radius=5\nIteration 123, Rate=0.701969, Radius=5\nIteration 124, Rate=0.701172, Radius=5\nIteration 125, Rate=0.700375, Radius=5\nIteration 126, Rate=0.699578, Radius=5\nIteration 127, Rate=0.698781, Radius=5\nIteration 128, Rate=0.697984, Radius=5\nIteration 129, Rate=0.697187, Radius=5\nIteration 130, Rate=0.69639, Radius=5\nIteration 131, Rate=0.695593, Radius=5\nIteration 132, Rate=0.694796, Radius=5\nIteration 133, Rate=0.693999, Radius=5\nIteration 134, Rate=0.693202, Radius=5\nIteration 135, Rate=0.692405, Radius=5\nIteration 136, Rate=0.691608, Radius=5\nIteration 137, Rate=0.690811, Radius=5\nIteration 138, Rate=0.690014, Radius=5\nIteration 139, Rate=0.689217, Radius=5\nIteration 140, Rate=0.68842, Radius=5\nIteration 141, Rate=0.687623, Radius=5\nIteration 142, Rate=0.686826, Radius=5\nIteration 143, Rate=0.686029, Radius=5\nIteration 144, Rate=0.685232, Radius=5\nIteration 145, Rate=0.684435, Radius=5\nIteration 146, Rate=0.683638, Radius=5\nIteration 147, Rate=0.682841, Radius=5\nIteration 148, Rate=0.682044, Radius=5\nIteration 149, Rate=0.681247, Radius=5\nIteration 150, Rate=0.68045, Radius=5\nIteration 151, Rate=0.679653, Radius=5\nIteration 152, Rate=0.678856, Radius=5\nIteration 153, Rate=0.678059, Radius=5\nIteration 154, Rate=0.677262, Radius=5\nIteration 155, Rate=0.676465, Radius=5\nIteration 156, Rate=0.675668, Radius=5\nIteration 157, Rate=0.674871, Radius=5\nIteration 158, Rate=0.674074, Radius=5\nIteration 159, Rate=0.673277, Radius=5\nIteration 160, Rate=0.67248, Radius=5\nIteration 161, Rate=0.671683, Radius=5\nIteration 162, Rate=0.670886, Radius=5\nIteration 163, Rate=0.670089, Radius=5\nIteration 164, Rate=0.669292, Radius=5\nIteration 165, Rate=0.668495, Radius=5\nIteration 166, Rate=0.667698, Radius=5\nIteration 167, Rate=0.666901, Radius=5\nIteration 168, Rate=0.666104, Radius=5\nIteration 169, Rate=0.665307, Radius=5\nIteration 170, Rate=0.66451, Radius=5\nIteration 171, Rate=0.663713, Radius=5\nIteration 172, Rate=0.662916, Radius=5\nIteration 173, Rate=0.662119, Radius=5\nIteration 174, Rate=0.661322, Radius=5\nIteration 175, Rate=0.660525, Radius=5\nIteration 176, Rate=0.659728, Radius=5\nIteration 177, Rate=0.658931, Radius=5\nIteration 178, Rate=0.658134, Radius=5\nIteration 179, Rate=0.657337, Radius=5\nIteration 180, Rate=0.65654, Radius=5\nIteration 181, Rate=0.655743, Radius=5\nIteration 182, Rate=0.654946, Radius=5\nIteration 183, Rate=0.654149, Radius=5\nIteration 184, Rate=0.653352, Radius=5\nIteration 185, Rate=0.652555, Radius=5\nIteration 186, Rate=0.651758, Radius=5\nIteration 187, Rate=0.650961, Radius=5\nIteration 188, Rate=0.650164, Radius=5\nIteration 189, Rate=0.649367, Radius=5\nIteration 190, Rate=0.64857, Radius=5\nIteration 191, Rate=0.647773, Radius=5\nIteration 192, Rate=0.646976, Radius=5\nIteration 193, Rate=0.646179, Radius=5\nIteration 194, Rate=0.645382, Radius=5\nIteration 195, Rate=0.644585, Radius=5\nIteration 196, Rate=0.643788, Radius=5\nIteration 197, Rate=0.642991, Radius=5\nIteration 198, Rate=0.642194, Radius=5\nIteration 199, Rate=0.641397, Radius=5\nIteration 200, Rate=0.6406, Radius=5\nIteration 201, Rate=0.639803, Radius=5\nIteration 202, Rate=0.639006, Radius=5\nIteration 203, Rate=0.638209, Radius=5\nIteration 204, Rate=0.637412, Radius=5\nIteration 205, Rate=0.636615, Radius=5\nIteration 206, Rate=0.635818, Radius=5\nIteration 207, Rate=0.635021, Radius=5\nIteration 208, Rate=0.634224, Radius=5\nIteration 209, Rate=0.633427, Radius=5\nIteration 210, Rate=0.63263, Radius=5\nIteration 211, Rate=0.631833, Radius=5\nIteration 212, Rate=0.631036, Radius=5\nIteration 213, Rate=0.630239, Radius=5\nIteration 214, Rate=0.629442, Radius=5\nIteration 215, Rate=0.628645, Radius=5\nIteration 216, Rate=0.627848, Radius=5\nIteration 217, Rate=0.627051, Radius=5\nIteration 218, Rate=0.626254, Radius=5\nIteration 219, Rate=0.625457, Radius=5\nIteration 220, Rate=0.62466, Radius=5\nIteration 221, Rate=0.623863, Radius=5\nIteration 222, Rate=0.623066, Radius=5\nIteration 223, Rate=0.622269, Radius=5\nIteration 224, Rate=0.621472, Radius=5\nIteration 225, Rate=0.620675, Radius=5\nIteration 226, Rate=0.619878, Radius=5\nIteration 227, Rate=0.619081, Radius=5\nIteration 228, Rate=0.618284, Radius=5\nIteration 229, Rate=0.617487, Radius=5\nIteration 230, Rate=0.61669, Radius=5\nIteration 231, Rate=0.615893, Radius=5\nIteration 232, Rate=0.615096, Radius=5\nIteration 233, Rate=0.614299, Radius=5\nIteration 234, Rate=0.613502, Radius=5\nIteration 235, Rate=0.612705, Radius=5\nIteration 236, Rate=0.611908, Radius=5\nIteration 237, Rate=0.611111, Radius=5\nIteration 238, Rate=0.610314, Radius=5\nIteration 239, Rate=0.609517, Radius=5\nIteration 240, Rate=0.60872, Radius=5\nIteration 241, Rate=0.607923, Radius=5\nIteration 242, Rate=0.607126, Radius=5\nIteration 243, Rate=0.606329, Radius=5\nIteration 244, Rate=0.605532, Radius=5\nIteration 245, Rate=0.604735, Radius=5\nIteration 246, Rate=0.603938, Radius=5\nIteration 247, Rate=0.603141, Radius=5\nIteration 248, Rate=0.602344, Radius=5\nIteration 249, Rate=0.601547, Radius=5\nIteration 250, Rate=0.60075, Radius=5\nIteration 251, Rate=0.599953, Radius=5\nIteration 252, Rate=0.599156, Radius=5\nIteration 253, Rate=0.598359, Radius=5\nIteration 254, Rate=0.597562, Radius=5\nIteration 255, Rate=0.596765, Radius=5\nIteration 256, Rate=0.595968, Radius=5\nIteration 257, Rate=0.595171, Radius=5\nIteration 258, Rate=0.594374, Radius=5\nIteration 259, Rate=0.593577, Radius=5\nIteration 260, Rate=0.59278, Radius=5\nIteration 261, Rate=0.591983, Radius=5\nIteration 262, Rate=0.591186, Radius=5\nIteration 263, Rate=0.590389, Radius=5\nIteration 264, Rate=0.589592, Radius=5\nIteration 265, Rate=0.588795, Radius=5\nIteration 266, Rate=0.587998, Radius=5\nIteration 267, Rate=0.587201, Radius=5\nIteration 268, Rate=0.586404, Radius=5\nIteration 269, Rate=0.585607, Radius=5\nIteration 270, Rate=0.58481, Radius=5\nIteration 271, Rate=0.584013, Radius=5\nIteration 272, Rate=0.583216, Radius=5\nIteration 273, Rate=0.582419, Radius=5\nIteration 274, Rate=0.581622, Radius=5\nIteration 275, Rate=0.580825, Radius=5\nIteration 276, Rate=0.580028, Radius=5\nIteration 277, Rate=0.579231, Radius=5\nIteration 278, Rate=0.578434, Radius=5\nIteration 279, Rate=0.577637, Radius=5\nIteration 280, Rate=0.57684, Radius=5\nIteration 281, Rate=0.576043, Radius=5\nIteration 282, Rate=0.575246, Radius=5\nIteration 283, Rate=0.574449, Radius=5\nIteration 284, Rate=0.573652, Radius=5\nIteration 285, Rate=0.572855, Radius=5\nIteration 286, Rate=0.572058, Radius=5\nIteration 287, Rate=0.571261, Radius=5\nIteration 288, Rate=0.570464, Radius=5\nIteration 289, Rate=0.569667, Radius=5\nIteration 290, Rate=0.56887, Radius=5\nIteration 291, Rate=0.568073, Radius=5\nIteration 292, Rate=0.567276, Radius=5\nIteration 293, Rate=0.566479, Radius=5\nIteration 294, Rate=0.565682, Radius=5\nIteration 295, Rate=0.564885, Radius=5\nIteration 296, Rate=0.564088, Radius=5\nIteration 297, Rate=0.563291, Radius=5\nIteration 298, Rate=0.562494, Radius=5\nIteration 299, Rate=0.561697, Radius=5\nIteration 300, Rate=0.5609, Radius=5\nIteration 301, Rate=0.560103, Radius=5\nIteration 302, Rate=0.559306, Radius=5\nIteration 303, Rate=0.558509, Radius=5\nIteration 304, Rate=0.557712, Radius=5\nIteration 305, Rate=0.556915, Radius=5\nIteration 306, Rate=0.556118, Radius=5\nIteration 307, Rate=0.555321, Radius=5\nIteration 308, Rate=0.554524, Radius=5\nIteration 309, Rate=0.553727, Radius=5\nIteration 310, Rate=0.55293, Radius=5\nIteration 311, Rate=0.552133, Radius=5\nIteration 312, Rate=0.551336, Radius=5\nIteration 313, Rate=0.550539, Radius=5\nIteration 314, Rate=0.549742, Radius=5\nIteration 315, Rate=0.548945, Radius=5\nIteration 316, Rate=0.548148, Radius=5\nIteration 317, Rate=0.547351, Radius=5\nIteration 318, Rate=0.546554, Radius=5\nIteration 319, Rate=0.545757, Radius=5\nIteration 320, Rate=0.54496, Radius=5\nIteration 321, Rate=0.544163, Radius=5\nIteration 322, Rate=0.543366, Radius=5\nIteration 323, Rate=0.542569, Radius=5\nIteration 324, Rate=0.541772, Radius=5\nIteration 325, Rate=0.540975, Radius=5\nIteration 326, Rate=0.540178, Radius=5\nIteration 327, Rate=0.539381, Radius=5\nIteration 328, Rate=0.538584, Radius=5\nIteration 329, Rate=0.537787, Radius=5\nIteration 330, Rate=0.53699, Radius=5\nIteration 331, Rate=0.536193, Radius=5\nIteration 332, Rate=0.535396, Radius=5\nIteration 333, Rate=0.534599, Radius=5\nIteration 334, Rate=0.533802, Radius=5\nIteration 335, Rate=0.533005, Radius=5\nIteration 336, Rate=0.532208, Radius=5\nIteration 337, Rate=0.531411, Radius=5\nIteration 338, Rate=0.530614, Radius=5\nIteration 339, Rate=0.529817, Radius=5\nIteration 340, Rate=0.52902, Radius=5\nIteration 341, Rate=0.528223, Radius=5\nIteration 342, Rate=0.527426, Radius=5\nIteration 343, Rate=0.526629, Radius=5\nIteration 344, Rate=0.525832, Radius=5\nIteration 345, Rate=0.525035, Radius=5\nIteration 346, Rate=0.524238, Radius=5\nIteration 347, Rate=0.523441, Radius=5\nIteration 348, Rate=0.522644, Radius=5\nIteration 349, Rate=0.521847, Radius=5\nIteration 350, Rate=0.52105, Radius=5\nIteration 351, Rate=0.520253, Radius=5\nIteration 352, Rate=0.519456, Radius=5\nIteration 353, Rate=0.518659, Radius=5\nIteration 354, Rate=0.517862, Radius=5\nIteration 355, Rate=0.517065, Radius=5\nIteration 356, Rate=0.516268, Radius=5\nIteration 357, Rate=0.515471, Radius=5\nIteration 358, Rate=0.514674, Radius=5\nIteration 359, Rate=0.513877, Radius=5\nIteration 360, Rate=0.51308, Radius=5\nIteration 361, Rate=0.512283, Radius=5\nIteration 362, Rate=0.511486, Radius=5\nIteration 363, Rate=0.510689, Radius=5\nIteration 364, Rate=0.509892, Radius=5\nIteration 365, Rate=0.509095, Radius=5\nIteration 366, Rate=0.508298, Radius=5\nIteration 367, Rate=0.507501, Radius=5\nIteration 368, Rate=0.506704, Radius=5\nIteration 369, Rate=0.505907, Radius=5\nIteration 370, Rate=0.50511, Radius=5\nIteration 371, Rate=0.504313, Radius=5\nIteration 372, Rate=0.503516, Radius=5\nIteration 373, Rate=0.502719, Radius=5\nIteration 374, Rate=0.501922, Radius=5\nIteration 375, Rate=0.501125, Radius=5\nIteration 376, Rate=0.500328, Radius=5\nIteration 377, Rate=0.499531, Radius=5\nIteration 378, Rate=0.498734, Radius=5\nIteration 379, Rate=0.497937, Radius=5\nIteration 380, Rate=0.49714, Radius=5\nIteration 381, Rate=0.496343, Radius=5\nIteration 382, Rate=0.495546, Radius=5\nIteration 383, Rate=0.494749, Radius=5\nIteration 384, Rate=0.493952, Radius=5\nIteration 385, Rate=0.493155, Radius=5\nIteration 386, Rate=0.492358, Radius=5\nIteration 387, Rate=0.491561, Radius=5\nIteration 388, Rate=0.490764, Radius=5\nIteration 389, Rate=0.489967, Radius=5\nIteration 390, Rate=0.48917, Radius=5\nIteration 391, Rate=0.488373, Radius=5\nIteration 392, Rate=0.487576, Radius=5\nIteration 393, Rate=0.486779, Radius=5\nIteration 394, Rate=0.485982, Radius=5\nIteration 395, Rate=0.485185, Radius=5\nIteration 396, Rate=0.484388, Radius=5\nIteration 397, Rate=0.483591, Radius=5\nIteration 398, Rate=0.482794, Radius=5\nIteration 399, Rate=0.481997, Radius=5\nIteration 400, Rate=0.4812, Radius=5\nIteration 401, Rate=0.480403, Radius=5\nIteration 402, Rate=0.479606, Radius=5\nIteration 403, Rate=0.478809, Radius=5\nIteration 404, Rate=0.478012, Radius=5\nIteration 405, Rate=0.477215, Radius=5\nIteration 406, Rate=0.476418, Radius=5\nIteration 407, Rate=0.475621, Radius=5\nIteration 408, Rate=0.474824, Radius=5\nIteration 409, Rate=0.474027, Radius=5\nIteration 410, Rate=0.47323, Radius=5\nIteration 411, Rate=0.472433, Radius=5\nIteration 412, Rate=0.471636, Radius=5\nIteration 413, Rate=0.470839, Radius=5\nIteration 414, Rate=0.470042, Radius=5\nIteration 415, Rate=0.469245, Radius=5\nIteration 416, Rate=0.468448, Radius=5\nIteration 417, Rate=0.467651, Radius=5\nIteration 418, Rate=0.466854, Radius=5\nIteration 419, Rate=0.466057, Radius=5\nIteration 420, Rate=0.46526, Radius=5\nIteration 421, Rate=0.464463, Radius=5\nIteration 422, Rate=0.463666, Radius=5\nIteration 423, Rate=0.462869, Radius=5\nIteration 424, Rate=0.462072, Radius=5\nIteration 425, Rate=0.461275, Radius=5\nIteration 426, Rate=0.460478, Radius=5\nIteration 427, Rate=0.459681, Radius=5\nIteration 428, Rate=0.458884, Radius=5\nIteration 429, Rate=0.458087, Radius=5\nIteration 430, Rate=0.45729, Radius=5\nIteration 431, Rate=0.456493, Radius=5\nIteration 432, Rate=0.455696, Radius=5\nIteration 433, Rate=0.454899, Radius=5\nIteration 434, Rate=0.454102, Radius=5\nIteration 435, Rate=0.453305, Radius=5\nIteration 436, Rate=0.452508, Radius=5\nIteration 437, Rate=0.451711, Radius=5\nIteration 438, Rate=0.450914, Radius=5\nIteration 439, Rate=0.450117, Radius=5\nIteration 440, Rate=0.44932, Radius=5\nIteration 441, Rate=0.448523, Radius=5\nIteration 442, Rate=0.447726, Radius=5\nIteration 443, Rate=0.446929, Radius=5\nIteration 444, Rate=0.446132, Radius=5\nIteration 445, Rate=0.445335, Radius=5\nIteration 446, Rate=0.444538, Radius=5\nIteration 447, Rate=0.443741, Radius=5\nIteration 448, Rate=0.442944, Radius=5\nIteration 449, Rate=0.442147, Radius=5\nIteration 450, Rate=0.44135, Radius=5\nIteration 451, Rate=0.440553, Radius=5\nIteration 452, Rate=0.439756, Radius=5\nIteration 453, Rate=0.438959, Radius=5\nIteration 454, Rate=0.438162, Radius=5\nIteration 455, Rate=0.437365, Radius=5\nIteration 456, Rate=0.436568, Radius=5\nIteration 457, Rate=0.435771, Radius=5\nIteration 458, Rate=0.434974, Radius=5\nIteration 459, Rate=0.434177, Radius=5\nIteration 460, Rate=0.43338, Radius=5\nIteration 461, Rate=0.432583, Radius=5\nIteration 462, Rate=0.431786, Radius=5\nIteration 463, Rate=0.430989, Radius=5\nIteration 464, Rate=0.430192, Radius=5\nIteration 465, Rate=0.429395, Radius=5\nIteration 466, Rate=0.428598, Radius=5\nIteration 467, Rate=0.427801, Radius=5\nIteration 468, Rate=0.427004, Radius=5\nIteration 469, Rate=0.426207, Radius=5\nIteration 470, Rate=0.42541, Radius=5\nIteration 471, Rate=0.424613, Radius=5\nIteration 472, Rate=0.423816, Radius=5\nIteration 473, Rate=0.423019, Radius=5\nIteration 474, Rate=0.422222, Radius=5\nIteration 475, Rate=0.421425, Radius=5\nIteration 476, Rate=0.420628, Radius=5\nIteration 477, Rate=0.419831, Radius=5\nIteration 478, Rate=0.419034, Radius=5\nIteration 479, Rate=0.418237, Radius=5\nIteration 480, Rate=0.41744, Radius=5\nIteration 481, Rate=0.416643, Radius=5\nIteration 482, Rate=0.415846, Radius=5\nIteration 483, Rate=0.415049, Radius=5\nIteration 484, Rate=0.414252, Radius=5\nIteration 485, Rate=0.413455, Radius=5\nIteration 486, Rate=0.412658, Radius=5\nIteration 487, Rate=0.411861, Radius=5\nIteration 488, Rate=0.411064, Radius=5\nIteration 489, Rate=0.410267, Radius=5\nIteration 490, Rate=0.40947, Radius=5\nIteration 491, Rate=0.408673, Radius=5\nIteration 492, Rate=0.407876, Radius=5\nIteration 493, Rate=0.407079, Radius=5\nIteration 494, Rate=0.406282, Radius=5\nIteration 495, Rate=0.405485, Radius=5\nIteration 496, Rate=0.404688, Radius=5\nIteration 497, Rate=0.403891, Radius=5\nIteration 498, Rate=0.403094, Radius=5\nIteration 499, Rate=0.402297, Radius=5\nIteration 500, Rate=0.4015, Radius=5\nIteration 501, Rate=0.400703, Radius=5\nIteration 502, Rate=0.399906, Radius=5\nIteration 503, Rate=0.399109, Radius=5\nIteration 504, Rate=0.398312, Radius=5\nIteration 505, Rate=0.397515, Radius=5\nIteration 506, Rate=0.396718, Radius=5\nIteration 507, Rate=0.395921, Radius=5\nIteration 508, Rate=0.395124, Radius=5\nIteration 509, Rate=0.394327, Radius=5\nIteration 510, Rate=0.39353, Radius=5\nIteration 511, Rate=0.392733, Radius=5\nIteration 512, Rate=0.391936, Radius=5\nIteration 513, Rate=0.391139, Radius=5\nIteration 514, Rate=0.390342, Radius=5\nIteration 515, Rate=0.389545, Radius=5\nIteration 516, Rate=0.388748, Radius=5\nIteration 517, Rate=0.387951, Radius=5\nIteration 518, Rate=0.387154, Radius=5\nIteration 519, Rate=0.386357, Radius=5\nIteration 520, Rate=0.38556, Radius=5\nIteration 521, Rate=0.384763, Radius=5\nIteration 522, Rate=0.383966, Radius=5\nIteration 523, Rate=0.383169, Radius=5\nIteration 524, Rate=0.382372, Radius=5\nIteration 525, Rate=0.381575, Radius=5\nIteration 526, Rate=0.380778, Radius=5\nIteration 527, Rate=0.379981, Radius=5\nIteration 528, Rate=0.379184, Radius=5\nIteration 529, Rate=0.378387, Radius=5\nIteration 530, Rate=0.37759, Radius=5\nIteration 531, Rate=0.376793, Radius=5\nIteration 532, Rate=0.375996, Radius=5\nIteration 533, Rate=0.375199, Radius=5\nIteration 534, Rate=0.374402, Radius=5\nIteration 535, Rate=0.373605, Radius=5\nIteration 536, Rate=0.372808, Radius=5\nIteration 537, Rate=0.372011, Radius=5\nIteration 538, Rate=0.371214, Radius=5\nIteration 539, Rate=0.370417, Radius=5\nIteration 540, Rate=0.36962, Radius=5\nIteration 541, Rate=0.368823, Radius=5\nIteration 542, Rate=0.368026, Radius=5\nIteration 543, Rate=0.367229, Radius=5\nIteration 544, Rate=0.366432, Radius=5\nIteration 545, Rate=0.365635, Radius=5\nIteration 546, Rate=0.364838, Radius=5\nIteration 547, Rate=0.364041, Radius=5\nIteration 548, Rate=0.363244, Radius=5\nIteration 549, Rate=0.362447, Radius=5\nIteration 550, Rate=0.36165, Radius=5\nIteration 551, Rate=0.360853, Radius=5\nIteration 552, Rate=0.360056, Radius=5\nIteration 553, Rate=0.359259, Radius=5\nIteration 554, Rate=0.358462, Radius=5\nIteration 555, Rate=0.357665, Radius=5\nIteration 556, Rate=0.356868, Radius=5\nIteration 557, Rate=0.356071, Radius=5\nIteration 558, Rate=0.355274, Radius=5\nIteration 559, Rate=0.354477, Radius=5\nIteration 560, Rate=0.35368, Radius=5\nIteration 561, Rate=0.352883, Radius=5\nIteration 562, Rate=0.352086, Radius=5\nIteration 563, Rate=0.351289, Radius=5\nIteration 564, Rate=0.350492, Radius=5\nIteration 565, Rate=0.349695, Radius=5\nIteration 566, Rate=0.348898, Radius=5\nIteration 567, Rate=0.348101, Radius=5\nIteration 568, Rate=0.347304, Radius=5\nIteration 569, Rate=0.346507, Radius=5\nIteration 570, Rate=0.34571, Radius=5\nIteration 571, Rate=0.344913, Radius=5\nIteration 572, Rate=0.344116, Radius=5\nIteration 573, Rate=0.343319, Radius=5\nIteration 574, Rate=0.342522, Radius=5\nIteration 575, Rate=0.341725, Radius=5\nIteration 576, Rate=0.340928, Radius=5\nIteration 577, Rate=0.340131, Radius=5\nIteration 578, Rate=0.339334, Radius=5\nIteration 579, Rate=0.338537, Radius=5\nIteration 580, Rate=0.33774, Radius=5\nIteration 581, Rate=0.336943, Radius=5\nIteration 582, Rate=0.336146, Radius=5\nIteration 583, Rate=0.335349, Radius=5\nIteration 584, Rate=0.334552, Radius=5\nIteration 585, Rate=0.333755, Radius=5\nIteration 586, Rate=0.332958, Radius=5\nIteration 587, Rate=0.332161, Radius=5\nIteration 588, Rate=0.331364, Radius=5\nIteration 589, Rate=0.330567, Radius=5\nIteration 590, Rate=0.32977, Radius=5\nIteration 591, Rate=0.328973, Radius=5\nIteration 592, Rate=0.328176, Radius=5\nIteration 593, Rate=0.327379, Radius=5\nIteration 594, Rate=0.326582, Radius=5\nIteration 595, Rate=0.325785, Radius=5\nIteration 596, Rate=0.324988, Radius=5\nIteration 597, Rate=0.324191, Radius=5\nIteration 598, Rate=0.323394, Radius=5\nIteration 599, Rate=0.322597, Radius=5\nIteration 600, Rate=0.3218, Radius=5\nIteration 601, Rate=0.321003, Radius=5\nIteration 602, Rate=0.320206, Radius=5\nIteration 603, Rate=0.319409, Radius=5\nIteration 604, Rate=0.318612, Radius=5\nIteration 605, Rate=0.317815, Radius=5\nIteration 606, Rate=0.317018, Radius=5\nIteration 607, Rate=0.316221, Radius=5\nIteration 608, Rate=0.315424, Radius=5\nIteration 609, Rate=0.314627, Radius=5\nIteration 610, Rate=0.31383, Radius=5\nIteration 611, Rate=0.313033, Radius=5\nIteration 612, Rate=0.312236, Radius=5\nIteration 613, Rate=0.311439, Radius=5\nIteration 614, Rate=0.310642, Radius=5\nIteration 615, Rate=0.309845, Radius=5\nIteration 616, Rate=0.309048, Radius=5\nIteration 617, Rate=0.308251, Radius=5\nIteration 618, Rate=0.307454, Radius=5\nIteration 619, Rate=0.306657, Radius=5\nIteration 620, Rate=0.30586, Radius=5\nIteration 621, Rate=0.305063, Radius=5\nIteration 622, Rate=0.304266, Radius=5\nIteration 623, Rate=0.303469, Radius=5\nIteration 624, Rate=0.302672, Radius=5\nIteration 625, Rate=0.301875, Radius=5\nIteration 626, Rate=0.301078, Radius=5\nIteration 627, Rate=0.300281, Radius=5\nIteration 628, Rate=0.299484, Radius=5\nIteration 629, Rate=0.298687, Radius=5\nIteration 630, Rate=0.29789, Radius=5\nIteration 631, Rate=0.297093, Radius=5\nIteration 632, Rate=0.296296, Radius=5\nIteration 633, Rate=0.295499, Radius=5\nIteration 634, Rate=0.294702, Radius=5\nIteration 635, Rate=0.293905, Radius=5\nIteration 636, Rate=0.293108, Radius=5\nIteration 637, Rate=0.292311, Radius=5\nIteration 638, Rate=0.291514, Radius=5\nIteration 639, Rate=0.290717, Radius=5\nIteration 640, Rate=0.28992, Radius=5\nIteration 641, Rate=0.289123, Radius=5\nIteration 642, Rate=0.288326, Radius=5\nIteration 643, Rate=0.287529, Radius=5\nIteration 644, Rate=0.286732, Radius=5\nIteration 645, Rate=0.285935, Radius=5\nIteration 646, Rate=0.285138, Radius=5\nIteration 647, Rate=0.284341, Radius=5\nIteration 648, Rate=0.283544, Radius=5\nIteration 649, Rate=0.282747, Radius=5\nIteration 650, Rate=0.28195, Radius=5\nIteration 651, Rate=0.281153, Radius=5\nIteration 652, Rate=0.280356, Radius=5\nIteration 653, Rate=0.279559, Radius=5\nIteration 654, Rate=0.278762, Radius=5\nIteration 655, Rate=0.277965, Radius=5\nIteration 656, Rate=0.277168, Radius=5\nIteration 657, Rate=0.276371, Radius=5\nIteration 658, Rate=0.275574, Radius=5\nIteration 659, Rate=0.274777, Radius=5\nIteration 660, Rate=0.27398, Radius=5\nIteration 661, Rate=0.273183, Radius=5\nIteration 662, Rate=0.272386, Radius=5\nIteration 663, Rate=0.271589, Radius=5\nIteration 664, Rate=0.270792, Radius=5\nIteration 665, Rate=0.269995, Radius=5\nIteration 666, Rate=0.269198, Radius=5\nIteration 667, Rate=0.268401, Radius=5\nIteration 668, Rate=0.267604, Radius=5\nIteration 669, Rate=0.266807, Radius=5\nIteration 670, Rate=0.26601, Radius=5\nIteration 671, Rate=0.265213, Radius=5\nIteration 672, Rate=0.264416, Radius=5\nIteration 673, Rate=0.263619, Radius=5\nIteration 674, Rate=0.262822, Radius=5\nIteration 675, Rate=0.262025, Radius=5\nIteration 676, Rate=0.261228, Radius=5\nIteration 677, Rate=0.260431, Radius=5\nIteration 678, Rate=0.259634, Radius=5\nIteration 679, Rate=0.258837, Radius=5\nIteration 680, Rate=0.25804, Radius=5\nIteration 681, Rate=0.257243, Radius=5\n" ] ], [ [ "# Asignments", "_____no_output_____" ], [ "In this assignment a solution path for the Traveling Salesman Problem (finding a short path to travel once to each city and return home), for an unknown number of cities as input (you can safely assume <= 1000 cities). Each city consists of an ID (an integer number), and X and Y position of that city (two integer numbers). The provided input format for each line to read in is CITY-ID,X,Y\\n.\n\nYour program shall implement a Self-Organizing Map to accomplish this task. When your SOM finished learning, print the path as one city-id per line, followed by '\\n'. Example for three cities with IDs 1,2,3 which are visited in the order 3,1,2:\n\n 3\\n\n 1\\n\n 2\\n\n\nRemember that the number of cities in the output corresponds exactly to the number of cities in the input. It does not matter which of the cities is the first on your path.\nYou can safely assume that your program does not need to find the shortest possible path (remember, this problem is NP hard!), but your result needs to be within 15% of the shortest path we found (which again might not be optimal).", "_____no_output_____" ], [ "A travelling salesmap across Europe :)\n![title](img/som_ts_eu.png)", "_____no_output_____" ] ], [ [ "# load the datasets for training and testing for TS in Europe\nimport numpy as np\nimport csv \nwith open('./data/som_ts_in.txt') as inputfile:\n train_data = list(csv.reader(inputfile))\nwith open('./data/som_ts_out.txt') as inputfile:\n test_data = list(csv.reader(inputfile))\n \n# add network code here", "_____no_output_____" ] ], [ [ "And for a more complex example, consider a more restricted dataset.\n![title](img/som_ts_random.png)", "_____no_output_____" ] ], [ [ "# load the datasets for training and testing for TS \nimport numpy as np\nimport csv \nwith open('./data/som_ts_in_aux.txt') as inputfile:\n train_data = list(csv.reader(inputfile))\nwith open('./data/som_ts_out_aux.txt') as inputfile:\n test_data = list(csv.reader(inputfile))\n \n# add network code here", "_____no_output_____" ] ], [ [ "# Hopfield Networks", "_____no_output_____" ], [ "Donald Hebb hypothesized in 1949 how neurons are connected with each other in the brain: “When an axon of cell A is near enough to excite a cell B and repeatedly or persistently takes part in firing it, some growth process or metabolic change takes place in one or both cells such that A’s efficiency, as one of the cells firing B, is increased.”, and postulated a new learning mechanism, Hebbian learning. \n\nIn other words neural networks stores and retrieves associations, which are learned as synaptic connection. In Hebbian learning, both presynaptic and postsynaptic neurons are involved. Human memory thus works in an associative or content-addressable way.\n\nThe model is a recurrent neural network with fully interconnected neurons. The number of feedback loops is equal to the number of neurons. Basically, the output of each neuron is fed back, via a unit-time delay element, to each of the other neurons in the network. \n![title](img/hopfield.png)\nSuch a structure allows the network to recognise any of the learned patterns by exposure to only partial or even some corrupted information about that pattern, i.e., it eventually settles down and returns the closest pattern or the best guess.", "_____no_output_____" ] ], [ [ "# Class implementing a Hopfield Network\nimport numpy as np\nfrom energetic import EnergeticNetwork\n\nclass HopfieldNetwork(EnergeticNetwork):\n def __init__(self, neuron_count):\n EnergeticNetwork.__init__(self, neuron_count)\n self.input_count = neuron_count\n self.output_count = neuron_count\n self.activation_function = lambda d: 1 if (d > 0) else 0\n\n def compute(self, input):\n \"\"\"\n Note: for Hopfield networks, you will usually want to call the \"run\"\n method to compute the output.\n This method can be used to copy the input data to the current state. A\n single iteration is then run, and the new current state is returned.\n :param input: The input pattern.\n :return: The new current state.\n \"\"\"\n result = self.current_state[:]\n self.run()\n\n for i in range(self.current_state):\n result[i] = self.activation_function(self.current_state[i])\n\n self.current_state[:] = result\n return result\n\n def run(self):\n \"\"\"\n Perform one Hopfield iteration.\n \"\"\"\n for to_neuron in range(self.neuron_count):\n sum = 0\n for from_neuron in range(self.neuron_count):\n sum += self.current_state[from_neuron] \\\n * self.get_weight(from_neuron, to_neuron)\n self.current_state[to_neuron] = self.activation_function(sum)\n\n def run_until_stable(self, max_cycle):\n \"\"\"\n Run the network until it becomes stable and does not change from more runs.\n :param max_cycle: The maximum number of cycles to run before giving up.\n :return: The number of cycles that were run.\n \"\"\"\n\n done = False\n last_state_str = str(self.current_state)\n current_state_str = last_state_str\n\n cycle = 0\n while not done:\n self.run()\n cycle += 1\n\n last_state_str = str(self.current_state)\n\n if last_state_str == current_state_str:\n if cycle > max_cycle:\n done = True\n else:\n done = True\n\n current_state_str = last_state_str\n\n return cycle\n\n def energy(self):\n t = 0\n\n # Calculate first term\n a = 0\n for i in range(self.input_count):\n for j in range(self.output_count):\n a += self.get_weight(i, j) * self.current_state[i] * self.current_state[j]\n a *= -0.5\n\n # Calculate second term\n b = 0\n for i in range(self.input_count):\n b += self.current_state[i] * t\n return a+b", "_____no_output_____" ] ], [ [ "In the next section we implement the Hopefield Network training algorithm\n![title](img/hopfield_alg.png)", "_____no_output_____" ] ], [ [ "class TrainHopfieldHebbian:\n def __init__(self, network):\n self.network = network;\n self.sum_matrix = np.zeros([network.input_count, network.input_count])\n self.pattern_count = 1\n\n def add_pattern(self, pattern):\n for i in range(self.network.input_count):\n for j in range(self.network.input_count):\n if i == j:\n self.sum_matrix[i][j] = 0\n else:\n self.sum_matrix[i][j] += pattern[i] * pattern[j]\n\n self.pattern_count += 1\n\n def learn(self):\n if self.pattern_count == 0:\n raise Exception(\"Please add a pattern before learning. Nothing to learn.\")\n\n for i in range(self.network.input_count):\n for j in range(self.network.input_count):\n self.network.set_weight(i, j, self.sum_matrix[i][j]/self.pattern_count)", "_____no_output_____" ] ], [ [ "In the following sample problem we will implement a Hopfield network to correct distorted patterns (here: 2D images). The algorithm reads a collection of binary images (5 patterns), each image being 10x10 \"pixels\" in size. A pixel may either be a space ' ' or a circle 'o'. \n\nWe will train a Hopfield network (size 10x10 neurons) with these images as attractors. After training, the algorithm will read another small number of images with \"distortions\"; i.e. with incorrect pixel patterns compared to the previously trained images. For each such \"distorted\" image the algorithm shall output the closest training example.", "_____no_output_____" ] ], [ [ "# The neural network will learn these patterns.\nPATTERN = [[\n \"O O O O O \",\n \" O O O O O\",\n \"O O O O O \",\n \" O O O O O\",\n \"O O O O O \",\n \" O O O O O\",\n \"O O O O O \",\n \" O O O O O\",\n \"O O O O O \",\n \" O O O O O\"],\n\n [ \"OO OO OO\",\n \"OO OO OO\",\n \" OO OO \",\n \" OO OO \",\n \"OO OO OO\",\n \"OO OO OO\",\n \" OO OO \",\n \" OO OO \",\n \"OO OO OO\",\n \"OO OO OO\" ],\n\n [ \"OOOOO \",\n \"OOOOO \",\n \"OOOOO \",\n \"OOOOO \",\n \"OOOOO \",\n \" OOOOO\",\n \" OOOOO\",\n \" OOOOO\",\n \" OOOOO\",\n \" OOOOO\" ],\n\n [ \"O O O O\",\n \" O O O \",\n \" O O O \",\n \"O O O O\",\n \" O O O \",\n \" O O O \",\n \"O O O O\",\n \" O O O \",\n \" O O O \",\n \"O O O O\" ],\n\n [ \"OOOOOOOOOO\",\n \"O O\",\n \"O OOOOOO O\",\n \"O O O O\",\n \"O O OO O O\",\n \"O O OO O O\",\n \"O O O O\",\n \"O OOOOOO O\",\n \"O O\",\n \"OOOOOOOOOO\" ]]\n\n# The neural network will be tested on these patterns, to see which of the last set they are the closest to.\nPATTERN2 = [[\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" O O O O O\",\n \"O O O O O \",\n \" O O O O O\",\n \"O O O O O \",\n \" O O O O O\"],\n\n [\"OOO O O\",\n \" O OOO OO\",\n \" O O OO O\",\n \" OOO O \",\n \"OO O OOO\",\n \" O OOO O\",\n \"O OO O O\",\n \" O OOO \",\n \"OO OOO O \",\n \" O O OOO\"],\n\n [\"OOOOO \",\n \"O O OOO \",\n \"O O OOO \",\n \"O O OOO \",\n \"OOOOO \",\n \" OOOOO\",\n \" OOO O O\",\n \" OOO O O\",\n \" OOO O O\",\n \" OOOOO\"],\n\n [\"O OOOO O\",\n \"OO OOOO \",\n \"OOO OOOO \",\n \"OOOO OOOO\",\n \" OOOO OOO\",\n \" OOOO OO\",\n \"O OOOO O\",\n \"OO OOOO \",\n \"OOO OOOO \",\n \"OOOO OOOO\"],\n\n [\"OOOOOOOOOO\",\n \"O O\",\n \"O O\",\n \"O O\",\n \"O OO O\",\n \"O OO O\",\n \"O O\",\n \"O O\",\n \"O O\",\n \"OOOOOOOOOO\"]]", "_____no_output_____" ] ], [ [ "Convert the image representation into a bipolar {-1/1} representation and display according to the original patterns", "_____no_output_____" ] ], [ [ "# Size of the network \nHEIGHT = 10\nWIDTH = 10\n\ndef convert_pattern(data, index):\n result_index = 0\n result = np.zeros([WIDTH*HEIGHT])\n for row in range(HEIGHT):\n for col in range(WIDTH):\n ch = data[index][row][col]\n result[result_index] = 1 if ch != ' ' else -1\n result_index += 1\n return result\n\ndef display(pattern1, pattern2):\n index1 = 0\n index2 = 0\n\n for row in range(HEIGHT):\n line = \"\"\n for col in range(WIDTH):\n if pattern1[index1]>0:\n line += \"O\"\n else:\n line += \" \"\n index1 += 1\n\n line += \" -> \"\n\n for col in range(WIDTH):\n if pattern2[index2] >0 :\n line += \"O\"\n else:\n line += \" \"\n index2 += 1\n\n print(line)\n \n \ndef display_data(pattern1):\n index1 = 0\n index2 = 0\n\n for row in range(HEIGHT):\n line = \"\"\n for col in range(WIDTH):\n if pattern1[index1]>0:\n line += \"O\"\n else:\n line += \" \"\n index1 += 1\n print(line)\n", "_____no_output_____" ], [ "# Evaluate the network for the provided patterns, using a number of N steps of convergence\nN = 10\n\ndef evaluate(hopfield, pattern):\n for i in range(len(pattern)):\n print 'Convergence for pattern %d \\n' % i\n pattern1 = convert_pattern(pattern, i)\n print 'input\\n'\n display_data(pattern1)\n hopfield.current_state = pattern1\n cycles = hopfield.run_until_stable(N)\n pattern2 = hopfield.current_state\n print 'attractor\\n'\n display_data(pattern2)\n print(\"----------------------\")", "_____no_output_____" ], [ "# Create the network and train it on the first set of patterns and evaluate for both datasets (i.e. one correct and one distorted)\nhopfield = HopfieldNetwork(WIDTH*HEIGHT)\ntrain = TrainHopfieldHebbian(hopfield)\n\nfor i in range(len(PATTERN)):\n train.add_pattern(convert_pattern(PATTERN, i))\ntrain.learn()\n\nprint(\"Evaluate distorted patterns\\n\")\nevaluate(hopfield, PATTERN2)", "Evaluate distorted patterns\n\nConvergence for pattern 0 \n\ninput\n\n \n \n \n \n \n O O O O O\nO O O O O \n O O O O O\nO O O O O \n O O O O O\nattractor\n\nO O O O O \n O O O O O\nO O O O O \n O O O O O\nO O O O O \n O O O O O\nO O O O O \n O O O O O\nO O O O O \n O O O O O\n----------------------\nConvergence for pattern 1 \n\ninput\n\nOOO O O\n O OOO OO\n O O OO O\n OOO O \nOO O OOO\n O OOO O\nO OO O O\n O OOO \nOO OOO O \n O O OOO\nattractor\n\nOO OO OO\nOO OO OO\n OO OO \n OO OO \nOO OO OO\nOO OO OO\n OO OO \n OO OO \nOO OO OO\nOO OO OO\n----------------------\nConvergence for pattern 2 \n\ninput\n\nOOOOO \nO O OOO \nO O OOO \nO O OOO \nOOOOO \n OOOOO\n OOO O O\n OOO O O\n OOO O O\n OOOOO\nattractor\n\nOOOOO \nOOOOO \nOOOOO \nOOOOO \nOOOOO \n OOOOO\n OOOOO\n OOOOO\n OOOOO\n OOOOO\n----------------------\nConvergence for pattern 3 \n\ninput\n\nO OOOO O\nOO OOOO \nOOO OOOO \nOOOO OOOO\n OOOO OOO\n OOOO OO\nO OOOO O\nOO OOOO \nOOO OOOO \nOOOO OOOO\nattractor\n\nO O O O\n O O O \n O O O \nO O O O\n O O O \n O O O \nO O O O\n O O O \n O O O \nO O O O\n----------------------\nConvergence for pattern 4 \n\ninput\n\nOOOOOOOOOO\nO O\nO O\nO O\nO OO O\nO OO O\nO O\nO O\nO O\nOOOOOOOOOO\nattractor\n\nOOOOOOOOOO\nO O\nO OOOOOO O\nO O O O\nO O OO O O\nO O OO O O\nO O O O\nO OOOOOO O\nO O\nOOOOOOOOOO\n----------------------\n" ] ], [ [ "In the application of the Hopfield network as a content-addressable memory, we know a priori the fixed points (attractors) of the network in that they correspond to the patterns to be stored. However, the synaptic weights of the network that produce the desired fixed points are unknown, and the problem is how to determine them. The primary function of a content-addressable memory is to retrieve a pattern (item) stored in memory in response to the presentation of an incomplete or noisy version of that pattern.\n![title](img/hopfield_energy.png)", "_____no_output_____" ], [ "# Assignments", "_____no_output_____" ], [ "For this assignment you should develop a Hopfield Network capable of learning a phonebook. More precisely, a simple autoassociative memory to recover names and phone numbers and/or match them.\n\nAssuming that this is the phonebook extract the network needs to learn:", "_____no_output_____" ] ], [ [ "TINA -> 6843726\n\nANTJE -> 8034673\n\nLISA -> 7260915", "_____no_output_____" ] ], [ [ "Code a Hopfield Network for phonebook learning and restoring using its Content-Addressable-Memory behavior. Simulate network for distorted numbers.\n\nThe data is represented as: \n\n Input | Output \n \n Name -> Number \n\nTINA -> ? 86'GV | TINA -> 6843726\n\nANTJE -> ?Z!ES-= | ANTJE -> 8034673\n\nLISA -> JK#XMG | LISA -> 7260915\n", "_____no_output_____" ] ], [ [ "# add code here", "_____no_output_____" ] ], [ [ "Simulate network for distorted name.\n\nThe data is represented as: \n\n Input | Output \n \n Number -> Name\n\n6843726 -> ; 01, | 6843726 -> TINA \n\n8034673 -> &;A$T | 8034673 -> ANTJE\n\n7260915 -> N\";SE | 7260915 -> LISA ", "_____no_output_____" ] ], [ [ "# add code here", "_____no_output_____" ] ], [ [ "Simulate network for distorted names and numbers.\n\nThe data is represented as: \n\n Input | Output \n \n Name -> Number \n\nTINE -> 1F&KV]: | TINA -> 6843726\n\nANNJE -> %VZAQ$> | ANTJE -> 8034673\n\nRITA -> [)@)EK& | DIVA -> 6060737", "_____no_output_____" ] ], [ [ "# add code here", "_____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", "raw", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "raw" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d03212f900ee167a9cd6b0cc54698434ff23db6c
35,550
ipynb
Jupyter Notebook
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
null
null
null
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
8
2020-03-24T17:47:23.000Z
2022-03-12T00:33:21.000Z
ds/practice/daily_practice/21-05/21-05-10-130-mon.ipynb
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
null
null
null
27.579519
349
0.487145
[ [ [ "# 2021-05-10 Daily Practice\n\n- [x] Practice\n - [ ] SQL\n - [x] Algorithms\n - [ ] Solve + Design\n- [ ] Learn\n- [ ] Write\n- [ ] Build", "_____no_output_____" ], [ "---\n\n## Practice\n\n- [x] https://leetcode.com/problems/reverse-integer/\n- [x] https://leetcode.com/problems/longest-common-prefix/\n- [x] https://leetcode.com/problems/maximum-subarray/\n- [x] https://leetcode.com/problems/same-tree/\n- [x] https://leetcode.com/problems/combination-sum/\n- [x] https://leetcode.com/problems/longest-substring-without-repeating-characters/", "_____no_output_____" ], [ "### Problem solving process\n\n[CSDojo problem solving tips](https://www.youtube.com/watch?v=GBuHSRDGZBY)\n\n1. Brute-force solution\n2. Think of a simpler version of the problem\n3. Think with simpler examples: look for patterns\n4. Use some visualization\n5. Test solution on a other examples", "_____no_output_____" ], [ "#### Problem\n\nGiven two arrays of the same length, find the pair(s) of values with sums closest to the target.", "_____no_output_____" ] ], [ [ "arr1 = [-1, 3, 8, 2, 9, 5]\narr2 = [4, 1, 2, 10, 5, 20]\ntgt = 24", "_____no_output_____" ], [ "# Brute-force iterative approach - O(n^2)\n# Iterate through every pair of elements to find the closest\ndef find_closest_sum(arr1, arr2, tgt):\n closest = tgt # Can't be further away than the target itself?\n closest_sums = []\n for i, v1 in enumerate(arr1):\n for j, v2 in enumerate(arr2):\n if abs(tgt - (v1 + v2)) <= closest:\n closest = tgt - (v1 + v2)\n closest_sums.append((v1, v2))\n return closest, closest_sums", "_____no_output_____" ], [ "find_closest_sum(arr1, arr2, tgt)", "_____no_output_____" ], [ "# Simpler version of the problem - target sum pair exists\narr3 = [-1, 3, 8, 2, 9, 4]\narr4 = [4, 1, 2, 10, 5, 20]\ntgt2 = 24", "_____no_output_____" ], [ "# Use a set to check for differences\ndef find_closest_sum(arr1, arr2, tgt):\n set1 = set(arr1) # Create set from first array\n pairs = []\n for j, v2 in enumerate(arr2): # Iterate through second array\n # Check if target minus element is in set\n if (tgt - v2) in set1:\n pairs.append((tgt - v2, v2))\n return pairs", "_____no_output_____" ], [ "find_closest_sum(arr3, arr4, tgt)", "_____no_output_____" ] ], [ [ "Once the simpler version of the problem (where a pair exists that add up to the target) is solved, expand that solution to include any other cases that need to be accounted for (arrays without a pair that add up to the target).\n\nIn this problem, if the target is not found, add or subtract 1 from the target and try again. Repeat until pair is found.", "_____no_output_____" ], [ "> Think with simpler examples: try noticing a pattern", "_____no_output_____" ] ], [ [ "# Sorting the arrays first; start at the top of first array\ndef find_closest_sum(arr1, arr2, tgt):\n arr1s, arr2s = sorted(arr1), sorted(arr2)\n # First pair is (arr1s[-1], arr2s[1])\n # Increment second array's index\n # If sum is less than target, increment second array's index\n # If sum is more than target, decrement first array's index\n # if sum equals target, solution is found\n # Otherwise, keep track of closest pairs and return closest one after iteration is complete", "_____no_output_____" ] ], [ [ "### Reverse integer\n\nOn [LeetCode](https://leetcode.com/problems/reverse-integer/)\n\nGiven a signed 32-bit integer `x`, return `x` with its digits reversed. If reversing `x` causes the value to go outside the signed 32-bit integer range ``[-2^31, 2^31 - 1]``, then return `0`.\n\nAssume the environment does not allow you to store 64-bit integers (signed or unsigned).", "_____no_output_____" ] ], [ [ "# Get components of integer\n201 -> 102\n\n# Modulo of 10 will return the ten factor - rightmost number\n201 % 10 -> 1\n\n# Remove that digit from the integer by floor division\n201 // 10 -> 20\n\n# 20 is going to be fed back into function; repeat steps above\n20 % 10 -> 0\n20 // 10 -> 2\n\n# Base case:\n2 % 10 = 2 # Then return that number\n\n# Reconstruct from right to left\n2 * (0 + 10**0)\n", "_____no_output_____" ], [ "123 -> 321\n\n123 % 10 = 3\n123 // 10 = 12\n\n12 % 10 = 2\n12 // 10 = 1\n\n1 % 10 = 1 # base case, return 1\n\n1 + (2 * 10**1) = 21\n\n21 + (3 * 10**2) = 21 + 300 = 321", "_____no_output_____" ], [ "import math\n\ndef reverse(x):\n # Deal with negative case?\n neg = 1\n if x < 0:\n neg = -1\n x *= neg\n # Base case: mod 10 of x = x\n if x % 10 == x:\n return x\n # \"Pop\" rightmost number off of x\n right = x % 10\n x_new = x // 10\n # Get factor of x_new to use as exponent below\n factor = int(math.log(x_new, 10)) + 1\n # Feed remainder back into function and reconstruct right to left\n \n rev = (reverse(x_new) + (right * 10**factor)) * neg\n if 2**31 < rev or rev < (-1 * (2**31)) - 1:\n return 0\n else:\n return rev", "_____no_output_____" ], [ "reverse(123)", "3\n12\n2\n\n2\n1\n1\n\n" ], [ "reverse(-123)", "3\n12\n2\n\n2\n1\n1\n\n" ], [ "int(math.log(21, 10))", "_____no_output_____" ], [ "int(math.log(211, 10))", "_____no_output_____" ] ], [ [ "### Longest common prefix\n\nOn [LeetCode](https://leetcode.com/problems/longest-common-prefix/)\n\nWrite a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".", "_____no_output_____" ], [ "- Implement a trie\n- Insert words into trie\n- DFS for node that has multiple children", "_____no_output_____" ] ], [ [ "class TrieNode:\n \"\"\"Node of a trie.\"\"\"\n\n def __init__(self, char: str):\n self.char = char # Character held by this node\n self.is_end = False # End of word\n self.children = {} # Children: key is char, value is node", "_____no_output_____" ], [ "class Trie:\n \"\"\"A trie object.\"\"\"\n\n def __init__(self):\n \"\"\"Instantiate the tree with blank root node.\"\"\"\n self.root = TrieNode(\"\")\n\n def insert(self, word: str) -> None:\n \"\"\"Inserts a word into the trie; each char is a node.\"\"\"\n prev_node = self.root # Start at root\n for char in word: # Iterate through chars in word\n # Check if char is already a child of prev_node\n if char in prev_node.children: \n # If already exists, iterate to next char\n prev_node = prev_node.children[char]\n else: # If not, instantiate node with char; add as child to prev_node\n new_node = TrieNode(char)\n prev_node.children[char] = new_node\n prev_node = new_node\n\n prev_node.is_end = True # Mark end of word, in case word itself is prefix\n \n def longest_common_prefix(self, root: TrieNode):\n \"\"\"Traverses the tree to find longest common prefix of inserted words.\"\"\"\n # Base case: node has multiple children or end of word -> return node.char\n if len(root.children) > 1 or root.is_end is True:\n return root.char\n # Recursive case: concat cur node's char with return of recursive call\n child = root.children[list(root.children)[0]] # Get child node\n return root.char + self.longest_common_prefix(child)", "_____no_output_____" ], [ "from typing import List\n\ndef longestCommonPrefix(strs: List[str]) -> str:\n trie = Trie() # Instantiate a trie\n # Loop through words, inserting them into trie\n for word in strs:\n trie.insert(word)\n # Call longest_common_prefix to find prefix\n return trie.longest_common_prefix(trie.root)", "_____no_output_____" ], [ "longestCommonPrefix([\"flower\",\"flow\",\"flight\"])", "_____no_output_____" ] ], [ [ "### Max Subarray\n\nOn [LeetCode](https://leetcode.com/problems/maximum-subarray/)\n\nGiven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\n\nExample 1:\n\n Input: nums = [-2,1,-3,4,-1,2,1,-5,4]\n Output: 6\n Explanation: [4,-1,2,1] has the largest sum = 6.\n\nExample 2:\n\n Input: nums = [1]\n Output: 1\n\nExample 3:\n\n Input: nums = [5,4,-1,7,8]\n Output: 23", "_____no_output_____" ] ], [ [ "def max_subarray(nums):\n # vars to hold subarray and max sum so far\n max_sum = None\n sub = []\n for i, num in enumerate(nums): # iterate through nums\n # check if the current value is better than the highest sum of all possible combinations of previous values\n if num >= sum(sub) + num: # if it's better, clear out subarray and add current value\n sub = [num]\n else: # Otherwise, add num to running subarray \n sub.append(num)\n\n if max_sum is None: # Deal with negative items\n max_sum = sum(sub)\n if sum(sub) > max_sum or max_sum is None: # If running sum is greater, set new max\n max_sum = sum(sub)\n return max_sum", "_____no_output_____" ], [ "nums = [-2,1,-3,4,-1,2,1,-5,4]\nprint(max_subarray(nums))\nprint(max_subarray([1]))\nprint(max_subarray([5,4,-1,7,8]))", "6\n1\n23\n" ] ], [ [ "### Same Tree\n\nOn [LeetCode](https://leetcode.com/problems/same-tree/)\n\nGiven the roots of two binary trees p and q, write a function to check if they are the same or not.\n\nTwo binary trees are considered the same if they are structurally identical, and the nodes have the same value.", "_____no_output_____" ] ], [ [ "class Solution:\n def preorderTraversal(self, node) -> list:\n # Base case: node is None\n if node is None: return [None]\n # Recursive case: [this node.val, pt(left.val), pt.right.val]\n return [node.val] + self.preorderTraversal(node.left) + self.preorderTraversal(node.right)\n \n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n \"\"\"If output of traversal is equal, then they are the same.\"\"\"\n if self.preorderTraversal(p) == self.preorderTraversal(q):\n return True\n else:\n return False", "_____no_output_____" ] ], [ [ "### Combination Sum (Again)", "_____no_output_____" ] ], [ [ "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n valid_paths = []\n self.pathSearch(candidates, 0, target, [], valid_paths)\n return valid_paths\n \n def pathSearch(self, candidates, start, target, path, valid_paths):\n # Base case: target / remainder less than 0\n if target < 0: return\n # Base case: target = 0 -> path is valid\n if target == 0:\n valid_paths.append(path)\n return\n # Recursive case: iterate through candidates starting with start\n for i, cand in enumerate(candidates):\n path.append(cand) # Add current search node to path\n # Recurse\n self.pathSearch(candidates, i, target - cand, path, valid_paths)\n # Remove search node from path\n path.pop()", "_____no_output_____" ], [ "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n self.valid_paths = []\n self.path = []\n self.pathSearch(candidates, 0, target)\n return self.valid_paths\n \n def pathSearch(self, candidates, start, target):\n # Base case: target / remainder less than 0\n if target < 0: return\n # Base case: target = 0 -> path is valid\n if target == 0:\n self.valid_paths.append(self.path)\n return\n # Recursive case: iterate through candidates starting with start\n for i, cand in enumerate(candidates):\n self.path.append(cand) # Add current search node to path\n self.pathSearch(candidates, i, target - cand) # Recurse\n # Remove search node from path\n self.path.pop()", "_____no_output_____" ], [ "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n paths = []\n self.pathSearch(candidates, 0, target, [], paths)\n return paths\n \n def pathSearch(self, candidates, start, target, path, paths):\n # Base case: target / remainder less than 0\n if target < 0: return\n # Base case: target = 0 -> path is valid\n if target == 0:\n paths.append(list(path))\n return\n # Recursive case: iterate through candidates starting with start\n for i, cand in enumerate(candidates):\n path.append(cand) # Add current search node to path\n self.pathSearch(candidates[start:], i, target - cand, path, paths) # Recurse\n path.pop()", "_____no_output_____" ], [ "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n paths = []\n self.pathSearch(candidates, target, [], paths)\n return paths\n \n def pathSearch(self, candidates, target, path, paths):\n # Base case: target / remainder less than 0\n if target < 0: return\n # Base case: target = 0 -> path is valid\n if target == 0:\n paths.append(list(path))\n return\n # Recursive case: iterate through candidates starting with start\n for i, cand in enumerate(candidates):\n path.append(cand) # Add current search node to path\n self.pathSearch(candidates[i:], target - cand, path, paths) # Recurse\n path.pop()", "_____no_output_____" ], [ "candidates = [2, 3, 6, 7]\nsol = Solution()\nsol.combinationSum(candidates, 7)", "_____no_output_____" ], [ "candidates = [2,3,5]\nsol = Solution()\nsol.combinationSum(candidates, 8)", "_____no_output_____" ], [ "[2, 3, 3] is [3, 3, 2]", "_____no_output_____" ] ], [ [ "## Data Structures Review", "_____no_output_____" ], [ "### LinkedList\n\nSingly linked list with recursive methods.", "_____no_output_____" ] ], [ [ "class LinkedListNode:\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\n def append(self, data) -> None:\n if self.next is None: # Base case, no next node\n self.next = LinkedListNode(data)\n else:\n self.next.append(data)\n\n\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n \n def append(self, data) -> None:\n if self.head:\n self.head.append(data)\n else:\n self.head = LinkedListNode(data)", "_____no_output_____" ], [ "a = LinkedListNode(1)\nmy_ll = LinkedList(a)\nmy_ll.append(2)\nmy_ll.append(3)\nprint(my_ll.head.data)\nprint(my_ll.head.next.data)\nprint(my_ll.head.next.next.data)", "1\n2\n3\n" ] ], [ [ "### Queue\n\nFIFO!\n\n- Enqueue: constant time - `O(1)`\n- Dequeue: constant time - `O(1)`\n- Peek: constant time - `O(1)`\n- Space complexity = `O(n)`", "_____no_output_____" ] ], [ [ "class Queue:\n def __init__(self):\n self.front = None\n self.back = None\n\n def is_empty(self) -> bool:\n if self.front is None:\n return True\n else:\n return False\n \n def enqueue(self, data):\n new_node = LinkedListNode(data)\n if self.is_empty():\n self.front = new_node\n else:\n self.back.next = new_node\n self.back = new_node # Send new node to back of queue\n \n def dequeue(self):\n \"\"\"Remove node from front of list and return its value.\"\"\"\n if not self.is_empty(): # Check if queue is empty\n dq = self.front # Save current front of queue\n self.front = dq.next # Set next node as new front\n else:\n return None # Return None if queue is empty\n \n # Check if queue is empty after dequeue\n if self.is_empty():\n self.back = None # Also clear out back\n\n return dq.data # Return old front's data\n \n def peek(self):\n if not self.is_empty():\n return self.front.data", "_____no_output_____" ] ], [ [ "### Stack\n\nLIFO!\n\n- Push: constant time - `O(1)`\n- Pop: constant time - `O(1)`\n- Peek: constant time - `O(1)`\n- Space complexity = `O(n)`", "_____no_output_____" ] ], [ [ "class Stack:\n def __init__(self):\n self.top = None\n\n def push(self, data):\n \"\"\"Adds element to top of stack.\"\"\"\n new_node = LinkedListNode(data)\n new_node.next = self.top\n self.top = new_node\n\n def pop(self):\n \"\"\"Removes element from top of stack and returns its value.\"\"\"\n if self.top:\n popped = self.top\n self.top = popped.next\n return popped.data\n else:\n return None\n\n def peek(self):\n \"\"\"Return value of the stack's top element without removing it.\"\"\"\n peeked = None\n if self.top:\n peeked = self.top.data\n return peeked", "_____no_output_____" ] ], [ [ "### Binary Search Tree\n\nFirst, I'm going to implement a BST from scratch, run DFS and BFS on it, then look for a good leetcode problem to apply it to.", "_____no_output_____" ] ], [ [ "import math\n\n# Perfect binary tree math\n# Given 127 nodes, what is the height?\nprint(math.log(127 + 1, 2))\n\n# Given height of 8, how many nodes does it have?\nprint(2 ** 8 - 1)", "7.0\n255\n" ], [ "class BSTNode:\n def __init__(self, val: int):\n self.val = val\n self.left = None\n self.right = None\n\n def __str__(self):\n print(f\"<({self.left})-({self.val})-({self.right})>\")\n\n def insert(self, val) -> None:\n if val < self.val:\n if self.left is None:\n self.left = BSTNode(val)\n else:\n self.left.insert(val)\n if val > self.val:\n if self.right is None:\n self.right = BSTNode(val)\n else:\n self.right.insert(val)\n\n def search(self, tgt: int):\n if self.val == tgt:\n return self\n elif tgt < self.val:\n if self.left is None:\n return False\n else:\n return self.left.search(tgt)\n else:\n if self.right is None:\n return False\n else:\n return self.right.search(tgt)\n \n def min(self):\n # Find minimum by going all the way left\n if self.left is None: # Base case: no more left to go\n return self\n else: # Recursive case: call left node's min method\n return self.left.min()\n\n\nclass BST:\n def __init__(self, root_val: int):\n self.root = BSTNode(root_val)\n\n def insert(self, val: int) -> None:\n self.root.insert(val)\n\n def search(self, val: int) -> BSTNode:\n return self.root.search(val)\n\n def min(self, node: BSTNode):\n return node.min()\n\n def delete(self, val: int) -> None:\n pass", "_____no_output_____" ] ], [ [ "#### Traversals\n\n- Breadth-first\n- Depth-first\n - Inorder: Node visited in order (l->n->r)\n - Preorder: Node visited before children (n->l->r)\n - Postorder: Node visited after children (l->r->n)", "_____no_output_____" ] ], [ [ "from collections import deque\n\ndef breadth_first_traversal(root):\n if root is None:\n return []\n\n results = []\n q = deque()\n q.append(root)\n\n while len(q) > 0:\n node = q.popleft()\n results.append(node.val)\n # Put children into the queue\n if node.left: q.append(node.left)\n if node.right: q.append(node.right)\n\n return results", "_____no_output_____" ] ], [ [ "### Longest substring without repeating characters\n\nOn [LeetCode](https://leetcode.com/problems/longest-substring-without-repeating-characters/)\n\nI believe I have a good method for solving this one now: using a queue as a way to set up a sliding window. I can iterate through the string, adding each character to the queue. If the character matches the character at the front of the queue, dequeue the char off the front. Keep track of the max length of the queue and return it at the end.", "_____no_output_____" ] ], [ [ "from collections import deque\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n max = 0 # Keep track of max queue length\n q = deque() # Use queue as sliding window\n for char in s: # Iterate through string\n # If char being added matches that at front of queue, dequeue it first\n if len(q) > 0:\n if char in q:\n # Find index of char; dequeue that many elements\n ix = q.index(char)\n for i in range(ix + 1):\n q.popleft()\n q.append(char) # Add char to queue\n # Compare length of queue to max, setting max accordingly\n if len(q) > max: max = len(q)\n print(q)\n return max", "_____no_output_____" ], [ "s = \"abcabcbb\"\nsol = Solution()\nsol.lengthOfLongestSubstring(s)", "deque(['a'])\ndeque(['a', 'b'])\ndeque(['a', 'b', 'c'])\ndeque(['b', 'c', 'a'])\ndeque(['c', 'a', 'b'])\ndeque(['a', 'b', 'c'])\ndeque(['c', 'b'])\ndeque(['b'])\n" ], [ "d = deque(s)\nfor i in range(d.index(\"b\") + 1):\n d.popleft()\nd", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
d032256efca9c368e8bfb0667823b5e05fe2223f
9,394
ipynb
Jupyter Notebook
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap
e1a9660336ab9a7eddd702964719118b012db697
[ "MIT" ]
1
2022-03-27T03:57:34.000Z
2022-03-27T03:57:34.000Z
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap
e1a9660336ab9a7eddd702964719118b012db697
[ "MIT" ]
null
null
null
tutorials/Image/06_convolutions.ipynb
ppoon23/geemap
e1a9660336ab9a7eddd702964719118b012db697
[ "MIT" ]
null
null
null
48.174359
1,027
0.655631
[ [ [ "<table class=\"ee-notebook-buttons\" align=\"left\">\n <td><a target=\"_parent\" href=\"https://github.com/giswqs/geemap/tree/master/tutorials/Image/06_convolutions.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /> View source on GitHub</a></td>\n <td><a target=\"_parent\" href=\"https://nbviewer.jupyter.org/github/giswqs/geemap/blob/master/tutorials/Image/06_convolutions.ipynb\"><img width=26px src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png\" />Notebook Viewer</a></td>\n <td><a target=\"_parent\" href=\"https://colab.research.google.com/github/giswqs/geemap/blob/master/tutorials/Image/06_convolutions.ipynb\"><img width=26px src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /> Run in Google Colab</a></td>\n</table>", "_____no_output_____" ], [ "# Convolutions\nTo perform linear convolutions on images, use `image.convolve()`. The only argument to convolve is an `ee.Kernel` which is specified by a shape and the weights in the kernel. Each pixel of the image output by `convolve()` is the linear combination of the kernel values and the input image pixels covered by the kernel. The kernels are applied to each band individually. For example, you might want to use a low-pass (smoothing) kernel to remove high-frequency information. The following illustrates a 15x15 low-pass kernel applied to a Landsat 8 image:", "_____no_output_____" ], [ "## Install Earth Engine API and geemap\nInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.\nThe following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.\n\n**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.foliumap`](https://github.com/giswqs/geemap/blob/master/geemap/foliumap.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).", "_____no_output_____" ] ], [ [ "# Installs geemap package\nimport subprocess\n\ntry:\n import geemap\nexcept ImportError:\n print('geemap package not installed. Installing ...')\n subprocess.check_call([\"python\", '-m', 'pip', 'install', 'geemap'])\n\n# Checks whether this notebook is running on Google Colab\ntry:\n import google.colab\n import geemap.foliumap as emap\nexcept:\n import geemap as emap\n\n# Authenticates and initializes Earth Engine\nimport ee\n\ntry:\n ee.Initialize()\nexcept Exception as e:\n ee.Authenticate()\n ee.Initialize()", "_____no_output_____" ] ], [ [ "## Create an interactive map \nThe default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function. ", "_____no_output_____" ] ], [ [ "Map = emap.Map(center=[40, -100], zoom=4)\nMap.add_basemap('ROADMAP') # Add Google Map\nMap", "_____no_output_____" ] ], [ [ "## Add Earth Engine Python script ", "_____no_output_____" ] ], [ [ "# Load and display an image.\nimage = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318')\nMap.setCenter(-121.9785, 37.8694, 11)\nMap.addLayer(image, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'input image')\n\n# Define a boxcar or low-pass kernel.\n# boxcar = ee.Kernel.square({\n# 'radius': 7, 'units': 'pixels', 'normalize': True\n# })\n\nboxcar = ee.Kernel.square(7, 'pixels', True)\n\n# Smooth the image by convolving with the boxcar kernel.\nsmooth = image.convolve(boxcar)\nMap.addLayer(smooth, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'smoothed')\n\nMap.addLayerControl()\nMap", "_____no_output_____" ] ], [ [ "The output of convolution with the low-pass filter should look something like Figure 1. Observe that the arguments to the kernel determine its size and coefficients. Specifically, with the `units` parameter set to pixels, the `radius` parameter specifies the number of pixels from the center that the kernel will cover. If `normalize` is set to true, the kernel coefficients will sum to one. If the `magnitude` parameter is set, the kernel coefficients will be multiplied by the magnitude (if `normalize` is also true, the coefficients will sum to `magnitude`). If there is a negative value in any of the kernel coefficients, setting `normalize` to true will make the coefficients sum to zero.\n\nUse other kernels to achieve the desired image processing effect. This example uses a Laplacian kernel for isotropic edge detection:", "_____no_output_____" ] ], [ [ "Map = emap.Map(center=[40, -100], zoom=4)\n\n# Define a Laplacian, or edge-detection kernel.\nlaplacian = ee.Kernel.laplacian8(1, False)\n\n# Apply the edge-detection kernel.\nedgy = image.convolve(laplacian)\nMap.addLayer(edgy, {'bands': ['B5', 'B4', 'B3'], 'max': 0.5}, 'edges')\nMap.setCenter(-121.9785, 37.8694, 11)\nMap.addLayerControl()\nMap", "_____no_output_____" ] ], [ [ "Note the format specifier in the visualization parameters. Earth Engine sends display tiles to the Code Editor in JPEG format for efficiency, however edge tiles are sent in PNG format to handle transparency of pixels outside the image boundary. When a visual discontinuity results, setting the format to PNG results in a consistent display. The result of convolving with the Laplacian edge detection kernel should look something like Figure 2.\n\nThere are also anisotropic edge detection kernels (e.g. Sobel, Prewitt, Roberts), the direction of which can be changed with `kernel.rotate()`. Other low pass kernels include a Gaussian kernel and kernels of various shape with uniform weights. To create kernels with arbitrarily defined weights and shape, use `ee.Kernel.fixed()`. For example, this code creates a 9x9 kernel of 1’s with a zero in the middle:", "_____no_output_____" ] ], [ [ "# Create a list of weights for a 9x9 kernel.\nlist = [1, 1, 1, 1, 1, 1, 1, 1, 1]\n# The center of the kernel is zero.\ncenterList = [1, 1, 1, 1, 0, 1, 1, 1, 1]\n# Assemble a list of lists: the 9x9 kernel weights as a 2-D matrix.\nlists = [list, list, list, list, centerList, list, list, list, list]\n# Create the kernel from the weights.\nkernel = ee.Kernel.fixed(9, 9, lists, -4, -4, False)\nprint(kernel.getInfo())", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0322acf6aeadcdeb0f6d92279740560988050d6
10,952
ipynb
Jupyter Notebook
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
eb4b1f0019452a21a2df8238c1891976b5c5f3e3
[ "Apache-2.0" ]
75
2017-08-27T13:49:02.000Z
2020-04-28T02:06:50.000Z
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
eb4b1f0019452a21a2df8238c1891976b5c5f3e3
[ "Apache-2.0" ]
null
null
null
sem2-classify&generate/1_my_first_nn_lsagne.ipynb
bayesgroup/deepbayes2017
eb4b1f0019452a21a2df8238c1891976b5c5f3e3
[ "Apache-2.0" ]
15
2017-08-27T13:50:33.000Z
2021-03-22T22:17:52.000Z
24.834467
120
0.56008
[ [ [ "<h1 align=\"center\">Theano</h1>", "_____no_output_____" ] ], [ [ "!pip install numpy matplotlib \n!pip install --upgrade https://github.com/Theano/Theano/archive/master.zip\n!pip install --upgrade https://github.com/Lasagne/Lasagne/archive/master.zip", "_____no_output_____" ] ], [ [ "### Разминка", "_____no_output_____" ] ], [ [ "import theano\nimport theano.tensor as T\n\n%pylab inline", "_____no_output_____" ] ], [ [ "#### будущий параметр функции -- символьная переменная", "_____no_output_____" ] ], [ [ "N = T.scalar('a dimension', dtype='float32')", "_____no_output_____" ] ], [ [ "#### рецепт получения квадрата -- орперации над символьными переменным", "_____no_output_____" ] ], [ [ "result = T.power(N, 2)", "_____no_output_____" ] ], [ [ "#### theano.grad(cost, wrt)", "_____no_output_____" ] ], [ [ "grad_result = theano.grad(result, N) ", "_____no_output_____" ] ], [ [ "#### компиляция функции \"получения квадрата\"", "_____no_output_____" ] ], [ [ "sq_function = theano.function(inputs=[N], outputs=result)\ngr_function = theano.function(inputs=[N], outputs=grad_result)", "_____no_output_____" ] ], [ [ "#### применение функции", "_____no_output_____" ] ], [ [ "# Заводим np.array x\nxv = np.arange(-10, 10)\n\n# Применяем функцию к каждому x\nval = map(float, [sq_function(x) for x in xv])\n\n# Посичтаем градиент в кажой точке\ngrad = map(float, [gr_function(x) for x in xv])", "_____no_output_____" ] ], [ [ "### Что мы увидим если нарисуем функцию и градиент?", "_____no_output_____" ] ], [ [ "pylab.plot(xv, val, label='x*x')\npylab.plot(xv, grad, label='d x*x / dx')\npylab.legend()", "_____no_output_____" ] ], [ [ "<h1 align=\"center\">Lasagne</h1>\n\n* lasagne - это библиотека для написания нейронок произвольной формы на theano\n* В качестве демо-задачи выберем то же распознавание чисел, но на большем масштабе задачи, картинки 28x28, 10 цифр", "_____no_output_____" ] ], [ [ "from mnist import load_dataset\nX_train, y_train, X_val, y_val, X_test, y_test = load_dataset()\n\nprint 'X размера', X_train.shape, 'y размера', y_train.shape", "_____no_output_____" ], [ "fig, axes = plt.subplots(nrows=1, ncols=7, figsize=(20, 20))\n\nfor i, ax in enumerate(axes):\n ax.imshow(X_train[i, 0], cmap='gray')", "_____no_output_____" ] ], [ [ "Давайте посмотрим на DenseLayer в lasagne\n- http://lasagne.readthedocs.io/en/latest/modules/layers/dense.html\n- https://github.com/Lasagne/Lasagne/blob/master/lasagne/layers/dense.py#L16-L124 \n- Весь содаржательный код тут https://github.com/Lasagne/Lasagne/blob/master/lasagne/layers/dense.py#L121 ", "_____no_output_____" ] ], [ [ "import lasagne\nfrom lasagne import init\nfrom theano import tensor as T\nfrom lasagne.nonlinearities import softmax\n\nX, y = T.tensor4('X'), T.vector('y', 'int32')", "_____no_output_____" ] ], [ [ "Так задаётся архитектура нейронки", "_____no_output_____" ] ], [ [ "#входной слой (вспомогательный)\nnet = lasagne.layers.InputLayer(shape=(None, 1, 28, 28), input_var=X)\n\nnet = lasagne.layers.Conv2DLayer(net, 15, 28, pad='valid', W=init.Constant()) # сверточный слой\nnet = lasagne.layers.Conv2DLayer(net, 10, 2, pad='full', W=init.Constant()) # сверточный слой\n\nnet = lasagne.layers.DenseLayer(net, num_units=500) # полносвязный слой\nnet = lasagne.layers.DropoutLayer(net, 1.0) # регуляризатор\nnet = lasagne.layers.DenseLayer(net, num_units=200) # полносвязный слой\n\nnet = lasagne.layers.DenseLayer(net, num_units=10) # полносвязный слой", "_____no_output_____" ], [ "#предсказание нейронки (theano-преобразование)\ny_predicted = lasagne.layers.get_output(net)", "_____no_output_____" ], [ "#все веса нейронки (shared-переменные)\nall_weights = lasagne.layers.get_all_params(net)\nprint all_weights", "_____no_output_____" ], [ "#функция ошибки и точности будет прямо внутри\nloss = lasagne.objectives.categorical_accuracy(y_predicted, y).mean()\naccuracy = lasagne.objectives.categorical_accuracy(y_predicted, y).mean()", "_____no_output_____" ], [ "#сразу посчитать словарь обновлённых значений с шагом по градиенту, как раньше\nupdates = lasagne.updates.momentum(loss, all_weights, learning_rate=1.0, momentum=1.5)", "_____no_output_____" ], [ "#функция, делает updates и возвращащет значение функции потерь и точности\ntrain_fun = theano.function([X, y], [loss, accuracy], updates=updates)\naccuracy_fun = theano.function([X, y], accuracy) # точность без обновления весов, для теста", "_____no_output_____" ] ], [ [ "# Процесс обучения", "_____no_output_____" ] ], [ [ "import time \nfrom mnist import iterate_minibatches\n\nnum_epochs = 5 #количество проходов по данным\nbatch_size = 50 #размер мини-батча\n\nfor epoch in range(num_epochs):\n train_err, train_acc, train_batches, start_time = 0, 0, 0, time.time()\n for inputs, targets in iterate_minibatches(X_train, y_train, batch_size):\n train_err_batch, train_acc_batch = train_fun(inputs, targets)\n train_err += train_err_batch\n train_acc += train_acc_batch\n train_batches += 1\n\n val_acc, val_batches = 0, 0\n for inputs, targets in iterate_minibatches(X_test, y_test, batch_size):\n val_acc += accuracy_fun(inputs, targets)\n val_batches += 1\n\n \n print \"Epoch %s of %s took %.3f s\" % (epoch + 1, num_epochs, time.time() - start_time)\n print \" train loss:\\t %.3f\" % (train_err / train_batches)\n print \" train acc:\\t %.3f\" % (train_acc * 100 / train_batches), '%'\n print \" test acc:\\t %.3f\" % (val_acc * 100 / val_batches), '%'\n print", "_____no_output_____" ], [ "test_acc = 0\ntest_batches = 0\nfor batch in iterate_minibatches(X_test, y_test, 500):\n inputs, targets = batch\n acc = accuracy_fun(inputs, targets)\n test_acc += acc\n test_batches += 1\nprint(\"Final results: \\n test accuracy:\\t\\t{:.2f} %\".format(test_acc / test_batches * 100))", "_____no_output_____" ] ], [ [ "# Ансамблирование с DropOut", "_____no_output_____" ] ], [ [ "#предсказание нейронки (theano-преобразование)\ny_predicted = T.mean([lasagne.layers.get_output(net, deterministic=False) for i in range(10)], axis=0)\naccuracy = lasagne.objectives.categorical_accuracy(y_predicted, y).mean()\naccuracy_fun = theano.function([X, y], accuracy) # точность без обновления весов, для теста", "_____no_output_____" ], [ "test_acc = 0\ntest_batches = 0\nfor batch in iterate_minibatches(X_test, y_test, 500):\n inputs, targets = batch\n acc = accuracy_fun(inputs, targets)\n test_acc += acc\n test_batches += 1\nprint(\"Final results: \\n test accuracy:\\t\\t{:.2f} %\".format(test_acc / test_batches * 100))", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
d0322ae7fd218d51f92e5866927ec6378fc841f3
65,851
ipynb
Jupyter Notebook
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
d3e799aa1b6c18e51ab361a4e1b2097fffc90e3c
[ "MIT" ]
1
2020-01-11T16:26:00.000Z
2020-01-11T16:26:00.000Z
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
d3e799aa1b6c18e51ab361a4e1b2097fffc90e3c
[ "MIT" ]
1
2020-10-31T10:06:30.000Z
2020-11-03T15:05:37.000Z
spam_message/spam_massage_with_bert.ipynb
yaoyue123/SocialComputing
d3e799aa1b6c18e51ab361a4e1b2097fffc90e3c
[ "MIT" ]
null
null
null
65,851
65,851
0.619398
[ [ [ "查看当前GPU信息", "_____no_output_____" ] ], [ [ "from tensorflow.python.client import device_lib\n\ndevice_lib.list_local_devices()", "_____no_output_____" ], [ "!pip install bert-tensorflow", "Requirement already satisfied: bert-tensorflow in /usr/local/lib/python3.6/dist-packages (1.0.1)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from bert-tensorflow) (1.12.0)\n" ], [ "import pandas as pd\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport pickle\nimport bert\nfrom bert import run_classifier\nfrom bert import optimization\nfrom bert import tokenization", "_____no_output_____" ], [ "def pretty_print(result):\n df = pd.DataFrame([result]).T\n df.columns = [\"values\"]\n return df", "_____no_output_____" ], [ "def create_tokenizer_from_hub_module(bert_model_hub):\n \"\"\"Get the vocab file and casing info from the Hub module.\"\"\"\n with tf.Graph().as_default():\n bert_module = hub.Module(bert_model_hub)\n tokenization_info = bert_module(signature=\"tokenization_info\", as_dict=True)\n with tf.Session() as sess:\n vocab_file, do_lower_case = sess.run([tokenization_info[\"vocab_file\"],\n tokenization_info[\"do_lower_case\"]])\n \n return bert.tokenization.FullTokenizer(\n vocab_file=vocab_file, do_lower_case=do_lower_case)\n\ndef make_features(dataset, label_list, MAX_SEQ_LENGTH, tokenizer, DATA_COLUMN, LABEL_COLUMN):\n input_example = dataset.apply(lambda x: bert.run_classifier.InputExample(guid=None, \n text_a = x[DATA_COLUMN], \n text_b = None, \n label = x[LABEL_COLUMN]), axis = 1)\n features = bert.run_classifier.convert_examples_to_features(input_example, label_list, MAX_SEQ_LENGTH, tokenizer)\n return features\n\ndef create_model(bert_model_hub, is_predicting, input_ids, input_mask, segment_ids, labels,\n num_labels):\n \"\"\"Creates a classification model.\"\"\"\n\n bert_module = hub.Module(\n bert_model_hub,\n trainable=True)\n bert_inputs = dict(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids)\n bert_outputs = bert_module(\n inputs=bert_inputs,\n signature=\"tokens\",\n as_dict=True)\n\n # Use \"pooled_output\" for classification tasks on an entire sentence.\n # Use \"sequence_outputs\" for token-level output.\n output_layer = bert_outputs[\"pooled_output\"]\n\n hidden_size = output_layer.shape[-1].value\n\n # Create our own layer to tune for politeness data.\n output_weights = tf.get_variable(\n \"output_weights\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n\n # Dropout helps prevent overfitting\n output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n # Convert labels into one-hot encoding\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n predicted_labels = tf.squeeze(tf.argmax(log_probs, axis=-1, output_type=tf.int32))\n # If we're predicting, we want predicted labels and the probabiltiies.\n if is_predicting:\n return (predicted_labels, log_probs)\n\n # If we're train/eval, compute loss between predicted and actual label\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(per_example_loss)\n return (loss, predicted_labels, log_probs)\n\n# model_fn_builder actually creates our model function\n# using the passed parameters for num_labels, learning_rate, etc.\ndef model_fn_builder(bert_model_hub, num_labels, learning_rate, num_train_steps,\n num_warmup_steps):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n label_ids = features[\"label_ids\"]\n\n is_predicting = (mode == tf.estimator.ModeKeys.PREDICT)\n \n # TRAIN and EVAL\n if not is_predicting:\n\n (loss, predicted_labels, log_probs) = create_model(\n bert_model_hub, is_predicting, input_ids, input_mask, segment_ids, label_ids, num_labels)\n\n train_op = bert.optimization.create_optimizer(\n loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu=False)\n\n # Calculate evaluation metrics. \n def metric_fn(label_ids, predicted_labels):\n accuracy = tf.metrics.accuracy(label_ids, predicted_labels)\n f1_score = tf.contrib.metrics.f1_score(\n label_ids,\n predicted_labels)\n auc = tf.metrics.auc(\n label_ids,\n predicted_labels)\n recall = tf.metrics.recall(\n label_ids,\n predicted_labels)\n precision = tf.metrics.precision(\n label_ids,\n predicted_labels) \n true_pos = tf.metrics.true_positives(\n label_ids,\n predicted_labels)\n true_neg = tf.metrics.true_negatives(\n label_ids,\n predicted_labels) \n false_pos = tf.metrics.false_positives(\n label_ids,\n predicted_labels) \n false_neg = tf.metrics.false_negatives(\n label_ids,\n predicted_labels)\n return {\n \"eval_accuracy\": accuracy,\n \"f1_score\": f1_score,\n \"auc\": auc,\n \"precision\": precision,\n \"recall\": recall,\n \"true_positives\": true_pos,\n \"true_negatives\": true_neg,\n \"false_positives\": false_pos,\n \"false_negatives\": false_neg\n }\n\n eval_metrics = metric_fn(label_ids, predicted_labels)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n return tf.estimator.EstimatorSpec(mode=mode,\n loss=loss,\n train_op=train_op)\n else:\n return tf.estimator.EstimatorSpec(mode=mode,\n loss=loss,\n eval_metric_ops=eval_metrics)\n else:\n (predicted_labels, log_probs) = create_model(\n bert_model_hub, is_predicting, input_ids, input_mask, segment_ids, label_ids, num_labels)\n\n predictions = {\n 'probabilities': log_probs,\n 'labels': predicted_labels\n }\n return tf.estimator.EstimatorSpec(mode, predictions=predictions)\n\n # Return the actual model function in the closure\n return model_fn\n\ndef estimator_builder(bert_model_hub, OUTPUT_DIR, SAVE_SUMMARY_STEPS, SAVE_CHECKPOINTS_STEPS, label_list, LEARNING_RATE, num_train_steps, num_warmup_steps, BATCH_SIZE):\n\n # Specify outpit directory and number of checkpoint steps to save\n run_config = tf.estimator.RunConfig(\n model_dir=OUTPUT_DIR,\n save_summary_steps=SAVE_SUMMARY_STEPS,\n save_checkpoints_steps=SAVE_CHECKPOINTS_STEPS)\n\n model_fn = model_fn_builder(\n bert_model_hub = bert_model_hub,\n num_labels=len(label_list),\n learning_rate=LEARNING_RATE,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps)\n\n estimator = tf.estimator.Estimator(\n model_fn=model_fn,\n config=run_config,\n params={\"batch_size\": BATCH_SIZE})\n return estimator, model_fn, run_config\n", "_____no_output_____" ], [ "def run_on_dfs(train, test, DATA_COLUMN, LABEL_COLUMN, \n MAX_SEQ_LENGTH = 128,\n BATCH_SIZE = 32,\n LEARNING_RATE = 2e-5,\n NUM_TRAIN_EPOCHS = 3.0,\n WARMUP_PROPORTION = 0.1,\n SAVE_SUMMARY_STEPS = 100,\n SAVE_CHECKPOINTS_STEPS = 10000,\n bert_model_hub = \"https://tfhub.dev/google/bert_uncased_L-12_H-768_A-12/1\"):\n\n label_list = train[LABEL_COLUMN].unique().tolist()\n \n tokenizer = create_tokenizer_from_hub_module(bert_model_hub)\n\n train_features = make_features(train, label_list, MAX_SEQ_LENGTH, tokenizer, DATA_COLUMN, LABEL_COLUMN)\n test_features = make_features(test, label_list, MAX_SEQ_LENGTH, tokenizer, DATA_COLUMN, LABEL_COLUMN)\n\n num_train_steps = int(len(train_features) / BATCH_SIZE * NUM_TRAIN_EPOCHS)\n num_warmup_steps = int(num_train_steps * WARMUP_PROPORTION)\n\n estimator, model_fn, run_config = estimator_builder(\n bert_model_hub, \n OUTPUT_DIR, \n SAVE_SUMMARY_STEPS, \n SAVE_CHECKPOINTS_STEPS, \n label_list, \n LEARNING_RATE, \n num_train_steps, \n num_warmup_steps, \n BATCH_SIZE)\n\n train_input_fn = bert.run_classifier.input_fn_builder(\n features=train_features,\n seq_length=MAX_SEQ_LENGTH,\n is_training=True,\n drop_remainder=False)\n\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n\n test_input_fn = run_classifier.input_fn_builder(\n features=test_features,\n seq_length=MAX_SEQ_LENGTH,\n is_training=False,\n drop_remainder=False)\n\n result_dict = estimator.evaluate(input_fn=test_input_fn, steps=None)\n return result_dict, estimator\n ", "_____no_output_____" ], [ "import random\nrandom.seed(10)", "_____no_output_____" ], [ "OUTPUT_DIR = 'output'", "_____no_output_____" ] ], [ [ "----- 只需更改下方代码 ------", "_____no_output_____" ], [ "导入数据集", "_____no_output_____" ] ], [ [ "!wget https://github.com/yaoyue123/SocialComputing/raw/master/spam_message/training.txt\n!wget https://github.com/yaoyue123/SocialComputing/raw/master/spam_message/validation.txt", "--2019-11-25 11:09:32-- https://github.com/yaoyue123/SocialComputing/raw/master/spam_message/training.txt\nResolving github.com (github.com)... 140.82.113.3\nConnecting to github.com (github.com)|140.82.113.3|:443... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://raw.githubusercontent.com/yaoyue123/SocialComputing/master/spam_message/training.txt [following]\n--2019-11-25 11:09:33-- https://raw.githubusercontent.com/yaoyue123/SocialComputing/master/spam_message/training.txt\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 1149258 (1.1M) [text/plain]\nSaving to: ‘training.txt.1’\n\n\rtraining.txt.1 0%[ ] 0 --.-KB/s \rtraining.txt.1 100%[===================>] 1.10M --.-KB/s in 0.07s \n\n2019-11-25 11:09:33 (14.7 MB/s) - ‘training.txt.1’ saved [1149258/1149258]\n\n--2019-11-25 11:09:36-- https://github.com/yaoyue123/SocialComputing/raw/master/spam_message/validation.txt\nResolving github.com (github.com)... 140.82.113.3\nConnecting to github.com (github.com)|140.82.113.3|:443... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://raw.githubusercontent.com/yaoyue123/SocialComputing/master/spam_message/validation.txt [following]\n--2019-11-25 11:09:37-- https://raw.githubusercontent.com/yaoyue123/SocialComputing/master/spam_message/validation.txt\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 151.101.0.133, 151.101.64.133, 151.101.128.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|151.101.0.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 144983 (142K) [text/plain]\nSaving to: ‘validation.txt.1’\n\nvalidation.txt.1 100%[===================>] 141.58K --.-KB/s in 0.04s \n\n2019-11-25 11:09:37 (3.78 MB/s) - ‘validation.txt.1’ saved [144983/144983]\n\n" ], [ "train = pd.read_table(\"training.txt\",sep='\\t',error_bad_lines=False)\n#mytrain= mytrain[order]\n\ntest = pd.read_table(\"validation.txt\",sep='\\t',error_bad_lines=False)\n#mytest= mytest[order]", "b'Skipping line 11224: expected 2 fields, saw 3\\n'\n" ], [ "train.head()", "_____no_output_____" ], [ "test.head()", "_____no_output_____" ] ], [ [ "在此更改你的参数,如标签,bert模型地址,epochs", "_____no_output_____" ] ], [ [ "myparam = {\n \"DATA_COLUMN\": \"massage\",\n \"LABEL_COLUMN\": \"label\",\n \"LEARNING_RATE\": 2e-5,\n \"NUM_TRAIN_EPOCHS\":1,\n \"bert_model_hub\":\"https://tfhub.dev/google/bert_chinese_L-12_H-768_A-12/1\"\n\n }", "_____no_output_____" ] ], [ [ "训练模型,通常情况下,一个epochs用k80训练大概在10min左右", "_____no_output_____" ] ], [ [ "result, estimator = run_on_dfs(train, test, **myparam)", "INFO:tensorflow:Saver not created because there are no variables in the graph to restore\n" ] ], [ [ "bert模型还是比较强的,一个epochs就能达到准确率为99%", "_____no_output_____" ] ], [ [ "pretty_print(result)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
d0322d2142576b022bab8c5e8748162086c5fe95
2,246
ipynb
Jupyter Notebook
pages/packages.ipynb
burkesquires/steps2rr
88b1ace1ce0acd1d0a701127446ebf9adb408e42
[ "CC0-1.0" ]
null
null
null
pages/packages.ipynb
burkesquires/steps2rr
88b1ace1ce0acd1d0a701127446ebf9adb408e42
[ "CC0-1.0" ]
null
null
null
pages/packages.ipynb
burkesquires/steps2rr
88b1ace1ce0acd1d0a701127446ebf9adb408e42
[ "CC0-1.0" ]
1
2018-11-17T23:22:58.000Z
2018-11-17T23:22:58.000Z
38.724138
448
0.647373
[ [ [ "# Package Functions For Reuse\n---\n\nPulling out the major parts of your scripts as separate functions has the advantage that you can more easily reuse that code.\n\nBut functions sitting deep within some project directory are not likely to be used again. (&ldquo;It's in a file called `func.R`, but which project was I working on?&rdquo;)\n\nWhen possible, package up those useful functions as a stand-alone thing. This will make it easier for you (and others) to reuse them. It's also a good opportunity to _document_ those functions.\n\nWriting R packages is really not so hard as one might think. See my [R package primer](http://kbroman.org/pkg_primer),\n[Hadley Wickham](http://had.co.nz/)'s [R packages book](http://r-pkgs.had.co.nz/), or [Hilary Parker](http://hilaryparker.com/)'s [tutorial on R packages](http://hilaryparker.com/2014/04/29/writing-an-r-package-from-scratch/). If you've written a [personal R package](http://hilaryparker.com/2013/04/03/personal-r-packages/), you might include your miscellaneous functions there, or write a separate small package specific to your project.\n\nIf you prefer python to R, this may be even easier for you: a [python module](https://docs.python.org/3/tutorial/modules.html) is not much more than a file with a bunch of function definitions. Just add some [docstrings](http://tovid.wikia.com/wiki/Python_tips/Docstrings).\n\n---\n\nNow go to the page about [version control](version_control.ipynb).", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
d03246dc380765ef600501e1752d4c0bda9a0522
37,431
ipynb
Jupyter Notebook
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
bd919b281d5c33fe9773e37b74509bfe15590d9d
[ "MIT" ]
null
null
null
tensorboard/Anna_KaRNNa.ipynb
smrutiranjans/deep-learning
bd919b281d5c33fe9773e37b74509bfe15590d9d
[ "MIT" ]
12
2022-01-13T03:31:58.000Z
2022-03-12T00:53:52.000Z
tensorboard/Anna_KaRNNa.ipynb
smruties/deep-learning
bd919b281d5c33fe9773e37b74509bfe15590d9d
[ "MIT" ]
null
null
null
45.206522
2,052
0.595122
[ [ [ "# Anna KaRNNa\n\nIn this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.\n\nThis network is based off of Andrej Karpathy's [post on RNNs](http://karpathy.github.io/2015/05/21/rnn-effectiveness/) and [implementation in Torch](https://github.com/karpathy/char-rnn). Also, some information [here at r2rt](http://r2rt.com/recurrent-neural-networks-in-tensorflow-ii.html) and from [Sherjil Ozair](https://github.com/sherjilozair/char-rnn-tensorflow) on GitHub. Below is the general architecture of the character-wise RNN.\n\n<img src=\"assets/charseq.jpeg\" width=\"500\">", "_____no_output_____" ] ], [ [ "import time\nfrom collections import namedtuple\n\nimport numpy as np\nimport tensorflow as tf", "_____no_output_____" ] ], [ [ "First we'll load the text file and convert it into integers for our network to use.", "_____no_output_____" ] ], [ [ "with open('anna.txt', 'r') as f:\n text=f.read()\nvocab = set(text)\nvocab_to_int = {c: i for i, c in enumerate(vocab)}\nint_to_vocab = dict(enumerate(vocab))\nchars = np.array([vocab_to_int[c] for c in text], dtype=np.int32)", "_____no_output_____" ], [ "text[:100]", "_____no_output_____" ], [ "chars[:100]", "_____no_output_____" ] ], [ [ "Now I need to split up the data into batches, and into training and validation sets. I should be making a test set here, but I'm not going to worry about that. My test will be if the network can generate new text.\n\nHere I'll make both input and target arrays. The targets are the same as the inputs, except shifted one character over. I'll also drop the last bit of data so that I'll only have completely full batches.\n\nThe idea here is to make a 2D matrix where the number of rows is equal to the number of batches. Each row will be one long concatenated string from the character data. We'll split this data into a training set and validation set using the `split_frac` keyword. This will keep 90% of the batches in the training set, the other 10% in the validation set.", "_____no_output_____" ] ], [ [ "def split_data(chars, batch_size, num_steps, split_frac=0.9):\n \"\"\" \n Split character data into training and validation sets, inputs and targets for each set.\n \n Arguments\n ---------\n chars: character array\n batch_size: Size of examples in each of batch\n num_steps: Number of sequence steps to keep in the input and pass to the network\n split_frac: Fraction of batches to keep in the training set\n \n \n Returns train_x, train_y, val_x, val_y\n \"\"\"\n \n \n slice_size = batch_size * num_steps\n n_batches = int(len(chars) / slice_size)\n \n # Drop the last few characters to make only full batches\n x = chars[: n_batches*slice_size]\n y = chars[1: n_batches*slice_size + 1]\n \n # Split the data into batch_size slices, then stack them into a 2D matrix \n x = np.stack(np.split(x, batch_size))\n y = np.stack(np.split(y, batch_size))\n \n # Now x and y are arrays with dimensions batch_size x n_batches*num_steps\n \n # Split into training and validation sets, keep the virst split_frac batches for training\n split_idx = int(n_batches*split_frac)\n train_x, train_y= x[:, :split_idx*num_steps], y[:, :split_idx*num_steps]\n val_x, val_y = x[:, split_idx*num_steps:], y[:, split_idx*num_steps:]\n \n return train_x, train_y, val_x, val_y", "_____no_output_____" ], [ "train_x, train_y, val_x, val_y = split_data(chars, 10, 200)", "_____no_output_____" ], [ "train_x.shape", "_____no_output_____" ], [ "train_x[:,:10]", "_____no_output_____" ] ], [ [ "I'll write another function to grab batches out of the arrays made by split data. Here each batch will be a sliding window on these arrays with size `batch_size X num_steps`. For example, if we want our network to train on a sequence of 100 characters, `num_steps = 100`. For the next batch, we'll shift this window the next sequence of `num_steps` characters. In this way we can feed batches to the network and the cell states will continue through on each batch.", "_____no_output_____" ] ], [ [ "def get_batch(arrs, num_steps):\n batch_size, slice_size = arrs[0].shape\n \n n_batches = int(slice_size/num_steps)\n for b in range(n_batches):\n yield [x[:, b*num_steps: (b+1)*num_steps] for x in arrs]", "_____no_output_____" ], [ "def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2,\n learning_rate=0.001, grad_clip=5, sampling=False):\n \n if sampling == True:\n batch_size, num_steps = 1, 1\n\n tf.reset_default_graph()\n \n # Declare placeholders we'll feed into the graph\n \n inputs = tf.placeholder(tf.int32, [batch_size, num_steps], name='inputs')\n x_one_hot = tf.one_hot(inputs, num_classes, name='x_one_hot')\n\n\n targets = tf.placeholder(tf.int32, [batch_size, num_steps], name='targets')\n y_one_hot = tf.one_hot(targets, num_classes, name='y_one_hot')\n y_reshaped = tf.reshape(y_one_hot, [-1, num_classes])\n \n keep_prob = tf.placeholder(tf.float32, name='keep_prob')\n \n # Build the RNN layers\n \n lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)\n drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n cell = tf.contrib.rnn.MultiRNNCell([drop] * num_layers)\n\n initial_state = cell.zero_state(batch_size, tf.float32)\n\n # Run the data through the RNN layers\n outputs, state = tf.nn.dynamic_rnn(cell, x_one_hot, initial_state=initial_state)\n final_state = state\n \n # Reshape output so it's a bunch of rows, one row for each cell output\n \n seq_output = tf.concat(outputs, axis=1,name='seq_output')\n output = tf.reshape(seq_output, [-1, lstm_size], name='graph_output')\n \n # Now connect the RNN putputs to a softmax layer and calculate the cost\n softmax_w = tf.Variable(tf.truncated_normal((lstm_size, num_classes), stddev=0.1),\n name='softmax_w')\n softmax_b = tf.Variable(tf.zeros(num_classes), name='softmax_b')\n logits = tf.matmul(output, softmax_w) + softmax_b\n\n preds = tf.nn.softmax(logits, name='predictions')\n \n loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_reshaped, name='loss')\n cost = tf.reduce_mean(loss, name='cost')\n\n # Optimizer for training, using gradient clipping to control exploding gradients\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), grad_clip)\n train_op = tf.train.AdamOptimizer(learning_rate)\n optimizer = train_op.apply_gradients(zip(grads, tvars))\n\n # Export the nodes \n export_nodes = ['inputs', 'targets', 'initial_state', 'final_state',\n 'keep_prob', 'cost', 'preds', 'optimizer']\n Graph = namedtuple('Graph', export_nodes)\n local_dict = locals()\n graph = Graph(*[local_dict[each] for each in export_nodes])\n \n return graph", "_____no_output_____" ] ], [ [ "## Hyperparameters\n\nHere I'm defining the hyperparameters for the network. The two you probably haven't seen before are `lstm_size` and `num_layers`. These set the number of hidden units in the LSTM layers and the number of LSTM layers, respectively. Of course, making these bigger will improve the network's performance but you'll have to watch out for overfitting. If your validation loss is much larger than the training loss, you're probably overfitting. Decrease the size of the network or decrease the dropout keep probability.", "_____no_output_____" ] ], [ [ "batch_size = 100\nnum_steps = 100\nlstm_size = 512\nnum_layers = 2\nlearning_rate = 0.001", "_____no_output_____" ] ], [ [ "## Write out the graph for TensorBoard", "_____no_output_____" ] ], [ [ "model = build_rnn(len(vocab),\n batch_size=batch_size,\n num_steps=num_steps,\n learning_rate=learning_rate,\n lstm_size=lstm_size,\n num_layers=num_layers)\n\nwith tf.Session() as sess:\n \n sess.run(tf.global_variables_initializer())\n file_writer = tf.summary.FileWriter('./logs/1', sess.graph)", "_____no_output_____" ] ], [ [ "## Training\n\nTime for training which is is pretty straightforward. Here I pass in some data, and get an LSTM state back. Then I pass that state back in to the network so the next batch can continue the state from the previous batch. And every so often (set by `save_every_n`) I calculate the validation loss and save a checkpoint.", "_____no_output_____" ] ], [ [ "!mkdir -p checkpoints/anna", "_____no_output_____" ], [ "epochs = 1\nsave_every_n = 200\ntrain_x, train_y, val_x, val_y = split_data(chars, batch_size, num_steps)\n\nmodel = build_rnn(len(vocab), \n batch_size=batch_size,\n num_steps=num_steps,\n learning_rate=learning_rate,\n lstm_size=lstm_size,\n num_layers=num_layers)\n\nsaver = tf.train.Saver(max_to_keep=100)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n \n # Use the line below to load a checkpoint and resume training\n #saver.restore(sess, 'checkpoints/anna20.ckpt')\n \n n_batches = int(train_x.shape[1]/num_steps)\n iterations = n_batches * epochs\n for e in range(epochs):\n \n # Train network\n new_state = sess.run(model.initial_state)\n loss = 0\n for b, (x, y) in enumerate(get_batch([train_x, train_y], num_steps), 1):\n iteration = e*n_batches + b\n start = time.time()\n feed = {model.inputs: x,\n model.targets: y,\n model.keep_prob: 0.5,\n model.initial_state: new_state}\n batch_loss, new_state, _ = sess.run([model.cost, model.final_state, model.optimizer], \n feed_dict=feed)\n loss += batch_loss\n end = time.time()\n print('Epoch {}/{} '.format(e+1, epochs),\n 'Iteration {}/{}'.format(iteration, iterations),\n 'Training loss: {:.4f}'.format(loss/b),\n '{:.4f} sec/batch'.format((end-start)))\n \n \n if (iteration%save_every_n == 0) or (iteration == iterations):\n # Check performance, notice dropout has been set to 1\n val_loss = []\n new_state = sess.run(model.initial_state)\n for x, y in get_batch([val_x, val_y], num_steps):\n feed = {model.inputs: x,\n model.targets: y,\n model.keep_prob: 1.,\n model.initial_state: new_state}\n batch_loss, new_state = sess.run([model.cost, model.final_state], feed_dict=feed)\n val_loss.append(batch_loss)\n\n print('Validation loss:', np.mean(val_loss),\n 'Saving checkpoint!')\n saver.save(sess, \"checkpoints/anna/i{}_l{}_{:.3f}.ckpt\".format(iteration, lstm_size, np.mean(val_loss)))", "_____no_output_____" ], [ "tf.train.get_checkpoint_state('checkpoints/anna')", "_____no_output_____" ] ], [ [ "## Sampling\n\nNow that the network is trained, we'll can use it to generate new text. The idea is that we pass in a character, then the network will predict the next character. We can use the new one, to predict the next one. And we keep doing this to generate all new text. I also included some functionality to prime the network with some text by passing in a string and building up a state from that.\n\nThe network gives us predictions for each character. To reduce noise and make things a little less random, I'm going to only choose a new character from the top N most likely characters.\n\n", "_____no_output_____" ] ], [ [ "def pick_top_n(preds, vocab_size, top_n=5):\n p = np.squeeze(preds)\n p[np.argsort(p)[:-top_n]] = 0\n p = p / np.sum(p)\n c = np.random.choice(vocab_size, 1, p=p)[0]\n return c", "_____no_output_____" ], [ "def sample(checkpoint, n_samples, lstm_size, vocab_size, prime=\"The \"):\n prime = \"Far\"\n samples = [c for c in prime]\n model = build_rnn(vocab_size, lstm_size=lstm_size, sampling=True)\n saver = tf.train.Saver()\n with tf.Session() as sess:\n saver.restore(sess, checkpoint)\n new_state = sess.run(model.initial_state)\n for c in prime:\n x = np.zeros((1, 1))\n x[0,0] = vocab_to_int[c]\n feed = {model.inputs: x,\n model.keep_prob: 1.,\n model.initial_state: new_state}\n preds, new_state = sess.run([model.preds, model.final_state], \n feed_dict=feed)\n\n c = pick_top_n(preds, len(vocab))\n samples.append(int_to_vocab[c])\n\n for i in range(n_samples):\n x[0,0] = c\n feed = {model.inputs: x,\n model.keep_prob: 1.,\n model.initial_state: new_state}\n preds, new_state = sess.run([model.preds, model.final_state], \n feed_dict=feed)\n\n c = pick_top_n(preds, len(vocab))\n samples.append(int_to_vocab[c])\n \n return ''.join(samples)", "_____no_output_____" ], [ "checkpoint = \"checkpoints/anna/i3560_l512_1.122.ckpt\"\nsamp = sample(checkpoint, 2000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)", "Farlathit that if had so\nlike it that it were. He could not trouble to his wife, and there was\nanything in them of the side of his weaky in the creature at his forteren\nto him.\n\n\"What is it? I can't bread to those,\" said Stepan Arkadyevitch. \"It's not\nmy children, and there is an almost this arm, true it mays already,\nand tell you what I have say to you, and was not looking at the peasant,\nwhy is, I don't know him out, and she doesn't speak to me immediately, as\nyou would say the countess and the more frest an angelembre, and time and\nthings's silent, but I was not in my stand that is in my head. But if he\nsay, and was so feeling with his soul. A child--in his soul of his\nsoul of his soul. He should not see that any of that sense of. Here he\nhad not been so composed and to speak for as in a whole picture, but\nall the setting and her excellent and society, who had been delighted\nand see to anywing had been being troed to thousand words on them,\nwe liked him.\n\nThat set in her money at the table, he came into the party. The capable\nof his she could not be as an old composure.\n\n\"That's all something there will be down becime by throe is\nsuch a silent, as in a countess, I should state it out and divorct.\nThe discussion is not for me. I was that something was simply they are\nall three manshess of a sensitions of mind it all.\"\n\n\"No,\" he thought, shouted and lifting his soul. \"While it might see your\nhonser and she, I could burst. And I had been a midelity. And I had a\nmarnief are through the countess,\" he said, looking at him, a chosing\nwhich they had been carried out and still solied, and there was a sen that\nwas to be completely, and that this matter of all the seconds of it, and\na concipation were to her husband, who came up and conscaously, that he\nwas not the station. All his fourse she was always at the country,,\nto speak oft, and though they were to hear the delightful throom and\nwhether they came towards the morning, and his living and a coller and\nhold--the children. \n" ], [ "checkpoint = \"checkpoints/anna/i200_l512_2.432.ckpt\"\nsamp = sample(checkpoint, 1000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)", "Farnt him oste wha sorind thans tout thint asd an sesand an hires on thime sind thit aled, ban thand and out hore as the ter hos ton ho te that, was tis tart al the hand sostint him sore an tit an son thes, win he se ther san ther hher tas tarereng,.\n\nAnl at an ades in ond hesiln, ad hhe torers teans, wast tar arering tho this sos alten sorer has hhas an siton ther him he had sin he ard ate te anling the sosin her ans and\narins asd and ther ale te tot an tand tanginge wath and ho ald, so sot th asend sat hare sother horesinnd, he hesense wing ante her so tith tir sherinn, anded and to the toul anderin he sorit he torsith she se atere an ting ot hand and thit hhe so the te wile har\nens ont in the sersise, and we he seres tar aterer, to ato tat or has he he wan ton here won and sen heren he sosering, to to theer oo adent har herere the wosh oute, was serild ward tous hed astend..\n\nI's sint on alt in har tor tit her asd hade shithans ored he talereng an soredendere tim tot hees. Tise sor and \n" ], [ "checkpoint = \"checkpoints/anna/i600_l512_1.750.ckpt\"\nsamp = sample(checkpoint, 1000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)", "Fard as astice her said he celatice of to seress in the raice, and to be the some and sere allats to that said to that the sark and a cast a the wither ald the pacinesse of her had astition, he said to the sount as she west at hissele. Af the cond it he was a fact onthis astisarianing.\n\n\n\"Or a ton to to be that's a more at aspestale as the sont of anstiring as\nthours and trey.\n\nThe same wo dangring the\nraterst, who sore and somethy had ast out an of his book. \"We had's beane were that, and a morted a thay he had to tere. Then to\nher homent andertersed his his ancouted to the pirsted, the soution for of the pirsice inthirgest and stenciol, with the hard and and\na colrice of to be oneres,\nthe song to this anderssad.\nThe could ounterss the said to serom of\nsoment a carsed of sheres of she\ntorded\nhar and want in their of hould, but\nher told in that in he tad a the same to her. Serghing an her has and with the seed, and the camt ont his about of the\nsail, the her then all houg ant or to hus to \n" ], [ "checkpoint = \"checkpoints/anna/i1000_l512_1.484.ckpt\"\nsamp = sample(checkpoint, 1000, lstm_size, len(vocab), prime=\"Far\")\nprint(samp)", "Farrat, his felt has at it.\n\n\"When the pose ther hor exceed\nto his sheant was,\" weat a sime of his sounsed. The coment and the facily that which had began terede a marilicaly whice whether the pose of his hand, at she was alligated herself the same on she had to\ntaiking to his forthing and streath how to hand\nbegan in a lang at some at it, this he cholded not set all her. \"Wo love that is setthing. Him anstering as seen that.\"\n\n\"Yes in the man that say the mare a crances is it?\" said Sergazy Ivancatching. \"You doon think were somether is ifficult of a mone of\nthough the most at the countes that the\nmean on the come to say the most, to\nhis feesing of\na man she, whilo he\nsained and well, that he would still at to said. He wind at his for the sore in the most\nof hoss and almoved to see him. They have betine the sumper into at he his stire, and what he was that at the so steate of the\nsound, and shin should have a geest of shall feet on the conderation to she had been at that imporsing the dre\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
d03251a9c2903842a1f452e5da16e73a21b11e87
5,796
ipynb
Jupyter Notebook
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
2eafa8b5b05b791c84c441afa45463032fa57563
[ "Unlicense" ]
null
null
null
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
2eafa8b5b05b791c84c441afa45463032fa57563
[ "Unlicense" ]
null
null
null
Numpy/Introduction to Numpy.ipynb
PhillipWongSeven/Machine-Learning-Simplified
2eafa8b5b05b791c84c441afa45463032fa57563
[ "Unlicense" ]
null
null
null
16.8
60
0.423913
[ [ [ "# Numpy", "_____no_output_____" ], [ "## Basic operations ", "_____no_output_____" ] ], [ [ "import numpy as np\nnumbers = [1, 2, 3, 4, 5]\nprint(np.mean(numbers))\nprint(np.median(numbers))\nprint(np.std(numbers)) #This is the standard deviation", "3.0\n3.0\n1.41421356237\n" ] ], [ [ "Numpy Arraies are optimize to run faster", "_____no_output_____" ] ], [ [ "array = np.array(numbers, float)\nprint (array)", "[ 1. 2. 3. 4. 5.]\n" ], [ "array[1]", "_____no_output_____" ], [ "array[:2]", "_____no_output_____" ], [ "array[1]=10.0", "_____no_output_____" ], [ "print array", "[ 1. 10. 3. 4. 5.]\n" ] ], [ [ "## Numpy Array can be two dimensional", "_____no_output_____" ] ], [ [ "array = np.array([[1,2,3], [4,5,6]], float)\nprint (array)\nprint \"\"\nprint array[1][1]\nprint \"\"\nprint array[1, :]\nprint \"\"\nprint array[:, 2]\nprint \"\"\nprint array[:, 1]", "[[ 1. 2. 3.]\n [ 4. 5. 6.]]\n\n5.0\n\n[ 4. 5. 6.]\n\n[ 3. 6.]\n\n[ 2. 5.]\n" ], [ "ray = np.array([[1,2,3], [4,5,6]], float)\n\nprint ray\nprint (ray[1][2])\nprint (ray[1][1])\nprint (ray[:, 2])", "[[ 1. 2. 3.]\n [ 4. 5. 6.]]\n6.0\n5.0\n[ 3. 6.]\n" ] ], [ [ "## Array arithmetics", "_____no_output_____" ] ], [ [ "ray1 = np.array([1, 2, 3], float)\nray2 = np.array([5, 2, 6], float)\n\nprint (ray1+ray2)\nprint (ray1*ray2)\nprint (np.mean(ray1))\nprint(np.dot(ray1, ray2))", "[ 6. 4. 9.]\n[ 5. 4. 18.]\n2.0\n27.0\n" ], [ " array_1 = np.array([1, 2, 3], float)\n array_2 = np.array([5, 2, 6], float)", "_____no_output_____" ], [ "array_1 + array_2", "_____no_output_____" ] ], [ [ "## Array multipliation", "_____no_output_____" ] ], [ [ "array_1 * array_2", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d03258a72e6e45e065af06af02e03de0da13bd35
4,815
ipynb
Jupyter Notebook
week3 logistic Regression.ipynb
SongChiyoon/study-Tensorflow
1c6332673eff779be98a60896b7c5b42fa82faac
[ "MIT" ]
null
null
null
week3 logistic Regression.ipynb
SongChiyoon/study-Tensorflow
1c6332673eff779be98a60896b7c5b42fa82faac
[ "MIT" ]
null
null
null
week3 logistic Regression.ipynb
SongChiyoon/study-Tensorflow
1c6332673eff779be98a60896b7c5b42fa82faac
[ "MIT" ]
null
null
null
28.323529
87
0.56864
[ [ [ "import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data", "_____no_output_____" ] ], [ [ "# Make logistic Regression model with MNIST", "_____no_output_____" ] ], [ [ "mnist = input_data.read_data_sets('data/',one_hot = True)\ntrainimg = mnist.train.images\ntrainLabel = mnist.train.labels\ntestimg = mnist.test.images\ntestLabel = mnist.test.labels\nprint(\"MNIST Loaded\")", "Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\nExtracting data/train-images-idx3-ubyte.gz\nSuccessfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\nExtracting data/train-labels-idx1-ubyte.gz\nSuccessfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\nExtracting data/t10k-images-idx3-ubyte.gz\nSuccessfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\nExtracting data/t10k-labels-idx1-ubyte.gz\nMNIST Loaded\n" ], [ "x = tf.placeholder('float', [None, 784])\ny = tf.placeholder('float', [None, 10])\nw = tf.Variable(tf.random_normal([784,10]))\nb = tf.Variable(tf.random_normal([10]))\n#Logistic Regression Model\nactiv = tf.nn.softmax(tf.matmul(x,w)+b)\n#cost function\ncost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(activ)))\n#optimizer\noptm = tf.train.GradientDescentOptimizer(0.01).minimize(cost)", "_____no_output_____" ], [ "#prediction\npred = tf.equal(tf.arg_max(activ,1), tf.arg_max(y, 1))\n#accuracy\naccr = tf.reduce_mean(tf.cast(pred, \"float\"))\ninit = tf.initialize_all_variables", "_____no_output_____" ], [ "training_epochs = 10\nbatch_size = 100\ndisplay_step = 2\n# SESSION\nsess = tf.Session()\nsess.run(tf.initialize_all_variables())\n# MINI-BATCH LEARNING\nfor epoch in range(training_epochs):\n avg_cost = 0.\n num_batch = int(mnist.train.num_examples/batch_size)\n for i in range(num_batch): \n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})\n feeds = {x: batch_xs, y: batch_ys}\n avg_cost += sess.run(cost, feed_dict=feeds)/num_batch\n # DISPLAY\n if epoch % display_step == 0:\n feeds_train = {x: batch_xs, y: batch_ys}\n feeds_test = {x: mnist.test.images, y: mnist.test.labels}\n train_acc = sess.run(accr, feed_dict=feeds_train)\n test_acc = sess.run(accr, feed_dict=feeds_test)\n print (\"Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f\" \n % (epoch, training_epochs, avg_cost, train_acc, test_acc))\nprint (\"DONE\")", "Epoch: 000/010 cost: 75.560586708 train_acc: 0.910 test_acc: 0.865\nEpoch: 002/010 cost: 32.222071790 train_acc: 0.910 test_acc: 0.895\nEpoch: 004/010 cost: 27.124585262 train_acc: 0.930 test_acc: 0.903\nEpoch: 006/010 cost: 24.715282281 train_acc: 0.940 test_acc: 0.911\nEpoch: 008/010 cost: 23.033731372 train_acc: 0.910 test_acc: 0.914\nDONE\n" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d03261c43190b6dd3128b825e9ed3f61526ef7ff
415,082
ipynb
Jupyter Notebook
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
7c3dfee3ac480a6511e18471fb3dc3e684dafe62
[ "Apache-2.0" ]
1
2020-04-25T00:01:39.000Z
2020-04-25T00:01:39.000Z
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
7c3dfee3ac480a6511e18471fb3dc3e684dafe62
[ "Apache-2.0" ]
null
null
null
training/predict_it_v2-Ray-attempt.ipynb
jasonfiacco/deeptrader
7c3dfee3ac480a6511e18471fb3dc3e684dafe62
[ "Apache-2.0" ]
null
null
null
179.689177
128,932
0.835871
[ [ [ "## Change sys.path to use my tensortrade instead of the one in env", "_____no_output_____" ] ], [ [ "import sys\nsys.path.append(\"/Users/jasonfiacco/Documents/Yale/Senior/thesis/deeptrader\")\nprint(sys.path)", "['/usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '', '/Users/jasonfiacco/Documents/Yale/Senior/thesis/env2/lib/python3.6/site-packages', '/Users/jasonfiacco/Documents/Yale/Senior/thesis/env2/lib/python3.6/site-packages/IPython/extensions', '/Users/jasonfiacco/.ipython', '/Users/jasonfiacco/Documents/Yale/Senior/thesis/deeptrader']\n" ] ], [ [ "## Read PredictIt Data Instead", "_____no_output_____" ] ], [ [ "import ssl\nimport pandas as pd\n\nssl._create_default_https_context = ssl._create_unverified_context # Only used if pandas gives a SSLError\n\ndef fetch_data(symbol):\n path = \"/Users/jasonfiacco/Documents/Yale/Senior/thesis/predictit_datasets/\"\n filename = \"{}.xlsx\".format(symbol)\n\n\n\n df = pd.read_excel(path + filename, skiprows=4)\n df = df.set_index(\"Date\")\n df = df.drop(df.columns[[7,8,9]], axis=1)\n df = df.drop(\"ID\", 1)\n df.columns = [symbol + \":\" + name.lower() for name in df.columns]\n\n return df", "_____no_output_____" ], [ "all_data = pd.concat([\n fetch_data(\"WARREN\"),\n fetch_data(\"CRUZ\"),\n fetch_data(\"MANCHIN\"),\n fetch_data(\"SANDERS\"),\n fetch_data(\"NELSON\"),\n fetch_data(\"DONNELLY\"),\n fetch_data(\"PELOSI\"),\n fetch_data(\"MANAFORT\"),\n fetch_data(\"BROWN\"),\n fetch_data(\"RYAN\"),\n fetch_data(\"STABENOW\")\n], axis=1)\nall_data.head()", "_____no_output_____" ] ], [ [ "## Plot the closing prices for all the markets", "_____no_output_____" ] ], [ [ "%matplotlib inline\nclosing_prices = all_data.loc[:, [(\"close\" in name) for name in all_data.columns]]\nclosing_prices.plot()", "_____no_output_____" ] ], [ [ "## Slice just a specific time period from the dataframe", "_____no_output_____" ] ], [ [ "all_data.index = pd.to_datetime(all_data.index)", "_____no_output_____" ], [ "subset_data = all_data[(all_data.index >= '09-01-2017') & (all_data.index <= '09-04-2019')]\nsubset_data.head()", "_____no_output_____" ] ], [ [ "## Define Exchanges\n\nAn exchange needs a name, an execution service, and streams of price data in order to function properly.\n\nThe setups supported right now are the simulated execution service using simulated or stochastic data. More execution services will be made available in the future, as well as price streams so that live data and execution can be supported.", "_____no_output_____" ] ], [ [ "from tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream\n\n#Exchange(name of exchange, service)\n#It looks like each Stream takes a name, and then a list of the closing prices.\n\npredictit_exch = Exchange(\"predictit\", service=execute_order)(\n Stream(\"USD-WARREN\", list(subset_data['WARREN:close'])),\n Stream(\"USD-CRUZ\", list(subset_data['CRUZ:close'])),\n Stream(\"USD-MANCHIN\", list(subset_data['MANCHIN:close'])),\n Stream(\"USD-SANDERS\", list(subset_data['SANDERS:close'])),\n Stream(\"USD-NELSON\", list(subset_data['NELSON:close'])),\n Stream(\"USD-DONNELLY\", list(subset_data['DONNELLY:close'])),\n Stream(\"USD-PELOSI\", list(subset_data['PELOSI:close'])),\n Stream(\"USD-MANAFORT\", list(subset_data['MANAFORT:close'])),\n Stream(\"USD-BROWN\", list(subset_data['BROWN:close'])),\n Stream(\"USD-RYAN\", list(subset_data['RYAN:close'])),\n Stream(\"USD-STABENOW\", list(subset_data['STABENOW:close']))\n)", "_____no_output_____" ] ], [ [ "Now that the exchanges have been defined we can define our features that we would like to include, excluding the prices we have provided for the exchanges.", "_____no_output_____" ], [ "### Doing it without adding other features. Just use price ", "_____no_output_____" ] ], [ [ "#You still have to add \"Streams\" for all the standard columns open, high, low, close, volume in this case\nfrom tensortrade.data import DataFeed, Module\n\nwith Module(\"predictit\") as predictit_ns:\n predictit_nodes = [Stream(name, list(subset_data[name])) for name in subset_data.columns]\n ", "_____no_output_____" ], [ "#Then create the Feed from it\nfeed = DataFeed([predictit_ns])\nfeed.next()", "_____no_output_____" ] ], [ [ "## Portfolio\n\nMake the portfolio using the any combinations of exchanges and intruments that the exchange supports", "_____no_output_____" ] ], [ [ "#I am going to have to add \"instruments\" for all 25 of the PredictIt markets I'm working with.\nfrom tensortrade.instruments import USD, WARREN, CRUZ, MANCHIN, SANDERS, NELSON, DONNELLY,\\\n PELOSI, MANAFORT, BROWN, RYAN, STABENOW\nfrom tensortrade.wallets import Wallet, Portfolio\n\nportfolio = Portfolio(USD, [\n Wallet(predictit_exch, 10000 * USD),\n Wallet(predictit_exch, 0 * WARREN),\n Wallet(predictit_exch, 0 * CRUZ),\n Wallet(predictit_exch, 0 * MANCHIN),\n Wallet(predictit_exch, 0 * SANDERS),\n Wallet(predictit_exch, 0 * NELSON),\n Wallet(predictit_exch, 0 * DONNELLY),\n Wallet(predictit_exch, 0 * PELOSI),\n Wallet(predictit_exch, 0 * MANAFORT),\n Wallet(predictit_exch, 0 * BROWN),\n Wallet(predictit_exch, 0 * RYAN),\n Wallet(predictit_exch, 0 * STABENOW)\n])", "_____no_output_____" ] ], [ [ "## Environment", "_____no_output_____" ] ], [ [ "from tensortrade.environments import TradingEnvironment\n\nenv = TradingEnvironment(\n feed=feed,\n portfolio=portfolio,\n action_scheme='simple',\n reward_scheme='simple',\n window_size=15,\n enable_logger=False,\n renderers = 'screenlog'\n)", "/Users/jasonfiacco/Documents/Yale/Senior/thesis/env2/lib/python3.6/site-packages/gym/logger.py:30: UserWarning:\n\n\u001b[33mWARN: Box bound precision lowered by casting to float32\u001b[0m\n\n" ], [ "env.feed.next()", "_____no_output_____" ] ], [ [ "#### ^An environment doesn't just show the OHLCV for each instrument. It also shows free, locked, total, as well as \"USD_BTC\"", "_____no_output_____" ], [ "## Using 123's Ray example", "_____no_output_____" ] ], [ [ "import os\nparent_dir = \"/Users/jasonfiacco/Documents/Yale/Senior/thesis/deeptrader\"\nos.environ[\"PYTHONPATH\"] = parent_dir + \":\" + os.environ.get(\"PYTHONPATH\", \"\")", "_____no_output_____" ], [ "!PYTHONWARNINGS=ignore::yaml.YAMLLoadWarning", "_____no_output_____" ], [ "#Import tensortrade\nimport tensortrade\n\n# Define Exchanges\nfrom tensortrade.exchanges import Exchange\nfrom tensortrade.exchanges.services.execution.simulated import execute_order\nfrom tensortrade.data import Stream\n\n\n# Define External Data Feed (features)\nimport ta\nfrom sklearn import preprocessing\nfrom tensortrade.data import DataFeed, Module\n\n# Portfolio\nfrom tensortrade.instruments import USD, BTC\nfrom tensortrade.wallets import Wallet, Portfolio\nfrom tensortrade.actions import ManagedRiskOrders\nfrom gym.spaces import Discrete\n\n# Environment\nfrom tensortrade.environments import TradingEnvironment\n\n\nimport gym\nimport ray\nfrom ray import tune\nfrom ray.tune import grid_search\nfrom ray.tune.registry import register_env\n\nimport ray.rllib.agents.ppo as ppo\nimport ray.rllib.agents.dqn as dqn\nfrom ray.tune.logger import pretty_print\nfrom tensortrade.rewards import RiskAdjustedReturns\n \nclass RayTradingEnv(TradingEnvironment):\n def __init__(self): \n env = TradingEnvironment(\n feed=feed,\n portfolio=portfolio,\n action_scheme=\"simple\",\n reward_scheme=\"simple\",\n window_size=15,\n enable_logger=False,\n renderers = 'screenlog'\n ) \n self.env = env\n self.action_space = self.env.action_space\n self.observation_space = self.env.observation_space\n \n\n def reset(self):\n return self.env.reset()\n\n def step(self, action):\n return self.env.step(action)\n\ndef env_creator(env_config):\n return RayTradingEnv()\n\nregister_env(\"ray_trading_env\", env_creator)\n\n\nray.init(ignore_reinit_error=True)\nconfig = dqn.DEFAULT_CONFIG.copy()\nconfig[\"num_gpus\"] = 0\n#config[\"num_workers\"] = 4\n\n#config[\"num_envs_per_worker\"] = 8\n# config[\"eager\"] = False\n\n# config[\"timesteps_per_iteration\"] = 100\n# config[\"train_batch_size\"] = 20\n\n#config['log_level'] = \"DEBUG\"\n\ntrainer = dqn.DQNTrainer(config=config, env=\"ray_trading_env\")\n\nconfig", "2020-03-05 22:30:39,190\tINFO resource_spec.py:212 -- Starting Ray with 5.71 GiB memory available for workers and up to 2.86 GiB for objects. You can adjust these settings with ray.init(memory=<bytes>, object_store_memory=<bytes>).\n2020-03-05 22:30:39,555\tINFO services.py:1078 -- View the Ray dashboard at \u001b[1m\u001b[32mlocalhost:8265\u001b[39m\u001b[22m\n2020-03-05 22:30:39,868\tINFO trainer.py:420 -- Tip: set 'eager': true or the --eager flag to enable TensorFlow eager execution\n2020-03-05 22:30:39,952\tINFO trainer.py:580 -- Current log_level is WARN. For more information, set 'log_level': 'INFO' / 'DEBUG' or use the -v and -vv flags.\n/Users/jasonfiacco/Documents/Yale/Senior/thesis/env2/lib/python3.6/site-packages/gym/logger.py:30: UserWarning:\n\n\u001b[33mWARN: Box bound precision lowered by casting to float32\u001b[0m\n\n/Users/jasonfiacco/Documents/Yale/Senior/thesis/env2/lib/python3.6/site-packages/ray/rllib/utils/from_config.py:134: YAMLLoadWarning:\n\ncalling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.\n\n2020-03-05 22:30:42,573\tWARNING util.py:37 -- Install gputil for GPU system monitoring.\n" ] ], [ [ "## Train using the old fashioned RLLib way", "_____no_output_____" ] ], [ [ "\nfor i in range(10):\n # Perform one iteration of training the policy with PPO\n print(\"Training iteration {}...\".format(i))\n result = trainer.train()\n print(\"result: {}\".format(result))\n \n if i % 100 == 0:\n checkpoint = trainer.save()\n print(\"checkpoint saved at\", checkpoint)", "Training iteration 0...\n" ], [ "result['hist_stats']['episode_reward']", "_____no_output_____" ] ], [ [ "## OR train using the tune way (better so far)", "_____no_output_____" ] ], [ [ "analysis = tune.run(\n \"DQN\",\n name = \"DQN10-paralellism\",\n checkpoint_at_end=True,\n stop={\n \"timesteps_total\": 4000,\n },\n config={\n \"env\": \"ray_trading_env\",\n \"lr\": grid_search([1e-4]), # try different lrs\n \"num_workers\": 2, # parallelism,\n\n },\n )", "_____no_output_____" ], [ "#Use the below command to see results\n#tensorboard --logdir=/Users/jasonfiacco/ray_results/DQN2", "_____no_output_____" ], [ "#Now you can plot the reward results of your tuner.\ndfs = analysis.trial_dataframes\n\nax = None\nfor d in dfs.values():\n ax = d.episode_reward_mean.plot(ax=ax, legend=True)", "_____no_output_____" ] ], [ [ "## Restoring an already existing agent that I tuned", "_____no_output_____" ] ], [ [ "import os\nlogdir = analysis.get_best_logdir(\"episode_reward_mean\", mode=\"max\")\ntrainer.restore(os.path.join(logdir, \"checkpoint_993/checkpoint-993\"))", "2020-03-04 21:52:15,295\tWARNING trainable.py:210 -- Getting current IP.\n2020-03-04 21:52:15,299\tINFO trainable.py:416 -- Restored on 172.27.234.225 from checkpoint: /Users/jasonfiacco/ray_results/DQN9-big/DQN_ray_trading_env_7a427ba4_0_lr=0.0001_2020-03-04_00-32-02kz2wv4_s/checkpoint_993/checkpoint-993\n2020-03-04 21:52:15,301\tINFO trainable.py:423 -- Current state after restoring: {'_iteration': 993, '_timesteps_total': 1000944, '_time_total': 75190.61388278008, '_episodes_total': 1717}\n" ], [ "trainer.restore(\"/Users/jasonfiacco/ray_results/DQN4/DQN_ray_trading_env_fedb24f0_0_lr=1e-06_2020-03-03_15-46-02kzbdv53d/checkpoint_5/checkpoint-5\")", "_____no_output_____" ] ], [ [ "## Testing", "_____no_output_____" ] ], [ [ "#Set up a testing environment with test data.\ntest_env = TradingEnvironment(\n feed=feed,\n portfolio=portfolio,\n action_scheme='simple',\n reward_scheme='simple',\n window_size=15,\n enable_logger=False,\n renderers = 'screenlog'\n)", "/Users/jasonfiacco/Documents/Yale/Senior/thesis/env2/lib/python3.6/site-packages/gym/logger.py:30: UserWarning:\n\n\u001b[33mWARN: Box bound precision lowered by casting to float32\u001b[0m\n\n" ], [ "for episode_num in range(1):\n state = test_env.reset()\n done = False\n cumulative_reward = 0\n step = 0\n action = trainer.compute_action(state)\n\n while not done:\n action = trainer.compute_action(state)\n state, reward, done, results = test_env.step(action)\n\n cumulative_reward += reward\n \n #Render every 100 steps:\n if step % 100 == 0:\n test_env.render()\n \n step += 1\n \nprint(\"Cumulative reward: \", cumulative_reward)", "[2020-03-04 9:54:39 PM] Step: 1\n[2020-03-04 9:54:41 PM] Step: 101\n[2020-03-04 9:54:44 PM] Step: 201\n[2020-03-04 9:54:47 PM] Step: 301\n[2020-03-04 9:54:50 PM] Step: 401\n[2020-03-04 9:54:52 PM] Step: 501\n[2020-03-04 9:54:55 PM] Step: 601\n[2020-03-04 9:54:58 PM] Step: 701\nCumulative reward: 4.969025307093819\n" ] ], [ [ "## Plot", "_____no_output_____" ] ], [ [ "%matplotlib inline\n\nportfolio.performance.plot()", "_____no_output_____" ], [ "portfolio.performance.net_worth.plot()", "_____no_output_____" ], [ "#Plot the total balance in each type of item\np = portfolio.performance\np2 = p.iloc[:, :]\nweights = p2.loc[:, [(\"/worth\" in name) for name in p2.columns]]\nweights.iloc[:, 1:8].plot()\n", "_____no_output_____" ] ], [ [ "## Try Plotly Render too", "_____no_output_____" ] ], [ [ "from tensortrade.environments.render import PlotlyTradingChart\nfrom tensortrade.environments.render import FileLogger\n\nchart_renderer = PlotlyTradingChart(\n height = 800\n)\n\nfile_logger = FileLogger(\n filename='example.log', # omit or None for automatic file name\n path='training_logs' # create a new directory if doesn't exist, None for no directory\n)", "_____no_output_____" ], [ "price_history.columns = ['datetime', 'open', 'high', 'low', 'close', 'volume']", "_____no_output_____" ], [ "env = TradingEnvironment(\n feed=feed,\n portfolio=portfolio,\n action_scheme='managed-risk',\n reward_scheme='risk-adjusted',\n window_size=20,\n price_history=price_history,\n renderers = [chart_renderer, file_logger]\n)", "_____no_output_____" ], [ "from tensortrade.agents import DQNAgent\n\nagent = DQNAgent(env)\nagent.train(n_episodes=1, n_steps=1000, render_interval=1)", "_____no_output_____" ] ], [ [ "## Extra Stuff", "_____no_output_____" ] ], [ [ "apath = \"/Users/jasonfiacco/Documents/Yale/Senior/thesis/jasonfiacco-selectedmarkets-mytickers.xlsx\"\ndf = pd.read_excel(apath, skiprows=2)\njason_tickers = df.iloc[:, 5].tolist()\ndescriptions = df.iloc[:, 1].tolist()\n\nfor ticker, description in zip(jason_tickers, descriptions):\n l = \"{} = Instrument(\\'{}\\', 2, \\'{}\\')\".format(ticker, ticker, description)\n print(l)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
d03262b56d43bff29e66d366f772cdcf55a91d35
10,361
ipynb
Jupyter Notebook
dict_ocr.ipynb
vanessapigwin/scrapingpractice
cfd9326e880ccaded215643eba5ddf9e1c7d72c2
[ "MIT" ]
null
null
null
dict_ocr.ipynb
vanessapigwin/scrapingpractice
cfd9326e880ccaded215643eba5ddf9e1c7d72c2
[ "MIT" ]
null
null
null
dict_ocr.ipynb
vanessapigwin/scrapingpractice
cfd9326e880ccaded215643eba5ddf9e1c7d72c2
[ "MIT" ]
null
null
null
28.231608
101
0.542033
[ [ [ "## 1. Convert pdf to image", "_____no_output_____" ] ], [ [ "## NOTE: install tesseract (https://github.com/UB-Mannheim/tesseract/wiki) and Poppler first\n# !pip install pytesseract\n# !pip install Pillow\n# !pip install pdf2image", "_____no_output_____" ], [ "# import statements\nfrom PIL import Image\nfrom pdf2image import convert_from_path\nimport sys\nimport os\nimport numpy as np", "_____no_output_____" ], [ "folder_path = 'C:\\\\Users\\Vanessa\\\\Downloads\\\\for_ocr'\nfile_list = os.listdir(folder_path)\n\n# remove duplicates from list\nunique_files = [file for file in file_list if \"(1)\" not in file]\n\n\n# convert pdf to image in PNG format \ndef pdf_to_imgs(folder_path, file):\n pages = convert_from_path(f\"{folder_path}\\\\{file}\", 500)\n \n # counter for image file\n img_counter = 1\n \n # for each unique page, make a filename and save as png\n for page in pages:\n filename = f\"{file}_{img_counter}.png\".replace('.pdf','')\n print(f'Saving {filename}')\n page.save(filename, 'PNG')\n img_counter += 1", "_____no_output_____" ], [ "for file in unique_files:\n pdf_to_imgs(folder_path, file)", "_____no_output_____" ] ], [ [ "## 2. Check file integrity, size", "_____no_output_____" ] ], [ [ "folder_path = 'C:\\\\Users\\\\Vanessa\\\\Jupyter Notebooks\\\\STUFF'\nfile_list = [f for f in os.listdir(folder_path) if f.endswith('.png')]\n\nprint('Total files to check:', len(file_list))\n\n# getting maximum dimension of each image\nmax_width = 0\nmax_height = 0\nfor file in file_list:\n try:\n with Image.open(os.path.join(folder_path, file)) as img:\n width, height = img.size\n if width > max_width:\n max_width = width\n if height > max_height:\n max_height = height\n except:\n print(file)\n\nprint('Maximum Width: ', max_width)\nprint('Maximum Height: ', max_height)", "_____no_output_____" ] ], [ [ "## 3. Convert image to OCR", "_____no_output_____" ] ], [ [ "import cv2 as cv\nimport pytesseract\n\npytesseract.pytesseract.tesseract_cmd=r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\ncustom_config = r' --psm 6'", "_____no_output_____" ], [ "# method to ocr\ndef remove_header_bg(img):\n \n # convert image to hsv\n img_hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)\n h, s, v = cv.split(img_hsv)\n\n # threshold saturation img\n thresh1 = cv.threshold(s, 92, 255, cv.THRESH_BINARY)[1]\n\n # threshold value img then invert\n thresh2 = cv.threshold(v, 128, 255, cv.THRESH_BINARY_INV)[1]\n\n # make mask\n mask = cv.add(thresh1, thresh2)\n\n # apply mask to remove unwanted background on figure\n processed_img = img.copy()\n processed_img[mask==0] = (255,255,255)\n lined_img = processed_img.copy()\n\n # convert to greyscale \n gray = cv.cvtColor(lined_img, cv.COLOR_BGR2GRAY)\n blur = cv.GaussianBlur(gray,(5,5),0)\n thresh = cv.threshold(blur, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)[1]\n\n # remove horizontal lines\n hor_kernel = cv.getStructuringElement(cv.MORPH_RECT, (100,1))\n remove_hor = cv.morphologyEx(thresh, cv.MORPH_OPEN, hor_kernel, iterations=2)\n cnts = cv.findContours(remove_hor, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n for c in cnts:\n cv.drawContours(lined_img, [c], -1, (255,255,255), 5)\n\n # try to read text\n text = pytesseract.image_to_string(lined_img, config=custom_config)\n return text\n ", "_____no_output_____" ], [ "# get imgage files\nimg_path = os.path.abspath('')\nimgs = [file for file in os.listdir(img_path) if file.endswith('.png')]\nimgs.sort()", "_____no_output_____" ], [ "for img in imgs:\n fname = os.path.splitext(img)[0]\n \n image = cv.imread(img)\n title = remove_header_bg(image[1200:1700 , 100:5900])\n header = remove_header_bg(image[1800:1950 , 100:5900])\n contents = remove_header_bg(image[2100:7100 , 100:5900])\n \n with open(f'{fname}.txt', 'a') as f:\n f.write(title)\n f.write(header)\n f.write(contents)\n \n print(fname,' converted')\n \nprint('All img files converted')", "HH-001_1 converted\nHH-002_1 converted\nHH-003_1 converted\nHH-004_1 converted\nHH-005_1 converted\nHH-006_1 converted\nHH-006_2 converted\nHH-007_1 converted\nHH-008_1 converted\nHH-010_1 converted\nHH-010_2 converted\nHH-011_1 converted\nHH-011_2 converted\nHH-012_1 converted\nHH-013_1 converted\nHH-013_2 converted\nHH-014_1 converted\nHH-014_2 converted\nHH-015_1 converted\nHH-015_2 converted\nHH-015_3 converted\nHH-015_4 converted\nIND-003_1 converted\nIND-003_2 converted\nIND-004_1 converted\nIND-004_2 converted\nIND-004_3 converted\nIND-005_1 converted\nIND-005_2 converted\nIND-005_3 converted\nIND-012_1 converted\nIND-015_1 converted\nIND-015_2 converted\nIND-015_3 converted\nIND-017_1 converted\nIND-017_2 converted\nIND-017_3 converted\nIND-047_1 converted\nIND_001_1 converted\nIND_002_1 converted\nIND_006_1 converted\nIND_007_1 converted\nIND_008_1 converted\nIND_009_1 converted\nIND_009_2 converted\nIND_010_1 converted\nIND_010_2 converted\nIND_010_3 converted\nIND_010_4 converted\nIND_010_5 converted\nIND_012_1 converted\nIND_013_1 converted\nIND_013_2 converted\nIND_014_1 converted\nIND_014_2 converted\nIND_014_3 converted\nIND_018_1 converted\nIND_019_1 converted\nIND_019_2 converted\nIND_020_1 converted\nIND_022_1 converted\nIND_022_2 converted\nIND_022_3 converted\nIND_022_4 converted\nIND_022_5 converted\nIND_023_1 converted\nIND_024_1 converted\nIND_024_2 converted\nIND_025_1 converted\nIND_025_2 converted\nIND_026_1 converted\nIND_027_1 converted\nIND_029_1 converted\nIND_031_1 converted\nIND_031_2 converted\nIND_032_1 converted\nIND_033_1 converted\nIND_033_2 converted\nIND_035_1 converted\nIND_035_2 converted\nIND_036_1 converted\nIND_037_1 converted\nIND_037_2 converted\nIND_038_1 converted\nIND_038_2 converted\nIND_039_1 converted\nIND_039_2 converted\nIND_039_3 converted\nIND_039_4 converted\nIND_039_5 converted\nIND_040_1 converted\nIND_040_2 converted\nIND_041_1 converted\nIND_041_2 converted\nIND_042_1 converted\nIND_042_2 converted\nIND_043_1 converted\nIND_043_2 converted\nIND_044_1 converted\nIND_044_2 converted\nIND_045_1 converted\nIND_047_1 converted\nIND_048_1 converted\nIND_049_1 converted\nIND_050_1 converted\nIND_051_1 converted\nIND_053_1 converted\nIND_055_1 converted\nAll img files converted\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
d03266823ea9870443a585ad855dc4af15678e96
234,758
ipynb
Jupyter Notebook
13-Smoothing.ipynb
yangzongsheng/kalman
0e43c1b9aef4242bf794fd5086319b1db496d057
[ "CC-BY-4.0" ]
1
2021-08-16T02:07:09.000Z
2021-08-16T02:07:09.000Z
13-Smoothing.ipynb
zhpfu/Kalman-and-Bayesian-Filters-in-Python
0e43c1b9aef4242bf794fd5086319b1db496d057
[ "CC-BY-4.0" ]
null
null
null
13-Smoothing.ipynb
zhpfu/Kalman-and-Bayesian-Filters-in-Python
0e43c1b9aef4242bf794fd5086319b1db496d057
[ "CC-BY-4.0" ]
2
2021-02-10T18:36:32.000Z
2022-01-02T02:17:23.000Z
283.866989
39,884
0.909025
[ [ [ "[Table of Contents](./table_of_contents.ipynb)", "_____no_output_____" ], [ "# Smoothing", "_____no_output_____" ] ], [ [ "#format the book\n%matplotlib inline\nfrom __future__ import division, print_function\nfrom book_format import load_style\nload_style()", "_____no_output_____" ] ], [ [ "## Introduction", "_____no_output_____" ], [ "The performance of the Kalman filter is not optimal when you consider future data. For example, suppose we are tracking an aircraft, and the latest measurement deviates far from the current track, like so (I'll only consider 1 dimension for simplicity):", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\n\ndata = [10.1, 10.2, 9.8, 10.1, 10.2, 10.3, \n 10.1, 9.9, 10.2, 10.0, 9.9, 11.4]\nplt.plot(data)\nplt.xlabel('time')\nplt.ylabel('position');", "_____no_output_____" ] ], [ [ "After a period of near steady state, we have a very large change. Assume the change is past the limit of the aircraft's flight envelope. Nonetheless the Kalman filter incorporates that new measurement into the filter based on the current Kalman gain. It cannot reject the noise because the measurement could reflect the initiation of a turn. Granted it is unlikely that we are turning so abruptly, but it is impossible to say whether \n \n* The aircraft started a turn awhile ago, but the previous measurements were noisy and didn't show the change.\n \n* The aircraft is turning, and this measurement is very noisy\n \n* The measurement is very noisy and the aircraft has not turned\n\n* The aircraft is turning in the opposite direction, and the measurement is extremely noisy\n\n\nNow, suppose the following measurements are:\n\n 11.3 12.1 13.3 13.9 14.5 15.2\n ", "_____no_output_____" ] ], [ [ "data2 = [11.3, 12.1, 13.3, 13.9, 14.5, 15.2]\nplt.plot(data + data2);", "_____no_output_____" ] ], [ [ "Given these future measurements we can infer that yes, the aircraft initiated a turn. \n\nOn the other hand, suppose these are the following measurements.", "_____no_output_____" ] ], [ [ "data3 = [9.8, 10.2, 9.9, 10.1, 10.0, 10.3, 9.9, 10.1]\nplt.plot(data + data3);", "_____no_output_____" ] ], [ [ "In this case we are led to conclude that the aircraft did not turn and that the outlying measurement was merely very noisy. ", "_____no_output_____" ], [ "## An Overview of How Smoothers Work\n\nThe Kalman filter is a *recursive* filter with the Markov property - it's estimate at step `k` is based only on the estimate from step `k-1` and the measurement at step `k`. But this means that the estimate from step `k-1` is based on step `k-2`, and so on back to the first epoch. Hence, the estimate at step `k` depends on all of the previous measurements, though to varying degrees. `k-1` has the most influence, `k-2` has the next most, and so on. \n\nSmoothing filters incorporate future measurements into the estimate for step `k`. The measurement from `k+1` will have the most effect, `k+2` will have less effect, `k+3` less yet, and so on. \n\nThis topic is called *smoothing*, but I think that is a misleading name. I could smooth the data above by passing it through a low pass filter. The result would be smooth, but not necessarily accurate because a low pass filter will remove real variations just as much as it removes noise. In contrast, Kalman smoothers are *optimal* - they incorporate all available information to make the best estimate that is mathematically achievable.", "_____no_output_____" ], [ "## Types of Smoothers\n\nThere are three classes of Kalman smoothers that produce better tracking in these situations.\n\n* Fixed-Interval Smoothing\n\nThis is a batch processing based filter. This filter waits for all of the data to be collected before making any estimates. For example, you may be a scientist collecting data for an experiment, and don't need to know the result until the experiment is complete. A fixed-interval smoother will collect all the data, then estimate the state at each measurement using all available previous and future measurements. If it is possible for you to run your Kalman filter in batch mode it is always recommended to use one of these filters a it will provide much better results than the recursive forms of the filter from the previous chapters.\n\n\n* Fixed-Lag Smoothing\n\nFixed-lag smoothers introduce latency into the output. Suppose we choose a lag of 4 steps. The filter will ingest the first 3 measurements but not output a filtered result. Then, when the 4th measurement comes in the filter will produce the output for measurement 1, taking measurements 1 through 4 into account. When the 5th measurement comes in, the filter will produce the result for measurement 2, taking measurements 2 through 5 into account. This is useful when you need recent data but can afford a bit of lag. For example, perhaps you are using machine vision to monitor a manufacturing process. If you can afford a few seconds delay in the estimate a fixed-lag smoother will allow you to produce very accurate and smooth results.\n\n\n* Fixed-Point Smoothing\n\nA fixed-point filter operates as a normal Kalman filter, but also produces an estimate for the state at some fixed time $j$. Before the time $k$ reaches $j$ the filter operates as a normal filter. Once $k>j$ the filter estimates $x_k$ and then also updates its estimate for $x_j$ using all of the measurements between $j\\dots k$. This can be useful to estimate initial paramters for a system, or for producing the best estimate for an event that happened at a specific time. For example, you may have a robot that took a photograph at time $j$. You can use a fixed-point smoother to get the best possible pose information for the camera at time $j$ as the robot continues moving.\n\n## Choice of Filters\n\nThe choice of these filters depends on your needs and how much memory and processing time you can spare. Fixed-point smoothing requires storage of all measurements, and is very costly to compute because the output is for every time step is recomputed for every measurement. On the other hand, the filter does produce a decent output for the current measurement, so this filter can be used for real time applications.\n\nFixed-lag smoothing only requires you to store a window of data, and processing requirements are modest because only that window is processed for each new measurement. The drawback is that the filter's output always lags the input, and the smoothing is not as pronounced as is possible with fixed-interval smoothing.\n\nFixed-interval smoothing produces the most smoothed output at the cost of having to be batch processed. Most algorithms use some sort of forwards/backwards algorithm that is only twice as slow as a recursive Kalman filter. ", "_____no_output_____" ], [ "## Fixed-Interval Smoothing", "_____no_output_____" ], [ "There are many fixed-lag smoothers available in the literature. I have chosen to implement the smoother invented by Rauch, Tung, and Striebel because of its ease of implementation and efficiency of computation. It is also the smoother I have seen used most often in real applications. This smoother is commonly known as an RTS smoother.\n\nDerivation of the RTS smoother runs to several pages of densely packed math. I'm not going to inflict it on you. Instead I will briefly present the algorithm, equations, and then move directly to implementation and demonstration of the smoother.\n\nThe RTS smoother works by first running the Kalman filter in a batch mode, computing the filter output for each step. Given the filter output for each measurement along with the covariance matrix corresponding to each output the RTS runs over the data backwards, incorporating its knowledge of the future into the past measurements. When it reaches the first measurement it is done, and the filtered output incorporates all of the information in a maximally optimal form.\n\nThe equations for the RTS smoother are very straightforward and easy to implement. This derivation is for the linear Kalman filter. Similar derivations exist for the EKF and UKF. These steps are performed on the output of the batch processing, going backwards from the most recent in time back to the first estimate. Each iteration incorporates the knowledge of the future into the state estimate. Since the state estimate already incorporates all of the past measurements the result will be that each estimate will contain knowledge of all measurements in the past and future. Here is it very important to distinguish between past, present, and future so I have used subscripts to denote whether the data is from the future or not.\n\n Predict Step\n \n$$\\begin{aligned}\n\\mathbf{P} &= \\mathbf{FP}_k\\mathbf{F}^\\mathsf{T} + \\mathbf{Q }\n\\end{aligned}$$\n\n Update Step\n \n$$\\begin{aligned}\n\\mathbf{K}_k &= \\mathbf{P}_k\\mathbf{F}^\\mathsf{T}\\mathbf{P}^{-1} \\\\\n\\mathbf{x}_k &= \\mathbf{x}_k + \\mathbf{K}_k(\\mathbf{x}_{k+1} - \\mathbf{Fx}_k) \\\\\n\\mathbf{P}_k &= \\mathbf{P}_k + \\mathbf{K}_k(\\mathbf{P}_{k+1} - \\mathbf{P})\\mathbf{K}_k^\\mathsf{T}\n\\end{aligned}$$\n\nAs always, the hardest part of the implementation is correctly accounting for the subscripts. A basic implementation without comments or error checking would be:\n\n```python\ndef rts_smoother(Xs, Ps, F, Q):\n n, dim_x, _ = Xs.shape\n\n # smoother gain\n K = zeros((n,dim_x, dim_x))\n x, P, Pp = Xs.copy(), Ps.copy(), Ps.copy\n\n for k in range(n-2,-1,-1):\n Pp[k] = dot(F, P[k]).dot(F.T) + Q # predicted covariance\n\n K[k] = dot(P[k], F.T).dot(inv(Pp[k]))\n x[k] += dot(K[k], x[k+1] - dot(F, x[k]))\n P[k] += dot(K[k], P[k+1] - Pp[k]).dot(K[k].T)\n return (x, P, K, Pp)\n```\n \nThis implementation mirrors the implementation provided in FilterPy. It assumes that the Kalman filter is being run externally in batch mode, and the results of the state and covariances are passed in via the `Xs` and `Ps` variable.\n\nHere is an example. ", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom numpy import random\nfrom numpy.random import randn\nimport matplotlib.pyplot as plt\nfrom filterpy.kalman import KalmanFilter\nimport kf_book.book_plots as bp\n\ndef plot_rts(noise, Q=0.001, show_velocity=False):\n random.seed(123)\n fk = KalmanFilter(dim_x=2, dim_z=1)\n\n fk.x = np.array([0., 1.]) # state (x and dx)\n\n fk.F = np.array([[1., 1.],\n [0., 1.]]) # state transition matrix\n\n fk.H = np.array([[1., 0.]]) # Measurement function\n fk.P = 10. # covariance matrix\n fk.R = noise # state uncertainty\n fk.Q = Q # process uncertainty\n\n # create noisy data\n zs = np.asarray([t + randn()*noise for t in range (40)])\n\n # filter data with Kalman filter, than run smoother on it\n mu, cov, _, _ = fk.batch_filter(zs)\n M, P, C, _ = fk.rts_smoother(mu, cov)\n\n # plot data\n if show_velocity:\n index = 1\n print('gu')\n else:\n index = 0\n if not show_velocity:\n bp.plot_measurements(zs, lw=1)\n plt.plot(M[:, index], c='b', label='RTS')\n plt.plot(mu[:, index], c='g', ls='--', label='KF output')\n if not show_velocity:\n N = len(zs)\n plt.plot([0, N], [0, N], 'k', lw=2, label='track') \n plt.legend(loc=4)\n plt.show()\n \nplot_rts(7.)", "_____no_output_____" ] ], [ [ "I've injected a lot of noise into the signal to allow you to visually distinguish the RTS output from the ideal output. In the graph above we can see that the Kalman filter, drawn as the green dotted line, is reasonably smooth compared to the input, but it still wanders from from the ideal line when several measurements in a row are biased towards one side of the line. In contrast, the RTS output is both extremely smooth and very close to the ideal output.\n\nWith a perhaps more reasonable amount of noise we can see that the RTS output nearly lies on the ideal output. The Kalman filter output, while much better, still varies by a far greater amount.", "_____no_output_____" ] ], [ [ "plot_rts(noise=1.)", "_____no_output_____" ] ], [ [ "However, we must understand that this smoothing is predicated on the system model. We have told the filter that what we are tracking follows a constant velocity model with very low process error. When the filter *looks ahead* it sees that the future behavior closely matches a constant velocity so it is able to reject most of the noise in the signal. Suppose instead our system has a lot of process noise. For example, if we are tracking a light aircraft in gusty winds its velocity will change often, and the filter will be less able to distinguish between noise and erratic movement due to the wind. We can see this in the next graph. ", "_____no_output_____" ] ], [ [ "plot_rts(noise=7., Q=.1)", "_____no_output_____" ] ], [ [ "This underscores the fact that these filters are not *smoothing* the data in colloquial sense of the term. The filter is making an optimal estimate based on previous measurements, future measurements, and what you tell it about the behavior of the system and the noise in the system and measurements.\n\nLet's wrap this up by looking at the velocity estimates of Kalman filter vs the RTS smoother.", "_____no_output_____" ] ], [ [ "plot_rts(7.,show_velocity=True)", "gu\n" ] ], [ [ "The improvement in the velocity, which is an hidden variable, is even more dramatic. ", "_____no_output_____" ], [ "## Fixed-Lag Smoothing\n\nThe RTS smoother presented above should always be your choice of algorithm if you can run in batch mode because it incorporates all available data into each estimate. Not all problems allow you to do that, but you may still be interested in receiving smoothed values for previous estimates. The number line below illustrates this concept.", "_____no_output_____" ] ], [ [ "from kf_book.book_plots import figsize\nfrom kf_book.smoothing_internal import *\n\nwith figsize(y=2):\n show_fixed_lag_numberline()", "_____no_output_____" ] ], [ [ "At step $k$ we can estimate $x_k$ using the normal Kalman filter equations. However, we can make a better estimate for $x_{k-1}$ by using the measurement received for $x_k$. Likewise, we can make a better estimate for $x_{k-2}$ by using the measurements recevied for $x_{k-1}$ and $x_{k}$. We can extend this computation back for an arbitrary $N$ steps.\n\nDerivation for this math is beyond the scope of this book; Dan Simon's *Optimal State Estimation* [2] has a very good exposition if you are interested. The essense of the idea is that instead of having a state vector $\\mathbf{x}$ we make an augmented state containing\n\n$$\\mathbf{x} = \\begin{bmatrix}\\mathbf{x}_k \\\\ \\mathbf{x}_{k-1} \\\\ \\vdots\\\\ \\mathbf{x}_{k-N+1}\\end{bmatrix}$$\n\nThis yields a very large covariance matrix that contains the covariance between states at different steps. FilterPy's class `FixedLagSmoother` takes care of all of this computation for you, including creation of the augmented matrices. All you need to do is compose it as if you are using the `KalmanFilter` class and then call `smooth()`, which implements the predict and update steps of the algorithm. \n\nEach call of `smooth` computes the estimate for the current measurement, but it also goes back and adjusts the previous `N-1` points as well. The smoothed values are contained in the list `FixedLagSmoother.xSmooth`. If you use `FixedLagSmoother.x` you will get the most recent estimate, but it is not smoothed and is no different from a standard Kalman filter output.", "_____no_output_____" ] ], [ [ "from filterpy.kalman import FixedLagSmoother, KalmanFilter\nimport numpy.random as random\n\nfls = FixedLagSmoother(dim_x=2, dim_z=1, N=8)\n\nfls.x = np.array([0., .5])\nfls.F = np.array([[1.,1.],\n [0.,1.]])\n\nfls.H = np.array([[1.,0.]])\nfls.P *= 200\nfls.R *= 5.\nfls.Q *= 0.001\n\nkf = KalmanFilter(dim_x=2, dim_z=1)\nkf.x = np.array([0., .5])\nkf.F = np.array([[1.,1.],\n [0.,1.]])\nkf.H = np.array([[1.,0.]])\nkf.P *= 200\nkf.R *= 5.\nkf.Q *= 0.001\n\nN = 4 # size of lag\n\nnom = np.array([t/2. for t in range (0, 40)])\nzs = np.array([t + random.randn()*5.1 for t in nom])\n\nfor z in zs:\n fls.smooth(z)\n \nkf_x, _, _, _ = kf.batch_filter(zs)\nx_smooth = np.array(fls.xSmooth)[:, 0]\n\n\nfls_res = abs(x_smooth - nom)\nkf_res = abs(kf_x[:, 0] - nom)\n\nplt.plot(zs,'o', alpha=0.5, marker='o', label='zs')\nplt.plot(x_smooth, label='FLS')\nplt.plot(kf_x[:, 0], label='KF', ls='--')\nplt.legend(loc=4)\n\nprint('standard deviation fixed-lag: {:.3f}'.format(np.mean(fls_res)))\nprint('standard deviation kalman: {:.3f}'.format(np.mean(kf_res)))", "standard deviation fixed-lag: 2.616\nstandard deviation kalman: 3.562\n" ] ], [ [ "Here I have set `N=8` which means that we will incorporate 8 future measurements into our estimates. This provides us with a very smooth estimate once the filter converges, at the cost of roughly 8x the amount of computation of the standard Kalman filter. Feel free to experiment with larger and smaller values of `N`. I chose 8 somewhat at random, not due to any theoretical concerns.", "_____no_output_____" ], [ "## References", "_____no_output_____" ], [ "[1] H. Rauch, F. Tung, and C. Striebel. \"Maximum likelihood estimates of linear dynamic systems,\" *AIAA Journal*, **3**(8), pp. 1445-1450 (August 1965).\n\n[2] Dan Simon. \"Optimal State Estimation,\" John Wiley & Sons, 2006.\n\nhttp://arc.aiaa.org/doi/abs/10.2514/3.3166", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
d032748b4a476184043cdde3fa1dcf78d70e1cfa
36,839
ipynb
Jupyter Notebook
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
1ff723cf37af902b400dbb68777a52e6e3dfcc89
[ "MIT" ]
57
2021-02-11T12:25:30.000Z
2022-03-16T11:47:21.000Z
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
1ff723cf37af902b400dbb68777a52e6e3dfcc89
[ "MIT" ]
8
2021-02-22T01:38:36.000Z
2021-06-29T15:55:04.000Z
chapter2/section2_1-AE.ipynb
tms-byte/gan_sample
1ff723cf37af902b400dbb68777a52e6e3dfcc89
[ "MIT" ]
11
2021-02-11T14:49:08.000Z
2022-01-26T04:18:11.000Z
36,839
36,839
0.762453
[ [ [ "# 準備", "_____no_output_____" ] ], [ [ "# バージョン指定時にコメントアウト\n#!pip install torch==1.7.0\n#!pip install torchvision==0.8.1\n\nimport torch\nimport torchvision\n# バージョンの確認\nprint(torch.__version__) \nprint(torchvision.__version__) ", "1.7.0+cu101\n0.8.1+cu101\n" ], [ "# Google ドライブにマウント\nfrom google.colab import drive\ndrive.mount('/content/gdrive')", "Mounted at /content/gdrive\n" ], [ "%cd '/content/gdrive/MyDrive/Colab Notebooks/gan_sample/chapter2'", "/content/gdrive/MyDrive/Colab Notebooks/gan_sample/chapter2\n" ], [ "import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optimizers\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ] ], [ [ "# データセットの作成", "_____no_output_____" ] ], [ [ "np.random.seed(1234)\ntorch.manual_seed(1234)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# データの取得\nroot = os.path.join('data', 'mnist')\ntransform = transforms.Compose([transforms.ToTensor(),\n lambda x: x.view(-1)])\nmnist_train = \\\n torchvision.datasets.MNIST(root=root,\n download=True,\n train=True,\n transform=transform)\nmnist_test = \\\n torchvision.datasets.MNIST(root=root,\n download=True,\n train=False,\n transform=transform)\ntrain_dataloader = DataLoader(mnist_train,\n batch_size=100,\n shuffle=True)\ntest_dataloader = DataLoader(mnist_test,\n batch_size=1,\n shuffle=False)", "Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to data/mnist/MNIST/raw/train-images-idx3-ubyte.gz\n" ] ], [ [ "# ネットワークの定義", "_____no_output_____" ] ], [ [ "class Autoencoder(nn.Module):\n def __init__(self, device='cpu'):\n super().__init__()\n self.device = device\n self.l1 = nn.Linear(784, 200)\n self.l2 = nn.Linear(200, 784)\n\n def forward(self, x):\n # エンコーダ\n h = self.l1(x)\n # 活性化関数\n h = torch.relu(h)\n\n # デコーダ\n h = self.l2(h)\n # シグモイド関数で0~1の値域に変換 \n y = torch.sigmoid(h)\n\n return y", "_____no_output_____" ] ], [ [ "# 学習の実行", "_____no_output_____" ] ], [ [ "# モデルの設定\nmodel = Autoencoder(device=device).to(device)\n# 損失関数の設定\ncriterion = nn.BCELoss()\n# 最適化関数の設定\noptimizer = optimizers.Adam(model.parameters())", "_____no_output_____" ], [ "epochs = 10\n# エポックのループ\nfor epoch in range(epochs):\n train_loss = 0.\n # バッチサイズのループ\n for (x, _) in train_dataloader:\n x = x.to(device)\n # 訓練モードへの切替\n model.train()\n # 順伝播計算\n preds = model(x)\n # 入力画像xと復元画像predsの誤差計算\n loss = criterion(preds, x)\n # 勾配の初期化\n optimizer.zero_grad()\n # 誤差の勾配計算\n loss.backward()\n # パラメータの更新\n optimizer.step()\n # 訓練誤差の更新\n train_loss += loss.item()\n\n train_loss /= len(train_dataloader)\n\n print('Epoch: {}, Loss: {:.3f}'.format(\n epoch+1,\n train_loss\n ))", "Epoch: 1, Loss: 0.153\nEpoch: 2, Loss: 0.085\nEpoch: 3, Loss: 0.075\nEpoch: 4, Loss: 0.071\nEpoch: 5, Loss: 0.069\nEpoch: 6, Loss: 0.068\nEpoch: 7, Loss: 0.067\nEpoch: 8, Loss: 0.067\nEpoch: 9, Loss: 0.066\nEpoch: 10, Loss: 0.066\n" ] ], [ [ "# 画像の復元", "_____no_output_____" ] ], [ [ "# dataloaderからのデータ取り出し\r\nx, _ = next(iter(test_dataloader))\r\nx = x.to(device)\r\n\r\n# 評価モードへの切替\r\nmodel.eval()\r\n# 復元画像\r\nx_rec = model(x)\r\n\r\n# 入力画像、復元画像の表示\r\nfor i, image in enumerate([x, x_rec]):\r\n image = image.view(28, 28).detach().cpu().numpy()\r\n plt.subplot(1, 2, i+1)\r\n plt.imshow(image, cmap='binary_r')\r\n plt.axis('off')\r\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
d0327a9a8970d057449ecec3a2b23285ce8bcba2
15,976
ipynb
Jupyter Notebook
docs/_sources/Module1/m1_06.ipynb
liuzhengqi1996/math452_Spring2022
b01d1d9bee4778b3069e314c775a54f16dd44053
[ "MIT" ]
null
null
null
docs/_sources/Module1/m1_06.ipynb
liuzhengqi1996/math452_Spring2022
b01d1d9bee4778b3069e314c775a54f16dd44053
[ "MIT" ]
null
null
null
docs/_sources/Module1/m1_06.ipynb
liuzhengqi1996/math452_Spring2022
b01d1d9bee4778b3069e314c775a54f16dd44053
[ "MIT" ]
null
null
null
37.067285
811
0.520468
[ [ [ "# Optimization and gradient descent method", "_____no_output_____" ] ], [ [ "from IPython.display import IFrame\n\nIFrame(src=\"https://cdnapisec.kaltura.com/p/2356971/sp/235697100/embedIframeJs/uiconf_id/41416911/partner_id/2356971?iframeembed=true&playerId=kaltura_player&entry_id=1_wota11ay&flashvars[streamerType]=auto&amp;flashvars[localizationCode]=en&amp;flashvars[leadWithHTML5]=true&amp;flashvars[sideBarContainer.plugin]=true&amp;flashvars[sideBarContainer.position]=left&amp;flashvars[sideBarContainer.clickToClose]=true&amp;flashvars[chapters.plugin]=true&amp;flashvars[chapters.layout]=vertical&amp;flashvars[chapters.thumbnailRotator]=false&amp;flashvars[streamSelector.plugin]=true&amp;flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&amp;flashvars[dualScreen.plugin]=true&amp;flashvars[hotspots.plugin]=1&amp;flashvars[Kaltura.addCrossoriginToIframe]=true&amp;&wid=1_o38cisoq\",width='800', height='500')", "_____no_output_____" ] ], [ [ "## Download the lecture notes here: [Notes](https://sites.psu.edu/math452/files/2021/12/A06GradientDescent_Video_Notes.pdf)", "_____no_output_____" ], [ "## Gradient descent method\n\nFor simplicity, let us just consider a general optimization problem\n\n$$\n \\label{optmodel}\n \\min_{x\\in \\mathbb{R}^n } f(x).\n$$ (problem)\n\n![image](../figures/diag_GD.png)\n\n### A general approach: line search method\n\nGiven any initial guess $x_1$, the line search method uses the following\nalgorithm\n\n$$\n \\eta_t= argmin_{\\eta\\in \\mathbb{R}^1} f(x_t - \\eta p_t)\\qquad \\mbox{(1D minimization problem)}\n$$\n\nto produce $\\{ x_{t}\\}_{t=1}^{\\infty}$ \n\n$$\n x_{t+1} = x_{t} - \\eta_t p_t.\n$$ (line-search)\n\nHere $\\eta_t$ is called the step size in\noptimization and also learning rate in machine learn\ning, $p_t$ is called\nthe descent direction, which is the critical component of this\nalgorithm. And $x_t$ tends to\n\n$$\n x^*= argmin_{x\\in \\mathbb{R}^n} f(x) \\iff f(x^*)=\\min_{x\\in \\mathbb{R}^n} f(x)\n$$\n\nas $t$ tends to infinity. There is a series of optimization algorithms\nwhich follow the above form just using different choices of $p_t$.\n\nThen, the next natural question is what a good choice of $p_t$ is? We\nhave the following theorem to show why gradient direction is a good\nchoice for $p_t$.\n\n```{admonition} lemma\nGiven $x \\in \\mathbb{R}^n$, if $\\nabla f(x)\\neq 0$, the fast descent\ndirection of $f$ at $x$ is the negative gradient direction, namely\n\n$$\n -\\frac{\\nabla f(x)}{\\|\\nabla f(x)\\|} = \\mathop{\\arg\\min}_{ p \\in \\mathbb{R}^n, \\|p\\|=1} \\left. \\frac{\\partial f(x + \\eta p)}{\\partial \\eta} \\right|_{\\eta=0}.\n$$\n\nIt means that $f(x)$ decreases most rapidly along the negative gradient\ndirection.\n```\n\n```{admonition} proof\n*Proof.* Let $p$ be a direction in $\\mathbb{R}^{n},\\|p\\|=1$. Consider\nthe local decrease of the function $f(\\cdot)$ along direction $p$\n\n$$\n \\Delta(p)=\\lim _{\\eta \\downarrow 0} \\frac{1}{\\eta}\\left(f(x+\\eta p)-f(x)\\right)=\\left. \\frac{\\partial f(x + \\eta p)}{\\partial \\eta} \\right|_{\\eta=0}.\n$$\n\nNote that \n\n$$\n \\begin{split}\n\\left. \\frac{\\partial f(x + \\eta p)}{\\partial \\eta} \\right|_{\\eta=0}=\\sum_{i=1}^n\\left. \\frac{\\partial f}{\\partial x_i}(x + \\eta p)p_i \\right|_{\\eta=0} =(\\nabla f, p),\n\\end{split}\n$$\n\nwhich means that\n\n$$\n f(x+\\eta p)-f(x)=\\eta(\\nabla f(x), p)+o(\\eta) .\n$$\n\nTherefore\n\n$$\n \\Delta(p)=(\\nabla f(x), p).\n$$\n\nUsing the Cauchy-Schwarz inequality\n$-\\|x\\| \\cdot\\|y\\| \\leq( x, y) \\leq\\|x\\| \\cdot\\|y\\|,$ we obtain\n\n$$\n -\\|\\nabla f(x)\\| \\le (\\nabla f(x), p)\\le \\|\\nabla f(x)\\| .\n$$\n\nLet us take\n\n$$\n \\bar{p}=-\\nabla f(x) /\\|\\nabla f(x)\\|.\n$$\n\nThen\n\n$$\n \\Delta(\\bar{p})=-(\\nabla f(x), \\nabla f(x)) /\\|\\nabla f(x)\\|=-\\|\\nabla f(x)\\|.\n$$\n\nThe direction $-\\nabla f(x)$ (the antigradient) is the direction of the\nfastest local decrease of the function $f(\\cdot)$ at point $x.$ ◻\n```\n\nHere is a simple diagram for this property.\n\nSince at each point, $f(x)$ decreases most rapidly along the negative\ngradient direction, it is then natural to choose the search direction in\n{eq}`line-search` in the negative gradient direction and the\nresulting algorithm is the so-called gradient descent method.\n\n```{prf:algorithm} Algrihthm\n:label: my_algorithm1\nGiven the initial guess $x_0$, learning rate $\\eta_t>0$\n\n**For** t=1,2,$\\cdots$,\n\n$$\n x_{t+1} = x_{t} - \\eta_{t} \\nabla f({x}_{t}),\n$$\n\n```\n\n\n\nIn practice, we need a \"stopping criterion\" that determines when the\nabove gradient descent method to stop. One possibility is\n\n> **While** $S(x_t; f) = \\|\\nabla f(x_t)\\|\\le \\epsilon$ or $t \\ge T$\n\nfor some small tolerance $\\epsilon>0$ or maximal number of iterations\n$T$. In general, a good stopping criterion is hard to come by and it is\na subject that has called a lot of research in optimization for machine\nlearning.\n\nIn the gradient method, the scalar factors for the gradients,\n$\\eta_{t},$ are called the step sizes. Of course, they must be positive.\nThere are many variants of the gradient method, which differ one from\nanother by the step-size strategy. Let us consider the most important\nexamples.\n\n1. The sequence $\\left\\{\\eta_t\\right\\}_{t=0}^{\\infty}$ is chosen in\n advance. For example, (constant step)\n \n $$\n \\eta_t=\\frac{\\eta}{\\sqrt{t+1}};\n $$\n\n2. Full relaxation:\n\n $$\n \\eta_t=\\arg \\min _{\\eta \\geq 0} f\\left(x_t-\\eta \\nabla f\\left(x_t\\right)\\right);\n $$\n\n3. The Armijo rule: Find $x_{t+1}=x_t-\\eta \\nabla f\\left(x_t\\right)$\n with $\\eta>0$ such that\n \n $$\n \\alpha\\left(\\nabla f\\left(x_t\\right), x_t-x_{t+1}\\right) \\leq f\\left(x_t\\right)-f\\left(x_{t+1}\\right),\n $$\n \n $$\n \\beta\\left(\\nabla f\\left(x_t\\right), x_t-x_{t+1}\\right) \\geq f\\left(x_t\\right)-f\\left(x_{t+1}\\right),\n $$\n \n where $0<\\alpha<\\beta<1$ are some fixed parameters.\n\nComparing these strategies, we see that\n\n1. The first strategy is the simplest one. It is often used in the\n context of convex optimization. In this framework, the behavior of\n functions is much more predictable than in the general nonlinear\n case.\n\n2. The second strategy is completely theoretical. It is never used in\n practice since even in one-dimensional case we cannot find the exact\n minimum in finite time.\n\n3. The third strategy is used in the majority of practical algorithms.\n It has the following geometric interpretation. Let us fix\n $x \\in \\mathbb{R}^{n}$ assuming that $\\nabla f(x) \\neq 0$. Consider\n the following function of one variable:\n \n $$\n \\phi (\\eta)=f(x-\\eta \\nabla f(x)),\\quad \\eta\\ge0.\n $$\n \n Then the\n step-size values acceptable for this strategy belong to the part of\n the graph of $\\phi$ which is located between two linear functions:\n \n $$\n \\phi_{1}(\\eta)=f(x)-\\alpha \\eta\\|\\nabla f(x)\\|^{2}, \\quad \\phi_{2}(\\eta)=f(x)-\\beta \\eta\\|\\nabla f(x)\\|^{2}\n $$\n \n Note that $\\phi(0)=\\phi_{1}(0)=\\phi_{2}(0)$ and\n $\\phi^{\\prime}(0)<\\phi_{2}^{\\prime}(0)<\\phi_{1}^{\\prime}(0)<0 .$\n Therefore, the acceptable values exist unless $\\phi(\\cdot)$ is not\n bounded below. There are several very fast one-dimensional\n procedures for finding a point satisfying the Armijo conditions.\n However, their detailed description is not important for us now.\n \n\n## Convergence of Gradient Descent method\n\nNow we are ready to study the rate of convergence of unconstrained\nminimization schemes. For the optimization problem {eq}`problem`\n\n\n$$\n \\min_{x\\in \\mathbb{R}^n} f(x).\n$$\n\nWe assume that $f(x)$ is convex. Then we say that $x^*$ is a minimizer if\n\n$$\n f(x^*) = \\min_{x \\in \\mathbb{R}^n} f(x).\n$$\n\nFor minimizer $x^*$, we have\n\n$$\n \\label{key}\n \\nabla f(x^*) = 0.\n$$\n\nWe have the next two properties of the minimizer\nfor convex functions:\n\n1. If $f(x) \\ge c_0$, for some $c_0 \\in \\mathbb{R}$, then we have\n\n $$\n \\mathop{\\arg\\min} f \\neq \\emptyset.\n $$\n\n2. If $f(x)$ is $\\lambda$-strongly convex, then $f(x)$ has a unique\n minimizer, namely, there exists a unique $x^*\\in \\mathbb{R}^n$ such\n that\n \n $$\n f(x^*) = \\min_{x\\in \\mathbb{R}^n }f(x).\n $$\n\nTo investigate the convergence of gradient descent method, let us recall\nthe gradient descent method:\n\n```{prf:algorithm} Algorithm\n:label: my_algorithm2\n\n**For**: $t = 1, 2, \\cdots$ \n \n$$\n \\label{equ:fgd-iteration}\n x_{t+1} = x_{t} - \\eta_t \\nabla f(x_t),\n$$\n\nwhere $\\eta_t$ is the stepsize / learning rate.\n```\n\nWe have the next theorem about the convergence of gradient descent\nmethod under the Assumption.\n\n```{admonition} Theorem\nFor Gradient Descent Algorithm {prf:ref}`my_algorithm2` , if\n$f(x)$ satisfies Assumption, then\n\n$$\n \\|x_t - x^*\\|^2 \\le \\alpha^t \\|x_0 - x^*\\|^2\n$$\n\nif $0<\\eta_t <\\frac{2\\lambda}{L^2}$ and $\\alpha < 1$.\n\nParticularly, if $\\eta_t = \\frac{\\lambda}{L^2}$, then\n\n$$\n \\|x_t - x^*\\|^2 \\le \\left(1 - \\frac{\\lambda^2}{L^2}\\right)^t \\|x_0 - x^*\\|^2.\n$$\n```\n\n```{admonition} Proof\n*Proof.* Note that \n\n$$\n x_{t+1} - x = x_{t} - \\eta_t \\nabla f(x_t) - x.\n$$\n\nBy taking $L^2$ norm for both sides, we get\n\n$$\n \\|x_{t+1} - x \\|^2 = \\|x_{t} - \\eta_t \\nabla f(x_t) - x \\|^2.\n$$\n\nLet\n$x = x^*$. It holds that \n\n$$\n \\begin{aligned}\n \\|x_{t+1} - x^* \\|^2 &= \\| x_{t} - \\eta_t \\nabla f(x_t) - x^* \\|^2 \\\\\n &= \\|x_t-x^*\\|^2 - 2\\eta_t \\nabla f(x_t)^\\top (x_t - x^*) + \\eta_t^2 \\|\\nabla f(x_t) - \\nabla f(x^*)\\|^2 \\qquad \\mbox{ (by $\\nabla f(x^*)=0$)}\\\\\n &\\le \\|x_t - x^*\\|^2 - 2\\eta_t \\lambda \\|x_t - x^*\\|^2 + \\eta_t ^2 L^2 \\|x_t - x^*\\|^2 \\quad\n \\mbox{(by $\\lambda$- strongly convex and Lipschitz)}\\\\\n &\\le (1 - 2\\eta_t \\lambda + \\eta_t^2 L^2) \\|x_t - x^*\\|^2\n =\\alpha \\|x_t - x^*\\|^2,\n \\end{aligned}\n$$\n\nwhere\n\n$$\n \\alpha = \\left(L^2 (\\eta_t -{\\lambda\\over L^2})^2 + 1-{\\lambda^2\\over L^2}\\right)<1\\ \\mbox{if } 0< \\eta_t<\\frac{2\\lambda}{L^2}.\n$$\n\nParticularly, if $\\eta_t =\\frac{\\lambda}{L^2}$,\n\n$$\n \\alpha=1-{\\lambda^2\\over L^2},\n$$ \n\nwhich finishes the proof. ◻\n```\n\nThis means that if the learning rate is chosen appropriatly,\n$\\{x_t\\}_{t=1}^\\infty$ from the gradient descent method will converge to\nthe minimizer $x^*$ of the function.\n\nThere are some issues on Gradient Descent method:\n\n- $\\nabla f(x_{t})$ is very expensive to compute.\n\n- Gradient Descent method does not yield generalization accuracy.\n\nThe stochastic gradient descent (SGD) method in the next section will\nfocus on these two issues.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
d0328ded12984dd432de3726984076d63d944505
4,018
ipynb
Jupyter Notebook
notebooks/2020_project/content/stats_sv_illumina_bng_overlap.ipynb
wharvey31/project-diploid-assembly
9c98871d039f1f6921b944eb1ab7f27e982c9b70
[ "MIT" ]
null
null
null
notebooks/2020_project/content/stats_sv_illumina_bng_overlap.ipynb
wharvey31/project-diploid-assembly
9c98871d039f1f6921b944eb1ab7f27e982c9b70
[ "MIT" ]
null
null
null
notebooks/2020_project/content/stats_sv_illumina_bng_overlap.ipynb
wharvey31/project-diploid-assembly
9c98871d039f1f6921b944eb1ab7f27e982c9b70
[ "MIT" ]
null
null
null
27.148649
131
0.483076
[ [ [ "import os\n\nimport pandas as pd\nimport upsetplot\nimport matplotlib_venn as mpv\n\n\"\"\"\nWhat does this do?\nPrint statistics about SV calls (missed by PAV) shared by Illumina and Bionano.\nDoes not produce a visualization / Venn because of the way Bionano is counting regions.\n\"\"\"\n\n\nillumina_columns = [\n 'chrom',\n 'start',\n 'end',\n 'name',\n 'svtype',\n 'samples',\n 'SVTYPE',\n 'SVLEN',\n 'AF',\n 'SOURCE'\n]\n\nbng_columns = [\n 'chrom',\n 'start',\n 'end',\n 'ClusterID',\n 'svtype',\n 'ClusterSVsize',\n 'CleanNumofSamples',\n 'sdovl',\n]\n\npath = '/home/local/work/data/hgsvc/roi'\n\nfull_sets = [\n '/home/local/work/data/hgsvc/roi/1KGP_3202.gatksv_svtools_novelins.PB_samples.manual_lq_removed.over5Kb_uniq_cnv.bed',\n '/home/local/work/data/hgsvc/bng_tables/Table_S13-4_Bionano_unique_clusters.bed'\n]\n\ndef load_full_set(filepath, is_bng=False):\n df = pd.read_csv(filepath, sep='\\t', header=0)\n if is_bng:\n df = df[['ClusterID', 'Type']].copy()\n else:\n df = df[['name', 'svtype']]\n df.columns = ['name', 'svtype']\n return df\n\nbng_clusters = load_full_set(full_sets[1], True)\nprint(bng_clusters.shape[0])\nillumina_sv = load_full_set(full_sets[0], False)\nprint(illumina_sv['svtype'].value_counts())\nprint(illumina_sv.shape[0])\n\nshared = 0\nbng_only = 0\nillumina_only = 0\n\nfor fn in os.listdir(path):\n if not fn.startswith('isect'):\n continue\n if '-ROI' in fn:\n continue\n fp = os.path.join(path, fn)\n if 'a-1KG' in fn:\n cols = illumina_columns\n illumina_set = True\n else:\n cols = bng_columns\n illumina_set = False\n df = pd.read_csv(fp, sep='\\t', header=None, names=cols)\n if 'uniq' in fn:\n if illumina_set:\n shared = df.shape[0]\n else:\n if illumina_set:\n illumina_only = df.shape[0]\n else:\n print(fn)\n bng_only = df.shape[0]\n \nprint(illumina_only)\nprint(shared)\nprint(bng_only)\n\n# mpv.venn2(\n# subsets=(illumina_only, bng_only, shared),\n# set_labels=('Illumina', 'Bionano'),\n# set_colors=('orange', 'skyblue'),\n# alpha = 0.7\n# )\n\n", "1175\nDUP 395\nDEL 289\nCNV 183\nDEL:ME 71\nName: svtype, dtype: int64\n938\nisect_compl_a-BNG-134_b-1KG-sv.tsv\n106\nAdaptive archaic introgression of copy number variants and the discovery of previously unknown human genes\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
d03299eda45eebd98e63cb0f19a3c00fe119468b
11,993
ipynb
Jupyter Notebook
DecisionTree.ipynb
jbell1991/DecisionTree
6d359b8b081c2195e4e394f24076c9010aa7fac9
[ "MIT" ]
null
null
null
DecisionTree.ipynb
jbell1991/DecisionTree
6d359b8b081c2195e4e394f24076c9010aa7fac9
[ "MIT" ]
null
null
null
DecisionTree.ipynb
jbell1991/DecisionTree
6d359b8b081c2195e4e394f24076c9010aa7fac9
[ "MIT" ]
null
null
null
31.727513
111
0.458934
[ [ [ "import numpy as np\nimport pandas as pd\nimport random", "_____no_output_____" ], [ "df = pd.read_csv('/Users/josephbell/Downloads/iris.csv')\ndf = df.drop(\"Id\", axis = 1)\ndf = df.rename(columns = {\"Species\" : \"target\"})\ndf.head()", "_____no_output_____" ], [ "# train test split\ndef train_test_split(df, target, test_size):\n # shuffles data\n random_df = df.sample(frac=1)\n # splits data into train and test based on test size %\n test_split = int(test_size * len(df))\n train_df = random_df[test_split:]\n test_df = random_df[:test_split]\n return train_df, test_df", "_____no_output_____" ], [ "train_df, test_df = train_test_split(df, target='target', test_size=.2)\n# check to see that data is split properly\ntrain_df.shape, test_df.shape", "_____no_output_____" ], [ "data = train_df.values\ndata[:5]", "_____no_output_____" ], [ "class Node(object):\n def __init__(self, target=None, attribute=None, splitvalue=None, left=None, right=None):\n self.target = target\n self.attribute = attribute\n self.splitvalue = splitvalue\n self.left = left\n self.right = right\n \n def set_target(self, target):\n self.target = target \n \n def set_attribute(self, attribute, splitvalue):\n self.attribute = attribute\n self.splitvalue = splitvalue", "_____no_output_____" ], [ "class DecisionTree():\n def __init__(self, min_samples_split=2):\n self.min_samples_split = min_samples_split\n\n # is the data pure meaning does the split contain only 1 class?\n def check_purity(self, data):\n # access all the rows of the target column of the data\n target_column = data[:, -1]\n # determine the number of unique classes\n unique_classes = np.unique(target_column)\n # if the number of unique classes is equal to 1\n if len(unique_classes) == 1:\n # the data is pure, return True\n return True\n else:\n # the data is not pure, return False\n return False\n \n def calculate_entropy(self, data):\n # access all the rows of the target column of the data\n target_column = data[:, -1]\n # determine the number of unique classes\n _, counts = np.unique(target_column, return_counts=True)\n # get probabilites of each class\n probabilities = counts / counts.sum()\n entropy = sum(probabilities * -np.log2(probabilities))\n return entropy\n\n def info_gain(self, data, column_index, splitval):\n split_column_values = data[:, column_index]\n data_left = data[split_column_values <= splitval]\n data_right = data[split_column_values > splitval]\n\n data_points = len(data_left) + len(data_right)\n p_data_left = len(data_left) / data_points\n p_data_right = len(data_right) / data_points\n\n info_gain = self.calculate_entropy(data) - (p_data_right * self.calculate_entropy(data_right) \n + p_data_left * self.calculate_entropy(data_left))\n return info_gain\n\n def find_best_split(self, data):\n bestgain = 0\n _, n_columns = data.shape\n for column_index in range(n_columns-1):\n values = data[:, column_index]\n unique_values = np.unique(values)\n for i in range(1,len(unique_values)):\n splitval = (unique_values[i-1] + unique_values[i]) / 2\n gain = self.info_gain(data, column_index, splitval)\n if gain >= bestgain:\n bestgain = gain\n bestattribute = column_index\n bestsplitval = splitval\n return bestattribute, bestsplitval\n \n def fit(self, data):\n if len(data) < self.min_samples_split or self.check_purity(data):\n node = Node()\n count = 0 \n target_column = data[:, -1]\n unique_classes, counts_unique_classes = np.unique(target_column, return_counts = True)\n index = counts_unique_classes.argmax()\n for i in counts_unique_classes:\n if counts_unique_classes[index] == i:\n count+=1\n if count == 1: \n node.set_target(unique_classes[index])\n return node\n node = Node()\n column_index ,split = self.find_best_split(data)\n node.set_attribute(attribute = column_index, splitvalue = split)\n node.left = self.fit(data[data[:, column_index] < split])\n node.right = self.fit(data[data[:, column_index] > split])\n return node\n \n def get_target(self, row, n):\n while n.target is None:\n if row[n.attribute] <= n.splitvalue:\n n = n.left \n else:\n n = n.right\n return n.target\n\n def predict(self, tree, X_test):\n targets = []\n for i in X_test:\n target = self.get_target(i, tree)\n targets.append(target)\n return targets\n\n def acc_score(self, y_true, y_pred):\n acc_score = np.sum(y_true == y_pred) / len(y_pred)\n return acc_score", "_____no_output_____" ], [ "data = train_df.values\nX_test = test_df.values[:, :-1]\ny_test = test_df['target'].values\n\ntree = DecisionTree(min_samples_split=10)\nroot = tree.fit(data)\ny_pred = tree.predict(root, X_test)\nacc_score = tree.acc_score(y_test, y_pred)\nprint(acc_score)", "0.9666666666666667\n" ], [ "from sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\n\nX_train = data[:, :-1]\ny_train = data[:, -1]\nX_test = test_df.values[:, :-1]\ny_test = test_df['target'].values\n\nclf = DecisionTreeClassifier(min_samples_split=10)\nclf = clf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\nprint(accuracy_score(y_test, y_pred))", "0.9666666666666667\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
d032bd649c7fda33ac73c49460dd0ddbac32c704
5,539
ipynb
Jupyter Notebook
notebooks/1-One-step-error-probability.ipynb
EdinCitaku/ANN-notebooks
5815cb8d7aaf64b9187bb72b31bfe14ea7f73f95
[ "MIT" ]
3
2021-04-08T04:33:21.000Z
2021-09-15T23:22:42.000Z
notebooks/1-One-step-error-probability.ipynb
EdinCitaku/ANN-notebooks
5815cb8d7aaf64b9187bb72b31bfe14ea7f73f95
[ "MIT" ]
null
null
null
notebooks/1-One-step-error-probability.ipynb
EdinCitaku/ANN-notebooks
5815cb8d7aaf64b9187bb72b31bfe14ea7f73f95
[ "MIT" ]
1
2021-09-15T23:29:31.000Z
2021-09-15T23:29:31.000Z
29.77957
362
0.52699
[ [ [ "# One-step error probability", "_____no_output_____" ], [ " Write a computer program implementing asynchronous deterministic updates for a Hopfield network. Use Hebb's rule with $w_{ii}=0$. Generate and store p=[12,24,48,70,100,120] random patterns with N=120 bits. Each bit is either +1 or -1 with probability $\\tfrac{1}{2}$.\n\nFor each value of ppp estimate the one-step error probability $P_{\\text {error}}^{t=1}$ based on $10^5$ independent trials. Here, one trial means that you generate and store a set of p random patterns, feed one of them, and perform one asynchronous update of a single randomly chosen neuron. If in some trials you encounter sgn(0), simply set sgn(0)=1.\n\nList below the values of $P_{\\text {error}}^{t=1}$ that you obtained in the following form: [$p_1,p_2,\\ldots,p_{6}$], where $p_n$ is the value of $P_{\\text {error}}^{t=1}$ for the n-th value of p from the list above. Give four decimal places for each $p_n$", "_____no_output_____" ] ], [ [ "import numpy as np\nimport time\ndef calculate_instance( n, p, zero_diagonal):\n #Create p random patterns\n patterns = []\n \n for i in range(p):\n patterns.append(np.random.choice([-1,1],n))\n #Create weights matrix according to hebbs rule\n weights = patterns[0][:,None]*patterns[0]\n for el in patterns[1:]:\n weights = weights + el[:,None]*el\n weights = np.true_divide(weights, n)\n \n #Fill diagonal with zeroes\n if zero_diagonal:\n np.fill_diagonal(weights,0)\n #Feed random pattern as input and test if an error occurs\n S1 = patterns[0]\n chosen_i = np.random.choice(range(n))\n S_i_old = S1[chosen_i]\n\n S_i = esign(np.dot(weights[chosen_i], S1))\n #breakpoint()\n return S_i_old == S_i\n\ndef esign(x):\n\n if(x == 0):\n return 1\n else:\n return np.sign(x)\n", "_____no_output_____" ] ], [ [ "List your numerically computed $P_{\\text {error}}^{t=1}$ for the parameters given above. ", "_____no_output_____" ] ], [ [ "p = [12, 24, 48, 70, 100, 120]\nN = 120\nI = 100000\nfor p_i in p:\n solve = [0,0]\n for i in range(I):\n ret = calculate_instance(N, p_i, True)\n if ret:\n solve[0]+=1\n else:\n solve[1]+=1\n p_error = float(solve[1]/I) \n print(f\"Number of patterns: {p_i}, P_error(t=1): {p_error} \")\n", "Number of patterns: 12, P_error(t=1): 0.00057 \nNumber of patterns: 24, P_error(t=1): 0.01143 \nNumber of patterns: 48, P_error(t=1): 0.05569 \nNumber of patterns: 70, P_error(t=1): 0.09447 \nNumber of patterns: 100, P_error(t=1): 0.13699 \nNumber of patterns: 120, P_error(t=1): 0.15952 \n" ] ], [ [ "Repeat the task, but now apply Hebb's rule without setting the diagonal weights to zero. For each value of p listed above, estimate the one-step error probability $P_{\\text {error}}^{t=1}$ based on $10^5$ independent trials.", "_____no_output_____" ] ], [ [ "p = [12, 24, 48, 70, 100, 120]\nN = 120\nI = 100000\nfor p_i in p:\n solve = [0,0]\n for i in range(I):\n ret = calculate_instance(N, p_i, False)\n if ret:\n solve[0]+=1\n else:\n solve[1]+=1\n p_error = float(solve[1]/I) \n print(f\"Number of patterns: {p_i}, P_error(t=1): {p_error} \")\n", "Number of patterns: 12, P_error(t=1): 0.00021 \nNumber of patterns: 24, P_error(t=1): 0.0029 \nNumber of patterns: 48, P_error(t=1): 0.0127 \nNumber of patterns: 70, P_error(t=1): 0.01841 \nNumber of patterns: 100, P_error(t=1): 0.02115 \nNumber of patterns: 120, P_error(t=1): 0.02116 \n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]