hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
list | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
list | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
list | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
list | cell_types
list | cell_type_groups
list |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cb7a163e3c762876eb464a3063f83f7ae4aaada9
| 490,872 |
ipynb
|
Jupyter Notebook
|
notebooks/full_search_distributions.ipynb
|
ChrisBeaumont/brut
|
f4223b84448d1db1b0e98e043dc6670adf05ee5d
|
[
"MIT"
] | 6 |
2015-03-06T20:32:50.000Z
|
2018-04-17T12:14:07.000Z
|
notebooks/full_search_distributions.ipynb
|
ChrisBeaumont/brut
|
f4223b84448d1db1b0e98e043dc6670adf05ee5d
|
[
"MIT"
] | 1 |
2016-08-14T17:12:58.000Z
|
2016-08-14T17:12:58.000Z
|
notebooks/full_search_distributions.ipynb
|
ChrisBeaumont/brut
|
f4223b84448d1db1b0e98e043dc6670adf05ee5d
|
[
"MIT"
] | 7 |
2015-07-29T16:17:02.000Z
|
2018-12-14T03:15:59.000Z
| 590.700361 | 272,321 | 0.929047 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cb7a22da43ddc92cbaaa65e035ec5128825d0ae8
| 863 |
ipynb
|
Jupyter Notebook
|
20 Graphs - 2/20.3 Detect Cycle.ipynb
|
suhassuhas/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
|
e660d5a83b80df9cb67b2d06f2b5ba182586f3da
|
[
"Unlicense"
] | 4 |
2021-09-09T06:52:31.000Z
|
2022-01-09T00:05:11.000Z
|
20 Graphs - 2/20.3 Detect Cycle.ipynb
|
rishitbhojak/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
|
3b5625df60f7ac554fae58dc8ea9fd42012cbfae
|
[
"Unlicense"
] | null | null | null |
20 Graphs - 2/20.3 Detect Cycle.ipynb
|
rishitbhojak/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
|
3b5625df60f7ac554fae58dc8ea9fd42012cbfae
|
[
"Unlicense"
] | 5 |
2021-09-15T13:49:32.000Z
|
2022-01-20T20:37:46.000Z
| 18.361702 | 96 | 0.529548 |
[
[
[
"Check whether a path exists between v1 and v2 if exists then if form a cylce else it won't",
"_____no_output_____"
],
[
"hasPath(v1, v2) has a complexity of O(E) --> O(V**2)",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown"
]
] |
cb7a24e7fdebd1f0fb0aad020bd49c03a76b535e
| 34,447 |
ipynb
|
Jupyter Notebook
|
andrew_ng/machine_learning/cnn/concepts/.ipynb_checkpoints/convolutions-checkpoint.ipynb
|
anaconda121/Machine-Learning-Projects
|
4b79b5f794f88626cd311de10ebed22170b98db5
|
[
"MIT"
] | 1 |
2021-03-11T03:28:24.000Z
|
2021-03-11T03:28:24.000Z
|
andrew_ng/machine_learning/cnn/concepts/.ipynb_checkpoints/convolutions-checkpoint.ipynb
|
anaconda121/Machine-Learning-Projects
|
4b79b5f794f88626cd311de10ebed22170b98db5
|
[
"MIT"
] | null | null | null |
andrew_ng/machine_learning/cnn/concepts/.ipynb_checkpoints/convolutions-checkpoint.ipynb
|
anaconda121/Machine-Learning-Projects
|
4b79b5f794f88626cd311de10ebed22170b98db5
|
[
"MIT"
] | null | null | null | 143.529167 | 26,064 | 0.866258 |
[
[
[
"import tensorflow as tf\nfrom tensorflow.keras import models\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"class myCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs={}):\n #creating a callback function that activates if the accuracy is greater than 60%\n if(logs.get('accuracy')>0.99):\n print(\"\\nim maxed out baby, too goated!\")\n self.model.stop_training = True",
"_____no_output_____"
],
[
"path = \"mnist.npz\"\n\nmnist = tf.keras.datasets.mnist\n(x_train, y_train),(x_test, y_test) = mnist.load_data(path=path)\n\ncallbacks = myCallback()\nx_train = x_train / 255.0\nx_train = x_train.reshape(60000, 28, 28, 1)\n\nx_test = x_test.reshape(10000, 28, 28, 1)\nx_test = x_test / 255.0",
"_____no_output_____"
],
[
"model = tf.keras.models.Sequential([\n #convolution part\n # creates a convolution layer with 64 filters with 3 by 3 dimensions\n # sets activation function to relu, with drops all negative values \n # sets input shape to 28 by 28 array, same as before, 1 denotes that the image is gray-scale, only 1 color channel\n tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),\n \n # create a max pooling layer with a 2 by 2 pooling filter\n # means that the largest pixel value with be chosen out of every 4 pixels\n tf.keras.layers.MaxPooling2D(2, 2),\n \n # insert another set of convolutions and pooling so that the network can learn another set of convolutions\n # then pooling layer is added so that the images can get smaller again\n # this reduces number of dense layers needed\n tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n \n #deep neural network part\n tf.keras.layers.MaxPooling2D(2,2),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dense(10, activation='softmax')\n])\nmodel.summary() #generates summary of parameters so we can see images journey throughout the network",
"Model: \"sequential_7\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_14 (Conv2D) (None, 26, 26, 64) 640 \n_________________________________________________________________\nmax_pooling2d_14 (MaxPooling (None, 13, 13, 64) 0 \n_________________________________________________________________\nconv2d_15 (Conv2D) (None, 11, 11, 64) 36928 \n_________________________________________________________________\nmax_pooling2d_15 (MaxPooling (None, 5, 5, 64) 0 \n_________________________________________________________________\nflatten_7 (Flatten) (None, 1600) 0 \n_________________________________________________________________\ndense_14 (Dense) (None, 128) 204928 \n_________________________________________________________________\ndense_15 (Dense) (None, 10) 1290 \n=================================================================\nTotal params: 243,786\nTrainable params: 243,786\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n#the model is much slower now when compiling\n#this is because there are 64 filters that are getting passed on each image multiple times, so the computation is much heavier\n#but our accuracy is much better now, hitting 99.7% on the first epoch\nmodel.fit(x_test, y_test, epochs=10, callbacks=[callbacks])",
"Epoch 1/10\n313/313 [==============================] - 16s 51ms/step - loss: 0.3163 - accuracy: 0.90601s -\nEpoch 2/10\n313/313 [==============================] - 14s 45ms/step - loss: 0.0832 - accuracy: 0.9739\nEpoch 3/10\n313/313 [==============================] - 16s 52ms/step - loss: 0.0485 - accuracy: 0.9839\nEpoch 4/10\n312/313 [============================>.] - ETA: 0s - loss: 0.0261 - accuracy: 0.9907 ETA: 0s - loss: 0.0258 - accu\nim maxed out baby, too goated!\n313/313 [==============================] - 14s 45ms/step - loss: 0.0261 - accuracy: 0.9907\n"
],
[
"print(y_test[:100])",
"[7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1 3 1 3 4 7 2 7\n 1 2 1 1 7 4 2 3 5 1 2 4 4 6 3 5 5 6 0 4 1 9 5 7 8 9 3 7 4 6 4 3 0 7 0 2 9\n 1 7 3 2 9 7 7 6 2 7 8 4 7 3 6 1 3 6 9 3 1 4 1 7 6 9]\n"
],
[
"f, axarr = plt.subplots(3,4)\nFIRST_IMAGE=0 #0th element is 7\nSECOND_IMAGE=11 #7th element is 9\nTHIRD_IMAGE=26 #26th element is 7\nCONVOLUTION_NUMBER = 1\n\nlayer_outputs = [layer.output for layer in model.layers]\nactivation_model = tf.keras.models.Model(inputs = model.input, outputs = layer_outputs)\n\n#looking at effect that the convolution has on our model\nfor x in range(4):\n f1 = activation_model.predict(x_test[FIRST_IMAGE].reshape(1, 28, 28, 1))[x]\n axarr[0,x].imshow(f1[0, : , :, CONVOLUTION_NUMBER], cmap='inferno')\n axarr[0,x].grid(False)\n \n f2 = activation_model.predict(x_test[SECOND_IMAGE].reshape(1, 28, 28, 1))[x]\n axarr[1,x].imshow(f2[0, : , :, CONVOLUTION_NUMBER], cmap='inferno')\n axarr[1,x].grid(False)\n \n f3 = activation_model.predict(x_test[THIRD_IMAGE].reshape(1, 28, 28, 1))[x]\n axarr[2,x].imshow(f3[0, : , :, CONVOLUTION_NUMBER], cmap='inferno')\n axarr[2,x].grid(False)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7a2bf39492c49ee16d2234e5f67d46c626d79c
| 7,231 |
ipynb
|
Jupyter Notebook
|
notebooks/SimpleMLFlow.ipynb
|
Sij-dev/MLOps_ChurnPred
|
60818c8bc35285ab075e001afeb9bbd6487b7568
|
[
"MIT"
] | null | null | null |
notebooks/SimpleMLFlow.ipynb
|
Sij-dev/MLOps_ChurnPred
|
60818c8bc35285ab075e001afeb9bbd6487b7568
|
[
"MIT"
] | null | null | null |
notebooks/SimpleMLFlow.ipynb
|
Sij-dev/MLOps_ChurnPred
|
60818c8bc35285ab075e001afeb9bbd6487b7568
|
[
"MIT"
] | null | null | null | 30.639831 | 110 | 0.5251 |
[
[
[
"import numpy as np\nfrom sklearn.linear_model import LogisticRegression\n\nimport mlflow\nimport mlflow.sklearn\n\nif __name__ == \"__main__\":\n X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)\n y = np.array([0, 0, 1, 1, 1, 0])\n lr = LogisticRegression()\n lr.fit(X, y)\n score = lr.score(X, y)\n print(\"Score: %s\" % score)\n mlflow.log_metric(\"score\", score)\n mlflow.sklearn.log_model(lr, \"model\")\n print(\"Model saved in run %s\" % mlflow.active_run().info.run_uuid)",
"Score: 0.6666666666666666\nModel saved in run 6b6118344aa44a9c99e4510a6ccc252f\n"
],
[
"mlflow.end_run()",
"_____no_output_____"
],
[
"# Wine Quality Sample\ndef train(in_alpha, in_l1_ratio):\n import os\n import warnings\n import sys\n\n import pandas as pd\n import numpy as np\n from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\n from sklearn.model_selection import train_test_split\n from sklearn.linear_model import ElasticNet\n\n import mlflow\n import mlflow.sklearn\n \n import logging\n logging.basicConfig(level=logging.WARN)\n logger = logging.getLogger(__name__)\n\n def eval_metrics(actual, pred):\n rmse = np.sqrt(mean_squared_error(actual, pred))\n mae = mean_absolute_error(actual, pred)\n r2 = r2_score(actual, pred)\n return rmse, mae, r2\n\n\n warnings.filterwarnings(\"ignore\")\n np.random.seed(40)\n\n # Read the wine-quality csv file from the URL\n csv_url =\\\n 'http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv'\n try:\n data = pd.read_csv(csv_url, sep=';')\n except Exception as e:\n logger.exception(\n \"Unable to download training & test CSV, check your internet connection. Error: %s\", e)\n\n # Split the data into training and test sets. (0.75, 0.25) split.\n train, test = train_test_split(data)\n\n # The predicted column is \"quality\" which is a scalar from [3, 9]\n train_x = train.drop([\"quality\"], axis=1)\n test_x = test.drop([\"quality\"], axis=1)\n train_y = train[[\"quality\"]]\n test_y = test[[\"quality\"]]\n\n # Set default values if no alpha is provided\n if float(in_alpha) is None:\n alpha = 0.5\n else:\n alpha = float(in_alpha)\n\n # Set default values if no l1_ratio is provided\n if float(in_l1_ratio) is None:\n l1_ratio = 0.5\n else:\n l1_ratio = float(in_l1_ratio)\n\n # Useful for multiple runs (only doing one run in this sample notebook) \n with mlflow.start_run():\n # Execute ElasticNet\n lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)\n lr.fit(train_x, train_y)\n\n # Evaluate Metrics\n predicted_qualities = lr.predict(test_x)\n (rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)\n\n # Print out metrics\n print(\"Elasticnet model (alpha=%f, l1_ratio=%f):\" % (alpha, l1_ratio))\n print(\" RMSE: %s\" % rmse)\n print(\" MAE: %s\" % mae)\n print(\" R2: %s\" % r2)\n\n # Log parameter, metrics, and model to MLflow\n mlflow.log_param(\"alpha\", alpha)\n mlflow.log_param(\"l1_ratio\", l1_ratio)\n mlflow.log_metric(\"rmse\", rmse)\n mlflow.log_metric(\"r2\", r2)\n mlflow.log_metric(\"mae\", mae)\n\n mlflow.sklearn.log_model(lr, \"model\")",
"_____no_output_____"
],
[
"train(0.5, 0.5)",
"Elasticnet model (alpha=0.500000, l1_ratio=0.500000):\n RMSE: 0.7931640229276851\n MAE: 0.6271946374319586\n R2: 0.10862644997792614\n"
],
[
"train(0.1, 0.1)",
"Elasticnet model (alpha=0.100000, l1_ratio=0.100000):\n RMSE: 0.7128829045893679\n MAE: 0.5462202174984664\n R2: 0.2799376066653344\n"
],
[
"!mlflow ui",
"[2022-01-10 23:53:36 +0400] [42043] [INFO] Starting gunicorn 20.1.0\n[2022-01-10 23:53:36 +0400] [42043] [INFO] Listening at: http://127.0.0.1:5000 (42043)\n[2022-01-10 23:53:36 +0400] [42043] [INFO] Using worker: sync\n[2022-01-10 23:53:36 +0400] [42044] [INFO] Booting worker with pid: 42044\n[2022-01-11 12:23:57 +0400] [42043] [CRITICAL] WORKER TIMEOUT (pid:42044)\n[2022-01-11 12:23:57 +0400] [42044] [INFO] Worker exiting (pid: 42044)\n[2022-01-11 12:23:57 +0400] [46593] [INFO] Booting worker with pid: 46593\n[2022-01-11 23:03:24 +0400] [42043] [CRITICAL] WORKER TIMEOUT (pid:46593)\n[2022-01-11 23:03:24 +0400] [46593] [INFO] Worker exiting (pid: 46593)\n[2022-01-11 23:03:24 +0400] [46633] [INFO] Booting worker with pid: 46633\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7a367c14c1a3d9734d546fc8d212c39a5ac113
| 48,843 |
ipynb
|
Jupyter Notebook
|
tv-script-generation/dlnd_tv_script_generation.ipynb
|
zhulingchen/deep-learning
|
6dd83f94db99936fb65fc1452d03b584fdd4c31b
|
[
"MIT"
] | 10 |
2019-03-27T00:32:51.000Z
|
2022-03-05T09:23:46.000Z
|
tv-script-generation/dlnd_tv_script_generation.ipynb
|
zhulingchen/deep-learning
|
6dd83f94db99936fb65fc1452d03b584fdd4c31b
|
[
"MIT"
] | 73 |
2020-01-28T22:51:51.000Z
|
2022-03-11T23:54:07.000Z
|
tv-script-generation/dlnd_tv_script_generation.ipynb
|
zhulingchen/deep-learning
|
6dd83f94db99936fb65fc1452d03b584fdd4c31b
|
[
"MIT"
] | 1 |
2021-08-20T17:33:26.000Z
|
2021-08-20T17:33:26.000Z
| 37.74575 | 559 | 0.560121 |
[
[
[
"# TV Script Generation\nIn this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at [Moe's Tavern](https://simpsonswiki.com/wiki/Moe's_Tavern).\n## Get the Data\nThe data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like \"Moe's Cavern\", \"Flaming Moe's\", \"Uncle Moe's Family Feed-Bag\", etc..",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\n\ndata_dir = './data/simpsons/moes_tavern_lines.txt'\ntext = helper.load_data(data_dir)\n# Ignore notice, since we don't use it for analysing the data\ntext = text[81:]",
"_____no_output_____"
],
[
"# test by Lingchen Zhu\nprint(\"First 100 characters in text: {}\".format(text[0:100]))\nwords = text.split()\nprint(\"First 10 words in text after splitting: {}\".format(words[0:10]))\ncharset = sorted(set(text)) # set up an ordered set of unique characters in text\nprint(\"Number of unique characters in text: {}\".format(len(charset)))\nprint(charset)\nvocab = sorted(set(words))\nprint(\"Number of unique words in text (before pre-processing): {}\".format(len(vocab)))",
"First 100 characters in text: \nMoe_Szyslak: (INTO PHONE) Moe's Tavern. Where the elite meet to drink.\nBart_Simpson: Eh, yeah, hell\nFirst 10 words in text after splitting: ['Moe_Szyslak:', '(INTO', 'PHONE)', \"Moe's\", 'Tavern.', 'Where', 'the', 'elite', 'meet', 'to']\nNumber of unique characters in text: 90\n['\\n', ' ', '!', '\"', '#', '$', '%', '&', \"'\", '(', ')', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '?', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\\xa0', '£', '¤', '¨', '©', '³', '¼', 'Ã', '€']\nNumber of unique words in text (before pre-processing): 11492\n"
]
],
[
[
"## Explore the Data\nPlay around with `view_sentence_range` to view different parts of the data.",
"_____no_output_____"
]
],
[
[
"view_sentence_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\nscenes = text.split('\\n\\n')\nprint('Number of scenes: {}'.format(len(scenes)))\nsentence_count_scene = [scene.count('\\n') for scene in scenes]\nprint('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))\n\nsentences = [sentence for scene in scenes for sentence in scene.split('\\n')]\nprint('Number of lines: {}'.format(len(sentences)))\nword_count_sentence = [len(sentence.split()) for sentence in sentences]\nprint('Average number of words in each line: {}'.format(np.average(word_count_sentence)))\n\nprint()\nprint('The sentences {} to {}:'.format(*view_sentence_range))\nprint('\\n'.join(text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))",
"Dataset Stats\nRoughly the number of unique words: 11492\nNumber of scenes: 262\nAverage number of sentences in each scene: 15.251908396946565\nNumber of lines: 4258\nAverage number of words in each line: 11.50164396430249\n\nThe sentences 0 to 10:\n\nMoe_Szyslak: (INTO PHONE) Moe's Tavern. Where the elite meet to drink.\nBart_Simpson: Eh, yeah, hello, is Mike there? Last name, Rotch.\nMoe_Szyslak: (INTO PHONE) Hold on, I'll check. (TO BARFLIES) Mike Rotch. Mike Rotch. Hey, has anybody seen Mike Rotch, lately?\nMoe_Szyslak: (INTO PHONE) Listen you little puke. One of these days I'm gonna catch you, and I'm gonna carve my name on your back with an ice pick.\nMoe_Szyslak: What's the matter Homer? You're not your normal effervescent self.\nHomer_Simpson: I got my problems, Moe. Give me another one.\nMoe_Szyslak: Homer, hey, you should not drink to forget your problems.\nBarney_Gumble: Yeah, you should only drink to enhance your social skills.\n\n"
]
],
[
[
"## Implement Preprocessing Functions\nThe first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:\n- Lookup Table\n- Tokenize Punctuation\n\n### Lookup Table\nTo create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:\n- Dictionary to go from the words to an id, we'll call `vocab_to_int`\n- Dictionary to go from the id to word, we'll call `int_to_vocab`\n\nReturn these dictionaries in the following tuple `(vocab_to_int, int_to_vocab)`",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport problem_unittests as tests\n\ndef create_lookup_tables(text):\n \"\"\"\n Create lookup tables for vocabulary\n :param text: The text of tv scripts split into words\n :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n \"\"\"\n # TODO: Implement Function\n vocab = sorted(set(text)) # set up an ordered set of unique elements in text\n int_to_vocab = dict(enumerate(vocab)) # set up a dictionary with int keys and char values\n vocab_to_int = {c: i for i, c in enumerate(vocab)} # set up a dictionary with char keys and int values\n \n return vocab_to_int, int_to_vocab\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_create_lookup_tables(create_lookup_tables)",
"C:\\ProgramData\\Anaconda2\\envs\\python3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n from ._conv import register_converters as _register_converters\n"
]
],
[
[
"### Tokenize Punctuation\nWe'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word \"bye\" and \"bye!\".\n\nImplement the function `token_lookup` to return a dict that will be used to tokenize symbols like \"!\" into \"||Exclamation_Mark||\". Create a dictionary for the following symbols where the symbol is the key and value is the token:\n- Period ( . )\n- Comma ( , )\n- Quotation Mark ( \" )\n- Semicolon ( ; )\n- Exclamation mark ( ! )\n- Question mark ( ? )\n- Left Parentheses ( ( )\n- Right Parentheses ( ) )\n- Dash ( -- )\n- Return ( \\n )\n\nThis dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token \"dash\", try using something like \"||dash||\".",
"_____no_output_____"
]
],
[
[
"def token_lookup():\n \"\"\"\n Generate a dict to turn punctuation into a token.\n :return: Tokenize dictionary where the key is the punctuation and the value is the token\n \"\"\"\n # TODO: Implement Function\n token_dict = {'.' : \"||period||\",\n ',' : \"||comma||\",\n '\"' : \"||quotation_mark||\",\n ';' : \"||semicolon||\",\n '!' : \"||exclamation_mark||\",\n '?' : \"||question_mark||\",\n '(' : \"||left_parentheses||\",\n ')' : \"||right_parentheses||\",\n '--' : \"||dash||\",\n '\\n': \"||return||\"}\n return token_dict\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_tokenize(token_lookup)",
"Tests Passed\n"
]
],
[
[
"## Preprocess all the data and save it\nRunning the code cell below will preprocess all the data and save it to file.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Preprocess Training, Validation, and Testing Data\n# load text, split text into words, set up vocabulary <-> int lookup tables and save data\nhelper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)",
"_____no_output_____"
]
],
[
[
"# Check Point\nThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport numpy as np\nimport problem_unittests as tests\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()",
"_____no_output_____"
],
[
"# test by Lingchen Zhu\nprint(\"Number of total words in the vocabulary (after-preprocessing): {}\".format(len(int_text)))\nprint(\"Number of unique words in the vocabulary (after pre-processing): {}\".format(len(vocab_to_int)))",
"Number of total words in the vocabulary (after-preprocessing): 69101\nNumber of unique words in the vocabulary (after pre-processing): 6780\n"
]
],
[
[
"## Build the Neural Network\nYou'll build the components necessary to build a RNN by implementing the following functions below:\n- get_inputs\n- get_init_cell\n- get_embed\n- build_rnn\n- build_nn\n- get_batches\n\n### Check the Version of TensorFlow and Access to GPU",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom distutils.version import LooseVersion\nimport warnings\nimport tensorflow as tf\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.3'), 'Please use TensorFlow version 1.3 or newer'\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))",
"TensorFlow Version: 1.4.0\nDefault GPU Device: /device:GPU:0\n"
]
],
[
[
"### Input\nImplement the `get_inputs()` function to create TF Placeholders for the Neural Network. It should create the following placeholders:\n- Input text placeholder named \"input\" using the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) `name` parameter.\n- Targets placeholder\n- Learning Rate placeholder\n\nReturn the placeholders in the following tuple `(Input, Targets, LearningRate)`",
"_____no_output_____"
]
],
[
[
"def get_inputs():\n \"\"\"\n Create TF Placeholders for input, targets, and learning rate.\n :return: Tuple (input, targets, learning rate)\n \"\"\"\n # TODO: Implement Function\n Input = tf.placeholder(tf.int32, [None, None], name='input')\n Targets = tf.placeholder(tf.int32, [None, None], name='targets')\n LearningRate = tf.placeholder(tf.float32, name='learning_rate')\n return Input, Targets, LearningRate\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_inputs(get_inputs)",
"Tests Passed\n"
]
],
[
[
"### Build RNN Cell and Initialize\nStack one or more [`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell) in a [`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell).\n- The Rnn size should be set using `rnn_size`\n- Initalize Cell State using the MultiRNNCell's [`zero_state()`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell#zero_state) function\n - Apply the name \"initial_state\" to the initial state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\n\nReturn the cell and initial state in the following tuple `(Cell, InitialState)`",
"_____no_output_____"
]
],
[
[
"def get_init_cell(batch_size, rnn_size):\n \"\"\"\n Create an RNN Cell and initialize it.\n :param batch_size: Size of batches\n :param rnn_size: Size of RNNs\n :return: Tuple (cell, initialize state)\n \"\"\"\n # TODO: Implement Function\n num_layers = 2\n keep_prob = 0.6\n \n def build_single_lstm_layer(rnn_size, keep_prob):\n lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)\n lstm_with_dropout = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n return lstm_with_dropout\n \n Cell = tf.contrib.rnn.MultiRNNCell([build_single_lstm_layer(rnn_size, keep_prob) for l in range(num_layers)])\n InitialState = Cell.zero_state(batch_size, tf.float32)\n InitialState = tf.identity(InitialState, name='initial_state')\n return Cell, InitialState\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_init_cell(get_init_cell)",
"Tests Passed\n"
]
],
[
[
"### Word Embedding\nApply embedding to `input_data` using TensorFlow. Return the embedded sequence.",
"_____no_output_____"
]
],
[
[
"def get_embed(input_data, vocab_size, embed_dim):\n \"\"\"\n Create embedding for <input_data>.\n :param input_data: TF placeholder for text input.\n :param vocab_size: Number of words in vocabulary.\n :param embed_dim: Number of embedding dimensions\n :return: Embedded input.\n \"\"\"\n # TODO: Implement Function\n embed = tf.contrib.layers.embed_sequence(input_data, vocab_size, embed_dim)\n return embed\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_embed(get_embed)",
"Tests Passed\n"
]
],
[
[
"### Build RNN\nYou created a RNN Cell in the `get_init_cell()` function. Time to use the cell to create a RNN.\n- Build the RNN using the [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn)\n - Apply the name \"final_state\" to the final state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\n\nReturn the outputs and final_state state in the following tuple `(Outputs, FinalState)` ",
"_____no_output_____"
]
],
[
[
"def build_rnn(cell, inputs):\n \"\"\"\n Create a RNN using a RNN Cell\n :param cell: RNN Cell\n :param inputs: Input text data\n :return: Tuple (Outputs, Final State)\n \"\"\"\n # TODO: Implement Function\n Outputs, FinalState = tf.nn.dynamic_rnn(cell, inputs, initial_state=None, dtype=tf.float32)\n FinalState = tf.identity(FinalState, name='final_state')\n return Outputs, FinalState\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_build_rnn(build_rnn)",
"Tests Passed\n"
]
],
[
[
"### Build the Neural Network\nApply the functions you implemented above to:\n- Apply embedding to `input_data` using your `get_embed(input_data, vocab_size, embed_dim)` function.\n- Build RNN using `cell` and your `build_rnn(cell, inputs)` function.\n- Apply a fully connected layer with a linear activation and `vocab_size` as the number of outputs.\n\nReturn the logits and final state in the following tuple (Logits, FinalState) ",
"_____no_output_____"
]
],
[
[
"def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):\n \"\"\"\n Build part of the neural network\n :param cell: RNN cell\n :param rnn_size: Size of rnns\n :param input_data: Input data\n :param vocab_size: Vocabulary size\n :param embed_dim: Number of embedding dimensions\n :return: Tuple (Logits, FinalState)\n \"\"\"\n # TODO: Implement Function\n input_embed = get_embed(input_data, vocab_size, embed_dim)\n \n rnn_output, FinalState = build_rnn(cell, input_embed)\n \n Logits = tf.contrib.layers.fully_connected(rnn_output, vocab_size, activation_fn=None,\n weights_initializer=tf.truncated_normal_initializer(stddev=0.1),\n biases_initializer=tf.zeros_initializer())\n \n return Logits, FinalState\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_build_nn(build_nn)",
"Tests Passed\n"
]
],
[
[
"### Batches\nImplement `get_batches` to create batches of input and targets using `int_text`. The batches should be a Numpy array with the shape `(number of batches, 2, batch size, sequence length)`. Each batch contains two elements:\n- The first element is a single batch of **input** with the shape `[batch size, sequence length]`\n- The second element is a single batch of **targets** with the shape `[batch size, sequence length]`\n\nIf you can't fill the last batch with enough data, drop the last batch.\n\nFor example, `get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2)` would return a Numpy array of the following:\n```\n[\n # First Batch\n [\n # Batch of Input\n [[ 1 2], [ 7 8], [13 14]]\n # Batch of targets\n [[ 2 3], [ 8 9], [14 15]]\n ]\n\n # Second Batch\n [\n # Batch of Input\n [[ 3 4], [ 9 10], [15 16]]\n # Batch of targets\n [[ 4 5], [10 11], [16 17]]\n ]\n\n # Third Batch\n [\n # Batch of Input\n [[ 5 6], [11 12], [17 18]]\n # Batch of targets\n [[ 6 7], [12 13], [18 1]]\n ]\n]\n```\n\nNotice that the last target value in the last batch is the first input value of the first batch. In this case, `1`. This is a common technique used when creating sequence batches, although it is rather unintuitive.",
"_____no_output_____"
]
],
[
[
"def get_batches(int_text, batch_size, seq_length):\n \"\"\"\n Return batches of input and target\n :param int_text: Text with the words replaced by their ids\n :param batch_size: The size of batch\n :param seq_length: The length of sequence\n :return: Batches as a Numpy array\n \"\"\"\n # TODO: Implement Function\n n_word_per_batch = batch_size * seq_length # number of words per batch\n n_batch = len(int_text) // n_word_per_batch # number of batches\n x_data = np.array(int_text[:n_batch * n_word_per_batch]) # keep only enough words to make full batches\n y_data = np.roll(x_data, -1) # shift the text to left by one place\n \n x_batches = np.split(x_data.reshape((batch_size, seq_length * n_batch)), n_batch, axis=1)\n y_batches = np.split(y_data.reshape((batch_size, seq_length * n_batch)), n_batch, axis=1)\n \n Batches = np.array(list(zip(x_batches, y_batches)))\n \n return Batches\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_batches(get_batches)",
"Tests Passed\n"
],
[
"# test by Lingchen Zhu\ntest_batches = get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2)\nprint(\"test_batches.shape = {}\".format(test_batches.shape))\nprint(test_batches)",
"test_batches.shape = (3, 2, 3, 2)\n[[[[ 1 2]\n [ 7 8]\n [13 14]]\n\n [[ 2 3]\n [ 8 9]\n [14 15]]]\n\n\n [[[ 3 4]\n [ 9 10]\n [15 16]]\n\n [[ 4 5]\n [10 11]\n [16 17]]]\n\n\n [[[ 5 6]\n [11 12]\n [17 18]]\n\n [[ 6 7]\n [12 13]\n [18 1]]]]\n"
]
],
[
[
"## Neural Network Training\n### Hyperparameters\nTune the following parameters:\n\n- Set `num_epochs` to the number of epochs.\n- Set `batch_size` to the batch size.\n- Set `rnn_size` to the size of the RNNs.\n- Set `embed_dim` to the size of the embedding.\n- Set `seq_length` to the length of sequence.\n- Set `learning_rate` to the learning rate.\n- Set `show_every_n_batches` to the number of batches the neural network should print progress.",
"_____no_output_____"
]
],
[
[
"# Number of Epochs\nnum_epochs = 100\n# Batch Size\nbatch_size = 256\n# RNN Size\nrnn_size = 1024\n# Embedding Dimension Size\nembed_dim = 300\n# Sequence Length\nseq_length = 20\n# Learning Rate\nlearning_rate = 0.005\n# Show stats for every n number of batches\nshow_every_n_batches = 10\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nsave_dir = './save'",
"_____no_output_____"
]
],
[
[
"### Build the Graph\nBuild the graph using the neural network you implemented.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom tensorflow.contrib import seq2seq\n\ntrain_graph = tf.Graph()\nwith train_graph.as_default():\n vocab_size = len(int_to_vocab)\n input_text, targets, lr = get_inputs()\n input_data_shape = tf.shape(input_text)\n cell, initial_state = get_init_cell(input_data_shape[0], rnn_size)\n logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size, embed_dim)\n\n # Probabilities for generating words\n probs = tf.nn.softmax(logits, name='probs')\n\n # Loss function\n cost = seq2seq.sequence_loss(\n logits,\n targets,\n tf.ones([input_data_shape[0], input_data_shape[1]]))\n\n # Optimizer\n optimizer = tf.train.AdamOptimizer(lr)\n\n # Gradient Clipping\n gradients = optimizer.compute_gradients(cost)\n capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]\n train_op = optimizer.apply_gradients(capped_gradients)",
"_____no_output_____"
]
],
[
[
"## Train\nTrain the neural network on the preprocessed data. If you have a hard time getting a good loss, check the [forums](https://discussions.udacity.com/) to see if anyone is having the same problem.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nbatches = get_batches(int_text, batch_size, seq_length)\n\nwith tf.Session(graph=train_graph) as sess:\n sess.run(tf.global_variables_initializer())\n\n for epoch_i in range(num_epochs):\n state = sess.run(initial_state, {input_text: batches[0][0]})\n\n for batch_i, (x, y) in enumerate(batches):\n feed = {\n input_text: x,\n targets: y,\n initial_state: state,\n lr: learning_rate}\n train_loss, state, _ = sess.run([cost, final_state, train_op], feed)\n\n # Show every <show_every_n_batches> batches\n if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0:\n print('Epoch {:>3} Batch {:>4}/{} train_loss = {:.3f}'.format(\n epoch_i,\n batch_i,\n len(batches),\n train_loss))\n\n # Save Model\n saver = tf.train.Saver()\n saver.save(sess, save_dir)\n print('Model Trained and Saved')",
"Epoch 0 Batch 0/13 train_loss = 8.822\nEpoch 0 Batch 10/13 train_loss = 7.138\nEpoch 1 Batch 7/13 train_loss = 6.391\nEpoch 2 Batch 4/13 train_loss = 6.097\nEpoch 3 Batch 1/13 train_loss = 5.921\nEpoch 3 Batch 11/13 train_loss = 5.758\nEpoch 4 Batch 8/13 train_loss = 5.527\nEpoch 5 Batch 5/13 train_loss = 5.347\nEpoch 6 Batch 2/13 train_loss = 5.129\nEpoch 6 Batch 12/13 train_loss = 5.110\nEpoch 7 Batch 9/13 train_loss = 4.904\nEpoch 8 Batch 6/13 train_loss = 4.848\nEpoch 9 Batch 3/13 train_loss = 4.684\nEpoch 10 Batch 0/13 train_loss = 4.541\nEpoch 10 Batch 10/13 train_loss = 4.478\nEpoch 11 Batch 7/13 train_loss = 4.391\nEpoch 12 Batch 4/13 train_loss = 4.295\nEpoch 13 Batch 1/13 train_loss = 4.123\nEpoch 13 Batch 11/13 train_loss = 4.046\nEpoch 14 Batch 8/13 train_loss = 3.933\nEpoch 15 Batch 5/13 train_loss = 3.914\nEpoch 16 Batch 2/13 train_loss = 3.836\nEpoch 16 Batch 12/13 train_loss = 3.759\nEpoch 17 Batch 9/13 train_loss = 3.576\nEpoch 18 Batch 6/13 train_loss = 3.524\nEpoch 19 Batch 3/13 train_loss = 3.384\nEpoch 20 Batch 0/13 train_loss = 3.220\nEpoch 20 Batch 10/13 train_loss = 3.146\nEpoch 21 Batch 7/13 train_loss = 2.988\nEpoch 22 Batch 4/13 train_loss = 3.015\nEpoch 23 Batch 1/13 train_loss = 2.831\nEpoch 23 Batch 11/13 train_loss = 2.721\nEpoch 24 Batch 8/13 train_loss = 2.705\nEpoch 25 Batch 5/13 train_loss = 2.673\nEpoch 26 Batch 2/13 train_loss = 2.645\nEpoch 26 Batch 12/13 train_loss = 2.505\nEpoch 27 Batch 9/13 train_loss = 2.369\nEpoch 28 Batch 6/13 train_loss = 2.391\nEpoch 29 Batch 3/13 train_loss = 2.334\nEpoch 30 Batch 0/13 train_loss = 2.212\nEpoch 30 Batch 10/13 train_loss = 2.117\nEpoch 31 Batch 7/13 train_loss = 2.053\nEpoch 32 Batch 4/13 train_loss = 2.015\nEpoch 33 Batch 1/13 train_loss = 1.892\nEpoch 33 Batch 11/13 train_loss = 1.749\nEpoch 34 Batch 8/13 train_loss = 1.736\nEpoch 35 Batch 5/13 train_loss = 1.789\nEpoch 36 Batch 2/13 train_loss = 1.661\nEpoch 36 Batch 12/13 train_loss = 1.592\nEpoch 37 Batch 9/13 train_loss = 1.484\nEpoch 38 Batch 6/13 train_loss = 1.427\nEpoch 39 Batch 3/13 train_loss = 1.355\nEpoch 40 Batch 0/13 train_loss = 1.282\nEpoch 40 Batch 10/13 train_loss = 1.242\nEpoch 41 Batch 7/13 train_loss = 1.152\nEpoch 42 Batch 4/13 train_loss = 1.192\nEpoch 43 Batch 1/13 train_loss = 1.099\nEpoch 43 Batch 11/13 train_loss = 1.040\nEpoch 44 Batch 8/13 train_loss = 1.019\nEpoch 45 Batch 5/13 train_loss = 1.037\nEpoch 46 Batch 2/13 train_loss = 0.985\nEpoch 46 Batch 12/13 train_loss = 0.927\nEpoch 47 Batch 9/13 train_loss = 0.891\nEpoch 48 Batch 6/13 train_loss = 0.835\nEpoch 49 Batch 3/13 train_loss = 0.818\nEpoch 50 Batch 0/13 train_loss = 0.741\nEpoch 50 Batch 10/13 train_loss = 0.731\nEpoch 51 Batch 7/13 train_loss = 0.703\nEpoch 52 Batch 4/13 train_loss = 0.682\nEpoch 53 Batch 1/13 train_loss = 0.658\nEpoch 53 Batch 11/13 train_loss = 0.623\nEpoch 54 Batch 8/13 train_loss = 0.586\nEpoch 55 Batch 5/13 train_loss = 0.609\nEpoch 56 Batch 2/13 train_loss = 0.573\nEpoch 56 Batch 12/13 train_loss = 0.532\nEpoch 57 Batch 9/13 train_loss = 0.522\nEpoch 58 Batch 6/13 train_loss = 0.530\nEpoch 59 Batch 3/13 train_loss = 0.476\nEpoch 60 Batch 0/13 train_loss = 0.466\nEpoch 60 Batch 10/13 train_loss = 0.456\nEpoch 61 Batch 7/13 train_loss = 0.458\nEpoch 62 Batch 4/13 train_loss = 0.451\nEpoch 63 Batch 1/13 train_loss = 0.446\nEpoch 63 Batch 11/13 train_loss = 0.445\nEpoch 64 Batch 8/13 train_loss = 0.411\nEpoch 65 Batch 5/13 train_loss = 0.457\nEpoch 66 Batch 2/13 train_loss = 0.440\nEpoch 66 Batch 12/13 train_loss = 0.448\nEpoch 67 Batch 9/13 train_loss = 0.452\nEpoch 68 Batch 6/13 train_loss = 0.415\nEpoch 69 Batch 3/13 train_loss = 0.407\nEpoch 70 Batch 0/13 train_loss = 0.383\nEpoch 70 Batch 10/13 train_loss = 0.364\nEpoch 71 Batch 7/13 train_loss = 0.371\nEpoch 72 Batch 4/13 train_loss = 0.369\nEpoch 73 Batch 1/13 train_loss = 0.341\nEpoch 73 Batch 11/13 train_loss = 0.347\nEpoch 74 Batch 8/13 train_loss = 0.327\nEpoch 75 Batch 5/13 train_loss = 0.331\nEpoch 76 Batch 2/13 train_loss = 0.336\nEpoch 76 Batch 12/13 train_loss = 0.316\nEpoch 77 Batch 9/13 train_loss = 0.310\nEpoch 78 Batch 6/13 train_loss = 0.311\nEpoch 79 Batch 3/13 train_loss = 0.315\nEpoch 80 Batch 0/13 train_loss = 0.286\nEpoch 80 Batch 10/13 train_loss = 0.284\nEpoch 81 Batch 7/13 train_loss = 0.285\nEpoch 82 Batch 4/13 train_loss = 0.300\nEpoch 83 Batch 1/13 train_loss = 0.296\nEpoch 83 Batch 11/13 train_loss = 0.274\nEpoch 84 Batch 8/13 train_loss = 0.279\nEpoch 85 Batch 5/13 train_loss = 0.281\nEpoch 86 Batch 2/13 train_loss = 0.299\nEpoch 86 Batch 12/13 train_loss = 0.270\nEpoch 87 Batch 9/13 train_loss = 0.260\nEpoch 88 Batch 6/13 train_loss = 0.270\nEpoch 89 Batch 3/13 train_loss = 0.280\nEpoch 90 Batch 0/13 train_loss = 0.256\nEpoch 90 Batch 10/13 train_loss = 0.261\nEpoch 91 Batch 7/13 train_loss = 0.269\nEpoch 92 Batch 4/13 train_loss = 0.267\nEpoch 93 Batch 1/13 train_loss = 0.273\nEpoch 93 Batch 11/13 train_loss = 0.257\nEpoch 94 Batch 8/13 train_loss = 0.247\nEpoch 95 Batch 5/13 train_loss = 0.263\nEpoch 96 Batch 2/13 train_loss = 0.274\nEpoch 96 Batch 12/13 train_loss = 0.251\nEpoch 97 Batch 9/13 train_loss = 0.250\nEpoch 98 Batch 6/13 train_loss = 0.268\nEpoch 99 Batch 3/13 train_loss = 0.262\nModel Trained and Saved\n"
]
],
[
[
"## Save Parameters\nSave `seq_length` and `save_dir` for generating a new TV script.",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Save parameters for checkpoint\nhelper.save_params((seq_length, save_dir))",
"_____no_output_____"
]
],
[
[
"# Checkpoint",
"_____no_output_____"
]
],
[
[
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport helper\nimport problem_unittests as tests\n\n_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\nseq_length, load_dir = helper.load_params()",
"_____no_output_____"
]
],
[
[
"## Implement Generate Functions\n### Get Tensors\nGet tensors from `loaded_graph` using the function [`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name). Get the tensors using the following names:\n- \"input:0\"\n- \"initial_state:0\"\n- \"final_state:0\"\n- \"probs:0\"\n\nReturn the tensors in the following tuple `(InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)` ",
"_____no_output_____"
]
],
[
[
"def get_tensors(loaded_graph):\n \"\"\"\n Get input, initial state, final state, and probabilities tensor from <loaded_graph>\n :param loaded_graph: TensorFlow graph loaded from file\n :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)\n \"\"\"\n # TODO: Implement Function\n InputTensor = loaded_graph.get_tensor_by_name('input:0')\n InitialStateTensor = loaded_graph.get_tensor_by_name('initial_state:0')\n FinalStateTensor = loaded_graph.get_tensor_by_name('final_state:0')\n ProbsTensor = loaded_graph.get_tensor_by_name('probs:0')\n \n return InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_tensors(get_tensors)",
"Tests Passed\n"
]
],
[
[
"### Choose Word\nImplement the `pick_word()` function to select the next word using `probabilities`.",
"_____no_output_____"
]
],
[
[
"def pick_word(probabilities, int_to_vocab):\n \"\"\"\n Pick the next word in the generated text\n :param probabilities: Probabilites of the next word\n :param int_to_vocab: Dictionary of word ids as the keys and words as the values\n :return: String of the predicted word\n \"\"\"\n # TODO: Implement Function\n # greedy search: may result in the network \"getting stuck\" and picking the same word over and over\n # idx_max_prob = np.argmax(probabilities)\n # word_predict = int_to_vocab[idx_max_prob]\n \n top_n = 5 # number of the next word with highest probabilities\n probabilities[np.argsort(probabilities)[:-top_n]] = 0 # suppress small probabilities to zeros\n probabilities = probabilities / np.sum(probabilities) # normalize the remaining large probabilities\n idx_max_prob_random = np.random.choice(len(int_to_vocab), 1, p=probabilities)[0] # generates a random sample index from range(len(int_to_vocab)) with probabilities\n word_predict = int_to_vocab[idx_max_prob_random]\n \n return word_predict\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_pick_word(pick_word)",
"Tests Passed\n"
]
],
[
[
"## Generate TV Script\nThis will generate the TV script for you. Set `gen_length` to the length of TV script you want to generate.",
"_____no_output_____"
]
],
[
[
"gen_length = 500\n# homer_simpson, moe_szyslak, or Barney_Gumble\nprime_word = 'moe_szyslak'\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nloaded_graph = tf.Graph()\nwith tf.Session(graph=loaded_graph) as sess:\n # Load saved model\n loader = tf.train.import_meta_graph(load_dir + '.meta')\n loader.restore(sess, load_dir)\n\n # Get Tensors from loaded model\n input_text, initial_state, final_state, probs = get_tensors(loaded_graph)\n\n # Sentences generation setup\n gen_sentences = [prime_word + ':']\n prev_state = sess.run(initial_state, {input_text: np.array([[1]])})\n\n # Generate sentences\n for n in range(gen_length):\n # Dynamic Input\n dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]\n dyn_seq_length = len(dyn_input[0])\n\n # Get Prediction\n probabilities, prev_state = sess.run(\n [probs, final_state],\n {input_text: dyn_input, initial_state: prev_state})\n \n pred_word = pick_word(probabilities[0][dyn_seq_length-1], int_to_vocab)\n\n gen_sentences.append(pred_word)\n \n # Remove tokens\n tv_script = ' '.join(gen_sentences)\n for key, token in token_dict.items():\n ending = ' ' if key in ['\\n', '(', '\"'] else ''\n tv_script = tv_script.replace(' ' + token.lower(), key)\n tv_script = tv_script.replace('\\n ', '\\n')\n tv_script = tv_script.replace('( ', '(')\n \n print(tv_script)",
"INFO:tensorflow:Restoring parameters from ./save\nmoe_szyslak: hey, come on, there's sexy bald of here.\nhomer_simpson:(upset) uh, you're all gonna get up on skinner.\nhomer_simpson: listen your beer! i'm a talkin' in the house.\nbarney_gumble: yeah, this is the real thing that really happened to the america table. it's makin' a dad now the points are good with that and i know, it's how.\nhomer_simpson: huh? uh, we all gonna do.\nseymour_skinner: homer, you're like you two about around.\nmoe_szyslak: what got it? i would go!(isotopes) screw it, but don't feel so that.\nmoe_szyslak:(sings) good king wenceslas looked out.\napu_nahasapeemapetilon: hm. just we're real busy. talking all over about a name.\nhomer_simpson: i'm talkin' to ever think there's gonna see, get just my back!\nhomer_simpson: oh, sorry.\nhomer_simpson: yeah, i've never got to open up with my money.(chuckles)\nmoe_szyslak:(sorry) no, the barflies of a chance in a new town!\nmoe_szyslak: what is all?\nlenny_leonard: we don't look!\nhomer_simpson: i'm going for. you've a no guy what of the only way in love.\nhomer_simpson: i'm sorry, homer.\nhomer_simpson:(looking at beer) aw, i love.\n\n\nhomer_simpson: i barflies to the time!\nhomer_simpson: you wish that, they-- my family wasn't\" in the world of not.\nmoe_szyslak: what, be these love for karaoke.\ncarl_carlson: moe, let's get for the new game of my wife.\nmoe_szyslak: all day.\nhomer_simpson:(reading) you owe me... i need to you.\nmoe_szyslak:(explaining) outside) do guys. i finally got you paid to save the secret, i--\nmoe_szyslak: hey, some on the back with a gag.\nkent_brockman:(good) what it better is. run or over.\nhomer_simpson: oh, no. not, the looking in a hand, huh? do you, remember?\nhomer_simpson: mr. a beer fat with.\nmoe_szyslak: ahh! well, i make ya... without being cash you,\" kid now, it was me.\nmoe_szyslak: you many family and this.\nhomer_simpson: the tap in the bar. he lost going to my birthday fat, i have a order to the little.\nhomer_simpson:(philosophic) eh, can you get back into a hobo?\ncarl_carlson: yeah, but it's the weird well, it wouldn't use, moe.\nhomer_simpson: i just not.\nkids is 1895.\n"
]
],
[
[
"# The TV Script is Nonsensical\nIt's ok if the TV script doesn't make any sense. We trained on less than a megabyte of text. In order to get good results, you'll have to use a smaller vocabulary or get more data. Luckily there's more data! As we mentioned in the beggining of this project, this is a subset of [another dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data). We didn't have you train on all the data, because that would take too long. However, you are free to train your neural network on all the data. After you complete the project, of course.\n# Submitting This Project\nWhen submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_tv_script_generation.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7a36beeef9f09db486fc7f0c984f505f15cb8e
| 885,805 |
ipynb
|
Jupyter Notebook
|
Kaggle Datasets/ML/Wine Quality Prediction/quality.ipynb
|
faizanxmulla/data-science-portfolio
|
5f5dcd3227ab8400e4161a5fecdcd3a3aaf8904f
|
[
"MIT"
] | 2 |
2021-09-29T18:24:58.000Z
|
2022-03-14T04:55:25.000Z
|
Kaggle Datasets/ML/Wine Quality Prediction/quality.ipynb
|
faizanxmulla/data-science-portfolio
|
5f5dcd3227ab8400e4161a5fecdcd3a3aaf8904f
|
[
"MIT"
] | null | null | null |
Kaggle Datasets/ML/Wine Quality Prediction/quality.ipynb
|
faizanxmulla/data-science-portfolio
|
5f5dcd3227ab8400e4161a5fecdcd3a3aaf8904f
|
[
"MIT"
] | null | null | null | 551.903427 | 108,270 | 0.940791 |
[
[
[
"## Importing Libraries & getting Data",
"_____no_output_____"
]
],
[
[
"import numpy as np \r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt \r\nimport seaborn as sns\r\n\r\nimport warnings \r\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"data = pd.read_csv(\"dataset/winequalityN.csv\")",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 6497 entries, 0 to 6496\nData columns (total 13 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 type 6497 non-null object \n 1 fixed acidity 6487 non-null float64\n 2 volatile acidity 6489 non-null float64\n 3 citric acid 6494 non-null float64\n 4 residual sugar 6495 non-null float64\n 5 chlorides 6495 non-null float64\n 6 free sulfur dioxide 6497 non-null float64\n 7 total sulfur dioxide 6497 non-null float64\n 8 density 6497 non-null float64\n 9 pH 6488 non-null float64\n 10 sulphates 6493 non-null float64\n 11 alcohol 6497 non-null float64\n 12 quality 6497 non-null int64 \ndtypes: float64(11), int64(1), object(1)\nmemory usage: 660.0+ KB\n"
],
[
"data.describe()",
"_____no_output_____"
],
[
"data.columns",
"_____no_output_____"
],
[
"columns = ['type', 'fixed acidity', 'volatile acidity', 'citric acid','residual sugar', 'chlorides', 'free sulfur dioxide','total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol','quality']\r\n",
"_____no_output_____"
],
[
"data['type']",
"_____no_output_____"
],
[
"sns.countplot(data=data ,x=\"quality\")",
"_____no_output_____"
]
],
[
[
"## Handling Missing Values",
"_____no_output_____"
]
],
[
[
"sns.heatmap(data.isnull(), yticklabels=False, cmap=\"viridis\", cbar=False)",
"_____no_output_____"
],
[
"data.isnull().values.sum()",
"_____no_output_____"
],
[
"# replacing missing values with mean \r\ndata = data.fillna(data.mean())\r\n\r\nsns.heatmap(data.isnull(), yticklabels=False, cmap=\"viridis\", cbar=False)",
"_____no_output_____"
],
[
"# as 'type' is categorical variable ,remove it from the list of our feature columns\r\n\r\nlabels = data.pop('type')\r\n",
"_____no_output_____"
],
[
"cat_columns = ['fixed acidity', 'volatile acidity', 'citric acid','residual sugar', 'chlorides', 'free sulfur dioxide','total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol','quality']\r\n\r\ndata.head()",
"_____no_output_____"
]
],
[
[
"## Scaling & Encoding",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import MinMaxScaler , LabelEncoder\r\n\r\ndef scale_data(data):\r\n scaler = MinMaxScaler(feature_range=(0,1))\r\n X = np.array(data)\r\n X = scaler.fit_transform(X)\r\n return X , scaler\r\n\r\ndef encode_data(labels):\r\n y = np.array(labels)\r\n le = LabelEncoder()\r\n y = le.fit_transform(y)\r\n return y , le",
"_____no_output_____"
],
[
"# another way to encode \r\n# labels.type = labels.type.apply(lambda x: 0 if x == \"red\" else 1)",
"_____no_output_____"
],
[
"X , scaler = scale_data(data)\r\nprint(X)",
"[[0.26446281 0.12666667 0.21686747 ... 0.12921348 0.11594203 0.5 ]\n [0.20661157 0.14666667 0.20481928 ... 0.15168539 0.2173913 0.5 ]\n [0.3553719 0.13333333 0.24096386 ... 0.12359551 0.30434783 0.5 ]\n ...\n [0.20661157 0.28666667 0.07831325 ... 0.29775281 0.43478261 0.5 ]\n [0.17355372 0.37666667 0.07228916 ... 0.2752809 0.31884058 0.33333333]\n [0.18181818 0.15333333 0.28313253 ... 0.24719101 0.43478261 0.5 ]]\n"
],
[
"print(scaler.inverse_transform(X))",
"[[ 7. 0.27 0.36 ... 0.45 8.8 6. ]\n [ 6.3 0.3 0.34 ... 0.49 9.5 6. ]\n [ 8.1 0.28 0.4 ... 0.44 10.1 6. ]\n ...\n [ 6.3 0.51 0.13 ... 0.75 11. 6. ]\n [ 5.9 0.645 0.12 ... 0.71 10.2 5. ]\n [ 6. 0.31 0.47 ... 0.66 11. 6. ]]\n"
],
[
"y , le = encode_data(labels)\r\nprint(y)",
"[1 1 1 ... 0 0 0]\n"
],
[
"print(le.inverse_transform(y))",
"['white' 'white' 'white' ... 'red' 'red' 'red']\n"
]
],
[
[
"## EDA",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10,10))\r\nsns.heatmap(data.corr() , annot=True)\r\nplt.show()",
"_____no_output_____"
]
],
[
[
"### For Handling Outliers",
"_____no_output_____"
]
],
[
[
"def univariate(var):\r\n sns.boxplot(data=data , y=var)\r\n plt.show()",
"_____no_output_____"
],
[
"cat_columns",
"_____no_output_____"
],
[
"univariate('fixed acidity')\r\n",
"_____no_output_____"
],
[
"univariate('volatile acidity')\r\n",
"_____no_output_____"
],
[
"univariate('citric acid')\r\n",
"_____no_output_____"
],
[
"univariate('pH')",
"_____no_output_____"
],
[
"univariate('sulphates')\r\n",
"_____no_output_____"
],
[
"univariate('alcohol')\r\n",
"_____no_output_____"
],
[
"univariate('total sulfur dioxide')\r\n",
"_____no_output_____"
],
[
"univariate('chlorides')\r\n",
"_____no_output_____"
],
[
"univariate('residual sugar')\r\n",
"_____no_output_____"
]
],
[
[
"### Density and pH",
"_____no_output_____"
]
],
[
[
"sns.displot(data ,x=\"density\" ,color='r',col=\"quality\")",
"_____no_output_____"
],
[
"sns.displot(data, x=\"pH\", color='g', col=\"quality\")\r\n",
"_____no_output_____"
]
],
[
[
"## Bivariate Analysis",
"_____no_output_____"
]
],
[
[
"data['quality'].describe()",
"_____no_output_____"
]
],
[
[
"### Numerical variables vs Target variable",
"_____no_output_____"
]
],
[
[
"for i in cat_columns:\r\n fig , ax = plt.subplots(1,3,figsize=(20,5))\r\n plt.subplots_adjust(hspace=1)\r\n\r\n sns.barplot(data=data , y=i ,x=\"quality\" , ax=ax[0])\r\n sns.lineplot(data=data, y=i, x=\"quality\", ax=ax[1])\r\n sns.violinplot(data=data, y=i, x=\"quality\", ax=ax[2])\r\n",
"_____no_output_____"
]
],
[
[
"## Model building with Random Forest classifier",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42)",
"_____no_output_____"
],
[
"from sklearn.ensemble import RandomForestClassifier\r\n\r\nrfc = RandomForestClassifier()\r\nrfc.fit(X_train , y_train)",
"_____no_output_____"
],
[
"y_predicted = rfc.predict(X_test)\r\n\r\ny_predicted[:15] , y_test[:15]",
"_____no_output_____"
]
],
[
[
"## Evaluation",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import accuracy_score ,confusion_matrix\r\nprint(\"Accuracy :\" , (accuracy_score(y_predicted , y_test)))",
"Accuracy : 0.9948717948717949\n"
],
[
"sns.heatmap(confusion_matrix(y_predicted ,y_test),annot=True ,cmap='Purples' ,fmt='.4g')",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb7a41da49a459c2d1eb82269e7d5661d0b92f60
| 36,621 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/UNET-UNIT_V5-checkpoint.ipynb
|
BradleyBrown19/UNET-UNIT
|
cdd0d0ab763feb255059263a52e7e513f80b11da
|
[
"Apache-2.0"
] | 4 |
2020-01-28T04:49:52.000Z
|
2020-12-27T03:26:12.000Z
|
.ipynb_checkpoints/UNET-UNIT_V5-checkpoint.ipynb
|
BradleyBrown19/UNET-UNIT
|
cdd0d0ab763feb255059263a52e7e513f80b11da
|
[
"Apache-2.0"
] | 3 |
2020-02-21T11:13:14.000Z
|
2022-02-26T08:28:09.000Z
|
.ipynb_checkpoints/UNET-UNIT_V5-checkpoint.ipynb
|
BradleyBrown19/UNET-UNIT
|
cdd0d0ab763feb255059263a52e7e513f80b11da
|
[
"Apache-2.0"
] | null | null | null | 37.831612 | 176 | 0.525245 |
[
[
[
"from fastai import *\nfrom fastai.vision import *\nfrom fastai.callbacks import *\nfrom fastai.utils.mem import *\nfrom fastai.vision.gan import *\nfrom PIL import Image\n\nimport numpy as np\n\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\n\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.dataset import TensorDataset\nimport pdb",
"_____no_output_____"
],
[
"path = Path()/'data'/'horse2zebra'",
"_____no_output_____"
]
],
[
[
"# Custom DataBunch Object",
"_____no_output_____"
]
],
[
[
"import fastai.vision.image as im",
"_____no_output_____"
],
[
"class DoubleImage(ItemBase):\n def __init__(self, img1, img2):\n self.img1,self.img2 = img1,img2\n self.data = [(-1+2*img1.data),(-1+2*img2.data)]\n \n def apply_tfms(self, tfms, **kwargs):\n self.img1 = self.img1.apply_tfms(tfms, **kwargs)\n self.img2 = self.img2.apply_tfms(tfms, **kwargs)\n self.data = [-1+2*self.img1.data,-1+2*self.img2.data]\n return self\n \n def __repr__(self)->str: return f'{self.__class__.__name__}'\n \n def to_one(self): \n tensor = 0.5+torch.cat(self.data,2)/2\n return im.Image(tensor)",
"_____no_output_____"
],
[
"class DoubleImageList(ImageList):\n def __init__(self, items, itemsB=None, **kwargs):\n super().__init__(items, **kwargs)\n self.itemsB = itemsB\n self.copy_new.append('itemsB')\n \n def get(self, i):\n img1 = super().get(i)\n fn = self.itemsB[random.randint(0, len(self.itemsB)-1)]\n return DoubleImage(img1, open_image(fn))\n \n def reconstruct(self, t:Tensor): return t\n \n @classmethod\n def from_folders(cls, path, folderA, folderB, **kwargs):\n itemsB = ImageList.from_folder(path/folderB).items\n res = super().from_folder(path/folderA, itemsB=itemsB, **kwargs)\n res.path = path\n return res\n \n def transform(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs):\n \"Set `tfms` to be applied to the xs of the train and validation set.\"\n if not tfms: tfms=(None,None)\n assert is_listy(tfms) and len(tfms) == 2, \"Please pass a list of two lists of transforms (train and valid).\"\n self.train.transform(tfms[0], **kwargs)\n self.valid.transform(tfms[1], **kwargs)\n if self.test: self.test.transform(tfms[1], **kwargs)\n return self\n \n def show_xys(self, xs, ys, figsize:Tuple[int,int]=(12,6), **kwargs):\n \"Show the `xs` and `ys` on a figure of `figsize`. `kwargs` are passed to the show method.\"\n rows = int(math.sqrt(len(xs)))\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten() if rows > 1 else [axs]):\n xs[i] = DoubleImage((xs[i][0]/2+0.5),(xs[i][1]/2+0.5))\n xs[i].to_one().show(ax=ax, **kwargs)\n plt.tight_layout()\n\n #UNTESTED\n def show_xyzs(self, xs, ys, zs, figsize:Tuple[int,int]=None, **kwargs):\n \"\"\"Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`.\n `kwargs` are passed to the show method.\"\"\"\n figsize = ifnone(figsize, (12,3*len(xs)))\n fig,axs = plt.subplots(len(xs), 2, figsize=figsize)\n fig.suptitle('Ground truth / Predictions', weight='bold', size=14)\n for i,(x,z) in enumerate(zip(xs,zs)):\n x.to_one().show(ax=axs[i,0], **kwargs)\n z.to_one().show(ax=axs[i,1], **kwargs)",
"_____no_output_____"
],
[
"data = DoubleImageList.from_folders(path, 'horse', 'zebra').split_by_rand_pct(0.2).label_from_folder()",
"_____no_output_____"
],
[
"data = ImageDataBunch.create_from_ll(data, bs=1, size=224)",
"_____no_output_____"
],
[
"data.show_batch()",
"_____no_output_____"
]
],
[
[
"# MultiUnet Trainer",
"_____no_output_____"
]
],
[
[
"class UnetBlock(nn.Module):\n \"A quasi-UNet block, using `PixelShuffle_ICNR upsampling`.\"\n def __init__(self, up_in_c:int, x_in_c:int, hook:Hook, final_div:bool=True, blur:bool=False, leaky:float=None,\n self_attention:bool=False):\n super().__init__()\n self.hook = hook\n self.shuf = PixelShuffle_ICNR(up_in_c, up_in_c//2, blur=blur, leaky=leaky)\n self.bn = batchnorm_2d(x_in_c)\n ni = up_in_c//2 + x_in_c\n nf = ni if final_div else ni//2\n self.conv1 = conv_layer(ni, nf, leaky=leaky)\n self.conv2 = conv_layer(nf, nf, leaky=leaky, self_attention=self_attention)\n self.relu = relu(leaky=leaky)\n\n def forward(self, up_in:Tensor) -> Tensor:\n s = self.hook.stored\n up_out = self.shuf(up_in)\n ssh = s.shape[-2:]\n if ssh != up_out.shape[-2:]:\n up_out = F.interpolate(up_out, s.shape[-2:], mode='nearest')\n cat_x = self.relu(torch.cat([up_out, self.bn(s)], dim=1))\n return self.conv2(self.conv1(cat_x))",
"_____no_output_____"
],
[
"def _get_sfs_idxs(sizes:Sizes) -> List[int]:\n \"Get the indexes of the layers where the size of the activation changes.\"\n feature_szs = [size[-1] for size in sizes]\n sfs_idxs = list(np.where(np.array(feature_szs[:-1]) != np.array(feature_szs[1:]))[0])\n if feature_szs[0] != feature_szs[1]: sfs_idxs = [0] + sfs_idxs\n return sfs_idxs",
"_____no_output_____"
],
[
"class UpBlock(nn.Module):\n def __init__(self, ni, nf):\n super(UpBlock, self).__init__()\n self.bn = batchnorm_2d(nf)\n self.conv = Conv2dBlock(nf, nf, ks=5, stride=1, norm=\"bn\", activation=\"relu\", padding=2)\n self.shuf = PixelShuffle_ICNR(ni, nf, blur=False, leaky=None)\n self.relu = nn.ReLU()\n \n def forward(self, xb, body=None):\n up_out = self.shuf(xb)\n \n if(body is not None):\n ssh = body.shape[-2:]\n if ssh != up_out.shape[-2:]:\n up_out = F.interpolate(up_out, body.shape[-2:], mode='nearest')\n up_out = self.relu(up_out+self.bn(body))\n\n xb = self.conv(up_out)\n return xb",
"_____no_output_____"
],
[
"class Conv2dBlock(nn.Module):\n def __init__(self, ni, nf, ks, stride, norm, activation, padding=1):\n super(Conv2dBlock, self).__init__()\n self.pad = nn.ZeroPad2d(padding)\n \n norm_dim = nf\n if norm == 'bn':\n self.norm = nn.BatchNorm2d(norm_dim)\n elif norm == 'in':\n #self.norm = nn.InstanceNorm2d(norm_dim, track_running_stats=True)\n self.norm = nn.InstanceNorm2d(norm_dim)\n elif norm == 'ln':\n self.norm = LayerNorm(norm_dim)\n elif norm == 'adain':\n self.norm = AdaptiveInstanceNorm2d(norm_dim)\n elif norm == 'none':\n self.norm = None\n \n if activation == 'relu':\n self.activation = nn.ReLU(inplace=True)\n elif activation == 'lrelu':\n self.activation = nn.LeakyReLU(0.2, inplace=True)\n elif activation == 'prelu':\n self.activation = nn.PReLU()\n elif activation == 'selu':\n self.activation = nn.SELU(inplace=True)\n elif activation == 'tanh':\n self.activation = nn.Tanh()\n elif activation == 'none':\n self.activation = None\n \n self.conv = nn.Conv2d(ni, nf, ks, stride)\n \n def forward(self, x):\n x = self.conv(self.pad(x))\n if self.norm:\n x = self.norm(x)\n if self.activation:\n x = self.activation(x)\n return x ",
"_____no_output_____"
],
[
"class LayerNorm(nn.Module):\n def __init__(self, num_features, eps=1e-5, affine=True):\n super(LayerNorm, self).__init__()\n self.num_features = num_features\n self.affine = affine\n self.eps = eps\n\n if self.affine:\n self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())\n self.beta = nn.Parameter(torch.zeros(num_features))\n\n def forward(self, x):\n shape = [-1] + [1] * (x.dim() - 1)\n # print(x.size())\n if x.size(0) == 1:\n # These two lines run much faster in pytorch 0.4 than the two lines listed below.\n mean = x.view(-1).mean().view(*shape)\n std = x.view(-1).std().view(*shape)\n else:\n mean = x.view(x.size(0), -1).mean(1).view(*shape)\n std = x.view(x.size(0), -1).std(1).view(*shape)\n\n x = (x - mean) / (std + self.eps)\n\n if self.affine:\n shape = [1, -1] + [1] * (x.dim() - 2)\n x = x * self.gamma.view(*shape) + self.beta.view(*shape)\n return x",
"_____no_output_____"
],
[
"class ResBlocks(nn.Module):\n def __init__(self, num_blocks, dim, norm='in', activation='relu', padding=1):\n super(ResBlocks, self).__init__()\n self.model = []\n for i in range(num_blocks):\n self.model += [ResBlock(dim, norm=norm, activation=activation, padding=padding)]\n self.model = nn.Sequential(*self.model)\n\n def forward(self, x):\n return self.model(x)\n\nclass ResBlock(nn.Module):\n def __init__(self, dim, norm='in', activation='relu', padding=1):\n super(ResBlock, self).__init__()\n self.model = []\n self.model += [Conv2dBlock(dim, dim, 3, 1, norm, activation, padding)]\n self.model += [Conv2dBlock(dim, dim, 3, 1, norm, activation, padding)]\n self.model = nn.Sequential(*self.model)\n \n def forward(self, x):\n return self.model(x) + x",
"_____no_output_____"
],
[
"class MultiUnet(nn.Module):\n def __init__(self, arch:Callable, pretrained:bool=True, cut=None):\n super().__init__()\n \n self.relu = relu(leaky=None)\n \n self.bodyA = create_body(arch, pretrained, cut=-3)\n self.bodyB = create_body(arch, pretrained, cut=-3)\n \n self.sfs_szs = model_sizes(self.bodyA, size=(224,224))\n self.sfs_idxs = list(reversed(_get_sfs_idxs(self.sfs_szs)))\n self.sfsA = hook_outputs([self.bodyA[i] for i in self.sfs_idxs])\n x = dummy_eval(self.bodyA, (224, 224)).detach()\n \n self.sfsB = hook_outputs([self.bodyB[i] for i in self.sfs_idxs])\n x = dummy_eval(self.bodyB, (224, 224)).detach()\n \n unet_blocksA = []\n x = torch.tensor([])\n x = x.new_full((1, 512, 7, 7), 0)\n up_in_c = []\n x_in_c = []\n for i,idx in enumerate(self.sfs_idxs):\n up_in_c.append(int(x.shape[1]))\n x_in_c.append(int(self.sfs_szs[idx][1]))\n not_final = i!=len(self.sfs_idxs)-1\n block = UnetBlock(int(x.shape[1]), int(self.sfs_szs[idx][1]), self.sfsA[i], final_div=not_final, blur=False, self_attention=False).eval()\n x = block(x)\n \n #DecoderA\n self.UpBlockA1 = UpBlock(256, 128)\n self.UpBlockA2 = UpBlock(128, 64)\n self.UpBlockA3 = UpBlock(64, 64)\n self.finalDecoderA = nn.Sequential(PixelShuffle_ICNR(64), conv_layer(64, 3))\n self.ResA = ResBlocks(4, 256, 'in', 'relu', padding=1)\n \n #DecoderB\n self.UpBlockB1 = UpBlock(256, 128)\n self.UpBlockB2 = UpBlock(128, 64)\n self.UpBlockB3 = UpBlock(64, 64)\n self.ResB = ResBlocks(4, 256, 'in', 'relu', padding=1)\n self.finalDecoderB = nn.Sequential(PixelShuffle_ICNR(64), conv_layer(64, 3))\n\n #Shared Layers\n self.sharedEncoderLayer = conv_layer(256, 512, stride=2)\n self.middleConv = nn.Sequential(nn.BatchNorm2d(512), nn.ReLU(512), conv_layer(512, 512*2, stride=1), nn.Conv2d(512*2, 512, 3, stride=1))\n self.UpShared = UpBlock(512, 256)\n\n #Tan layer\n self.tanLayer = nn.Tanh()\n \n \n def EncoderA(self, xb):\n result = self.bodyA(xb)\n return result\n \n def EncoderB(self, xb):\n result = self.bodyB(xb)\n return result\n \n def sharedEncoder(self, xb):\n result = self.sharedEncoderLayer(xb)\n return result\n \n def MiddleConv(self, xb):\n result = self.middleConv(xb)\n return result\n \n def sharedDecoder(self, xb):\n return self.UpShared(xb, None)\n \n def DecoderA(self, xb, body):\n xb = self.ResA(xb)\n xb = self.UpBlockA1(xb, body[0].stored)\n xb = self.UpBlockA2(xb, body[1].stored)\n xb = self.UpBlockA3(xb, body[2].stored)\n\n return self.finalDecoderA(xb)\n \n def DecoderB(self, xb, body):\n xb = self.ResB(xb)\n xb = self.UpBlockB1(xb, body[0].stored)\n xb = self.UpBlockB2(xb, body[1].stored)\n xb = self.UpBlockB3(xb, body[2].stored)\n\n return self.finalDecoderB(xb)\n \n def forward(self, a, b, *pred):\n \n #get initial encodings of both\n a,b = self.EncoderA(a), self.EncoderB(b)\n \n #put both through shared encoder and middle conv\n a,b = self.sharedEncoder(a), self.sharedEncoder(b)\n a,b = self.middleConv(a), self.middleConv(b)\n \n #put images through shared decoder\n a,b = self.sharedDecoder(a), self.sharedDecoder(b)\n \n #Get images that are supposed to be\n aToA, bToB = self.DecoderA(a, body=self.sfsA),self.DecoderB(b, body=self.sfsB)\n\n #Get switched images\n aToB, bToA = self.DecoderB(a, body=self.sfsA), self.DecoderA(b, body=self.sfsB)\n \n allIm = torch.cat((self.tanLayer(aToA), self.tanLayer(bToB), self.tanLayer(aToB), self.tanLayer(bToA)), 0)\n \n return allIm\n ",
"_____no_output_____"
]
],
[
[
"# Critic",
"_____no_output_____"
]
],
[
[
"def conv_and_res(ni, nf): return nn.Sequential(res_block(ni), conv_layer(ni, nf, stride=2, bias=True, use_activ=False, leaky=0.1))",
"_____no_output_____"
],
[
"class MultiUNITDiscriminator(nn.Module):\n def __init__(self):\n super(MultiUNITDiscriminator, self).__init__()\n self.convs = nn.Sequential(\n nn.Conv2d(3, 64, 3, 2, 1),\n conv_and_res(64, 128),\n conv_and_res(128, 256),\n conv_and_res(256, 512),\n nn.Conv2d(512, 1, 3, stride=1),\n Flatten()\n )\n \n def forward(self, not_switched, switched, down=2):\n\n not_switched = self.convs(not_switched)\n switched = self.convs(switched)\n\n return (not_switched,switched)",
"_____no_output_____"
],
[
"class critic_loss(nn.Module):\n #a is 0 and b is 1 for predictions\n def forward(self, output, garbage):\n pred_winter = output[0]\n pred_summer = output[1]\n targWin = pred_winter.new_zeros(*pred_winter.size())\n targSum = pred_summer.new_ones(*pred_summer.size())\n result_winter = F.mse_loss(pred_winter, targWin)\n result_summer = F.mse_loss(pred_summer, targSum)\n return result_winter + result_summer",
"_____no_output_____"
],
[
"critic_learner = Learner(data, MultiUNITDiscriminator(), loss_func=critic_loss(), wd=1e-3)",
"_____no_output_____"
],
[
"#critic_learner.fit_one_cycle(4, wd=0.1)",
"_____no_output_____"
],
[
"#critic_learner.save('critic')",
"_____no_output_____"
],
[
"#critic_learner.load('criticV5-h2z-zfirst')\ncritic_learner.load('criticV5-sum2win-wfirst')\n#critic_learner.load('criticV5-an2la')",
"_____no_output_____"
]
],
[
[
"# Gan Wrapper",
"_____no_output_____"
]
],
[
[
"class GANLearner(Learner):\n \"A `Learner` suitable for GANs.\"\n def __init__(self, data:DataBunch, generator:nn.Module, critic:nn.Module, gen_loss_func:LossFunction,\n crit_loss_func:LossFunction, n_crit=None, n_gen=None, switcher:Callback=None, gen_first:bool=False, switch_eval:bool=True,\n show_img:bool=True, clip:float=None, **learn_kwargs):\n print('in GANLearner')\n gan = GANModule(generator, critic)\n loss_func = GANLoss(gen_loss_func, crit_loss_func, gan)\n switcher = ifnone(switcher, partial(FixedGANSwitcher, n_crit=n_crit, n_gen=n_gen))\n super().__init__(data, gan, loss_func=loss_func, callback_fns=[switcher], **learn_kwargs)\n trainer = GANTrainer(self, clip=clip, switch_eval=switch_eval, show_img=show_img)\n self.gan_trainer = trainer\n self.callbacks.append(trainer)",
"_____no_output_____"
],
[
"class GANModule(nn.Module):\n \"Wrapper around a `generator` and a `critic` to create a GAN.\"\n def __init__(self, generator:nn.Module=None, critic:nn.Module=None, gen_mode:bool=True):\n super().__init__()\n print('in GANModule')\n self.gen_mode = gen_mode\n if generator: self.generator,self.critic = generator,critic\n\n def forward(self, *args):\n return self.generator(*args) if self.gen_mode else self.critic(*args)\n\n def switch(self, gen_mode:bool=None):\n \"Put the model in generator mode if `gen_mode`, in critic mode otherwise.\"\n self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode",
"_____no_output_____"
],
[
"class GANLoss(GANModule):\n \"Wrapper around `loss_funcC` (for the critic) and `loss_funcG` (for the generator).\"\n def __init__(self, loss_funcG:Callable, loss_funcC:Callable, gan_model:GANModule):\n super().__init__()\n print('in GANLoss')\n self.loss_funcG,self.loss_funcC,self.gan_model = loss_funcG,loss_funcC,gan_model\n\n def generator(self, output, x_a, x_b):\n \"Evaluate the `output` with the critic then uses `self.loss_funcG` to combine it with `target`.\"\n output = torch.split(output, 2, dim=0)\n x_a_recon, x_b_recon = torch.split(output[0], 1, dim=0)\n x_ab, x_ba = torch.split(output[1], 1, dim=0)\n fake_pred_x_aa, fake_pred_x_bb = self.gan_model.critic(x_a_recon, x_b_recon)\n fake_pred_x_ab, fake_pred_x_ba = self.gan_model.critic(x_ab, x_ba)\n \n cycled_output = self.gan_model.generator(x_ba, x_ab)\n cycle_a = cycled_output[3]\n cycle_b = cycled_output[2]\n return self.loss_funcG(x_a, x_b, x_a_recon, x_b_recon, cycle_a, cycle_b, fake_pred_x_ab, fake_pred_x_ba)\n\n def critic(self, real_pred, b, c):\n fake = self.gan_model.generator(b.requires_grad_(False), c.requires_grad_(False)).requires_grad_(True)\n fake = torch.split(fake, 2, dim=0)\n fake_ns = torch.split(fake[0], 1, dim=0)\n fake_s = torch.split(fake[1], 1, dim=0)\n fake_pred_aToA, fake_pred_bToB = self.gan_model.critic(fake_ns[0], fake_ns[1])\n fake_pred_aToB, fake_pred_bToA = self.gan_model.critic(fake_s[0], fake_s[1])\n return self.loss_funcC(real_pred[0], real_pred[1], fake_pred_aToA, fake_pred_bToB, fake_pred_aToB, fake_pred_bToA)",
"_____no_output_____"
],
[
"class GANTrainer(LearnerCallback):\n \"Handles GAN Training.\"\n _order=-20\n def __init__(self, learn:Learner, switch_eval:bool=False, clip:float=None, beta:float=0.98, gen_first:bool=False,\n show_img:bool=True):\n super().__init__(learn)\n self.switch_eval,self.clip,self.beta,self.gen_first,self.show_img = switch_eval,clip,beta,gen_first,show_img\n self.generator,self.critic = self.model.generator,self.model.critic\n\n def _set_trainable(self):\n train_model = self.generator if self.gen_mode else self.critic\n loss_model = self.generator if not self.gen_mode else self.critic\n requires_grad(train_model, True)\n requires_grad(loss_model, False)\n if self.switch_eval:\n train_model.train()\n loss_model.eval()\n\n def on_train_begin(self, **kwargs):\n \"Create the optimizers for the generator and critic if necessary, initialize smootheners.\"\n if not getattr(self,'opt_gen',None):\n self.opt_gen = self.opt.new([nn.Sequential(*flatten_model(self.generator))])\n else: self.opt_gen.lr,self.opt_gen.wd = self.opt.lr,self.opt.wd\n if not getattr(self,'opt_critic',None):\n self.opt_critic = self.opt.new([nn.Sequential(*flatten_model(self.critic))])\n else: self.opt_critic.lr,self.opt_critic.wd = self.opt.lr,self.opt.wd\n self.gen_mode = self.gen_first\n self.switch(self.gen_mode)\n self.closses,self.glosses = [],[]\n self.smoothenerG,self.smoothenerC = SmoothenValue(self.beta),SmoothenValue(self.beta)\n self.recorder.add_metric_names(['gen_loss', 'disc_loss'])\n self.imgs,self.titles = [],[]\n\n def on_train_end(self, **kwargs):\n \"Switch in generator mode for showing results.\"\n self.switch(gen_mode=True)\n\n def on_batch_begin(self, last_input, last_target, **kwargs):\n \"Clamp the weights with `self.clip` if it's not None, return the correct input.\"\n if self.gen_mode:\n self.last_input = last_input\n \n if self.clip is not None:\n for p in self.critic.parameters(): p.data.clamp_(-self.clip, self.clip)\n test = {'last_input':last_input,'last_target':last_input}\n #print(test)\n return test\n \n def on_backward_begin(self, last_loss, last_output, **kwargs):\n \"Record `last_loss` in the proper list.\"\n last_loss = last_loss.detach().cpu()\n if self.gen_mode:\n self.smoothenerG.add_value(last_loss)\n self.glosses.append(self.smoothenerG.smooth)\n self.last_gen = last_output.detach().cpu()\n last_gen_split = torch.split(self.last_gen, 1, 0)\n self.last_critic_preds_ns = self.gan_trainer.critic(last_gen_split[0].cuda(), last_gen_split[1].cuda())\n self.last_critic_preds_s = self.gan_trainer.critic(last_gen_split[2].cuda(), last_gen_split[3].cuda())\n else:\n self.smoothenerC.add_value(last_loss)\n self.closses.append(self.smoothenerC.smooth)\n\n def on_epoch_begin(self, epoch, **kwargs):\n \"Put the critic or the generator back to eval if necessary.\"\n self.switch(self.gen_mode)\n\n def on_epoch_end(self, pbar, epoch, last_metrics, **kwargs):\n \"Put the various losses in the recorder and show a sample image.\"\n if not hasattr(self, 'last_gen') or not self.show_img: return\n data = self.learn.data\n inputBPre = torch.unbind(self.last_input[1], dim=0)\n aToA = im.Image(self.last_gen[0]/2+0.5)\n bToB = im.Image(self.last_gen[1]/2+0.5)\n aToB = im.Image(self.last_gen[2]/2+0.5)\n bToA = im.Image(self.last_gen[3]/2+0.5)\n self.imgs.append(aToA)\n self.imgs.append(aToB)\n self.imgs.append(bToB)\n self.imgs.append(bToA)\n self.titles.append(f'Epoch {epoch}-A to A')\n self.titles.append(f'Epoch {epoch}-A to B')\n self.titles.append(f'Epoch {epoch}-B to B')\n self.titles.append(f'Epoch {epoch}-B to A')\n pbar.show_imgs(self.imgs, self.titles)\n return add_metrics(last_metrics, [getattr(self.smoothenerG,'smooth',None),getattr(self.smoothenerC,'smooth',None)])\n\n def switch(self, gen_mode:bool=None):\n \"Switch the model, if `gen_mode` is provided, in the desired mode.\"\n self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode\n self.opt.opt = self.opt_gen.opt if self.gen_mode else self.opt_critic.opt\n self._set_trainable()\n self.model.switch(gen_mode)\n self.loss_func.switch(gen_mode)",
"_____no_output_____"
],
[
"class FixedGANSwitcher(LearnerCallback):\n \"Switcher to do `n_crit` iterations of the critic then `n_gen` iterations of the generator.\"\n def __init__(self, learn:Learner, n_crit=5, n_gen=1):\n super().__init__(learn)\n self.n_crit,self.n_gen = 1,1\n\n def on_train_begin(self, **kwargs):\n \"Initiate the iteration counts.\"\n self.n_c,self.n_g = 0,0\n\n def on_batch_end(self, iteration, **kwargs):\n \"Switch the model if necessary.\"\n if self.learn.gan_trainer.gen_mode:\n self.n_g += 1\n n_iter,n_in,n_out = self.n_gen,self.n_c,self.n_g\n else:\n self.n_c += 1\n n_iter,n_in,n_out = self.n_crit,self.n_g,self.n_c\n target = n_iter if isinstance(n_iter, int) else n_iter(n_in)\n if target == n_out:\n self.learn.gan_trainer.switch()\n self.n_c,self.n_g = 0,0",
"_____no_output_____"
]
],
[
[
"# Training",
"_____no_output_____"
]
],
[
[
"class disc_loss(nn.Module):\n #a is 0 and b is 1 for predictions\n def forward(self, real_pred_a, real_pred_b, aToA, bToB, aToB, bToA):\n loss = 0\n #Real Image Predictions\n loss += F.mse_loss(real_pred_a, real_pred_a.new_zeros(*real_pred_a.size()))\n\n loss += F.mse_loss(real_pred_b, real_pred_b.new_zeros(*real_pred_b.size()))\n\n #Translated Predictions\n loss += F.mse_loss(aToB, aToB.new_zeros(*aToB.size()))\n\n loss += F.mse_loss(bToA, bToA.new_ones(*bToA.size()))\n \n return loss",
"_____no_output_____"
],
[
"class gen_loss(nn.Module):\n \n def content_similar(self, input, target):\n return F.l1_loss(input, target)*(10)\n \n def should_look_like_a(self, input_fake_pred):\n target = input_fake_pred.new_zeros(*input_fake_pred.size())\n return F.mse_loss(input_fake_pred, target)\n \n def should_look_like_b(self, input_fake_pred):\n target = input_fake_pred.new_ones(*input_fake_pred.size())\n return F.mse_loss(input_fake_pred, target)\n \n def forward(self, x_a, x_b, x_a_recon, x_b_recon, x_a_cycled, x_b_cycled, fake_pred_x_ab, fake_pred_x_ba):\n loss = 0\n x_a, x_b, x_a_recon, x_b_recon = torch.unbind(x_a, dim=0)[0], torch.unbind(x_b, dim=0)[0], torch.unbind(x_a_recon, dim=0)[0], torch.unbind(x_a_recon, dim=0)[0]\n \n loss += self.should_look_like_a(fake_pred_x_ba)\n loss += self.should_look_like_b(fake_pred_x_ab)\n \n loss += self.content_similar(x_a, x_a_recon)*(0.5)\n loss += self.content_similar(x_b, x_b_recon)*(0.5)\n \n loss += self.content_similar(x_a, x_a_cycled)\n loss += self.content_similar(x_b, x_b_cycled)\n return loss",
"_____no_output_____"
]
],
[
[
"# GAN Training",
"_____no_output_____"
]
],
[
[
"generator = MultiUnet(models.resnet34)\nmultiGan = GANLearner(data,\n generator=generator,\n critic=critic_learner.model,\n gen_loss_func=gen_loss(),\n crit_loss_func=disc_loss(), opt_func=partial(optim.Adam, betas=(0.5,0.99)))",
"_____no_output_____"
],
[
"multiGan.fit_one_cycle(100, 1e-4)",
"_____no_output_____"
],
[
"multiGan.load('v5-trial1')",
"_____no_output_____"
]
],
[
[
"# Results",
"_____no_output_____"
]
],
[
[
"#Show input images\nrows=2\nx,y = next(iter(data.train_dl))\nbeforeA = torch.unbind(x[0], dim=0)[0].cpu()\nbeforeA = im.Image(beforeA/2+0.5)\nbeforeB = torch.unbind(x[1], dim=0)[0].cpu()\nbeforeB = im.Image(beforeB/2+0.5)\nimages = [beforeA, beforeB]\nfig, axs = plt.subplots(1,2,figsize=(8,8))\nfor i, ax in enumerate(axs.flatten() if rows > 1 else [axs]):\n images[i].show(ax=ax)\nplt.tight_layout()",
"_____no_output_____"
],
[
"#Show results\npred = multiGan.gan_trainer.generator(x[0], x[1], True)\npredAA = pred[0]\npredBB = pred[1]\npredAB = pred[2]\npredBA = pred[3]\npredAA = im.Image(predAA.detach()/2+0.5)\npredBB = im.Image(predBB.detach()/2+0.5)\npredAB = im.Image(predAB.detach()/2+0.5)\npredBA = im.Image(predBA.detach()/2+0.5)\nimages = [predAA, predAB, predBB, predBA]\ntitles = [\"A to A\", \"A to B\", \"B to B\", \"B to A\"]\nfig, axs = plt.subplots(2,2,figsize=(8,8))\nfor i, ax in enumerate(axs.flatten() if rows > 1 else [axs]):\n images[i].show(ax=ax, title=titles[i])\nplt.tight_layout()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb7a462caeb6b958bb5ab08f36e634a27ec154a5
| 169,478 |
ipynb
|
Jupyter Notebook
|
Kaggle/Mercedes-Benz Greener Manufacturing/Stacked_model.ipynb
|
datitran/Krimskrams
|
24089f960c31934287ee8ad4eba8093991c06d7a
|
[
"MIT"
] | null | null | null |
Kaggle/Mercedes-Benz Greener Manufacturing/Stacked_model.ipynb
|
datitran/Krimskrams
|
24089f960c31934287ee8ad4eba8093991c06d7a
|
[
"MIT"
] | null | null | null |
Kaggle/Mercedes-Benz Greener Manufacturing/Stacked_model.ipynb
|
datitran/Krimskrams
|
24089f960c31934287ee8ad4eba8093991c06d7a
|
[
"MIT"
] | 2 |
2020-02-15T08:10:42.000Z
|
2020-02-15T08:36:16.000Z
| 176.539583 | 28,354 | 0.863687 |
[
[
[
"import xgboost as xgb\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use(\"ggplot\")\n%matplotlib inline\n\nfrom xgboost import XGBRegressor\nfrom sklearn import preprocessing\nfrom sklearn.base import BaseEstimator, TransformerMixin, ClassifierMixin\nfrom sklearn.linear_model import ElasticNetCV, LassoLarsCV\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.utils import check_array\nfrom sklearn.decomposition import PCA, FastICA\nfrom sklearn.metrics import r2_score",
"_____no_output_____"
],
[
"class StackingEstimator(BaseEstimator):\n \n def __init__(self, estimator):\n self.estimator = estimator\n \n def fit(self, X, y=None, **fit_params):\n self.estimator.fit(X, y, **fit_params)\n return self\n \n def transform(self, X):\n X = check_array(X)\n X_transformed = np.copy(X)\n X_transformed = np.hstack((np.reshape(self.estimator.predict(X), (-1, 1)), X_transformed))\n return X_transformed",
"_____no_output_____"
],
[
"train = pd.read_csv(\"data/train.csv\", index_col=\"ID\")\ntest = pd.read_csv(\"data/test.csv\", index_col=\"ID\")",
"_____no_output_____"
],
[
"for c in train.columns:\n if train[c].dtype == \"object\":\n lbl = preprocessing.LabelEncoder()\n lbl.fit(list(train[c].values) + list(test[c].values))\n train[c] = lbl.transform(list(train[c].values))\n test[c] = lbl.transform(list(test[c].values))",
"_____no_output_____"
],
[
"n_comp = 10\n\n# PCA\npca = PCA(n_components=n_comp, random_state=42)\npca2_results_train = pca.fit_transform(train.drop([\"y\"], axis=1))\npca2_results_test = pca.transform(test)\n\n# ICA\nica = FastICA(n_components=n_comp, random_state=42)\nica2_results_train = ica.fit_transform(train.drop([\"y\"], axis=1))\nica2_results_test = ica.transform(test)",
"_____no_output_____"
],
[
"y_train = train[\"y\"].values\ny_mean = np.mean(y_train)",
"_____no_output_____"
],
[
"stacked_pipeline = make_pipeline(\n StackingEstimator(estimator=LassoLarsCV(normalize=True)),\n StackingEstimator(estimator=XGBRegressor(\n n_estimators=700,\n learning_rate=0.005,\n max_depth=3,\n gamma=0.3,\n min_child_weight=6,\n subsample=0.8,\n colsample_bytree=0.65,\n objective=\"reg:linear\",\n base_score=y_mean)),\n LassoLarsCV()\n)",
"_____no_output_____"
],
[
"stacked_pipeline.fit(train.drop(\"y\", axis=1), y_train)",
"/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 2 iterations, i.e. alpha=6.025e-02, with an active set of 2 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 3 iterations, i.e. alpha=5.597e-02, with an active set of 3 regressors, and the smallest cholesky pivot element being 1.825e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:377: RuntimeWarning: overflow encountered in true_divide\n g1 = arrayfuncs.min_pos((C - Cov) / (AA - corr_eq_dir + tiny))\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:381: RuntimeWarning: overflow encountered in true_divide\n g2 = arrayfuncs.min_pos((C + Cov) / (AA + corr_eq_dir + tiny))\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=4.307e-02, with an active set of 4 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 5 iterations, i.e. alpha=3.743e-02, with an active set of 5 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 9 iterations, i.e. alpha=2.938e-02, with an active set of 9 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 12 iterations, i.e. alpha=2.070e-02, with an active set of 12 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:334: ConvergenceWarning: Early stopping the lars path, as the residues are small and the current value of alpha is no longer well controlled. 15 iterations, alpha=1.924e-02, previous alpha=1.920e-02, with an active set of 14 regressors.\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 2 iterations, i.e. alpha=5.893e-02, with an active set of 2 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=3.462e-02, with an active set of 4 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 5 iterations, i.e. alpha=2.886e-02, with an active set of 5 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 14 iterations, i.e. alpha=1.865e-02, with an active set of 12 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 14 iterations, i.e. alpha=1.852e-02, with an active set of 12 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 15 iterations, i.e. alpha=1.661e-02, with an active set of 13 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 15 iterations, i.e. alpha=1.652e-02, with an active set of 13 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 19 iterations, i.e. alpha=1.421e-02, with an active set of 17 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 20 iterations, i.e. alpha=1.360e-02, with an active set of 18 regressors, and the smallest cholesky pivot element being 5.162e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:334: ConvergenceWarning: Early stopping the lars path, as the residues are small and the current value of alpha is no longer well controlled. 24 iterations, alpha=1.273e-02, previous alpha=1.237e-02, with an active set of 19 regressors.\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 3 iterations, i.e. alpha=5.688e-02, with an active set of 3 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=3.728e-02, with an active set of 4 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=3.728e-02, with an active set of 4 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 9 iterations, i.e. alpha=1.933e-02, with an active set of 9 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 12 iterations, i.e. alpha=1.826e-02, with an active set of 12 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 12 iterations, i.e. alpha=1.826e-02, with an active set of 12 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 18 iterations, i.e. alpha=1.075e-02, with an active set of 18 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 20 iterations, i.e. alpha=9.662e-03, with an active set of 20 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 20 iterations, i.e. alpha=9.662e-03, with an active set of 20 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 23 iterations, i.e. alpha=9.090e-03, with an active set of 23 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:334: ConvergenceWarning: Early stopping the lars path, as the residues are small and the current value of alpha is no longer well controlled. 27 iterations, alpha=8.497e-03, previous alpha=8.374e-03, with an active set of 26 regressors.\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 3 iterations, i.e. alpha=4.682e-02, with an active set of 3 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 3 iterations, i.e. alpha=4.682e-02, with an active set of 3 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 3 iterations, i.e. alpha=4.682e-02, with an active set of 3 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=2.341e-02, with an active set of 4 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=2.341e-02, with an active set of 4 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=2.341e-02, with an active set of 4 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 14 iterations, i.e. alpha=1.330e-02, with an active set of 14 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 15 iterations, i.e. alpha=1.282e-02, with an active set of 15 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 16 iterations, i.e. alpha=1.211e-02, with an active set of 16 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 17 iterations, i.e. alpha=1.130e-02, with an active set of 17 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 17 iterations, i.e. alpha=1.130e-02, with an active set of 17 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 19 iterations, i.e. alpha=1.049e-02, with an active set of 19 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 19 iterations, i.e. alpha=1.049e-02, with an active set of 19 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 21 iterations, i.e. alpha=9.503e-03, with an active set of 19 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 21 iterations, i.e. alpha=9.364e-03, with an active set of 19 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 21 iterations, i.e. alpha=9.326e-03, with an active set of 19 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 5 iterations, i.e. alpha=6.224e-03, with an active set of 5 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:377: RuntimeWarning: overflow encountered in true_divide\n g1 = arrayfuncs.min_pos((C - Cov) / (AA - corr_eq_dir + tiny))\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 6 iterations, i.e. alpha=6.068e-03, with an active set of 6 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 33 iterations, i.e. alpha=2.976e-03, with an active set of 31 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 33 iterations, i.e. alpha=2.976e-03, with an active set of 31 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:381: RuntimeWarning: overflow encountered in true_divide\n g2 = arrayfuncs.min_pos((C + Cov) / (AA + corr_eq_dir + tiny))\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 65 iterations, i.e. alpha=2.105e-03, with an active set of 59 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 68 iterations, i.e. alpha=2.047e-03, with an active set of 62 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 70 iterations, i.e. alpha=2.004e-03, with an active set of 64 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 79 iterations, i.e. alpha=1.839e-03, with an active set of 71 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 79 iterations, i.e. alpha=1.839e-03, with an active set of 71 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 80 iterations, i.e. alpha=1.833e-03, with an active set of 72 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 82 iterations, i.e. alpha=1.792e-03, with an active set of 74 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 87 iterations, i.e. alpha=1.733e-03, with an active set of 79 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 87 iterations, i.e. alpha=1.733e-03, with an active set of 79 regressors, and the smallest cholesky pivot element being 6.829e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:334: ConvergenceWarning: Early stopping the lars path, as the residues are small and the current value of alpha is no longer well controlled. 91 iterations, alpha=1.661e-03, previous alpha=1.661e-03, with an active set of 82 regressors.\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 4 iterations, i.e. alpha=6.781e-03, with an active set of 4 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 21 iterations, i.e. alpha=4.066e-03, with an active set of 21 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 23 iterations, i.e. alpha=3.953e-03, with an active set of 23 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 23 iterations, i.e. alpha=3.953e-03, with an active set of 23 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 43 iterations, i.e. alpha=2.638e-03, with an active set of 43 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 43 iterations, i.e. alpha=2.638e-03, with an active set of 43 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 48 iterations, i.e. alpha=2.507e-03, with an active set of 48 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 53 iterations, i.e. alpha=2.350e-03, with an active set of 53 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 53 iterations, i.e. alpha=2.350e-03, with an active set of 53 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 53 iterations, i.e. alpha=2.350e-03, with an active set of 53 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 66 iterations, i.e. alpha=1.923e-03, with an active set of 64 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 66 iterations, i.e. alpha=1.923e-03, with an active set of 64 regressors, and the smallest cholesky pivot element being 1.825e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 67 iterations, i.e. alpha=1.883e-03, with an active set of 65 regressors, and the smallest cholesky pivot element being 6.989e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 75 iterations, i.e. alpha=1.758e-03, with an active set of 73 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 75 iterations, i.e. alpha=1.758e-03, with an active set of 73 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 78 iterations, i.e. alpha=1.703e-03, with an active set of 76 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 78 iterations, i.e. alpha=1.703e-03, with an active set of 76 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 78 iterations, i.e. alpha=1.700e-03, with an active set of 76 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 81 iterations, i.e. alpha=1.672e-03, with an active set of 79 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 83 iterations, i.e. alpha=1.582e-03, with an active set of 81 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 99 iterations, i.e. alpha=1.387e-03, with an active set of 97 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 99 iterations, i.e. alpha=1.387e-03, with an active set of 97 regressors, and the smallest cholesky pivot element being 4.081e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 102 iterations, i.e. alpha=1.314e-03, with an active set of 100 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 105 iterations, i.e. alpha=1.257e-03, with an active set of 103 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 106 iterations, i.e. alpha=1.237e-03, with an active set of 104 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 111 iterations, i.e. alpha=1.144e-03, with an active set of 109 regressors, and the smallest cholesky pivot element being 6.664e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 111 iterations, i.e. alpha=1.139e-03, with an active set of 109 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 115 iterations, i.e. alpha=1.108e-03, with an active set of 113 regressors, and the smallest cholesky pivot element being 3.799e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 116 iterations, i.e. alpha=1.100e-03, with an active set of 114 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 120 iterations, i.e. alpha=1.050e-03, with an active set of 118 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 124 iterations, i.e. alpha=1.010e-03, with an active set of 120 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 128 iterations, i.e. alpha=9.533e-04, with an active set of 124 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 129 iterations, i.e. alpha=9.529e-04, with an active set of 125 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 129 iterations, i.e. alpha=9.529e-04, with an active set of 125 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:334: ConvergenceWarning: Early stopping the lars path, as the residues are small and the current value of alpha is no longer well controlled. 131 iterations, alpha=1.066e-03, previous alpha=9.387e-04, with an active set of 126 regressors.\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 7 iterations, i.e. alpha=6.391e-03, with an active set of 7 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 31 iterations, i.e. alpha=3.195e-03, with an active set of 31 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 31 iterations, i.e. alpha=3.195e-03, with an active set of 31 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 38 iterations, i.e. alpha=2.847e-03, with an active set of 38 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 44 iterations, i.e. alpha=2.693e-03, with an active set of 44 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 47 iterations, i.e. alpha=2.519e-03, with an active set of 47 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 49 iterations, i.e. alpha=2.460e-03, with an active set of 49 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 51 iterations, i.e. alpha=2.411e-03, with an active set of 51 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 56 iterations, i.e. alpha=2.323e-03, with an active set of 56 regressors, and the smallest cholesky pivot element being 1.825e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 61 iterations, i.e. alpha=2.207e-03, with an active set of 61 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 65 iterations, i.e. alpha=2.098e-03, with an active set of 65 regressors, and the smallest cholesky pivot element being 2.107e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 65 iterations, i.e. alpha=2.098e-03, with an active set of 65 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 65 iterations, i.e. alpha=2.098e-03, with an active set of 65 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 69 iterations, i.e. alpha=2.021e-03, with an active set of 69 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 78 iterations, i.e. alpha=1.783e-03, with an active set of 76 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 94 iterations, i.e. alpha=1.505e-03, with an active set of 92 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 94 iterations, i.e. alpha=1.505e-03, with an active set of 92 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 94 iterations, i.e. alpha=1.505e-03, with an active set of 92 regressors, and the smallest cholesky pivot element being 4.215e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 100 iterations, i.e. alpha=1.385e-03, with an active set of 98 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 101 iterations, i.e. alpha=1.378e-03, with an active set of 99 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 101 iterations, i.e. alpha=1.378e-03, with an active set of 99 regressors, and the smallest cholesky pivot element being 2.220e-16\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 101 iterations, i.e. alpha=1.378e-03, with an active set of 99 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 102 iterations, i.e. alpha=1.354e-03, with an active set of 100 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 102 iterations, i.e. alpha=1.354e-03, with an active set of 100 regressors, and the smallest cholesky pivot element being 4.081e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 103 iterations, i.e. alpha=1.329e-03, with an active set of 101 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 103 iterations, i.e. alpha=1.327e-03, with an active set of 101 regressors, and the smallest cholesky pivot element being 5.162e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 104 iterations, i.e. alpha=1.303e-03, with an active set of 102 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 112 iterations, i.e. alpha=1.194e-03, with an active set of 108 regressors, and the smallest cholesky pivot element being 4.081e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 112 iterations, i.e. alpha=1.194e-03, with an active set of 108 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 114 iterations, i.e. alpha=1.159e-03, with an active set of 110 regressors, and the smallest cholesky pivot element being 1.490e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:309: ConvergenceWarning: Regressors in active set degenerate. Dropping a regressor, after 115 iterations, i.e. alpha=1.147e-03, with an active set of 111 regressors, and the smallest cholesky pivot element being 1.054e-08\n ConvergenceWarning)\n/Users/datitran/anaconda/envs/kaggle/lib/python3.5/site-packages/sklearn/linear_model/least_angle.py:334: ConvergenceWarning: Early stopping the lars path, as the residues are small and the current value of alpha is no longer well controlled. 117 iterations, alpha=1.233e-03, previous alpha=1.135e-03, with an active set of 112 regressors.\n ConvergenceWarning)\n"
],
[
"y_pred_train_stack = stacked_pipeline.predict(train.drop(\"y\", axis=1))\nprint(r2_score(y_train, y_pred_train_stack))",
"0.592427725976\n"
],
[
"y_predict_stacked = stacked_pipeline.predict(test)",
"_____no_output_____"
],
[
"y_predict_stacked",
"_____no_output_____"
]
],
[
[
"### XGBoost",
"_____no_output_____"
]
],
[
[
"xgb_params = XGBRegressor(n_estimators=700,\n learning_rate=0.005,\n max_depth=3,\n gamma=0.3,\n min_child_weight=6,\n subsample=0.8,\n colsample_bytree=0.65,\n objective=\"reg:linear\",\n base_score=y_mean)",
"_____no_output_____"
],
[
"dtrain = xgb.DMatrix(train.drop(\"y\", axis=1), y_train)\ndtest = xgb.DMatrix(test)",
"_____no_output_____"
],
[
"cv_output = xgb.cv(xgb_params.get_params(), dtrain, num_boost_round=2000, early_stopping_rounds=50, \n verbose_eval=50, show_stdv=False)",
"[0]\ttrain-rmse:12.6411\ttest-rmse:12.6384\n[50]\ttrain-rmse:11.1835\ttest-rmse:11.1891\n[100]\ttrain-rmse:10.1723\ttest-rmse:10.1908\n[150]\ttrain-rmse:9.49111\ttest-rmse:9.52495\n[200]\ttrain-rmse:9.04012\ttest-rmse:9.08874\n[250]\ttrain-rmse:8.7446\ttest-rmse:8.80755\n[300]\ttrain-rmse:8.55546\ttest-rmse:8.63224\n[350]\ttrain-rmse:8.42953\ttest-rmse:8.52163\n[400]\ttrain-rmse:8.3432\ttest-rmse:8.45131\n[450]\ttrain-rmse:8.28158\ttest-rmse:8.4066\n[500]\ttrain-rmse:8.23576\ttest-rmse:8.37736\n[550]\ttrain-rmse:8.19845\ttest-rmse:8.35889\n[600]\ttrain-rmse:8.16816\ttest-rmse:8.34559\n[650]\ttrain-rmse:8.14054\ttest-rmse:8.33755\n[700]\ttrain-rmse:8.1166\ttest-rmse:8.33257\n[750]\ttrain-rmse:8.09468\ttest-rmse:8.32906\n[800]\ttrain-rmse:8.07387\ttest-rmse:8.32693\n[850]\ttrain-rmse:8.05142\ttest-rmse:8.32566\n"
],
[
"cv_output[[\"train-rmse-mean\", \"test-rmse-mean\"]].plot()\npass",
"_____no_output_____"
],
[
"num_boost_rounds = len(cv_output)\nmodel = xgb.train(dict(xgb_params.get_params(), silent=0), dtrain, num_boost_round=num_boost_rounds)",
"_____no_output_____"
],
[
"y_pred_train = model.predict(dtrain)",
"_____no_output_____"
],
[
"r2_score(y_train, y_pred_train)",
"_____no_output_____"
],
[
"y_predict_xgb = model.predict(dtest)",
"_____no_output_____"
],
[
"y_predict_xgb",
"_____no_output_____"
]
],
[
[
"### Need to do cross-validation for stack and xgb; in terms of r2_score\n\n0.5 * xgb + 0.5 * stacked = test vs. test -> optimization problem; find x1 and x2 where it perfect",
"_____no_output_____"
]
],
[
[
"x1 = np.arange(0, 1.1, 0.1)\nr2_values = []\nfor i in x1:\n r2_values.append(r2_score(y_train, i * y_pred_train_stack + (1-i) * y_pred_train))",
"_____no_output_____"
],
[
"r2_values",
"_____no_output_____"
]
],
[
[
"### Visualization",
"_____no_output_____"
]
],
[
[
"pd.Series(y_train).hist(bins=100)",
"_____no_output_____"
],
[
"pd.Series(y_pred_train_stack).hist(bins=100)",
"_____no_output_____"
],
[
"pd.Series(y_predict_stacked).hist(bins=100)",
"_____no_output_____"
],
[
"# xgboost normal\npd.Series(y_pred_train).hist(bins=100)",
"_____no_output_____"
],
[
"pd.Series(y_train).plot()",
"_____no_output_____"
]
],
[
[
"### Output",
"_____no_output_____"
]
],
[
[
"weight = 0.2\ny_predict_combined = weight * y_predict_stacked + (1-weight) * y_predict_xgb",
"_____no_output_____"
],
[
"output = pd.DataFrame({\"ID\": test.index, \"y\": y_predict_combined})",
"_____no_output_____"
],
[
"output.to_csv(\"submissions_stacked_combined.csv\", index=False)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb7a4ff0817c28cdcb54220750e03016dec4528c
| 240,091 |
ipynb
|
Jupyter Notebook
|
Traffic_Sign_Classifier.ipynb
|
NicholasPHansen/CarND-Traffic-Sign-Classifier-Project
|
567e0e31b791a79aa3ee89d50c3d967a06191524
|
[
"MIT"
] | null | null | null |
Traffic_Sign_Classifier.ipynb
|
NicholasPHansen/CarND-Traffic-Sign-Classifier-Project
|
567e0e31b791a79aa3ee89d50c3d967a06191524
|
[
"MIT"
] | null | null | null |
Traffic_Sign_Classifier.ipynb
|
NicholasPHansen/CarND-Traffic-Sign-Classifier-Project
|
567e0e31b791a79aa3ee89d50c3d967a06191524
|
[
"MIT"
] | null | null | null | 239.372881 | 162,632 | 0.892945 |
[
[
[
"# Self-Driving Car Engineer Nanodegree\n\n## Deep Learning\n\n## Project: Build a Traffic Sign Recognition Classifier\n\nIn this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary. \n\n> **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython 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 is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) that can be used to guide the writing process. Completing the code template and writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/481/view) for this project.\n\nThe [rubric](https://review.udacity.com/#!/rubrics/481/view) contains \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the \"stand out suggestions\", you can include the code in this Ipython notebook and also discuss the results in the writeup file.\n\n\n>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.",
"_____no_output_____"
],
[
"---\n## Step 0: Load The Data",
"_____no_output_____"
]
],
[
[
"# Load pickled data\nimport pickle\n\ntraining_file = 'traffic-signs-data/train.p'\nvalidation_file='traffic-signs-data/valid.p'\ntesting_file = 'traffic-signs-data/test.p'\n\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\nwith open(validation_file, mode='rb') as f:\n valid = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n test = pickle.load(f)\n \nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']",
"_____no_output_____"
]
],
[
[
"---\n\n## Step 1: Dataset Summary & Exploration\n\nThe pickled data is a dictionary with 4 key/value pairs:\n\n- `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).\n- `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.csv` contains id -> name mappings for each id.\n- `'sizes'` is a list containing tuples, (width, height) representing the original width and height the image.\n- `'coords'` is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. **THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES**\n\nComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the [pandas shape method](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html) might be useful for calculating some of the summary results. ",
"_____no_output_____"
],
[
"### Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas",
"_____no_output_____"
]
],
[
[
"### Replace each question mark with the appropriate value. \n### Use python, pandas or numpy methods rather than hard coding the results\nimport numpy as np\n\n# TODO: Number of training examples\nn_train = X_train.shape[0]\n\n# TODO: Number of validation examples\nn_validation = X_valid.shape[0]\n\n# TODO: Number of testing examples.\nn_test = X_test.shape[0]\n\n# TODO: What's the shape of an traffic sign image?\nimage_shape = X_train.shape[1:3]\n\n# TODO: How many unique classes/labels there are in the dataset.\nn_classes = len(np.unique(y_train))\n\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Number of validation examples =\", n_validation)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)",
"Number of training examples = 34799\nNumber of testing examples = 12630\nNumber of validation examples = 4410\nImage data shape = (32, 32)\nNumber of classes = 43\n"
]
],
[
[
"### Include an exploratory visualization of the dataset",
"_____no_output_____"
],
[
"Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. \n\nThe [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index.html) and [gallery](http://matplotlib.org/gallery.html) pages are a great resource for doing visualizations in Python.\n\n**NOTE:** It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?",
"_____no_output_____"
]
],
[
[
"### Data exploration visualization code goes here.\n### Feel free to use as many code cells as needed.\nimport matplotlib.pyplot as plt\n# Visualizations will be shown in the notebook.\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Plotting random images of the training set\n\nBelow is shown a 5x5 grid of randomly chosen images of the dataset.\nThe images are of dimension 32x32x3, so 32x32 pixel of RGB values.",
"_____no_output_____"
]
],
[
[
"width = 5\nheight = 5\n\nfig, axes = plt.subplots(height, width, figsize=(18, 16))\nfor i in range(height):\n for j in range(width):\n idx = np.random.choice(n_train, 1)[0]\n axes[i, j].imshow(X_train[idx])",
"_____no_output_____"
]
],
[
[
"To visualize the different datasets (test, train & validation), the amount of each image type in each of the sets, is shown below in a bar plot.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\nunique, train_counts = np.unique(y_train, return_counts=True)\nunique, test_counts = np.unique(y_test, return_counts=True)\nunique, valid_counts = np.unique(y_valid, return_counts=True)\n\ndf = pd.DataFrame({'train': train_counts, 'test': test_counts, 'validation': valid_counts}, index=unique)\naxes = df.plot(kind=\"bar\", subplots=True, layout=(2,2), sharey=True, sharex=True, figsize=(18, 16))\n\nfig=axes[0,0].figure\nfig.text(0.5,0.04, \"Image labels\", ha=\"center\", va=\"center\")\nfig.text(0.05,0.5, \"Number of images\", ha=\"center\", va=\"center\", rotation=90)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"At a first glance the validation set seemingly is much more uniform in its distribution than e.g. the training dataset, which can contain vastly different numbers of each label. An example would be the labels `0` and `2`, where there are almost 10 times (approx. 2000 images) the amount of images of label `2` than that of label `0` (around 220 images).\n\nHowever, on further inspection, all the datasets seem to have the same \"shape\" of the distribution across labels, this distribution is just scaled.\nThis make sense, if all the datasets are completely randomly sampled for the same pool of images, each subset of would contain more or less the same distribution (in an ideal world).\n\nThe training, testing and validation sets are divided from the total dataset, as follows:\n\n Training : 34799/51839 * 100 = 67.13 %\n Testings : 12630/51839 * 100 = 24.36 %\n Validation: 4410/51839 * 100 = 8.50 %\n \nWhich means that the network will only ever learn from 75.5 % of the data, and will then be compared to the remainder.",
"_____no_output_____"
],
[
"----\n\n## Step 2: Design and Test a Model Architecture\n\nDesign and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).\n\nThe LeNet-5 implementation shown in the [classroom](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play! \n\nWith the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission. \n\nThere are various aspects to consider when thinking about this problem:\n\n- Neural network architecture (is the network over or underfitting?)\n- Play around preprocessing techniques (normalization, rgb to grayscale, etc)\n- Number of examples per label (some have more than others).\n- Generate fake data.\n\nHere is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf). It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.",
"_____no_output_____"
],
[
"### Pre-process the Data Set (normalization, grayscale, etc.)",
"_____no_output_____"
],
[
"Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project. \n\nOther pre-processing steps are optional. You can try different techniques to see if it improves performance. \n\nUse the code cell (or multiple code cells, if necessary) to implement the first step of your project.",
"_____no_output_____"
]
],
[
[
"from skimage.color import rgb2gray\n\ndef rgb2grayscale(rbg):\n return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])[..., np.newaxis]\n\ndef normalize(img):\n \"\"\"Normalize the data\"\"\"\n return (img.astype(np.float32) - 128)/128\n\ndef preprocess_image(img, channels=3):\n out = img\n# if channels == 1:\n# out = rgb2gray(out)\n# out = out[:, :, np.newaxis]\n out = rgb2gray(out)\n out = (out - 0.5) * 2.\n out = out[:, :, np.newaxis]\n return out\n\ndef preprocess_data(samples, channels=3):\n return np.array([preprocess_image(im, channels) for im in samples])\n",
"_____no_output_____"
],
[
"CHANNELS = 1\n\nX_train_proc = preprocess_data(X_train, CHANNELS) # convert_img(X_train)\nX_test_proc = preprocess_data(X_test, CHANNELS) # convert_img(X_test)\nX_valid_proc = preprocess_data(X_valid, CHANNELS) # convert_img(X_valid)",
"_____no_output_____"
]
],
[
[
"### Model Architecture",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\nfrom tensorflow.contrib.layers import flatten\nfrom sklearn.utils import shuffle",
"_____no_output_____"
],
[
"def convolutional_layer(x, W, b, strides=1, padding='SAME'):\n \"\"\"Create a convolutional layer\n Returns a ful convolutional layer with a RELU activation function at the end.\n \n Args:\n x (np.array): Input to the layer\n W (np.array): Weights matrix\n b (np.array): Bias vector\n strides (int, optional): The number of pixel between each application of the kernel\n padding (str, optional): Padding of the image.\n \n Returns:\n tf.nn.conv2d: Convolutional layer\n \"\"\"\n layer = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding=padding)\n layer = tf.nn.bias_add(layer, b)\n layer = tf.nn.relu(layer)\n return layer\n\ndef fully_connected_layer(x, W, b, relu_activation=False):\n \"\"\"Creates a fully connected linear layer\n Returns a fully connected layer possible RELU activation function\n \n Args:\n x (np.array): Input to the layer\n W (np.array): Weights matrix\n b (np.array): Bias vector\n \n Returns:\n tf.Operation: Fully connected layer\n \"\"\"\n layer = tf.nn.bias_add(tf.matmul(x, W), b)\n if relu_activation:\n layer = tf.nn.relu(layer)\n return layer\n\ndef maxpool2d(x, k=2):\n return tf.nn.max_pool(\n x,\n ksize=[1, k, k, 1],\n strides=[1, k, k, 1],\n padding='SAME')",
"_____no_output_____"
]
],
[
[
"#### Hyper parameters",
"_____no_output_____"
]
],
[
[
"MU = 0\nSIGMA = 0.1\nLEARNING_RATE = 0.001\nEPOCHS = 10\nBATCH_SIZE = 128\nKERNEL_SIZE = 5\nKEEP_PROB = 0.",
"_____no_output_____"
]
],
[
[
"Create dictionaries for the weights and biases for the net",
"_____no_output_____"
]
],
[
[
"WEIGHTS = {\n 'conv1': tf.Variable(tf.truncated_normal(shape=(KERNEL_SIZE, KERNEL_SIZE, CHANNELS, 6), mean = MU, stddev = SIGMA)),\n 'conv2': tf.Variable(tf.truncated_normal(shape=(KERNEL_SIZE, KERNEL_SIZE, 6, 16), mean = MU, stddev = SIGMA)),\n 'fc1': tf.Variable(tf.truncated_normal(shape=(400, 120), mean = MU, stddev = SIGMA)),\n 'fc2': tf.Variable(tf.truncated_normal(shape=(120, 84), mean = MU, stddev = SIGMA)),\n 'fc3': tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = MU, stddev = SIGMA)),\n \n}\nBIASES = {\n 'conv1': tf.Variable(tf.zeros(6)),\n 'conv2': tf.Variable(tf.zeros(16)),\n 'fc1': tf.Variable(tf.zeros(120)),\n 'fc2': tf.Variable(tf.zeros(84)),\n 'fc3': tf.Variable(tf.zeros(n_classes)),\n}",
"_____no_output_____"
],
[
"x = tf.placeholder(tf.float32, [None, 32, 32, CHANNELS], name='input')\ny = tf.placeholder(tf.int32, (None), name='output')\nkeep_prob = tf.placeholder(tf.float32, name='keep_prob')\none_hot_y = tf.one_hot(y, n_classes)",
"_____no_output_____"
]
],
[
[
"#### Define the network\n\nThe network is defined in the function `traffic_sign_net()`.",
"_____no_output_____"
]
],
[
[
"def traffic_sign_net(x, dropout=False):\n \n # First layer: Convolutional layer - Input is 32x32x1 - output is 28x28x6\n # Maxpooling with a stride of 2, converts output to 14x14x6\n conv1 = convolutional_layer(x, WEIGHTS['conv1'], BIASES['conv1'], strides=1, padding='VALID')\n conv1 = maxpool2d(conv1, k=2)\n \n \n # Second layer: Convolutional layer - input is 14x14x6 output is 10x10x16\n # Maxpooling with a stride of 2, converts output to 5x5x16\n conv2 = convolutional_layer(conv1, WEIGHTS['conv2'], BIASES['conv2'], strides=1, padding='VALID')\n conv2 = maxpool2d(conv2, k=2)\n \n \n # Flatten output of the convolutional layer: output is 5x5x16 = 400.\n fc0 = flatten(conv2)\n# if dropout:\n fc0 = tf.nn.dropout(fc0, keep_prob)\n \n # Third layer: Fully Connected. Input = 400. Output = 120.\n fc1 = fully_connected_layer(fc0, WEIGHTS['fc1'], BIASES['fc1'], relu_activation=True)\n if dropout:\n fc1 = tf.nn.dropout(fc1, keep_prob)\n \n # Fourth layer: Fully Connected. Input = 120. Output = 84.\n fc2 = fully_connected_layer(fc1, WEIGHTS['fc2'], BIASES['fc2'], relu_activation=True)\n if dropout:\n fc2 = tf.nn.dropout(fc2, keep_prob)\n \n # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.\n logits = fully_connected_layer(fc2, WEIGHTS['fc3'], BIASES['fc3'], relu_activation=False)\n\n return logits",
"_____no_output_____"
],
[
"# Create a Model\nlogits = traffic_sign_net(x, dropout=True)\n\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)\nloss_operation = tf.reduce_mean(cross_entropy)\noptimizer = tf.train.AdamOptimizer(learning_rate = LEARNING_RATE)\ntraining_operation = optimizer.minimize(loss_operation)\n\n# Instanciate saver class\nsaver = tf.train.Saver()",
"_____no_output_____"
],
[
"correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))\naccuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsaver = tf.train.Saver()\n\ndef evaluate(X_data, y_data):\n num_examples = len(X_data)\n total_accuracy = 0\n sess = tf.get_default_session()\n for offset in range(0, num_examples, BATCH_SIZE):\n batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]\n accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})\n total_accuracy += (accuracy * len(batch_x))\n return total_accuracy / num_examples",
"_____no_output_____"
]
],
[
[
"### Train, Validate and Test the Model",
"_____no_output_____"
],
[
"A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation\nsets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.",
"_____no_output_____"
]
],
[
[
"from datetime import datetime\n\nstart_time = datetime.now()\nprint('Starting at: {}'.format(start_time))\n\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n num_examples = len(X_train)\n \n print(\"Training...\")\n print()\n for i in range(EPOCHS):\n epoch_start = datetime.now()\n X_train_proc, y_train = shuffle(X_train_proc, y_train)\n for offset in range(0, num_examples, BATCH_SIZE):\n end = offset + BATCH_SIZE\n batch_x, batch_y = X_train_proc[offset:end], y_train[offset:end]\n sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: KEEP_PROB})\n \n train_accuracy = evaluate(X_train_proc, y_train)\n validation_accuracy = evaluate(X_valid_proc, y_valid)\n print(\"EPOCH {} ...\".format(i+1))\n print(\"Training Accuracy = {:.3f}\".format(train_accuracy))\n print(\"Validation Accuracy = {:.3f}\".format(validation_accuracy))\n print('Epoch took: {}'.format(datetime.now() - epoch_start))\n print()\n \n saver.save(sess, './lenet')\n print(\"Model saved\")\n print('Total time: {}'.format(datetime.now() - start_time))",
"Starting at: 2018-04-30 07:25:54.559812\nTraining...\n\nEPOCH 1 ...\nTraining Accuracy = 0.690\nValidation Accuracy = 0.666\nEpoch took: 0:00:36.503151\n\nEPOCH 2 ...\nTraining Accuracy = 0.884\nValidation Accuracy = 0.831\nEpoch took: 0:00:36.126888\n\nEPOCH 3 ...\nTraining Accuracy = 0.927\nValidation Accuracy = 0.870\nEpoch took: 0:00:36.364163\n\nEPOCH 4 ...\nTraining Accuracy = 0.950\nValidation Accuracy = 0.901\nEpoch took: 0:00:36.260809\n\nEPOCH 5 ...\nTraining Accuracy = 0.963\nValidation Accuracy = 0.908\nEpoch took: 0:00:36.364230\n\nEPOCH 6 ...\nTraining Accuracy = 0.972\nValidation Accuracy = 0.914\nEpoch took: 0:00:36.352074\n\nEPOCH 7 ...\nTraining Accuracy = 0.978\nValidation Accuracy = 0.921\nEpoch took: 0:00:36.591245\n\nEPOCH 8 ...\nTraining Accuracy = 0.982\nValidation Accuracy = 0.934\nEpoch took: 0:00:36.348567\n\nEPOCH 9 ...\nTraining Accuracy = 0.984\nValidation Accuracy = 0.937\nEpoch took: 0:00:36.480033\n\nEPOCH 10 ...\nTraining Accuracy = 0.988\nValidation Accuracy = 0.940\nEpoch took: 0:00:36.426270\n\nModel saved\nTotal time: 0:06:05.023266\n"
]
],
[
[
"### Model validation\n\nWe can now validate the models performance, by testing it on images it has not seen before.\nUsing the `test` dataset, we get the following performance:",
"_____no_output_____"
]
],
[
[
"with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n\n test_accuracy = evaluate(X_test_proc, y_test)\n print(\"Test Set Accuracy = {:.3f}\".format(test_accuracy))",
"Test Set Accuracy = 0.925\n"
]
],
[
[
"---\n\n## Step 3: Test a Model on New Images\n\nTo give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.\n\nYou may find `signnames.csv` useful as it contains mappings from the class id (integer) to the actual sign name.",
"_____no_output_____"
],
[
"### Load and Output the Images",
"_____no_output_____"
]
],
[
[
"import os\nimport matplotlib.pyplot as plt\n\n# Load images\npath = 'test_data/'\nfiles = [os.path.join(path, file) for file in os.listdir(path) if file.endswith('.jpg')]\n\n# Grab label from the filename\ny_webdata = np.array([int(os.path.splitext(os.path.basename(file))[0]) for file in files])\n\ndef import_img(path, resize_dim=(32, 32)):\n \"\"\"Read image from path and resize\"\"\"\n img = plt.imread(path)\n return cv2.resize(img, resize_dim)\n\n# Import the data \nX_webdata = np.array([import_img(file) for file in files])\nX_webdata = normalize(X_webdata)\n\n\nX_webdata = np.array([plt.imread('test_data/web1.png'),\n plt.imread('test_data/web2.png'),\n plt.imread('test_data/web3.png'),\n plt.imread('test_data/web4.png'),\n plt.imread('test_data/web5.png')])\n\nX_webdata = preprocess_data(X_webdata, channels=CHANNELS)\ny_webdata = np.array([18, 12, 13, 11, 4])\nprint(\"Actual Sign Types:\", y_webdata)",
"Actual Sign Types: [18 12 13 11 4]\n"
]
],
[
[
"### Predict the Sign Type for Each Image",
"_____no_output_____"
]
],
[
[
"# Run the predictions using the model to output the prediction for each image.\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n predicted = sess.run(tf.argmax(logits, 1), feed_dict={x: X_webdata, y: y_webdata, keep_prob: 1.0}) \n print('Predicted Sign Types:', predicted)\n print('Actual labels:', y_webdata)",
"Predicted Sign Types: [31 12 13 37 4]\nActual labels: [18 12 13 11 4]\n"
]
],
[
[
"### Analyze Performance",
"_____no_output_____"
]
],
[
[
"correct = np.sum(y_webdata == predicted)\ntotal = len(y_webdata)\nprint('Model estimated {} out of {} images correctly, giving {:.0f} % accuracy'.format(correct, total, correct/total*100))",
"Model estimated 3 out of 5 images correctly, giving 60 % accuracy\n"
]
],
[
[
"### Output Top 5 Softmax Probabilities For Each Image Found on the Web",
"_____no_output_____"
]
],
[
[
"k = 5\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('.'))\n top_k_softmax, indicies = sess.run(tf.nn.top_k(tf.nn.softmax(logits), k), feed_dict={x: X_webdata, y: y_webdata, keep_prob: 1.0}) \n \n for idx, val in enumerate(top_k_softmax):\n print('Image {} - Top {} probabilites: {}'.format(idx+1, k, val))\n print('Image {} - Corresponding indicies: {}'.format(idx+1, indicies[idx]))",
"Image 1 - Top 5 probabilites: [ 9.58632529e-01 3.46702524e-02 5.96961752e-03 6.92229834e-04\n 1.37078114e-05]\nImage 1 - Corresponding indicies: [31 18 21 24 29]\nImage 2 - Top 5 probabilites: [ 9.99980450e-01 1.15358071e-05 3.11002418e-06 2.73251021e-06\n 4.95497545e-07]\nImage 2 - Corresponding indicies: [12 40 7 2 5]\nImage 3 - Top 5 probabilites: [ 9.99986529e-01 5.91974458e-06 3.80067263e-06 1.56599026e-06\n 7.74218904e-07]\nImage 3 - Corresponding indicies: [13 3 35 28 1]\nImage 4 - Top 5 probabilites: [ 0.91669071 0.06882875 0.01030109 0.00268922 0.00096359]\nImage 4 - Corresponding indicies: [37 18 25 17 21]\nImage 5 - Top 5 probabilites: [ 9.94186044e-01 3.76160070e-03 2.05235276e-03 1.78364434e-08\n 6.56539134e-09]\nImage 5 - Corresponding indicies: [ 4 0 1 8 40]\n"
]
],
[
[
"### Project Writeup\n\nOnce you have completed the code implementation, document your results in a project writeup using this [template](https://github.com/udacity/CarND-Traffic-Sign-Classifier-Project/blob/master/writeup_template.md) as a guide. The writeup can be in a markdown or pdf file. ",
"_____no_output_____"
],
[
"> **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this 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.",
"_____no_output_____"
],
[
"---\n\n## Step 4 (Optional): Visualize the Neural Network's State with Test Images\n\n This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.\n\n Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the [LeNet lab's](https://classroom.udacity.com/nanodegrees/nd013/parts/fbf77062-5703-404e-b60c-95b78b2f3f9e/modules/6df7ae49-c61c-4bb2-a23e-6527e69209ec/lessons/601ae704-1035-4287-8b11-e2c2716217ad/concepts/d4aca031-508f-4e0b-b493-e7b706120f81) feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.\n\nFor an example of what feature map outputs look like, check out NVIDIA's results in their paper [End-to-End Deep Learning for Self-Driving Cars](https://devblogs.nvidia.com/parallelforall/deep-learning-self-driving-cars/) in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.\n\n<figure>\n <img src=\"visualize_cnn.png\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above)</p> \n </figcaption>\n</figure>\n <p></p> \n",
"_____no_output_____"
]
],
[
[
"### Visualize your network's feature maps here.\n### Feel free to use as many code cells as needed.\n\n# image_input: the test image being fed into the network to produce the feature maps\n# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer\n# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output\n# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry\n\ndef outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):\n # Here make sure to preprocess your image_input in a way your network expects\n # with size, normalization, ect if needed\n # image_input =\n # Note: x should be the same name as your network's tensorflow data placeholder variable\n # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function\n activation = tf_activation.eval(session=sess,feed_dict={x : image_input})\n featuremaps = activation.shape[3]\n plt.figure(plt_num, figsize=(15,15))\n for featuremap in range(featuremaps):\n plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column\n plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number\n if activation_min != -1 & activation_max != -1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin =activation_min, vmax=activation_max, cmap=\"gray\")\n elif activation_max != -1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmax=activation_max, cmap=\"gray\")\n elif activation_min !=-1:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", vmin=activation_min, cmap=\"gray\")\n else:\n plt.imshow(activation[0,:,:, featuremap], interpolation=\"nearest\", 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",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
cb7a59f3bd98863ee81f28364475e653f92f1afd
| 5,194 |
ipynb
|
Jupyter Notebook
|
examples/notebooks/85_postgis.ipynb
|
jkariukidev/geemap
|
d56eb9312020927b5adc7becd13fcfdfc1fa975b
|
[
"MIT"
] | 3 |
2020-10-10T12:31:33.000Z
|
2022-03-08T01:46:02.000Z
|
examples/notebooks/85_postgis.ipynb
|
jkariukidev/geemap
|
d56eb9312020927b5adc7becd13fcfdfc1fa975b
|
[
"MIT"
] | null | null | null |
examples/notebooks/85_postgis.ipynb
|
jkariukidev/geemap
|
d56eb9312020927b5adc7becd13fcfdfc1fa975b
|
[
"MIT"
] | 2 |
2020-10-01T14:19:22.000Z
|
2021-01-04T06:36:40.000Z
| 23.716895 | 312 | 0.554678 |
[
[
[
"[](https://githubtocolab.com/giswqs/geemap/blob/master/examples/notebooks/85_postgis.ipynb)\n[](https://gishub.org/geemap-pangeo)\n\n**Adding data from a PostGIS database to the map**\n\nSetting up the conda env:\n\n```\nconda create -n geo python=3.8\nconda activate geo\nconda install geopandas\nconda install mamba -c conda-forge\nmamba install geemap sqlalchemy psycopg2 -c conda-forge\n```\n\nSample dataset:\n- [nyc_data.zip](https://github.com/giswqs/postgis/raw/master/data/nyc_data.zip) (Watch this [video](https://youtu.be/fROzLrjNDrs) to load data into PostGIS)",
"_____no_output_____"
],
[
"**Connecting to the database**",
"_____no_output_____"
]
],
[
[
"import geemap",
"_____no_output_____"
]
],
[
[
"You can directly pass in the user name and password to access the database. Alternative, you can define environment variables. The default environment variables for user and password are `SQL_USER` and `SQL_PASSWORD`, respectively.",
"_____no_output_____"
],
[
"The `try...except...` statements are only used for building the documentation website (https://geemap.org) because the PostGIS database is not available on GitHub. If you are running the notebook with Jupyter installed locally and PostGIS set up properly, you don't need these `try...except...` statements.",
"_____no_output_____"
]
],
[
[
"try:\n con = geemap.connect_postgis(database=\"nyc\", host=\"localhost\", user=None, password=None, use_env_var=True)\nexcept:\n pass",
"_____no_output_____"
]
],
[
[
"Create a GeoDataFrame from a sql query.",
"_____no_output_____"
]
],
[
[
"sql = 'SELECT * FROM nyc_neighborhoods'",
"_____no_output_____"
],
[
"try:\n gdf = geemap.read_postgis(sql, con)\n display(gdf)\nexcept:\n pass",
"_____no_output_____"
]
],
[
[
"Convert gdf to ee.FeatureCollection",
"_____no_output_____"
]
],
[
[
"try:\n m = geemap.Map()\n fc = geemap.gdf_to_ee(gdf)\n m.addLayer(fc, {}, \"NYC EE\")\n m.centerObject(fc)\n display(m)\nexcept:\n pss",
"_____no_output_____"
]
],
[
[
"Display the GeoDataFrame on the interactive map. ",
"_____no_output_____"
]
],
[
[
"try:\n m = geemap.Map()\n m.add_gdf_from_postgis(sql, con, layer_name=\"NYC Neighborhoods\", fill_colors=[\"red\", \"green\", \"blue\"])\n display(m)\nexcept:\n pass ",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7a625c3ef459f59eb21bd960bfea8e71b95d41
| 138,088 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/Finding Lane Lines on the Road-checkpoint.ipynb
|
suljaxm/LaneLines-P1
|
b61a9afdb27083107d90c43205bd6961fd51381a
|
[
"MIT"
] | 1 |
2019-07-19T01:41:31.000Z
|
2019-07-19T01:41:31.000Z
|
.ipynb_checkpoints/Finding Lane Lines on the Road-checkpoint.ipynb
|
suljaxm/LaneLines-P1
|
b61a9afdb27083107d90c43205bd6961fd51381a
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Finding Lane Lines on the Road-checkpoint.ipynb
|
suljaxm/LaneLines-P1
|
b61a9afdb27083107d90c43205bd6961fd51381a
|
[
"MIT"
] | null | null | null | 245.708185 | 116,880 | 0.912281 |
[
[
[
"# Self-Driving Car Engineer Nanodegree\n\n\n## Project: **Finding Lane Lines on the Road** \n***\nIn this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n\nOnce you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n\nIn addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n\n---\nLet's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n\n**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n\n---",
"_____no_output_____"
],
[
"**The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**\n\n---\n\n<figure>\n <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n </figcaption>\n</figure>\n <p></p> \n<figure>\n <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n </figcaption>\n</figure>",
"_____no_output_____"
],
[
"**Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** ",
"_____no_output_____"
],
[
"## Import Packages",
"_____no_output_____"
]
],
[
[
"#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Read in an Image",
"_____no_output_____"
]
],
[
[
"#reading in an image\nimage = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\nplt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')",
"This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)\n"
]
],
[
[
"## Ideas for Lane Detection Pipeline",
"_____no_output_____"
],
[
"**Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n\n`cv2.inRange()` for color selection \n`cv2.fillPoly()` for regions selection \n`cv2.line()` to draw lines on an image given endpoints \n`cv2.addWeighted()` to coadd / overlay two images \n`cv2.cvtColor()` to grayscale or change color \n`cv2.imwrite()` to output images to file \n`cv2.bitwise_and()` to apply a mask to an image\n\n**Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**",
"_____no_output_____"
],
[
"## Helper Functions",
"_____no_output_____"
],
[
"Below are some helper functions to help get you started. They should look familiar from the lesson!",
"_____no_output_____"
]
],
[
[
"import math\n\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n (assuming your grayscaled image is called 'gray')\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Or use BGR2GRAY if you read an image with cv2.imread()\n # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n `vertices` should be a numpy array of integer points.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=2):\n \"\"\"\n NOTE: this is the function you might want to use as a starting point once you want to \n average/extrapolate the line segments you detect to map out the full\n extent of the lane (going from the result shown in raw-lines-example.mp4\n to that shown in P1_example.mp4). \n \n Think about things like separating line segments by their \n slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n line vs. the right line. Then, you can average the position of each of \n the lines and extrapolate to the top and bottom of the lane.\n \n This function draws `lines` with `color` and `thickness`. \n Lines are drawn on the image inplace (mutates the image).\n If you want to make the lines semi-transparent, think about combining\n this function with the weighted_img() function below\n \"\"\"\n for line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines)\n return line_img\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, α=0.8, β=1., γ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + γ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, γ)",
"_____no_output_____"
]
],
[
[
"## Test Images\n\nBuild your pipeline to work on the images in the directory \"test_images\" \n**You should make sure your pipeline works well on these images before you try the videos.**",
"_____no_output_____"
]
],
[
[
"import os\nos.listdir(\"test_images/\")",
"_____no_output_____"
]
],
[
[
"## Build a Lane Finding Pipeline\n\n",
"_____no_output_____"
],
[
"Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n\nTry tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.",
"_____no_output_____"
]
],
[
[
"# TODO: Build your pipeline that will draw lane lines on the test_images\n# then save them to the test_images_output directory.",
"_____no_output_____"
]
],
[
[
"## Test on Videos\n\nYou know what's cooler than drawing lanes over images? Drawing lanes over video!\n\nWe can test our solution on two provided videos:\n\n`solidWhiteRight.mp4`\n\n`solidYellowLeft.mp4`\n\n**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n\n**If you get an error that looks like this:**\n```\nNeedDownloadError: Need ffmpeg exe. \nYou can download it by calling: \nimageio.plugins.ffmpeg.download()\n```\n**Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**",
"_____no_output_____"
]
],
[
[
"# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML",
"_____no_output_____"
],
[
"def process_image(image):\n # NOTE: The output you return should be a color image (3 channel) for processing video below\n # TODO: put your pipeline here,\n # you should return the final output (image where lines are drawn on lanes)\n\n return result",
"_____no_output_____"
]
],
[
[
"Let's try the one with the solid white lane on the right first ...",
"_____no_output_____"
]
],
[
[
"white_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\n%time white_clip.write_videofile(white_output, audio=False)",
"_____no_output_____"
]
],
[
[
"Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.",
"_____no_output_____"
]
],
[
[
"HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))",
"_____no_output_____"
]
],
[
[
"## Improve the draw_lines() function\n\n**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n\n**Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**",
"_____no_output_____"
],
[
"Now for the one with the solid yellow lane on the left. This one's more tricky!",
"_____no_output_____"
]
],
[
[
"yellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\n%time yellow_clip.write_videofile(yellow_output, audio=False)",
"_____no_output_____"
],
[
"HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))",
"_____no_output_____"
]
],
[
[
"## Writeup and Submission\n\nIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n",
"_____no_output_____"
],
[
"## Optional Challenge\n\nTry your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!",
"_____no_output_____"
]
],
[
[
"challenge_output = 'test_videos_output/challenge.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)\nclip3 = VideoFileClip('test_videos/challenge.mp4')\nchallenge_clip = clip3.fl_image(process_image)\n%time challenge_clip.write_videofile(challenge_output, audio=False)",
"_____no_output_____"
],
[
"HTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(challenge_output))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cb7a6b6cce11d0fc71695ed1f0c9ce82ba3189d9
| 32,593 |
ipynb
|
Jupyter Notebook
|
neural-machine-translation/34.lstm-birnn-seq2seq-contrib-beam-luong.ipynb
|
huseinzol05/Tensorflow-NLP-Models
|
0741216aa8235e1228b3de7903cc36d73f8f2b45
|
[
"MIT"
] | 1,705 |
2018-11-03T17:34:22.000Z
|
2022-03-29T04:30:01.000Z
|
neural-machine-translation/34.lstm-birnn-seq2seq-contrib-beam-luong.ipynb
|
huseinzol05/Tensorflow-NLP-Models
|
0741216aa8235e1228b3de7903cc36d73f8f2b45
|
[
"MIT"
] | 26 |
2019-03-16T17:23:00.000Z
|
2021-10-08T08:06:09.000Z
|
neural-machine-translation/34.lstm-birnn-seq2seq-contrib-beam-luong.ipynb
|
huseinzol05/Tensorflow-NLP-Models
|
0741216aa8235e1228b3de7903cc36d73f8f2b45
|
[
"MIT"
] | 705 |
2018-11-03T17:34:25.000Z
|
2022-03-24T02:29:14.000Z
| 39.893513 | 255 | 0.50698 |
[
[
[
"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '3'",
"_____no_output_____"
],
[
"import numpy as np\nimport tensorflow as tf\nimport json",
"_____no_output_____"
],
[
"with open('dataset-bpe.json') as fopen:\n data = json.load(fopen)",
"_____no_output_____"
],
[
"train_X = data['train_X']\ntrain_Y = data['train_Y']\ntest_X = data['test_X']\ntest_Y = data['test_Y']",
"_____no_output_____"
],
[
"EOS = 2\nGO = 1\nvocab_size = 32000",
"_____no_output_____"
],
[
"train_Y = [i + [2] for i in train_Y]\ntest_Y = [i + [2] for i in test_Y]",
"_____no_output_____"
],
[
"from tensor2tensor.utils import beam_search\n\ndef pad_second_dim(x, desired_size):\n padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n return tf.concat([x, padding], 1)\n\nclass Translator:\n def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n beam_width = 5):\n \n def cells(size_layer = size_layer, reuse=False):\n return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n \n def attention(encoder_out, seq_len, reuse=False):\n attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n memory = encoder_out,\n memory_sequence_length = seq_len)\n return tf.contrib.seq2seq.AttentionWrapper(\n cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n attention_mechanism = attention_mechanism,\n attention_layer_size = size_layer)\n \n self.X = tf.placeholder(tf.int32, [None, None])\n self.Y = tf.placeholder(tf.int32, [None, None])\n \n self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n batch_size = tf.shape(self.X)[0]\n \n embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n \n for n in range(num_layers):\n (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n cell_fw = cells(size_layer // 2),\n cell_bw = cells(size_layer // 2),\n inputs = encoder_out,\n sequence_length = self.X_seq_len,\n dtype = tf.float32,\n scope = 'bidirectional_rnn_%d'%(n))\n encoder_out = tf.concat((out_fw, out_bw), 2)\n bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n encoder_state = tuple([bi_lstm_state] * num_layers)\n \n main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n dense = tf.layers.Dense(vocab_size)\n \n with tf.variable_scope('decode'):\n decoder_cells = attention(encoder_out, self.X_seq_len)\n states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n\n training_helper = tf.contrib.seq2seq.TrainingHelper(\n inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n sequence_length = self.Y_seq_len,\n time_major = False)\n training_decoder = tf.contrib.seq2seq.BasicDecoder(\n cell = decoder_cells,\n helper = training_helper,\n initial_state = states,\n output_layer = dense)\n training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n decoder = training_decoder,\n impute_finished = True,\n maximum_iterations = tf.reduce_max(self.Y_seq_len))\n self.training_logits = training_decoder_output.rnn_output\n \n with tf.variable_scope('decode', reuse=True):\n encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n cell_state = encoder_state_tiled)\n predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n cell = decoder_cell,\n embedding = embeddings,\n start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n end_token = EOS,\n initial_state = states,\n beam_width = beam_width,\n output_layer = dense,\n length_penalty_weight = 0.0)\n predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n decoder = predicting_decoder,\n impute_finished = False,\n maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n \n masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n targets = self.Y,\n weights = masks)\n self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n y_t = tf.argmax(self.training_logits,axis=2)\n y_t = tf.cast(y_t, tf.int32)\n self.prediction = tf.boolean_mask(y_t, masks)\n mask_label = tf.boolean_mask(self.Y, masks)\n correct_pred = tf.equal(self.prediction, mask_label)\n correct_index = tf.cast(correct_pred, tf.float32)\n self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))",
"_____no_output_____"
],
[
"size_layer = 512\nnum_layers = 2\nembedded_size = 256\nlearning_rate = 1e-3\nbatch_size = 128\nepoch = 20",
"_____no_output_____"
],
[
"tf.reset_default_graph()\nsess = tf.InteractiveSession()\nmodel = Translator(size_layer, num_layers, embedded_size, learning_rate)\nsess.run(tf.global_variables_initializer())",
"WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.cast` instead.\n"
],
[
"pad_sequences = tf.keras.preprocessing.sequence.pad_sequences",
"_____no_output_____"
],
[
"batch_x = pad_sequences(train_X[:10], padding='post')\nbatch_y = pad_sequences(train_Y[:10], padding='post')\n\nsess.run([model.fast_result, model.cost, model.accuracy], \n feed_dict = {model.X: batch_x, model.Y: batch_y})",
"_____no_output_____"
],
[
"import tqdm\n\nfor e in range(epoch):\n pbar = tqdm.tqdm(\n range(0, len(train_X), batch_size), desc = 'minibatch loop')\n train_loss, train_acc, test_loss, test_acc = [], [], [], []\n for i in pbar:\n index = min(i + batch_size, len(train_X))\n batch_x = pad_sequences(train_X[i : index], padding='post')\n batch_y = pad_sequences(train_Y[i : index], padding='post')\n feed = {model.X: batch_x,\n model.Y: batch_y}\n accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n feed_dict = feed)\n train_loss.append(loss)\n train_acc.append(accuracy)\n pbar.set_postfix(cost = loss, accuracy = accuracy)\n \n \n pbar = tqdm.tqdm(\n range(0, len(test_X), batch_size), desc = 'minibatch loop')\n for i in pbar:\n index = min(i + batch_size, len(test_X))\n batch_x = pad_sequences(test_X[i : index], padding='post')\n batch_y = pad_sequences(test_Y[i : index], padding='post')\n feed = {model.X: batch_x,\n model.Y: batch_y,}\n accuracy, loss = sess.run([model.accuracy,model.cost],\n feed_dict = feed)\n\n test_loss.append(loss)\n test_acc.append(accuracy)\n pbar.set_postfix(cost = loss, accuracy = accuracy)\n \n print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n np.mean(train_loss),np.mean(train_acc)))\n print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n np.mean(test_loss),np.mean(test_acc)))",
"minibatch loop: 100%|██████████| 1563/1563 [13:51<00:00, 1.88it/s, accuracy=0.374, cost=3.87]\nminibatch loop: 100%|██████████| 40/40 [00:10<00:00, 3.83it/s, accuracy=0.43, cost=3.42] \nminibatch loop: 0%| | 0/1563 [00:00<?, ?it/s]"
],
[
"from tensor2tensor.utils import bleu_hook",
"_____no_output_____"
],
[
"results = []\nfor i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n index = min(i + batch_size, len(test_X))\n batch_x = pad_sequences(test_X[i : index], padding='post')\n feed = {model.X: batch_x}\n p = sess.run(model.fast_result,feed_dict = feed)\n result = []\n for row in p:\n result.append([i for i in row if i > 3])\n results.extend(result)",
"100%|██████████| 40/40 [00:28<00:00, 1.38it/s]\n"
],
[
"rights = []\nfor r in test_Y:\n rights.append([i for i in r if i > 3])",
"_____no_output_____"
],
[
"bleu_hook.compute_bleu(reference_corpus = rights,\n translation_corpus = results)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7a6bc83f978ca4a9157dfa524230ba69ff5684
| 135,676 |
ipynb
|
Jupyter Notebook
|
notebooks/workshop-2/Regression.ipynb
|
Imperial-College-Data-Science-Society/workshops
|
8ce86f9f70ab47644e1f2e988da3bac41c0b9625
|
[
"MIT"
] | 17 |
2020-08-05T03:17:50.000Z
|
2021-02-06T05:07:28.000Z
|
notebooks/workshop-2/Regression.ipynb
|
Imperial-College-Data-Science-Society/Workshops
|
8ce86f9f70ab47644e1f2e988da3bac41c0b9625
|
[
"MIT"
] | 4 |
2021-01-31T09:23:26.000Z
|
2022-03-12T00:50:02.000Z
|
notebooks/workshop-2/Regression.ipynb
|
Imperial-College-Data-Science-Society/workshops
|
8ce86f9f70ab47644e1f2e988da3bac41c0b9625
|
[
"MIT"
] | 12 |
2020-10-15T17:16:58.000Z
|
2021-03-04T18:27:39.000Z
| 124.587695 | 34,180 | 0.860513 |
[
[
[
"# Workshop 2: Regression and Neural Networks\n\nhttps://github.com/Imperial-College-Data-Science-Society/workshops\n\n1. Introduction to Data Science\n2. **Regression and Neural Networks**\n3. Classifying Character and Organ Images\n4. Demystifying Causality and Causal Inference\n5. A Primer to Data Engineering\n6. Natural Language Processing (NLP) by using Attention\n7. Art and Music using GANs\n8. Probabilistic Programming in Practice\n9. Missing Data in Supervised Learning\n\n## Today ##\nYou can access the material via:\n- Binder\n- Local Jupyter Notebook with a suitable virtual environment and dependencies installed\n- The PDF slides\n- Following my slides on MS Teams\n\n",
"_____no_output_____"
],
[
"# Projects\n\nThoughts?\n\n",
"_____no_output_____"
],
[
"References I used to prepare this session:\n\n- Past ICDSS workshops\n- Patrick Rebischini's notes: http://www.stats.ox.ac.uk/~rebeschi/teaching/AFoL/20/index.html\n- https://fleuret.org/ee559/\n- https://en.wikipedia.org/wiki/Ordinary_least_squares\n- https://www.astroml.org/book_figures/chapter9/fig_neural_network.html\n- https://github.com/pytorch/examples/blob/master/mnist/main.py\n- Lakshminarayanan et al. (2016) http://papers.nips.cc/paper/5234-mondrian-forests-efficient-online-random-forests.pdf\n- Garnelo et al. (2018) https://arxiv.org/pdf/1807.01622.pdf\nOther recommended reading:\n- Regression and Other Stories by Andrew Gelman, Jennifer Hill and Aki Vehtari\n- Elements of Statistical Learning",
"_____no_output_____"
],
[
"## Introduction\n\nSuppose we have some $(x_1, y_1),\\ldots,(x_{100},y_{100})$ that is generated by $y=2x + \\text{noise}$.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nx = np.linspace(0, 1, 30)\nnoise = 0.1*np.random.normal(size=30)\ny = 2*x + noise\nplt.scatter(x, y)\nplt.plot(x, 2*x)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")",
"_____no_output_____"
]
],
[
[
"In practice, we don't know the underlying data-generating process, but rather we can pose **\"hypotheses\"** as to how the data is generated. For example in the above example:\n\n- **Linear Models:** $y = x\\beta + \\sigma\\mathcal{N}(0,1)$ where $\\beta$ represents the gradient of the slope and $\\sigma$ is the amplitude of the noise.\n- **Nonparametric models:**$y = f(x) + \\sigma\\mathcal{N}(0,1)$ where $f$ is some function in some hypothesis function space $\\mathcal{H}$. E.g. $f(x) = x\\beta$\n - Neural networks\n - Regression trees, random forests\n - Gaussian processes\n- $y = \\sum_{i=1}^T w_i\\times f_i(x) + g(x)$ where $w_i$ represent weights, $f_i\\in\\mathcal{H}$ and $g(x)$ represents the noise for value $x$.\n- etc...\n\nOnce we have a hypothesis we can **estimate $f$** using many different tools!\n\n## Out of sample prediction##\n\nGiven $x_*$, the prediction would be $f_*(x_*)$, where $f_*$ is the estimated function of $f$.",
"_____no_output_____"
],
[
"But first, to formulate the hypothesis, we need to scrutinate the data via exploratory data analysis.\n\nFor the data above, clearly a linear model (straight line) plus some small Gaussian noise is sufficient. So the task is just to estimate $\\beta$ and $\\sigma$ so that the line **fits the dots well**.",
"_____no_output_____"
],
[
"## General setting\nIn practice, we have to deal with data coming in different formats and possible generating processes. E.g. from the exponential family:\n\n- **Count data**: $y_i\\sim\\text{Poisson}(f(x_i))$ or $y_i\\sim\\text{NegativeBinomial}(f(x_i))$\n - Football goals, disease infection counts\n- **Binomial or Multinomial**: $y_i\\sim\\text{Binomial}(n, f(x_i))$, $y_i\\sim\\text{Multinomial}(f_1(x_i),\\ldots, f_k(x_i))$ etc...\n - Coin toss outcomes, customer subscription outcome, classifying digits or characters\n- **Gamma**: $y_i\\sim \\text{Gamma}(k, f(x_i))$\n - Rainfall",
"_____no_output_____"
],
[
"## Gaussian noise regression\n\nFor illustration purposes, let's focus on regression in the setting $y=f(x) + \\sigma \\mathcal{N}(0,1)$ for $f\\in\\mathcal{H}$ and $\\sigma\\geq0$.",
"_____no_output_____"
],
[
"## Foundations of Statistical Learning\n\nPreviously, I mentioned that we need to build a function that **fits the dots well**. There are 2 types of notions in statistical learning: **prediction** and **estimation**. We will use the following notation:\n\n- $n$ training points\n- $X_1,\\ldots,X_n $ are *features* in a *feature space* $\\mathcal{X}$. Could be a mixture of categorial or continuous features.\n- $Y_1,\\ldots,Y_n $ are labels/response in a space $\\mathcal{Y}$ (e.g. $\\mathbb{R}$ or $\\mathbb{R}^k$)\n- **[For your interest:]** Some probability space $(\\mathcal{X}, \\mathcal{B}, \\mathbb{P})$ where we can measure probabilities of events in the set $\\mathcal{B}$. e.g. the set of all possible cointoss outcomes is a set $\\mathcal{B}$\n- **Hypothesis space** $\\mathcal{H}\\subset \\mathcal{C}:=\\{f: f:\\mathcal{X}\\rightarrow\\mathcal{Y}\\}$: Restriction of the types of functions we want to use. e.g. for a type of neural network, the multilayer perceptron (MLP) with $m$ layers, we have $\\mathcal{H}:= \\{f:\\mathcal{X}\\rightarrow\\mathcal{Y}: f(\\cdot) = f(\\cdot; \\sigma_1,\\ldots,\\sigma_m, W_1,\\ldots,W_m), \\text{ where }\\sigma_i, W_i \\text{ are the activation functions and weights} \\}$.\n- **Prediction Loss function** $\\ell:\\mathcal{H}\\times\\mathcal{X}\\times\\mathcal{Y}\\rightarrow \\mathbb{R}_+$: To define what **fits the dots well** means.\n ",
"_____no_output_____"
],
[
"## Prediction\n\nWe want to pick $f$ such that it minimises the **expected or population risk** when a new independent datapoint $(X, Y)$ comes in\n\n$$\nf_* := \\text{argmin}_{f\\in\\mathcal{C}} \\mathbb{E}_{\\mathbb{P}}\\left[ \\ell(f, X, Y) \\right] := \\text{argmin}_{f\\in\\mathcal{C}} r(f) \n$$\n\nWe denote $f_*$ is the **optimum**, which is unknown. We want to construct an approximation to $f_*$ based on the $n$ training points and the hypothesis $\\mathcal{H}$ that controls the complexity of $f$. This approximation is close to\n\n$$\nf_{**}:= \\text{argmin}_{f\\in\\mathcal{H}} \\mathbb{E}_{\\mathbb{P}}\\left[ \\ell(f, X, Y) \\right]\n$$\n\nDefine the **excess risk** as\n\n$$\nr(f) - r(f_{**}) = [r(f) - r(f_*)] + [r(f_*) - r(f_{**})],\n$$\n\nwhere $f\\in \\mathcal{H}$. **The goal of statistical learning for prediction is to minimise the excess risk** with respect to the sample size $n$ and the space of functions $\\mathcal{H}$. Note that the decomposition yields an approximation and estimation error.",
"_____no_output_____"
],
[
"Difficult to do in practice, so we need **empirical risk minimisation** via the observed training set $(X_i,Y_i)_{i=1}^n$ as a proxy for the expected/population risk:\n\n$$\nR(f):= \\frac{1}{n}\\sum_{i=1}^n \\ell(f, X_i, Y_i) ,\\quad f_*^R := \\text{argmin}_{f\\in\\mathcal{H}} R(f)\n$$\n\nto minimise\n\n$$\nr(f) - r(f_{**}).\n$$",
"_____no_output_____"
],
[
"## Key takeaways and Bigger Picture:##\n\n- It is important to understand the tradeoff between optimisation and statistical errors. \n- Optimisation is only 1 part of the inequality, and vice versa for statistical modelling errors.\n\n\nMore details in Rebischini's notes!",
"_____no_output_____"
],
[
"## Estimation\n\nWe need:\n- Some training set of size $n$ generated by $f_*\\in\\mathcal{H}$\n- Loss function $\\ell:\\mathcal{H}\\times\\mathcal{H}\\rightarrow \\mathbb{R}_+$\n\nReturn:\n- An algorithm that returns an estimate of $f_*$ that minimises and controls $\\ell(f,f_*)$ based on the $n$ training points and $\\mathcal{H}$.",
"_____no_output_____"
],
[
"## Back to Gaussian noise regression\n\nThere are lots of ways we can pose this problem. One way is to use \n\n- $\\ell(f, X, Y) = ||f(X) - y||_2^2 = (f(X) - y)^2$ - the **\\ell_2 loss**\n- $\\ell(f, X, Y) = |f(X) - y|$ - the **\\ell_1 loss**\n- This yields the **mean squared error (MSE)** $R(f) = \\frac{1}{n}\\sum_{i=1}^n (f(x_i) - y_i)^2$\n\nIn theory, these give\n$$\\ell_2: f_{**}(x) = E[Y|X=x]$$\n\n$$\\ell_1: f_{**}(x) = \\text{Median}[Y|X=x]$$\n\nDepending on the situation, we can either use approximate gradient-based methods (e.g. gradient descent), Monte Carlo methods or the analytical maximum likelihood estimation (MLE). ",
"_____no_output_____"
],
[
"## Linear regression\n\n$$\ny = X\\beta_0 + \\sigma\\mathcal{N}(0,1)\n$$\n\n$\\beta_0 = (1,\\beta_{0,1},\\ldots,\\beta_{0,d-1})^T$ - the 1 represents the intercept.\n\nWe also call this **ordinary least squares**:\n\n- Assume that $X$ is full rank\n$$\\hat{\\beta} = \\text{argmin}_{\\beta} ||y- X\\beta ||_2^2 \\iff X^T(y - X\\beta) = 0 \\iff \\hat{\\beta} = X(X^TX)^{-1}X^T y \\sim \\mathcal{N}(X\\beta_0, \\sigma^2 X(X^TX)^{-1}X^T)$$",
"_____no_output_____"
],
[
"Geometrically: $y - X\\hat{\\beta} \\perp X\\beta_0 \\iff \\hat{\\beta}$ minimises $||y-X\\beta ||_2^2$\n\nhttps://en.wikipedia.org/wiki/Ordinary_least_squares:\n\n\nCan also solve this via gradient descent:\n\n- Remember excess risk <= approximationLoss + statisticalLoss",
"_____no_output_____"
]
],
[
[
"import statsmodels.api as sm\n\n# fit the model\nm = sm.OLS(y, sm.tools.add_constant(x))\nres = m.fit()\n\nprint(res.summary(), \"\\n sigma~\", np.sqrt(sum(res.resid**2) / (30 - 2)))",
" OLS Regression Results \n==============================================================================\nDep. Variable: y R-squared: 0.962\nModel: OLS Adj. R-squared: 0.960\nMethod: Least Squares F-statistic: 704.6\nDate: Sun, 18 Oct 2020 Prob (F-statistic): 2.16e-21\nTime: 17:39:37 Log-Likelihood: 22.372\nNo. Observations: 30 AIC: -40.74\nDf Residuals: 28 BIC: -37.94\nDf Model: 1 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nconst 0.0381 0.042 0.901 0.375 -0.049 0.125\nx1 1.9292 0.073 26.543 0.000 1.780 2.078\n==============================================================================\nOmnibus: 0.416 Durbin-Watson: 2.299\nProb(Omnibus): 0.812 Jarque-Bera (JB): 0.547\nSkew: 0.017 Prob(JB): 0.761\nKurtosis: 2.339 Cond. No. 4.25\n==============================================================================\n\nNotes:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified. \n sigma~ 0.11881627238852428\n"
]
],
[
[
"We can see that our algorithm manages to estimate the parameters of the models pretty well:\n\n- $\\hat{\\beta}\\approx 2$ with $95\\%$ confidence intervals [1.945, 2.091]\n- $const\\approx 0$ with $95\\%$ confidence intervals [-0.048, 0.036]\n- $\\hat{\\sigma}^2 \\approx 0.01$\n- **95% confidence intervals** = if I sample the data infinitely many times and estimate infinitely many confidence intervals, I will expect that 95% of the time the confidence intervals will contain the true, unknown parameter value.\n\nGiven $x_*$ as a test point, the prediction would be $\\hat{y} = x_*^T \\hat{\\beta}$.",
"_____no_output_____"
]
],
[
[
"# Fit of the OLS estimator\nx_test = np.linspace(1, 2, 10)\nnoise = 0.1*np.random.normal(size=10)\ny_test = 2*x_test + noise\nplt.figure(figsize=(4,4))\nplt.scatter(x, y)\nplt.plot(x, res.predict(sm.add_constant(x)))\npred_int_train = res.get_prediction(sm.add_constant(x)).conf_int()\nplt.plot(x, pred_int_train[:,0], 'r--', lw=2); plt.plot(x, pred_int_train[:,1], 'r--', lw=2)\n\n# the prediction intervals. Note that htey can be larger\nplt.scatter(x_test, y_test)\nplt.plot(x_test, res.predict(sm.add_constant(x_test)))\npred_int_test = res.get_prediction(sm.add_constant(x_test)).conf_int()\nplt.plot(x_test, pred_int_test[:,0], 'r--', lw=2); plt.plot(x_test, pred_int_test[:,1], 'r--', lw=2)\nplt.xlabel(\"x\"); plt.ylabel(\"y\")",
"_____no_output_____"
]
],
[
[
"## Other regression methods\n\n- Regression trees: Classification and Regression Trees (CART)\n- XGBoost: Tree-boosting algorithm widely used in production pipelines for firms like Amazon \n- Random forest: Most popular tree-based algorithm\n- Mondrian Forest: Nice statistical and online properties\n",
"_____no_output_____"
],
[
"## Regression tree\n\nA tree is a histogram or step function. $f(x) = \\sum_{k=1}^K \\beta_k I(x\\in \\Omega_k)$.\n\nExample of a tree (Lakshminarayanan et al. (2016))\n",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import DecisionTreeRegressor\n# Fit regression model\nm_tree = DecisionTreeRegressor(max_depth=5)\nm_tree.fit(np.expand_dims(x, 1), y)\ny_pred = m_tree.predict(np.expand_dims(x_test, 1))\n\nplt.figure(figsize=(4,4))\nplt.scatter(x, y)\nplt.plot(x, m_tree.predict(np.expand_dims(x, 1)))\n\n# the prediction intervals. Note that htey can be larger\nplt.scatter(x_test, y_test)\nplt.plot(x_test, y_pred)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")",
"_____no_output_____"
]
],
[
[
"## XGBoost",
"_____no_output_____"
]
],
[
[
"import xgboost as xgb\n\nnum_round = 10\nm_xgb = xgb.XGBRegressor(objective ='reg:squarederror', n_estimators=1000)\nm_xgb.fit(np.expand_dims(x, 1), y)\n\nplt.figure(figsize=(4,4))\nplt.scatter(x, y)\nplt.plot(x, m_xgb.predict(np.expand_dims(x, 1)))\n\n# the prediction intervals. Note that htey can be larger\nplt.scatter(x_test, y_test)\nplt.plot(x_test, m_xgb.predict(np.expand_dims(x_test, 1)))\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")",
"_____no_output_____"
]
],
[
[
"## Random Forest\n\nThis essentially uses bagging:\n$$\\hat{f}(x) = \\frac{1}{T}\\sum_{t=1}^T \\hat{f}_t(x)$$,\nwhere $\\hat{f}_t$ are trained regression trees from randomly sampled (with replacement) sets $\\{(x_j, y_j)_j\\}_t$ using random feature subsets. ",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import RandomForestRegressor\nfrom sklearn.datasets import make_regression\nm_rf = RandomForestRegressor(max_depth=2, random_state=0)\nm_rf.fit(np.expand_dims(x, 1), y)\nm_rf.predict(np.expand_dims(x_test, 1))\n\nplt.figure(figsize=(4,4))\nplt.scatter(x, y)\nplt.plot(x, m_rf.predict(np.expand_dims(x, 1)))\n\n# the prediction intervals. Note that htey can be larger\nplt.scatter(x_test, y_test)\nplt.plot(x_test,m_rf.predict(np.expand_dims(x_test, 1)))\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")",
"_____no_output_____"
]
],
[
[
"## Neural Networks\n\nNeural networks are essentially parametric functions that are composed of **layers of neurons**.\n\nhttps://www.astroml.org/book_figures/chapter9/fig_neural_network.html\n\n\n\n- Multilayer Perceptron (MLP): $f(x) = f_n\\circ\\cdots f_1(x)$ with $f_j = W_j x + b_j$ with weights $W_j$ and biases $b_j$.\n- Can also have other useful layers like max-pooling, batch normalisation, attention and convolution (feature extraction).\n- Parameter optimisation via gradient-based methods such as stochastic gradient descent. Using the backpropagation trick, can allow for efficient optimisation. Optimisation speed can be enhanced using multiple GPU or TPU memory.",
"_____no_output_____"
],
[
"**Key applications:**\n- Image processing: classification, denoising, inpainting, generation\n- Function approximations for complex models and algorithms\n- Time series, recommendation engines\n\n**Key issues:**\n- Overparameterisation: regularisation and sparsity\n- Feature engineering\n- Vanishing gradient: batch normalisation and dropout",
"_____no_output_____"
],
[
"## Image Classification",
"_____no_output_____"
]
],
[
[
"# https://github.com/pytorch/examples/blob/master/mnist/main.py\n# Code is in the folder in the main.py script\n# Don't run it during the session - might take a while!\n# %run main.py\n\n# we will use pretrained models from torchvision\nimport torch\nfrom torchvision import datasets, transforms\ntransform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n])\n\n# https://github.com/rois-codh/kmnist\n# We will use the Kuzushiji-MNIST dataset\ndataset2 = datasets.KMNIST('../data', train=False,\n transform=transform, download=True)\ntest_loader = torch.utils.data.DataLoader(dataset2, batch_size=16)\nfor img_batch, label_batch in test_loader:\n print(img_batch.shape, label_batch)\n break",
"torch.Size([16, 1, 28, 28]) tensor([2, 9, 3, 8, 3, 3, 8, 3, 2, 5, 6, 3, 3, 3, 1, 5])\n"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"from torchvision.utils import make_grid\n\n# Read images into torch.Tensor\nall_imgs = img_batch\n# Visualize sample on a grid\nimg_grid = make_grid(all_imgs, nrow=4)\nplt.figure(figsize=(5,5))\nplt.imshow(img_grid.permute(1, 2, 0).numpy())",
"Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\n"
],
[
"from main import Net \nmodel = Net()\n# load some model I pretrained on GPU memory into CPU memory\nmodel.load_state_dict(torch.load(\"kmnist_cnn.pt\", map_location=torch.device('cpu')))\nmodel.eval()\nmodel(img_batch).argmax(dim=1, keepdim=True), label_batch",
"_____no_output_____"
]
],
[
[
"## Image Inpainting",
"_____no_output_____"
],
[
"https://arxiv.org/pdf/1807.01622.pdf\n",
"_____no_output_____"
],
[
"## High-dimensional regression\n\nOverview:\n- Classical statistics: $d < \\infty$, $n\\rightarrow\\infty$\n- Non-asymptotic: $d<\\infty, n<\\infty$\n- Non-parametric: $d\\rightarrow \\infty, n<\\infty$\n- Asymptotic: $d\\rightarrow \\infty, n\\rightarrow\\infty$\n\nIn the realm of high-dimensional statistics, we usually have $d>n$ or e.g. $d= \\mathcal{O}(n^\\alpha)$, where $d$ is the number of features and $n$ is the number of data points. \n\nThis happens when you have lots of features and the actual data generating features are **sparse**, i.e. $d$ is large but a small $d_0$ is used or are important for the regression. Therefore the usual linear regression assumption that **$X$ is full rank** will not hold. We can, however, introduce regularisation and use the Least-angle regression (LARS; Efron, Hastie, Johnstone and Tibshirani (2004)) algorithm to fit our model. The Lasso\n\n$$\n\\text{minimise } || y - X\\beta||_2^2, \\quad \\text{subject to } \\sum_{j=1}^d |\\beta_j| \\leq t\n$$\n\nWe now work with a diabetes dataset:",
"_____no_output_____"
],
[
"Suppose we have a large number of features. We want to **select** the ones that can represent the sparsity.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn import linear_model\nfrom sklearn import datasets\n\nX, y = datasets.load_diabetes(return_X_y=True)\n\nprint(\"Computing regularization path using the LARS ...\")\n_, _, coefs = linear_model.lars_path(X, y, method='lasso', verbose=True)\n\nxx = np.sum(np.abs(coefs.T), axis=1)\nxx /= xx[-1]",
"Computing regularization path using the LARS ...\n."
],
[
"plt.plot(xx, coefs.T)\nymin, ymax = plt.ylim()\nplt.vlines(xx, ymin, ymax, linestyle='dashed')\nplt.xlabel('|coef| / max|coef|')\nplt.ylabel('Coefficients')\nplt.title('LASSO Path')\nplt.axis('tight')\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Importance Notice!\n\nWe are proposal a constitution change so that we can better deliver quality events to you! Please do participate in our upcoming general meeting (even just coming for a vote will be very helpful!). \n\nSome of the changes:\n- Introduction of more official committee roles\n- Update of the manifesto e.g. societal goals, motto - we were only founded 3 years ago!\n\nMore details to come!",
"_____no_output_____"
],
[
"Thank you for your attention! \n\nhttps://github.com/Imperial-College-Data-Science-Society/workshops\n\n1. Introduction to Data Science\n2. **Regression and Neural Networks**\n3. Classifying Character and Organ Images\n4. Demystifying Causality and Causal Inference\n5. A Primer to Data Engineering\n6. Natural Language Processing (NLP) by using Attention\n7. Art and Music using GANs\n8. Probabilistic Programming in Practice\n9. Missing Data in Supervised Learning\n\n\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cb7a72a7ae516fb3df62d8d5f22e176771335c60
| 45,070 |
ipynb
|
Jupyter Notebook
|
examples/vacuum_scan_subtract.ipynb
|
ercius/stempy
|
4f8ddeb5b089c5ac2d634cb348cee5113df506a3
|
[
"BSD-3-Clause"
] | 11 |
2019-11-08T11:13:11.000Z
|
2022-03-31T19:58:25.000Z
|
examples/vacuum_scan_subtract.ipynb
|
ercius/stempy
|
4f8ddeb5b089c5ac2d634cb348cee5113df506a3
|
[
"BSD-3-Clause"
] | 146 |
2018-12-27T16:00:09.000Z
|
2022-03-31T23:06:04.000Z
|
examples/vacuum_scan_subtract.ipynb
|
ercius/stempy
|
4f8ddeb5b089c5ac2d634cb348cee5113df506a3
|
[
"BSD-3-Clause"
] | 12 |
2019-04-08T11:16:13.000Z
|
2022-02-25T21:59:24.000Z
| 27.959057 | 143 | 0.521566 |
[
[
[
"%matplotlib widget\n\nfrom pathlib import Path\nfrom collections import namedtuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.linalg import svd\nimport imageio\nfrom scipy import ndimage\n\nimport h5py\nimport stempy.io as stio\nimport stempy.image as stim\n\n# Set up Cori paths\nncemhub = Path('/global/cfs/cdirs/ncemhub/4Dcamera/')\nscratch = Path('/global/cscratch1/sd/percius/')\n# Set up mothership6 paths\nhdd1 = Path('/mnt/hdd1')",
"_____no_output_____"
],
[
"def com_sparse_iterative(electron_events, scan_dimensions, crop_to=(576,576)):\n # Iterative version. Will be replaced in a future stempy release\n # Calculate the center of mass as a test\n com2 = np.zeros((2, scan_dimensions[0]*scan_dimensions[1]), np.float32)\n for ii, ev in enumerate(electron_events):\n if len(ev) > 0:\n x,y = np.unravel_index(ev,(576,576))\n mm = len(ev)\n comx0 = np.sum(x) / mm\n comy0 = np.sum(y) / mm\n # Crop around the center\n keep = (x > comx0-crop_to[0]) & (x <= comx0+crop_to[0]) & (y > comy0-crop_to[1]) & (y <= comy0+crop_to[1])\n x = x[keep]\n y = y[keep]\n mm = len(x)\n if mm > 0:\n comx = np.sum(x)\n comy = np.sum(y)\n comx = comx / mm\n comy = comy / mm\n else:\n comx = comx0\n comy = comy0\n com2[:, ii] = (comy,comx)\n else:\n com2[:, ii] = (np.nan, np.nan)\n \n com2 = com2.reshape((2, scan_dimensions[0], scan_dimensions[1]))\n return com2\n\ndef planeFit(points):\n \"\"\"\n p, n = planeFit(points)\n\n Given an array, points, of shape (d,...)\n representing points in d-dimensional space,\n fit an d-dimensional plane to the points.\n Return a point, p, on the plane (the point-cloud centroid),\n and the normal, n.\n\n \"\"\"\n\n points = np.reshape(points, (np.shape(points)[0], -1)) # Collapse trialing dimensions\n assert points.shape[0] <= points.shape[1], \"There are only {} points in {} dimensions.\".format(points.shape[1], points.shape[0])\n ctr = points.mean(axis=1)\n x = points - ctr[:,np.newaxis]\n M = np.dot(x, x.T) # Could also use np.cov(x) here.\n return ctr, svd(M)[0][:,-1]",
"_____no_output_____"
],
[
"# Close all previous windows to avoid too many windows\nplt.close('all')\n\n# Load a sparse vacuum 4D camera data set \nscan_num = 105\nthreshold = 4.0\ndata_dir = Path('2020.11.23')\n\nfname = hdd1 / data_dir / Path('data_scan{}_th{}_electrons.h5'.format(scan_num, threshold))\n\nvacuum_scan = stio.load_electron_counts(fname)\n\nprint('File: {}'.format(fname))\nprint('Initial scan dimensions = {}'.format(vacuum_scan.scan_dimensions))",
"File: /mnt/hdd1/2020.11.23/data_scan105_th4.0_electrons.h5\nInitial scan dimensions = [257, 1024]\n"
],
[
"# Show the summed diffraction pattern\ndp = stim.calculate_sum_sparse(vacuum_scan.data, vacuum_scan.frame_dimensions)\n\nfg,ax = plt.subplots(1,1)\nax.imshow(dp)",
"_____no_output_____"
],
[
"# Calculate the com iteratively\n#com2 = stim.com_sparse(vacuum_scan.data, vacuum_scan.frame_dimensions)\ncom2 = com_sparse_iterative(vacuum_scan.data, vacuum_scan.scan_dimensions, crop_to=(30, 30))\n\n# These will be removed in a future release\nprint('Remove the code below in a future release.')\n# Nan values to average value\nnp.nan_to_num(com2[0,],copy=False,nan=np.nanmean(com2[0,]))\nnp.nan_to_num(com2[1,],copy=False,nan=np.nanmean(com2[1,]));\n\ncom2 = com2.reshape((2,*vacuum_scan.scan_dimensions[::-1]))\n",
"Remove the code below in a future release.\n"
],
[
"# Remove the outliers by median filtering\ncom2_filt = np.zeros_like(com2)\ncom2_filt[0,] = ndimage.median_filter(com2[0,], size=(3,3))\ncom2_filt[1,] = ndimage.median_filter(com2[1,], size=(3,3))\n\ncom2_median = np.median(com2_filt,axis=(1,2))\n\nfg,ax = plt.subplots(1, 2,sharex=True,sharey=True)\nax[0].imshow(com2_filt[0,]-com2_median[0],cmap='bwr',vmin=-25,vmax=25)\nax[1].imshow(com2_filt[1,]-com2_median[1],cmap='bwr',vmin=-25,vmax=25)",
"_____no_output_____"
],
[
"# Fit the COMs to planes to smooth it out\nYY, XX = np.mgrid[0:com2.shape[1],0:com2.shape[2]]\n\nplaneCOM0 = planeFit(np.stack((YY,XX,com2_filt[0,])))\nplaneCOM1 = planeFit(np.stack((YY,XX,com2_filt[1,])))\n\nprint(planeCOM0)\nprint(planeCOM1)",
"(array([511.5 , 128. , 281.50863554]), array([-0.01335387, -0.01116126, 0.99984854]))\n(array([511.5 , 128. , 296.8526089]), array([0.01876338, 0.03832418, 0.99908918]))\n"
],
[
"# Generate points on the plane to fit the dataset size\nYY, XX = np.mgrid[0:vacuum_scan.scan_dimensions[1], 0:vacuum_scan.scan_dimensions[0]]\n\nnormal = planeCOM0[1]\nd = np.dot(-planeCOM0[0], normal)\n# calculate corresponding z\nz0 = (-normal[0]*YY - normal[1]*XX - d)/normal[2]\n\nnormal = planeCOM1[1]\nd = np.dot(-planeCOM1[0], normal)\n# calculate corresponding z\nz1 = (-normal[0]*YY - normal[1]*XX - d)/normal[2]\n\nfg,ax = plt.subplots(2,2)\nax[0,0].imshow(com2_filt[0,],cmap='bwr')\nax[0,1].imshow(z0, cmap='bwr')\nax[1,0].imshow(com2_filt[1,],cmap='bwr')\nax[1,1].imshow(z1, cmap='bwr');",
"_____no_output_____"
],
[
"# Test centering on the vacuum scan itself\nvacuum_scan_centered = namedtuple('ElectronCountedData',\n ['data', 'scan_dimensions', 'frame_dimensions'])\nvacuum_scan_centered.scan_dimensions = vacuum_scan.scan_dimensions\nvacuum_scan_centered.frame_dimensions = vacuum_scan.frame_dimensions\n\nvacuum_scan_centered.data = []\n\nz0_round = np.round(z0).astype(np.int32) - int(z0.mean())\nz1_round = np.round(z1).astype(np.int32) - int(z1.mean())\n\nfor ev, x, y in zip(vacuum_scan.data, z0_round.ravel(), z1_round.ravel()):\n evx, evy = np.unravel_index(ev, (576,576))\n evx_centered = evx - y\n evy_centered = evy - x\n \n keep = (evx_centered < 576) & (evx_centered >= 0) * (evy_centered < 576) & (evy_centered >= 0)\n evx_centered = evx_centered[keep]\n evy_centered = evy_centered[keep]\n \n vacuum_scan_centered.data.append(np.ravel_multi_index((evx_centered,evy_centered), (576,576)))\nvacuum_scan_centered.data = np.array(vacuum_scan_centered.data, dtype=object)\n\ndp = stim.calculate_sum_sparse(vacuum_scan.data, vacuum_scan.frame_dimensions)\n \ndp2 = stim.calculate_sum_sparse(vacuum_scan_centered.data, vacuum_scan_centered.frame_dimensions)\n\nfg,ax = plt.subplots(1,2,sharex=True,sharey=True)\nax[0].imshow(dp)\nax[1].imshow(dp2)\n",
"_____no_output_____"
],
[
"# Compare com_filtered to plane fit\n# Nan values to average value\nnp.nan_to_num(com2[0,],copy=False,nan=np.nanmean(com2[0,]))\nnp.nan_to_num(com2[1,],copy=False,nan=np.nanmean(com2[1,]))\n\nfg,ax = plt.subplots(2,2)\nax[0,0].imshow(z0,cmap='bwr')\nax[0,1].imshow(z1,cmap='bwr')\nax[1,0].imshow(com2[0,]-z0,cmap='bwr')\nax[1,1].imshow(com2[1,]-z1,cmap='bwr')",
"_____no_output_____"
]
],
[
[
"# Apply to experiment from a sample",
"_____no_output_____"
]
],
[
[
"# Load a sparse 4D camera data set\nscan_num =102\nthreshold = 4.0\ndata_dir = Path('2020.11.23')\n\nfname = hdd1 / data_dir / Path('data_scan{}_th{}_electrons.h5'.format(scan_num, threshold))\n#fname = Path.home() / Path('data/temp/data_scan{scan_num}_th{}_electrons.h5'.format(scan_num, threshold))\n\nexperiment = stio.load_electron_counts(fname)\n\nprint('File: {}'.format(fname))\nprint('Initial scan dimensions = {}'.format(experiment.scan_dimensions))",
"File: /mnt/hdd1/2020.11.23/data_scan102_th4.0_electrons.h5\nInitial scan dimensions = [257, 1024]\n"
],
[
"# Generate points on the plane to fit the dataset size\nfactor = (experiment.scan_dimensions[0] / vacuum_scan.scan_dimensions[0],\n experiment.scan_dimensions[1] / vacuum_scan.scan_dimensions[1])\n\n# Generate positions between vacuum positions\nYY, XX = np.mgrid[0:experiment.scan_dimensions[0], 0:experiment.scan_dimensions[1]]\nYY = YY.astype('<f4') / factor[1]\nXX = XX.astype('<f4') / factor[0]\n\nnormal = planeCOM0[1]\nd = np.dot(-planeCOM0[0], normal)\n# calculate corresponding z\nz0 = (-normal[0]*YY - normal[1]*XX - d)/normal[2]\n\nnormal = planeCOM1[1]\nd = np.dot(-planeCOM1[0], normal)\n# calculate corresponding z\nz1 = (-normal[0]*YY - normal[1]*XX - d)/normal[2]\n\n# Round to integers\nz0_round = np.round(z0 - z0.mean()).astype(np.int64)\nz1_round = np.round(z1 - z1.mean()).astype(np.int64)\n\nfg,ax = plt.subplots(2,2)\nax[0,0].imshow(z0,cmap='bwr')\nax[0,1].imshow(z0_round, cmap='bwr')\nax[1,0].imshow(z1,cmap='bwr')\nax[1,1].imshow(z1_round, cmap='bwr');",
"_____no_output_____"
],
[
"# Use the fitted plane from the vacuum scan to recenter the events\nscan_centered = []\n\nfor ev, x, y in zip(experiment.data, z0_round.ravel(), z1_round.ravel()):\n evx, evy = np.unravel_index(ev, (576,576))\n evx_centered = evx - y # need to flip x and y\n evy_centered = evy - x\n \n # Some events will get pushed off the detetor by the shift. Remove them\n keep = (evx_centered < 576) & (evx_centered >= 0) & (evy_centered < 576) & (evy_centered >= 0)\n evx_centered = evx_centered[keep]\n evy_centered = evy_centered[keep]\n \n scan_centered.append(np.ravel_multi_index((evx_centered,evy_centered), (576,576)))\nscan_centered = np.array(scan_centered, dtype=object)\n\n# Create a stempy counted data namedtuple\nexperiment_centered = namedtuple('ElectronCountedData',\n ['data', 'scan_dimensions', 'frame_dimensions'])\nexperiment_centered.data = scan_centered\nexperiment_centered.scan_dimensions = experiment.scan_dimensions[::1]\nexperiment_centered.frame_dimensions = experiment.frame_dimensions\n\ndp = stim.calculate_sum_sparse(experiment.data, experiment.frame_dimensions)\ndp2 = stim.calculate_sum_sparse(experiment_centered.data, experiment_centered.frame_dimensions)\n\nfg,ax = plt.subplots(2,1,sharex=True,sharey=True)\nax[0].imshow(dp)\nax[1].imshow(np.log(dp2+0.1))",
"_____no_output_____"
],
[
"# Save to a stempy dataset\nout_name = fname.with_name('data_scan{}_th{}_electrons_centered.h5'.format(scan_num,threshold))\nstio.save_electron_counts(out_name,experiment_centered)\nprint(out_name)",
"/mnt/hdd1/2020.11.23/temp.h5\n"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb7a772a91ee1aab92f9da90467717fe4f799807
| 94,712 |
ipynb
|
Jupyter Notebook
|
src/nb_scripts/pre_process/preparing_ft_data.ipynb
|
sujunhao/RENET2
|
21fb57d17544556e5f62737a6df40ff5e5f990ba
|
[
"BSD-3-Clause"
] | 16 |
2021-03-06T10:41:00.000Z
|
2022-03-29T02:16:04.000Z
|
src/nb_scripts/pre_process/preparing_ft_data.ipynb
|
sujunhao/RENET2
|
21fb57d17544556e5f62737a6df40ff5e5f990ba
|
[
"BSD-3-Clause"
] | 2 |
2021-06-16T10:19:47.000Z
|
2021-07-16T08:12:18.000Z
|
src/nb_scripts/pre_process/preparing_ft_data.ipynb
|
sujunhao/RENET2
|
21fb57d17544556e5f62737a6df40ff5e5f990ba
|
[
"BSD-3-Clause"
] | 1 |
2022-03-22T02:13:19.000Z
|
2022-03-22T02:13:19.000Z
| 37.288189 | 295 | 0.48449 |
[
[
[
"# input\n\n# pmid list: ../../data/ft_info/ft_id_lst.csv\n# (ft json file) ../../data/raw_data/ft/\n# (ft abs file) ../../data/raw_data/abs/\n# result file at ../../data/raw_data/ft/T0 (all section)\n# ../../data/raw_data/ft/T1 (no abs), etc",
"_____no_output_____"
],
[
"# setp 1 download full-text",
"_____no_output_____"
],
[
"import pandas as pd\nimport pickle\nimport os",
"_____no_output_____"
],
[
"# get pmid list",
"_____no_output_____"
],
[
"tar_lst = pd.read_csv(\"../../data/ft_info/ft_id_lst.csv\", dtype=str)",
"_____no_output_____"
],
[
"tar_lst.head()",
"_____no_output_____"
],
[
"tar_lst.PMID",
"_____no_output_____"
],
[
"# _f = os.path.join('../../data/ft_info/', 'PMID_lst') \n# with open(_f, 'rb' ) as fp:\n# PMID_lst = pickle.load(fp)\n# print(len(PMID_lst))\n",
"_____no_output_____"
],
[
"nl = list(tar_lst.PMID.values)",
"_____no_output_____"
],
[
"import numpy as np\nnp.random.shuffle(nl)",
"_____no_output_____"
],
[
"nl",
"_____no_output_____"
],
[
"# PMID_lst",
"_____no_output_____"
],
[
"# if we only have pmid, we can obatin pmcid by:\n# # get pmcid\n# # !wget https://ftp.ncbi.nlm.nih.gov/pub/pmc/PMC-ids.csv.gz\n# # !gzip -d PMC-ids.csv.gz\n\n# _pmc_id_map = pd.read_csv(\"../../data/ft_info/PMC-ids.csv\", dtype=str)\n# pmc_id_map = _pmc_id_map[['PMCID', 'PMID']]\n# pmc_id_map = pmc_id_map[pmc_id_map.notnull()]\n# tar_lst = pmc_id_map[pmc_id_map['PMID'].isin(pmid_l)]",
"_____no_output_____"
],
[
"import sys\nsys.path.insert(1, '..')",
"_____no_output_____"
],
[
"# import download_data",
"_____no_output_____"
],
[
"# # downloading full-text\n# tar_id_lst = list(tar_lst.PMCID.values)\n# tar_dir = '../../data/raw_data/ft/'\n# url_prefix = \"https://www.ncbi.nlm.nih.gov/research/pubtator-api/publications/export/biocjson?pmcids=\"\n# _type='json'\n# cores=3\n\n# hit_rec = download_data.download_from_lst_hd(tar_id_lst, tar_dir, url_prefix, _type, cores)",
"_____no_output_____"
],
[
"# # downloading abs (as some full-text have no abstract)\n# tar_id_lst = list(tar_lst.PMID.values)\n# tar_dir = '../../data/raw_data/abs/'\n# url_prefix = \"https://www.ncbi.nlm.nih.gov/research/pubtator-api/publications/export/pubtator?pmids=\"\n# _type='abs'\n# cores=3\n\n# hit_rec = download_data.download_from_lst_hd(tar_id_lst, tar_dir, url_prefix, _type, cores)",
"_____no_output_____"
],
[
"s_df = pd.read_csv('../../data/ft_info/ft_500_n.tsv', sep = '\\t')\n\nprint('annotated table shape', s_df.shape)\ns_df = s_df[s_df['2nd_label'] != 0][['pmid', 'geneId', 'diseaseId', '2nd_label']]\ns_df.rename(columns={'2nd_label':'label'}, inplace=True)\ns_df.to_csv('../../data/ft_info/labels_n.tsv', sep=',', index=False)",
"annotated table shape (1556, 26)\n"
],
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"import parse_data\nimport subprocess\n",
"_____no_output_____"
],
[
"# original all sections",
"_____no_output_____"
],
[
"# in_pmid_d = '/mnt/bal31/jhsu/old/data/ptc/raw_ft/abs_off/'\n# in_pmcid_d = '/mnt/bal31/jhsu/old/data/ptc/raw_ft/ft/'",
"_____no_output_____"
],
[
"# import subprocess\n# _lst = list(tar_lst.PMID.values)\n# for i in list(_lst):\n# cmd = 'cp ' + '/mnt/bal31/jhsu/old/data/ptc/raw_ft/abs_off/' + i + ' ' + '../../data/raw_data/abs/' + i\n# subprocess.check_call(cmd, shell=True)\n \n# _lst = list(tar_lst.PMCID.values)\n# for i in list(_lst):\n# cmd = 'cp ' + '/mnt/bal31/jhsu/old/data/ptc/raw_ft/ft/' + i + ' ' + '../../data/raw_data/ft/' + i\n# subprocess.check_call(cmd, shell=True)",
"_____no_output_____"
],
[
"!mkdir -p ../../data/raw_data/ft/T0\nout_dir = '../../data/raw_data/ft/T0/'",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T0/\n--- 4.005 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T0/docs.txt ../../data/raw_data/ft/T0/sentences.txt /usr/bin/ruby\n--- 12.785 seconds ---\n"
],
[
"#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"python ../normalize_ann.py --in_f ../../data/raw_data/ft/T0/anns.txt --out_f ../../data/raw_data/ft/T0/anns_n.txt\n"
],
[
"!mkdir -p ../../data/raw_data/ft/T1\nout_dir = '../../data/raw_data/ft/T1/'",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nori_tar=['TITLE', '#', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', '#', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T1/\n--- 4.058 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T1/docs.txt ../../data/raw_data/ft/T1/sentences.txt /usr/bin/ruby\n--- 12.668 seconds ---\n"
],
[
"#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"python ../normalize_ann.py --in_f ../../data/raw_data/ft/T1/anns.txt --out_f ../../data/raw_data/ft/T1/anns_n.txt\n"
],
[
"!mkdir -p ../../data/raw_data/ft/T2\nout_dir = '../../data/raw_data/ft/T2/'\n#ori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nori_tar=['TITLE', 'ABSTRACT', '#', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)\n\n#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', '#', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T2/\n--- 4.171 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T2/docs.txt ../../data/raw_data/ft/T2/sentences.txt /usr/bin/ruby\n--- 8.910 seconds ---\npython ../normalize_ann.py --in_f ../../data/raw_data/ft/T2/anns.txt --out_f ../../data/raw_data/ft/T2/anns_n.txt\n"
],
[
"!mkdir -p ../../data/raw_data/ft/T3\nout_dir = '../../data/raw_data/ft/T3/'\n#ori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nori_tar=['TITLE', 'ABSTRACT', 'INTRO', '#', 'RESULTS', 'DISCUSS', 'CONCL']",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)\n\n#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', 'INTRO', '#', 'RESULTS', 'DISCUSS', 'CONCL'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T3/\n--- 3.388 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T3/docs.txt ../../data/raw_data/ft/T3/sentences.txt /usr/bin/ruby\n--- 9.870 seconds ---\npython ../normalize_ann.py --in_f ../../data/raw_data/ft/T3/anns.txt --out_f ../../data/raw_data/ft/T3/anns_n.txt\n"
],
[
"!mkdir -p ../../data/raw_data/ft/T4\nout_dir = '../../data/raw_data/ft/T4/'\n#ori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', '#', 'DISCUSS', 'CONCL']",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)\n\n#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', '#', 'DISCUSS', 'CONCL'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T4/\n--- 3.842 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T4/docs.txt ../../data/raw_data/ft/T4/sentences.txt /usr/bin/ruby\n--- 8.707 seconds ---\npython ../normalize_ann.py --in_f ../../data/raw_data/ft/T4/anns.txt --out_f ../../data/raw_data/ft/T4/anns_n.txt\n"
],
[
"!mkdir -p ../../data/raw_data/ft/T5\nout_dir = '../../data/raw_data/ft/T5/'\n#ori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', '#', 'CONCL']",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)\n\n#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', '#', 'CONCL'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T5/\n--- 3.341 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T5/docs.txt ../../data/raw_data/ft/T5/sentences.txt /usr/bin/ruby\n--- 9.320 seconds ---\npython ../normalize_ann.py --in_f ../../data/raw_data/ft/T5/anns.txt --out_f ../../data/raw_data/ft/T5/anns_n.txt\n"
],
[
"!mkdir -p ../../data/raw_data/ft/T5\nout_dir = '../../data/raw_data/ft/T5/'\n#ori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', '#']",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)\n\n#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', '#'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T5/\n--- 3.959 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T5/docs.txt ../../data/raw_data/ft/T5/sentences.txt /usr/bin/ruby\n--- 12.608 seconds ---\npython ../normalize_ann.py --in_f ../../data/raw_data/ft/T5/anns.txt --out_f ../../data/raw_data/ft/T5/anns_n.txt\n"
],
[
"!mkdir -p ../../data/raw_data/ft/T6\nout_dir = '../../data/raw_data/ft/T6/'\n#ori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\nori_tar=['TITLE', 'ABSTRACT', 'INTRO', '#', 'RESULTS', 'DISCUSS', '#']",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nis_SeFi = True\n\nparse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)\n\n#optional normalize the annotation\ncmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\nprint(cmd)\nsubprocess.check_call(cmd, shell=True)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', 'INTRO', '#', 'RESULTS', 'DISCUSS', '#'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T6/\n--- 4.087 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T6/docs.txt ../../data/raw_data/ft/T6/sentences.txt /usr/bin/ruby\n--- 9.471 seconds ---\npython ../normalize_ann.py --in_f ../../data/raw_data/ft/T6/anns.txt --out_f ../../data/raw_data/ft/T6/anns_n.txt\n"
],
[
"# import json\n\n# _pmcid = 'PMC7102640'\n# _pmid = '32171866'\n# abs_f_path = in_pmid_d + _pmid\n# print(_pmcid, end=', ')\n# with open(in_pmcid_d + _pmcid, encoding='utf-8') as f:\n# data = json.load(f)\n\n# rst = parse_data.parse_doc(data, abs_f_path, ori_tar, is_SeFi)\n\n# rst",
"_____no_output_____"
],
[
"!mkdir -p ../../data/raw_data/ft/T7\nout_dir = '../../data/raw_data/ft/T7/'\nori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\n# ori_tar=['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL']\n# ori_tar=['TITLE', 'ABSTRACT', '#', '#', '#', '#', '#']",
"_____no_output_____"
],
[
"tar_id_lst = list(tar_lst.PMCID.values)\nin_pmid_d = '../../data/raw_data/abs/'\nin_pmcid_d = '../../data/raw_data/ft/'\nparse_t = 'ft' # 'ft' or 'abs'\nif_has_s_f = True # if have section file\nis_SeFi = True\n\ninfo_l = parse_data.parse_data_lst_hd(tar_id_lst, in_pmid_d, in_pmcid_d, parse_t, out_dir, if_has_s_f, ori_tar, is_SeFi)\n\n# #optional normalize the annotation\n# cmd = 'python ../normalize_ann.py ' + '--in_f ' + out_dir + 'anns.txt' + ' ' + '--out_f ' + out_dir + 'anns_n.txt'\n# print(cmd)\n# subprocess.check_call(cmd, shell=True)",
"will parser doc at ../../data/raw_data/ft/ & ../../data/raw_data/abs/, doc # 500, with sections ['TITLE', 'ABSTRACT', 'INTRO', 'METHODS', 'RESULTS', 'DISCUSS', 'CONCL'], if have SeFi\nhit 500, miss 0C7295272\nresult RENET2 model's input is at ../../data/raw_data/ft/T7/\n--- 3.846 seconds ---\nusing GENIA Sentence Splitter\n/autofs/bal31/jhsu/home/projects/RENET2/renet2\nusing geniass /autofs/bal31/jhsu/home/projects/RENET2/renet2/../tools/geniass/run_geniass.sh ../../data/raw_data/ft/T7/docs.txt ../../data/raw_data/ft/T7/sentences.txt /usr/bin/ruby\n--- 12.668 seconds ---\n"
],
[
"info_l",
"_____no_output_____"
],
[
"info_df = pd.DataFrame(info_l, columns=['pmid', 'pmcid', 'ttl_l', 'abs_l', 'par_l', 'txt_l', 'g_#', 'd_#', 'gd_p', 'gd_vp'])\ninfo_df.describe()",
"_____no_output_____"
],
[
"# READING Sentences and tokenizer\nimport argparse\nimport sys\nimport os\n\nimport pandas as pd\nimport numpy as np\nfrom raw import load_documents_vis\nfrom raw_handler import init_parser, loading_tokenizer\n\nfrom IPython.display import display, clear_output, HTML\nimport ipywidgets as widgets",
"_____no_output_____"
],
[
"import sys\nsys.argv = ['']\nparser = init_parser()\nargs = parser.parse_args()\n\nargs.ori_tokenizer = loading_tokenizer(args)\nargs.token_voc_l = len(args.ori_tokenizer)\nprint('tokenizer size %d' % (args.token_voc_l))\n",
"loading word index from /mnt/bal31/jhsu/home/git/renet2/src/utils/word_index\nloaded word index, voc size 82948\ntokenizer size 82949\n"
],
[
"# RENET2 input data dir, target GDA file, etc\nargs.raw_data_dir = out_dir\nargs.fix_snt_n, args.fix_token_n = 400, 54\nprint('fix input sentences# %d, tokens# %d, batch size %d' % (args.fix_snt_n, args.fix_token_n, args.batch_size))\n\nargs.no_cache_file = True\ntext_path = os.path.join(args.raw_data_dir, args.file_name_doc) \nsentence_path = os.path.join(args.raw_data_dir, args.file_name_snt)\nner_path = os.path.join(args.raw_data_dir, args.file_name_ann)",
"fix input sentences# 400, tokens# 54, batch size 64\n"
],
[
"all_ori_seq, ner_df, session_info, ori_ner, all_sentence, all_session_map = load_documents_vis(text_path, sentence_path, ner_path, args.ori_tokenizer, args)",
"loading sorce info\nread 500 doc, max token len 0 42\n\n"
],
[
"def get_token_l(snt_l):\n tokens_s = 0\n snt_s = 0\n for snt in snt_l:\n tokens = tokenize(snt)\n tokens_l = len(tokens)\n tokens_s += tokens_l\n snt_s += 1\n# print(tokens_l, tokens)\n return tokens_s, snt_s\n# all_sentence['16963499']",
"_____no_output_____"
],
[
"get_token_l(all_sentence['16963499'])",
"_____no_output_____"
],
[
"t_s, t_t = 0, 0\nfor k, v in all_sentence.items():\n _a, _b = get_token_l(v)\n t_s += _a\n t_t += _b\n# print(token_s)\n# break\nprint(t_s / 500, t_t/500)",
"1501.614 55.888\n"
],
[
"token_s / 500",
"_____no_output_____"
],
[
"from utils.tokenizer import tokenize",
"_____no_output_____"
],
[
"tokenize(all_sentence['16963499'][0])",
"_____no_output_____"
],
[
"all_sentence['16963499'][0]",
"_____no_output_____"
],
[
"12.4*16.1",
"_____no_output_____"
],
[
"PMID32171866",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7a78880c593a00811b14f9a564b0809b9ee69c
| 31,885 |
ipynb
|
Jupyter Notebook
|
AI 이노베이션 스퀘어 시각지능 과정/202004/20200420/Cifar10_Challenge_with_augmentation.ipynb
|
donddog/AI_Innovation_Square_Codes
|
a04d50db011d25e00d8486146c24124c50242aa7
|
[
"MIT"
] | 1 |
2021-02-11T16:45:21.000Z
|
2021-02-11T16:45:21.000Z
|
AI 이노베이션 스퀘어 시각지능 과정/202004/20200420/Cifar10_Challenge_with_augmentation.ipynb
|
donddog/AI_Innovation_Square_Codes
|
a04d50db011d25e00d8486146c24124c50242aa7
|
[
"MIT"
] | null | null | null |
AI 이노베이션 스퀘어 시각지능 과정/202004/20200420/Cifar10_Challenge_with_augmentation.ipynb
|
donddog/AI_Innovation_Square_Codes
|
a04d50db011d25e00d8486146c24124c50242aa7
|
[
"MIT"
] | null | null | null | 56.634103 | 12,704 | 0.713031 |
[
[
[
"from __future__ import print_function\nimport warnings\n\nwarnings.filterwarnings(action='ignore')\n\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, BatchNormalization\nimport os",
"Using TensorFlow backend.\n"
],
[
"batch_size = 16\nnum_classes = 10\nepochs = 15\n\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()",
"_____no_output_____"
],
[
"print('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\nprint(y_train)",
"x_train shape: (50000, 32, 32, 3)\n50000 train samples\n10000 test samples\n[[6]\n [9]\n [9]\n ...\n [9]\n [1]\n [1]]\n"
],
[
"y_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)",
"_____no_output_____"
],
[
"y_train",
"_____no_output_____"
],
[
"x_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255",
"_____no_output_____"
],
[
"print('Using real-time data augmentation.')\n # This will do preprocessing and realtime data augmentation:\ndatagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n zca_epsilon=1e-06, # epsilon for ZCA whitening\n rotation_range=60, # randomly rotate images in the range (degrees, 0 to 180)\n # randomly shift images horizontally (fraction of total width)\n width_shift_range=0.1,\n # randomly shift images vertically (fraction of total height)\n height_shift_range=0.3,\n shear_range=0., # set range for random shear\n zoom_range=1.5, # set range for random zoom\n channel_shift_range=0., # set range for random channel shifts\n # set mode for filling points outside the input boundaries\n fill_mode='nearest',\n cval=0., # value used for fill_mode = \"constant\"\n horizontal_flip=True, # randomly flip images\n vertical_flip=True, # randomly flip images\n # set rescaling factor (applied before any other transformation)\n rescale=None,\n # set function that will be applied on each input\n preprocessing_function=None,\n # image data format, either \"channels_first\" or \"channels_last\"\n data_format=None,\n # fraction of images reserved for validation (strictly between 0 and 1)\n validation_split=0.0)\n\n# Compute quantities required for feature-wise normalization\n# (std, mean, and principal components if ZCA whitening is applied).\ndatagen.fit(x_train)",
"Using real-time data augmentation.\n"
],
[
"filepath = \"./savemodels/cifar10-model-{epoch:02d}-{val_accuracy:.2f}.hdf5\"\ncheckpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')",
"_____no_output_____"
],
[
"model = Sequential()\nmodel.add(Conv2D(32, (3, 3), padding='same',\n input_shape=x_train.shape[1:]))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes))\nmodel.add(Activation('softmax'))",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_1 (Conv2D) (None, 32, 32, 32) 896 \n_________________________________________________________________\nactivation_1 (Activation) (None, 32, 32, 32) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 30, 30, 32) 9248 \n_________________________________________________________________\nactivation_2 (Activation) (None, 30, 30, 32) 0 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 15, 15, 32) 0 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 15, 15, 32) 0 \n_________________________________________________________________\nconv2d_3 (Conv2D) (None, 15, 15, 64) 18496 \n_________________________________________________________________\nactivation_3 (Activation) (None, 15, 15, 64) 0 \n_________________________________________________________________\nconv2d_4 (Conv2D) (None, 13, 13, 64) 36928 \n_________________________________________________________________\nactivation_4 (Activation) (None, 13, 13, 64) 0 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 6, 6, 64) 0 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 6, 6, 64) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 2304) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 512) 1180160 \n_________________________________________________________________\nactivation_5 (Activation) (None, 512) 0 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 512) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 5130 \n_________________________________________________________________\nactivation_6 (Activation) (None, 10) 0 \n=================================================================\nTotal params: 1,250,858\nTrainable params: 1,250,858\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"opt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)",
"_____no_output_____"
],
[
"model.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"history = model.fit_generator(datagen.flow(x_train, y_train,\n batch_size=batch_size),\n epochs=epochs,\n validation_data=(x_test, y_test),\n workers=4, callbacks=[checkpoint])",
"Epoch 1/15\n3125/3125 [==============================] - 121s 39ms/step - loss: 2.0728 - accuracy: 0.2186 - val_loss: 1.8797 - val_accuracy: 0.3313\n\nEpoch 00001: val_accuracy improved from -inf to 0.33130, saving model to ./savemodels/cifar10-model-01-0.33.hdf5\nEpoch 2/15\n3125/3125 [==============================] - 121s 39ms/step - loss: 1.9830 - accuracy: 0.2645 - val_loss: 1.7935 - val_accuracy: 0.3555\n\nEpoch 00002: val_accuracy improved from 0.33130 to 0.35550, saving model to ./savemodels/cifar10-model-02-0.36.hdf5\nEpoch 3/15\n3125/3125 [==============================] - 121s 39ms/step - loss: 1.9459 - accuracy: 0.2833 - val_loss: 1.7590 - val_accuracy: 0.3727\n\nEpoch 00003: val_accuracy improved from 0.35550 to 0.37270, saving model to ./savemodels/cifar10-model-03-0.37.hdf5\nEpoch 4/15\n3125/3125 [==============================] - 121s 39ms/step - loss: 1.9163 - accuracy: 0.2987 - val_loss: 1.7871 - val_accuracy: 0.3518\n\nEpoch 00004: val_accuracy did not improve from 0.37270\nEpoch 5/15\n3125/3125 [==============================] - 121s 39ms/step - loss: 1.8980 - accuracy: 0.3059 - val_loss: 1.6900 - val_accuracy: 0.3967\n\nEpoch 00005: val_accuracy improved from 0.37270 to 0.39670, saving model to ./savemodels/cifar10-model-05-0.40.hdf5\nEpoch 6/15\n3125/3125 [==============================] - 121s 39ms/step - loss: 1.8806 - accuracy: 0.3143 - val_loss: 1.6877 - val_accuracy: 0.3941\n\nEpoch 00006: val_accuracy did not improve from 0.39670\nEpoch 7/15\n3125/3125 [==============================] - 122s 39ms/step - loss: 1.8632 - accuracy: 0.3218 - val_loss: 1.6762 - val_accuracy: 0.3963\n\nEpoch 00007: val_accuracy did not improve from 0.39670\nEpoch 8/15\n3125/3125 [==============================] - 122s 39ms/step - loss: 1.8539 - accuracy: 0.3247 - val_loss: 1.6426 - val_accuracy: 0.4110\n\nEpoch 00008: val_accuracy improved from 0.39670 to 0.41100, saving model to ./savemodels/cifar10-model-08-0.41.hdf5\nEpoch 9/15\n3125/3125 [==============================] - 122s 39ms/step - loss: 1.8460 - accuracy: 0.3288 - val_loss: 1.7073 - val_accuracy: 0.3960\n\nEpoch 00009: val_accuracy did not improve from 0.41100\nEpoch 10/15\n3125/3125 [==============================] - 123s 39ms/step - loss: 1.8359 - accuracy: 0.3331 - val_loss: 1.6715 - val_accuracy: 0.4138\n\nEpoch 00010: val_accuracy improved from 0.41100 to 0.41380, saving model to ./savemodels/cifar10-model-10-0.41.hdf5\nEpoch 11/15\n3125/3125 [==============================] - 122s 39ms/step - loss: 1.8299 - accuracy: 0.3357 - val_loss: 1.6618 - val_accuracy: 0.4246\n\nEpoch 00011: val_accuracy improved from 0.41380 to 0.42460, saving model to ./savemodels/cifar10-model-11-0.42.hdf5\nEpoch 12/15\n3125/3125 [==============================] - 122s 39ms/step - loss: 1.8303 - accuracy: 0.3376 - val_loss: 1.6354 - val_accuracy: 0.4210\n\nEpoch 00012: val_accuracy did not improve from 0.42460\nEpoch 13/15\n3125/3125 [==============================] - 121s 39ms/step - loss: 1.8264 - accuracy: 0.3389 - val_loss: 1.6559 - val_accuracy: 0.4060\n\nEpoch 00013: val_accuracy did not improve from 0.42460\nEpoch 14/15\n3125/3125 [==============================] - 118s 38ms/step - loss: 1.8209 - accuracy: 0.3395 - val_loss: 1.5862 - val_accuracy: 0.4338\n\nEpoch 00014: val_accuracy improved from 0.42460 to 0.43380, saving model to ./savemodels/cifar10-model-14-0.43.hdf5\nEpoch 15/15\n3125/3125 [==============================] - 117s 38ms/step - loss: 1.8229 - accuracy: 0.3391 - val_loss: 1.6355 - val_accuracy: 0.4149\n\nEpoch 00015: val_accuracy did not improve from 0.43380\n"
],
[
"epochs_range = range(15)\nvalidation_accuracy = history.history['val_accuracy']\ntraining_accuracy = history.history['accuracy']",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\nplt.plot(epochs_range, training_accuracy, 'b+', label='training accuracy')\nplt.plot(epochs_range, validation_accuracy, 'bo', label='validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Validation accuracy')\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"scores = model.evaluate(x_test, y_test, verbose=1)\n\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])",
"10000/10000 [==============================] - 3s 320us/step\nTest loss: 1.6354773641586304\nTest accuracy: 0.414900004863739\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7a7987baf283b2cc2365390b4c3db20e914f65
| 8,772 |
ipynb
|
Jupyter Notebook
|
ray-crash-course/06-Ray-multi-pool.ipynb
|
dmatrix/academy
|
dbcac28e08caf83a9d7937f3bcb2747d6f6e67ef
|
[
"Apache-2.0"
] | null | null | null |
ray-crash-course/06-Ray-multi-pool.ipynb
|
dmatrix/academy
|
dbcac28e08caf83a9d7937f3bcb2747d6f6e67ef
|
[
"Apache-2.0"
] | null | null | null |
ray-crash-course/06-Ray-multi-pool.ipynb
|
dmatrix/academy
|
dbcac28e08caf83a9d7937f3bcb2747d6f6e67ef
|
[
"Apache-2.0"
] | null | null | null | 25.8 | 709 | 0.564295 |
[
[
[
"# A Guided Tour of Ray Core: Multiprocessing Pool\n\n\n\n© 2019-2022, Anyscale. All Rights Reserved",
"_____no_output_____"
],
[
"[*Distributed multiprocessing.Pool*](https://docs.ray.io/en/latest/multiprocessing.html) makes it easy to scale existing Python applications that use [`multiprocessing.Pool`](https://docs.python.org/3/library/multiprocessing.html) by leveraging *actors*. Ray supports running distributed python programs with the **multiprocessing.Pool** API using Ray Actors, each running on a [workder node](https://docs.ray.io/en/latest/ray-core/actors.html#faq-actors-workers-and-resources), instead of local processes. This makes it easy to scale existing applications that use `multiprocessing.Pool` from a single node to a cluster.\n\n<img src=\"../images/dist_multi_pool.png\" width=\"70%\" height=\"35%\">",
"_____no_output_____"
],
[
"First, let's start Ray…",
"_____no_output_____"
]
],
[
[
"import multiprocessing as mp\nimport time\nimport logging\nimport ray",
"_____no_output_____"
]
],
[
[
"## Multiprocessing Pool example",
"_____no_output_____"
],
[
"The following is a simple Python function with a slight delay added (to make it behave like a more complex calculation)...",
"_____no_output_____"
]
],
[
[
"# this could be some complicated and compute intensive task\ndef func(x):\n time.sleep(1.5)\n return x ** 2",
"_____no_output_____"
]
],
[
[
"Then, use the Ray's drop-in replacement for [multiprocessing pool](https://docs.ray.io/en/latest/multiprocessing.html)",
"_____no_output_____"
]
],
[
[
"ray.init(\n ignore_reinit_error=True,\n logging_level=logging.ERROR,\n)",
"_____no_output_____"
]
],
[
[
"Now we'll create a *Pool* using and distribute its tasks across a cluster (or across the available cores on a laptop):",
"_____no_output_____"
]
],
[
[
"%%time\n\nfrom ray.util.multiprocessing import Pool\n\npool = Pool()\n\nfor result in pool.map(func, range(10)):\n print(result)",
"0\n1\n4\n9\n16\n25\n36\n49\n64\n81\nCPU times: user 118 ms, sys: 53.1 ms, total: 172 ms\nWall time: 3.66 s\n"
]
],
[
[
"The distributed version has the trade-off of increased overhead, although now it can scale-out horizontally across a cluster. The benefits would be more pronounced with a more computationally expensive calculation.",
"_____no_output_____"
]
],
[
[
"pool.terminate()",
"_____no_output_____"
]
],
[
[
"Let's define a compute intensive class that does some matrix computation. Consider this could be a compute intenstive task doing massive tensor transformation or computation.",
"_____no_output_____"
]
],
[
[
"def task(n):\n # Simulate a long intensive task\n #TODO\n \n # do some matrix computation \n # and return results\n return",
"_____no_output_____"
]
],
[
[
"Define a Ray remote task that launches task() across a pool of Actors on the cluster. It creates a pool of Ray Actors, each scheduled on a cluster worker.\n",
"_____no_output_____"
]
],
[
[
"@ray.remote\ndef launch_long_running_tasks(num_pool):\n # Doing the work, collecting data, updating the database\n # create an Actor pool of num_pool workers nodes\n pool = Pool(num_pool)\n results = []\n # Iterate over 50 times in batches of 10\n for result in pool.map(func, range(1, 50, 10)):\n results.append(result)\n \n # Done so terminate pool\n pool.terminate()\n \n return results",
"_____no_output_____"
]
],
[
[
"### Create a Actor like supervisor that launches all these remote tasks\n",
"_____no_output_____"
]
],
[
[
"@ray.remote\nclass LaunchDistributedTasks:\n def __init__(self, limit=5):\n self._limit = limit\n\n def launch(self):\n # launch the remote task\n return launch_long_running_tasks.remote(self._limit)",
"_____no_output_____"
]
],
[
[
"### Launch our supervisor",
"_____no_output_____"
]
],
[
[
"hdl = LaunchDistributedTasks.remote(5)\nprint(\"Launched remote jobs\")",
"Launched remote jobs\n"
]
],
[
[
"### Launched remote jobs",
"_____no_output_____"
]
],
[
[
"values = ray.get(ray.get(hdl.launch.remote()))\nprint(f\" list of results :{values}\")\nprint(f\" Total results: {len(values)}\")",
" list of results :[1, 121, 441, 961, 1681]\n Total results: 5\n"
]
],
[
[
"Finally, shutdown Ray",
"_____no_output_____"
]
],
[
[
"ray.shutdown()",
"_____no_output_____"
]
],
[
[
"### Excercises\n1. Can you convert task() into a complicated function?\n2. Use `task()` in pool.map(task,....)",
"_____no_output_____"
],
[
"### Homework\n1. Write a Python multiprocessing.pool version of task() and compare the timings with the Ray distributed multiprocessing.pool.\n2. Do you see a difference in timings?\n3. Write a distributed crawler that downloads gifs or pdfs",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb7a7f595a589ffd4d207bfbcc6e4bf540de463e
| 489,390 |
ipynb
|
Jupyter Notebook
|
2021_02_Krause_Blogpost.ipynb
|
snkrause/airbnb_revenue
|
7ecb717ce363be70da6a5ba77abe18582d8f683e
|
[
"CNRI-Python"
] | null | null | null |
2021_02_Krause_Blogpost.ipynb
|
snkrause/airbnb_revenue
|
7ecb717ce363be70da6a5ba77abe18582d8f683e
|
[
"CNRI-Python"
] | null | null | null |
2021_02_Krause_Blogpost.ipynb
|
snkrause/airbnb_revenue
|
7ecb717ce363be70da6a5ba77abe18582d8f683e
|
[
"CNRI-Python"
] | null | null | null | 350.817204 | 100,992 | 0.917877 |
[
[
[
"# <b>Blog project - Airbnb revenue maximization",
"_____no_output_____"
],
[
"## <b> What do I want to learn about the data\n\n1. What is the main factor for high revenue?\n2. Which neighbourhoods in Boston and Seattle are giving the most revenue and which ones the least?\n3. Is it more lucrative to rent out a full apartment/house or individual rooms?\n4. How important are the review scores and which one in particular?\n5. Which months are yielding the highest revenue in Boston vs. Seattle? ",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport data_prep as dp\n\npath_abnb=\"//RT01FS21.DE.BOSCH.COM/KRS1BBH$/udacity/Data_Science/project_1_blogpost/data/\"\n\n\nsns.set(font_scale=1.5)\nsns.set_style('ticks')",
"_____no_output_____"
]
],
[
[
"<b>Load AirBnB date from path_abnb:\n- the data is organized by city in folders\n- in each folder are the files\n - listings.csv\n - reviews.csv\n - calendar.csv\n- the files are parsed and in the case of listings only mutual columns are kept in the join of different city files\n- the city is then specified in the new column \"folder\"",
"_____no_output_____"
]
],
[
[
"listings, calendar, review=dp.load_data(path_abnb)",
"_____no_output_____"
]
],
[
[
"## <b>Understanding the data and preparing it for a linear regression analysis",
"_____no_output_____"
],
[
"<b>Sum revenue from calendar up for each listing and provide in new dataframe:\n- extract month of date column\n- calculate revenue by month and year\n- pivot the monthly sums by listing_id in \"calendar_revenue\"\n- provide the unpivoted data in \"calendar_stats\"",
"_____no_output_____"
]
],
[
[
"calendar_revenue, calendar_stats=dp.analyze_calendar(calendar)",
"_____no_output_____"
]
],
[
[
"<b>Preprocessing of listings:\n- df_vis is a merge of listings and the calendar_revenue results\n- df is the ML ready dataframe after the merge calender_revenue results\n - filtering of irrelevant and duplicate data\n - dropping of nan-containing rows\n - using mode to convert non-numeric columns\n - removal of \"$\" and \"%\" and conversion into numeric columns\n - in order to quantify the influence of written descriptions or amenities I simply counted the number of characters w/o an analysis if it is a good or bad description",
"_____no_output_____"
]
],
[
[
"df_vis, df=dp.preprocess_listings(listings, calendar_revenue)",
"_____no_output_____"
]
],
[
[
"<b>Plot of the revenue_year distribution<b>:\n- most of the distribution is between 0 and \\\\$200000\n- there are lots of outliers above\n- I chose \\\\$150000 as a cut-off to allow my linear regression model to find a stabil solution",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(20,8))\np2=sns.histplot(data=df_vis, x='revenue_year')\np2.axvline(150000)\nplt.show()",
"_____no_output_____"
]
],
[
[
"<b>Plot of the distribution of \"accommodates:\n- the overall distribution is quite similar between the two cities\n- Boston has more single person listings\n- after 8 persons there are only few listings, which is why I chose to put a cut-off there",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10,5))\np3=sns.histplot(data=df_vis, x=\"accommodates\", hue=\"folder\", stat=\"probability\", common_norm=False, multiple=\"dodge\")\np3.axvline(8.5)\nplt.show()",
"_____no_output_____"
]
],
[
[
"<b>Plot of listings per \"neighbourhood_cleansed\" and \"property_type\":\n- in the first trials to apply a linear regression model the neighbourhoods with few listings disturbed the modelling\n- I defined a cut-off at a minimum of 10 listings for a neighbourhood/p to be included",
"_____no_output_____"
]
],
[
[
"neighbourhoods=df_vis['neighbourhood_cleansed'].value_counts().reset_index().rename(columns={'index':'neighbourhood_cleansed', 'neighbourhood_cleansed':'counts'})\nplt.figure(figsize=(17,7.5))\np3=sns.barplot(x=\"neighbourhood_cleansed\", y=\"counts\", data=neighbourhoods)\np3.axhline(10)\nplt.xticks(rotation=90, fontsize=9)\nplt.show()",
"_____no_output_____"
],
[
"property_type=df_vis['property_type'].value_counts().reset_index().rename(columns={'index':'property_type', 'property_type':'counts'})\nplt.figure(figsize=(17,7.5))\np3=sns.barplot(x=\"property_type\", y=\"counts\", data=property_type)\np3.axhline(20)\nplt.xticks(rotation=90, fontsize=9)\nplt.show()",
"_____no_output_____"
]
],
[
[
"## <b>Setting up the model and applying it to the data",
"_____no_output_____"
],
[
"I now applied a <b>linear modelling</b> to my dataset df to find the strongest influences to yearly revenue\n- for that I dropped all columns that are duplicate (e.g., folder) or contain revenue information\n- the r-squared is quite alright with about <b>0.73</b> for this",
"_____no_output_____"
]
],
[
[
"target='revenue_year'\ndrop=['revenue_year',1,2,3,4,5,6,7,8,9,10,11,12,'folder_Boston','folder_Seattle','revenue_month_mean']\nlm_model_rev, X_train_rev=dp.regression_model(df,target, drop)",
"The r-squared score for your model was 0.7282541880332372 on 1369 values.\n"
]
],
[
[
"First I looked at the features that <b>positively</b> influence my revenue:\n\nThe answer is not surprising for any realtor... <b>location, location, location</b>\n\nThe top 20 features that <b>negatively</b> influence my revenue are property types and location",
"_____no_output_____"
],
[
"## <b> Evalution of the results and their interpretation",
"_____no_output_____"
]
],
[
[
"#Use the function and look at the top 30 \ncoef_df_rev = dp.coef_weights(lm_model_rev.coef_, X_train_rev)\ncoef_df_rev.nlargest(20,'coefs')",
"_____no_output_____"
],
[
"coef_df_rev.nsmallest(20,'coefs')",
"_____no_output_____"
]
],
[
[
"The top influences were all neighbourhoods, but I also wanted to know which of the review scores \n- location is also here the number 1\n- cleanliness is number 2",
"_____no_output_____"
]
],
[
[
"coef_df_rev[coef_df_rev['est_int'].str[0:6]=='review'].sort_values('coefs', ascending=False)",
"_____no_output_____"
]
],
[
[
"The description of the listing or the neighbourhood seems rather unimportant. Only the number of listed amenities seems to count. A rather long name seems to be more repelling than inviting.",
"_____no_output_____"
]
],
[
[
"coef_df_rev[coef_df_rev['est_int'].str[-5:]=='count'].sort_values('coefs', ascending=False)",
"_____no_output_____"
],
[
"coef_df_rev[coef_df_rev['est_int'].str[0:5]=='prope'].sort_values('coefs', ascending=False)",
"_____no_output_____"
],
[
"coef_df_rev[coef_df_rev['est_int'].str[0:5]=='accom'].sort_values('coefs', ascending=False)",
"_____no_output_____"
]
],
[
[
"The plot of the yearly revenue by neighbourhood reflects the results of the linear model",
"_____no_output_____"
]
],
[
[
"df_2=df_plot.groupby(by=['neighbourhood_cleansed','folder'], as_index=False)['revenue_year'].median()\nplt.figure(figsize=(15,6))\np6=sns.scatterplot(data=df_2.nlargest(20,'revenue_year'), x=\"neighbourhood_cleansed\", y=\"revenue_year\", hue=\"folder\")\nplt.xticks(rotation=90)\nplt.show()\nplt.figure(figsize=(15,6))\np7=sns.scatterplot(data=df_2.nsmallest(20,'revenue_year'), x=\"neighbourhood_cleansed\", y=\"revenue_year\", hue=\"folder\")\nplt.xticks(rotation=90)\nplt.show()",
"_____no_output_____"
]
],
[
[
"How do Boston and Seattle compare in the average revenue per month over a year?",
"_____no_output_____"
]
],
[
[
"df_plot_month=df_plot.merge(calendar_stats, left_on=['id','folder'],right_on=['listing_id','folder'])\ndf_plot_month_2=df_plot_month.groupby(by=['month','folder'], as_index=False)['revenue'].median()",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,5))\np8=sns.scatterplot(data=df_plot_month_2, x=\"month\", y=\"revenue\", hue=\"folder\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"<b>df_plot</b> is the version of df_vis that has all those previous cut-offs applied",
"_____no_output_____"
]
],
[
[
"df_plot=df_vis[(df_vis['revenue_year']<150000)&(df_vis['accommodates']<8.5)]\nneighbourhoods=df_plot['neighbourhood_cleansed'].value_counts().reset_index()\nremove_list=neighbourhoods[neighbourhoods['neighbourhood_cleansed']<10]['index'].to_list()\ndf_plot=df_plot[~df_plot['neighbourhood_cleansed'].isin(remove_list)]",
"_____no_output_____"
]
],
[
[
"In this plot the <b>revenue_year</b> is plotted against the number of people a listing <b>accommodates</b>\n- Up to 8 people it is a near linear function\n- the slope of it is not 1 though\n- therefore you can expect more revenue per person for smaller listings",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(12,7))\np5=sns.regplot(data=df_plot.groupby(by=['accommodates'], as_index=False)['revenue_year'].mean(), x=\"accommodates\", y=\"revenue_year\",ci=None)#, hue=\"folder\")\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7a8064e26cd697d7aa761c04158e1fab618b8d
| 9,536 |
ipynb
|
Jupyter Notebook
|
Compiled Competition #04 Code.ipynb
|
jamesgsw/Shopee-Code-League-2020
|
8aeebddfdf81457ceb4735c9c4d784737aef967f
|
[
"Apache-2.0"
] | null | null | null |
Compiled Competition #04 Code.ipynb
|
jamesgsw/Shopee-Code-League-2020
|
8aeebddfdf81457ceb4735c9c4d784737aef967f
|
[
"Apache-2.0"
] | null | null | null |
Compiled Competition #04 Code.ipynb
|
jamesgsw/Shopee-Code-League-2020
|
8aeebddfdf81457ceb4735c9c4d784737aef967f
|
[
"Apache-2.0"
] | null | null | null | 101.446809 | 1,503 | 0.699874 |
[
[
[
"# 1. Importing Relevant Libraries",
"_____no_output_____"
]
],
[
[
"import datetime\nimport pandas as pd\nimport math\nimport numpy as np",
"_____no_output_____"
],
[
"#Mounting Kaggle Drive\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n for filename in filenames:\n print(os.path.join(dirname, filename))",
"_____no_output_____"
],
[
"df_orders = pd.read_csv(\"/kaggle/input/challenge04-dataset/delivery_orders_march.csv\")\ndf_sla = pd.read_csv(\"/kaggle/input/shopeechallenge04dataset/SLA.csv\")",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb7a818f37e160e620b765796e6fd56f24573565
| 1,004,753 |
ipynb
|
Jupyter Notebook
|
3D_param_regimes_sweep_stats.ipynb
|
rkp8000/seq_speak
|
dfac742952d57c436fb5a07f251ce83b9f2d8fb2
|
[
"MIT"
] | null | null | null |
3D_param_regimes_sweep_stats.ipynb
|
rkp8000/seq_speak
|
dfac742952d57c436fb5a07f251ce83b9f2d8fb2
|
[
"MIT"
] | null | null | null |
3D_param_regimes_sweep_stats.ipynb
|
rkp8000/seq_speak
|
dfac742952d57c436fb5a07f251ce83b9f2d8fb2
|
[
"MIT"
] | 3 |
2019-05-28T11:34:31.000Z
|
2021-04-25T16:41:07.000Z
| 1,207.635817 | 149,228 | 0.954665 |
[
[
[
"# Graphical view of param sweep results (Figure 3A-C, G)",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nfrom copy import deepcopy as copy\nimport json\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom disp import set_font_size, set_n_x_ticks, set_n_y_ticks\nfrom replay import analysis\n\ncc = np.concatenate\n\n\nHMAP_PARAMS = {\n 'FR_NTRJ_MIN_BLOWUP': 1.5, # Hz\n 'FR_NTRJ_TRJ_BLOWUP_RATIO': .3, # frac\n 'MIN_EVTS_ONE_WAY_FRAC_CALC': 5,\n 'MIN_EVTS_SPD_CALC': 5,\n 'MIN_SPD_SPD_CALC': 10, # m/s\n}\n\nSCT_SIZE = 150\nW_SCALE_PLOT = .05/.0005 # T_M_PC/DT\n\ndef evt_frq_hmap(f_name, v_mins, v_maxs, x_ticks, c_ticks, hmap_params):\n \"\"\"Make heatmaps of spontaneous replay event frequency given param sweep file.\"\"\"\n \n df, rslts, header = analysis.make_df(f_name)\n params_varied = header['params_varied']\n assert len(params_varied) == 2\n \n n_trials = header['sweep_params']['N_TRIALS']\n dur = header['s_params']['schedule']['D_SMLN'] - header['a_params']['MIN_START']\n \n # get data into numpy arrays\n p_0 = np.array(df[params_varied[0]])\n p_1 = np.array(df[params_varied[1]])\n \n if params_varied[0].startswith('W_PC'):\n p_0 = p_0 * W_SCALE_PLOT\n \n if params_varied[1].startswith('W_PC'):\n p_1 = p_1 * W_SCALE_PLOT\n \n p_0_min = np.min(p_0)\n p_0_max = np.max(p_0)\n p_0_range = p_0_max - p_0_min\n \n p_1_min = np.min(p_1)\n p_1_max = np.max(p_1)\n p_1_range = p_1_max - p_1_min\n \n fr_trj = np.array(df['FR_TRJ'])\n fr_ntrj = np.array(df['FR_NTRJ'])\n \n print('Min fr_trj = ', np.nanmin(fr_trj), 'Hz')\n print('Max fr_trj = ', np.nanmax(fr_trj), 'Hz')\n print('Min fr_ntrj = ', np.nanmin(fr_ntrj), 'Hz')\n print('Max fr_ntrj = ', np.nanmax(fr_ntrj), 'Hz')\n \n evt_ct = np.array(df['EVT_CT'])\n evt_frq = evt_ct / dur\n \n print('Min evt_ct = ', np.min(evt_ct))\n print('Max evt_ct = ', np.max(evt_ct))\n print('Min evt_frq = ', np.min(evt_frq), 'Hz')\n print('Max evt_frq = ', np.max(evt_frq), 'Hz')\n \n one_way_ct = np.array(df['ONE_WAY_CT'])\n one_way_frq = one_way_ct / dur\n \n print('Min one_way_ct', np.min(one_way_ct))\n print('Max one_way_ct', np.max(one_way_ct))\n \n # make plots\n fig, axs = plt.subplots(3, 2, figsize=(12.5, 15), tight_layout=True)\n \n ## fr trj\n im_00 = axs[0, 0].scatter(p_0, p_1, SCT_SIZE, c=fr_trj, marker='s', vmin=v_mins['fr_trj'], vmax=v_maxs['fr_trj'])\n axs[0, 0].set_title('LTP-IE-tagged firing rates')\n cb_00 = fig.colorbar(im_00, ax=axs[0, 0])\n cb_00.set_label('Firing rate (Hz)', fontsize=16)\n\n ## fr ntrj\n im_01 = axs[0, 1].scatter(p_0, p_1, SCT_SIZE, c=fr_ntrj, marker='s', vmin=v_mins['fr_ntrj'], vmax=v_maxs['fr_ntrj'])\n axs[0, 1].set_title('Non-LTP-IE-tagged firing rates')\n cb_01 = fig.colorbar(im_01, ax=axs[0, 1])\n cb_01.set_label('Firing rate (Hz)', fontsize=16)\n \n ## evt frq\n im_10 = axs[1, 0].scatter(p_0, p_1, SCT_SIZE, c=evt_frq, marker='s', vmin=v_mins['evt_frq'], vmax=v_maxs['evt_frq'])\n axs[1, 0].set_title('Event frequency')\n cb_10 = fig.colorbar(im_10, ax=axs[1, 0])\n cb_10.set_label('Event frequency (Hz)', fontsize=16)\n \n ## replay zones\n ### plot event freq\n im_11 = axs[1, 1].scatter(\n p_0, p_1, SCT_SIZE, c=evt_frq, marker='s', vmin=v_mins['evt_frq'], vmax=v_maxs['evt_frq'], cmap='plasma', zorder=0)\n axs[1, 1].set_title('Replay regimes')\n cb_11 = fig.colorbar(im_11, ax=axs[1, 1], ticks=c_ticks)\n cb_11.set_label('Event frequency (Hz)', fontsize=16)\n \n ### set blowup vals to green\n mask = \\\n (fr_ntrj >= hmap_params['FR_NTRJ_MIN_BLOWUP']) \\\n | (fr_ntrj / fr_trj >= hmap_params['FR_NTRJ_TRJ_BLOWUP_RATIO'])\n axs[1, 1].scatter(\n p_0[mask], p_1[mask], SCT_SIZE+2, c='k', marker='s', zorder=2)\n \n c_tick_labels = [str(c_tick) for c_tick in c_ticks]\n c_tick_labels[-1] = '>{}'.format(c_ticks[-1])\n\n cb_11.ax.set_yticklabels(c_tick_labels)\n \n ## plot frequency of one-way events\n im_20 = axs[2, 0].scatter(p_0, p_1, SCT_SIZE, c=one_way_frq, marker='s', vmin=v_mins['evt_frq'], vmax=v_maxs['evt_frq'])\n axs[2, 0].set_title('One-way frequency')\n cb_20 = fig.colorbar(im_20, ax=axs[2, 0])\n cb_20.set_label('One-way frequency (Hz)', fontsize=16)\n \n ## plot fraction of one-way events\n ### put trial-wise total event counts into np array\n evt_cts_trials = np.transpose([np.array(df['EVT_CT_{}'.format(ctr)]) for ctr in range(n_trials)])\n ### put trial-wise one-way event counts into np array\n one_way_cts_trials = np.transpose([np.array(df['ONE_WAY_CT_{}'.format(ctr)]) for ctr in range(n_trials)])\n \n ### get trial-wise one-way count fractions\n #### set evt cts to nan if less than min evts to use for one-way frac calc\n evt_cts_trials[evt_cts_trials < hmap_params['MIN_EVTS_ONE_WAY_FRAC_CALC']]\n #### divide\n one_way_fracs_trials = one_way_cts_trials / evt_cts_trials\n #### take mean across trials\n one_way_fracs = np.nanmean(one_way_fracs_trials, axis=1)\n \n ## plot one-way event fractions\n im_21 = axs[2, 1].scatter(p_0, p_1, SCT_SIZE, c=one_way_fracs, vmin=0, vmax=1, marker='s', cmap='cool')\n axs[2, 1].set_title('Unidirectional replay')\n cb_21 = fig.colorbar(im_21, ax=axs[2, 1])\n cb_21.set_label('Fraction unidirectional', fontsize=16)\n \n ## set blowup vals to green\n mask = \\\n (fr_ntrj >= hmap_params['FR_NTRJ_MIN_BLOWUP']) \\\n | (fr_ntrj / fr_trj >= hmap_params['FR_NTRJ_TRJ_BLOWUP_RATIO'])\n axs[2, 1].scatter(\n p_0[mask], p_1[mask], SCT_SIZE+2, c='k', marker='s', zorder=2)\n \n for ax in axs.flatten():\n \n ax.set_xlim(p_0_min - .05*p_0_range, p_0_max + .05*p_0_range)\n ax.set_ylim(p_1_min - .05*p_1_range, p_1_max + .05*p_1_range)\n \n if x_ticks is not None:\n ax.set_xticks(x_ticks)\n \n ax.set_xlabel(params_varied[0])\n ax.set_ylabel(params_varied[1])\n \n ax.set_facecolor((.8, .8, .8))\n set_font_size(ax, 16)\n \n set_font_size(axs[2, 1], 20)\n \n for cb in [cb_00, cb_01, cb_10, cb_11]:\n \n set_font_size(cb.ax, 16)\n \n set_font_size(cb_21.ax, 20)\n \n return df, rslts, header",
"_____no_output_____"
]
],
[
[
"## Dynamics vs $\\lambda^{PC,PC}$ and $w^{PC,PC}$ (Figure 3B)",
"_____no_output_____"
]
],
[
[
"v_mins = {'fr_trj': 0, 'fr_ntrj': 0, 'evt_frq': 0}\nv_maxs = {'fr_trj': 10, 'fr_ntrj': 10, 'evt_frq': 4}\nx_ticks = [2, 2.5, 3, 3.5, 4]\nc_ticks = [0, 1, 2, 3, 4]\n\ndfs, rslts, header = evt_frq_hmap(\n 'PARAM_SWEEP_RESULTS_0_W_PC_PC_L_PC_PC.txt',\n v_mins, v_maxs, x_ticks, c_ticks,\n HMAP_PARAMS)",
"/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n"
]
],
[
[
"## Dynamics vs $w^{PC,PC}$ and $w^{PC,INH}$ (Figure 3A)",
"_____no_output_____"
]
],
[
[
"v_mins = {'fr_trj': 0, 'fr_ntrj': 0, 'evt_frq': 0}\nv_maxs = {'fr_trj': 10, 'fr_ntrj': 10, 'evt_frq': 4}\nx_ticks = [0.0, .02, 0.04, 0.06]\nc_ticks = [0, 1, 2, 3, 4]\n\ndfs, rslts, header = evt_frq_hmap(\n 'PARAM_SWEEP_RESULTS_1_W_PC_PC_W_PC_INH.txt',\n v_mins, v_maxs, x_ticks, c_ticks,\n HMAP_PARAMS)",
"/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n"
]
],
[
[
"## Additional param sweep (not in manuscript)",
"_____no_output_____"
]
],
[
[
"v_mins = {'fr_trj': 0, 'fr_ntrj': 0, 'evt_frq': 0}\nv_maxs = {'fr_trj': 10, 'fr_ntrj': 10, 'evt_frq': 4}\nx_ticks = [2, 2.5, 3, 3.5, 4]\nc_ticks = [0, 1, 2, 3, 4]\n\ndfs, rslts, header = evt_frq_hmap(\n 'PARAM_SWEEP_RESULTS_2_W_PC_PC_SGM_MAX.txt',\n v_mins, v_maxs, x_ticks, c_ticks,\n HMAP_PARAMS)",
"/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n"
]
],
[
[
"## Additional param sweep (not in manuscript)",
"_____no_output_____"
]
],
[
[
"v_mins = {'fr_trj': 0, 'fr_ntrj': 0, 'evt_frq': 0}\nv_maxs = {'fr_trj': 10, 'fr_ntrj': 10, 'evt_frq': 4}\nx_ticks = [0.0, .02, 0.04, 0.06]\nc_ticks = [0, 1, 2, 3, 4]\n\ndfs, rslts, header = evt_frq_hmap(\n 'PARAM_SWEEP_RESULTS_3_L_PC_PC_W_PC_INH.txt',\n v_mins, v_maxs, x_ticks, c_ticks,\n HMAP_PARAMS)",
"/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n"
]
],
[
[
"## Dynamics vs $r^G$ and $\\sigma_{max}$ (Figure 3C)",
"_____no_output_____"
]
],
[
[
"v_mins = {'fr_trj': 0, 'fr_ntrj': 0, 'evt_frq': 0}\nv_maxs = {'fr_trj': 10, 'fr_ntrj': 10, 'evt_frq': 4}\nx_ticks = None # [0.0, .0002, 0.0004, 0.0006]\nc_ticks = [0, 1, 2, 3, 4]\n\ndfs, rslts, header = evt_frq_hmap(\n 'PARAM_SWEEP_RESULTS_4_R_G_SGM_MAX.txt',\n v_mins, v_maxs, x_ticks, c_ticks,\n HMAP_PARAMS)",
"/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n"
]
],
[
[
"## Additional param sweep (not in manuscript)",
"_____no_output_____"
]
],
[
[
"v_mins = {'fr_trj': 0, 'fr_ntrj': 0, 'evt_frq': 0}\nv_maxs = {'fr_trj': 10, 'fr_ntrj': 10, 'evt_frq': 6}\nx_ticks = None # [0.0, .0002, 0.0004, 0.0006]\nc_ticks = [0, 1, 2, 3, 4]\n\ndfs, rslts, header = evt_frq_hmap(\n 'PARAM_SWEEP_RESULTS_5_R_G_W_PC_INH.txt',\n v_mins, v_maxs, x_ticks, c_ticks,\n HMAP_PARAMS)",
"/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n"
]
],
[
[
"## Additional param sweep (not in manuscript)",
"_____no_output_____"
]
],
[
[
"v_mins = {'fr_trj': 0, 'fr_ntrj': 0, 'evt_frq': 0}\nv_maxs = {'fr_trj': 10, 'fr_ntrj': 10, 'evt_frq': 6}\nx_ticks = None # [0.0, .0002, 0.0004, 0.0006]\nc_ticks = [0, 1, 2, 3, 4]\n\ndfs, rslts, header = evt_frq_hmap(\n 'PARAM_SWEEP_RESULTS_6_R_G_W_PC_G.txt',\n v_mins, v_maxs, x_ticks, c_ticks,\n HMAP_PARAMS)",
"/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/fromnumeric.py:2920: RuntimeWarning: Mean of empty slice.\n out=out, **kwargs)\n/home/rkp/miniconda3/envs/sci/lib/python3.5/site-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars\n ret = ret.dtype.type(ret / rcount)\n"
]
],
[
[
"## Replay speed param sweep (Figure 3G)",
"_____no_output_____"
]
],
[
[
"def plot_speed_hmap(f_name, v_min, v_max, fig_w=6.5, n_x_ticks=5):\n \"\"\"Plot heatmap of triggered replay speeds.\"\"\"\n # load dataframe\n df, rslts, header = analysis.make_df_ext(f_name)\n \n fig, ax = plt.subplots(1, 1, figsize=(fig_w, 5.5), tight_layout=True)\n mask = (df['EVT_CT'] >= HMAP_PARAMS['MIN_EVTS_SPD_CALC']) & (df['SPD_MIN'] >= HMAP_PARAMS['MIN_SPD_SPD_CALC'])\n \n df_valid = df[mask]\n \n param_0, param_1 = header['params_varied']\n p_0 = df_valid[param_0]\n p_1 = df_valid[param_1]\n \n if param_0.startswith('W_PC'):\n p_0 = p_0 * W_SCALE_PLOT\n \n if param_1.startswith('W_PC'):\n p_1 = p_1 * W_SCALE_PLOT\n \n im = ax.scatter(\n p_0, p_1, c=df_valid['SPD_MED'], vmin=v_min, vmax=v_max,\n s=SCT_SIZE, marker='s')\n \n cb = fig.colorbar(im, ax=ax)\n cb.set_label('Speed (m/s)')\n \n print('PARAMS:', header['m_params'])\n \n ax.set_xlim(p_0.min(), p_0.max())\n ax.set_ylim(p_1.min(), p_1.max())\n \n ax.set_facecolor((.8, .8, .8))\n \n set_n_x_ticks(ax, n_x_ticks)\n ax.set_xlabel(param_0)\n ax.set_ylabel(param_1)\n \n ax.set_title('Replay speed')\n \n set_font_size(ax, 20)\n set_font_size(cb.ax, 20)",
"_____no_output_____"
],
[
"plot_speed_hmap('PARAM_SWEEP_RESULTS_EXT_0_W_PC_PC_L_PC_PC.txt', v_min=None, v_max=None, fig_w=6.5)",
"PARAMS: {'N_PC': 3000, 'E_L_INH': -0.06, 'R_G': 125, 'S_PC_G': 0, 'N_INH': 300, 'W_PC_INH': 0.0002, 'S_PC_PL': 0, 'T_M_PC': 0.05, 'E_L_PC': -0.068, 'E_I': -0.08, 'V_R_PC': -0.068, 'T_E': 0.002, 'T_M_INH': 0.005, 'L_PL': 0.15, 'T_I': 0.002, 'T_R_INH': 0.002, 'T_R_PC': 0.008, 'W_PC_PC': 0.026, 'W_MIN_PC_PC': 0.001, 'W_INH_PC': 0.003, 'W_PC_PL': 0.02, 'B_SGM': 1, 'V_TH_INH': -0.05, 'E_E': 0, 'V_R_INH': -0.06, 'L_PC_PC': 0.053, 'V_TH_PC': -0.036, 'W_PC_G': 0.008216, 'R_SGM': 10, 'SGM_MAX': 2, 'R_MAX': 20}\n"
]
],
[
[
"## Additional param sweep for replay speed (not in manuscript)",
"_____no_output_____"
]
],
[
[
"plot_speed_hmap('PARAM_SWEEP_RESULTS_EXT_1_W_PC_PC_W_PC_INH.txt', v_min=10, v_max=None, fig_w=7, n_x_ticks=4)",
"PARAMS: {'N_PC': 3000, 'E_L_INH': -0.06, 'S_PC_PL': 0, 'S_PC_G': 0, 'N_INH': 300, 'T_M_PC': 0.05, 'V_R_PC': -0.068, 'W_PC_INH': 0.0002, 'E_L_PC': -0.068, 'E_I': -0.08, 'V_TH_INH': -0.05, 'R_G': 125, 'T_M_INH': 0.005, 'T_E': 0.002, 'W_PC_PL': 0.02, 'L_PL': 0.15, 'T_I': 0.002, 'T_R_INH': 0.002, 'T_R_PC': 0.008, 'W_PC_PC': 0.026, 'W_INH_PC': 0.003, 'B_SGM': 1, 'W_MIN_PC_PC': 0.001, 'E_E': 0, 'V_R_INH': -0.06, 'L_PC_PC': 0.053, 'V_TH_PC': -0.036, 'W_PC_G': 0.008216, 'R_SGM': 10, 'SGM_MAX': 2, 'R_MAX': 20}\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7a9ea92a48b537e01dbe4fb71389e81ea3c97d
| 8,702 |
ipynb
|
Jupyter Notebook
|
site/id/tutorials/quickstart/beginner.ipynb
|
akalakheti/docs
|
ad602b40f8f968520d21ae81e304dde80861f745
|
[
"Apache-2.0"
] | 3 |
2020-01-09T02:58:22.000Z
|
2020-09-11T09:02:01.000Z
|
site/id/tutorials/quickstart/beginner.ipynb
|
akalakheti/docs
|
ad602b40f8f968520d21ae81e304dde80861f745
|
[
"Apache-2.0"
] | 1 |
2020-01-11T03:55:25.000Z
|
2020-01-11T03:55:25.000Z
|
site/id/tutorials/quickstart/beginner.ipynb
|
akalakheti/docs
|
ad602b40f8f968520d21ae81e304dde80861f745
|
[
"Apache-2.0"
] | 2 |
2020-01-15T21:50:31.000Z
|
2020-01-15T21:56:30.000Z
| 33.859922 | 351 | 0.550218 |
[
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# TensorFlow 2 quickstart for beginners",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/quickstart/beginner\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />Lihat di TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/id/tutorials/quickstart/beginner.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Jalankan di Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/id/tutorials/quickstart/beginner.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />Lihat sumber kode di GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/id/tutorials/quickstart/beginner.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Unduh notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"Note: Komunitas TensorFlow kami telah menerjemahkan dokumen-dokumen ini. Tidak ada jaminan bahwa translasi ini akurat, dan translasi terbaru dari [Official Dokumentasi - Bahasa Inggris](https://www.tensorflow.org/?hl=en) karena komunitas translasi ini adalah usaha terbaik dari komunitas translasi.\nJika Anda memiliki saran untuk meningkatkan terjemahan ini, silakan kirim pull request ke [tensorflow/docs](https://github.com/tensorflow/docs) repositori GitHub.\nUntuk menjadi sukarelawan untuk menulis atau memeriksa terjemahan komunitas, hubungi\n[daftar [email protected]](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs).",
"_____no_output_____"
],
[
"Panduan singkat ini akan menggunakan [Keras](https://www.tensorflow.org/guide/keras/overview) untuk:\n\n1. Membangun jaringan saraf tiruan yang mengklasifikasikan gambar.\n2. Melatih jaringan saraf tiruan tersebut.\n3. Dan, pada akhirnya, mengevaluasi keakuratan dari model.",
"_____no_output_____"
],
[
"Ini adalah file notebook [Google Colaboratory](https://colab.research.google.com/notebooks/welcome.ipynb). Program python akan dijalankan langsung dari browser — cara yang bagus untuk mempelajari dan menggunakan TensorFlow. Untuk mengikuti tutorial ini, jalankan notebook di Google Colab dengan mengklik tombol di bagian atas halaman ini.\n\n1. Di halaman Colab, sambungkan ke runtime Python: Di menu sebelah kanan atas, pilih * CONNECT *.\n2. Untuk menjalankan semua sel kode pada notebook: Pilih * Runtime *> * Run all *.",
"_____no_output_____"
],
[
"Download dan instal TensorFlow 2 dan impor TensorFlow ke dalam program Anda:",
"_____no_output_____"
]
],
[
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\n# Install TensorFlow\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\n\nimport tensorflow as tf",
"_____no_output_____"
]
],
[
[
"Siapkan [dataset MNIST](http://yann.lecun.com/exdb/mnist/). Ubah sampel dari bilangan bulat menjadi angka floating-point (desimal):",
"_____no_output_____"
]
],
[
[
"mnist = tf.keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train, x_test = x_train / 255.0, x_test / 255.0",
"_____no_output_____"
]
],
[
[
"Build model `tf.keras.Sequential` dengan cara menumpuk lapisan layer. Untuk melatih data, pilih fungsi untuk mengoptimalkan dan fungsi untuk menghitung kerugian:",
"_____no_output_____"
]
],
[
[
"model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
]
],
[
[
"Melatih dan mengevaluasi model:",
"_____no_output_____"
]
],
[
[
"model.fit(x_train, y_train, epochs=5)\n\nmodel.evaluate(x_test, y_test, verbose=2)",
"_____no_output_____"
]
],
[
[
"Penggolong gambar tersebut, sekarang dilatih untuk akurasi ~ 98% pada dataset ini. Untuk mempelajari lebih lanjut, baca [tutorial TensorFlow](https://www.tensorflow.org/tutorials/).",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7ab6c8febcd8667e9a349da23eae955ddb2861
| 76,717 |
ipynb
|
Jupyter Notebook
|
1_InterpretingFeatures/TemplateMatching.ipynb
|
mgalbright/Keras-Exercises
|
cc9ec6b7a2873584f6b104b1fa0edc0231a48509
|
[
"MIT"
] | 1 |
2018-03-20T12:00:59.000Z
|
2018-03-20T12:00:59.000Z
|
1_InterpretingFeatures/TemplateMatching.ipynb
|
mgalbright/Keras-Exercises
|
cc9ec6b7a2873584f6b104b1fa0edc0231a48509
|
[
"MIT"
] | null | null | null |
1_InterpretingFeatures/TemplateMatching.ipynb
|
mgalbright/Keras-Exercises
|
cc9ec6b7a2873584f6b104b1fa0edc0231a48509
|
[
"MIT"
] | null | null | null | 100.414921 | 16,480 | 0.83911 |
[
[
[
"# Interpreting Neural Network Weights\n\nNeural nets (especially deep neural nets) are some of the most powerful machine learning algorithms available. However, it can be difficult to understand (intuitively) how they work. \n\nIn the first part of this notebook, I highlight the connection between neural networks and template matching--a simple technique for classification that is popular in computer vision and signal processing. I find this observation is helpful for intution about how neural nets classify images--I hope you find this useful too!\n\nIn the second part of the notebook, I point out that for convolutional neural nets it can be helpful to think of weights as sliding filters (e.g. edge detecting filters) which in the early network layers detect low-level image features .\n\n## Template Matching\n\n[Template matching](https://en.wikipedia.org/wiki/Template_matching) is used in computer vision to compare images. It does this by treating images as vectors and computing their dot product: very similar images give a large dot product, and very disimilar images give a small (or negative) dot product. Why?\n\nMathematically, if you represent images as vectors, you can compute the difference between two images $I_1$ and $I_2$ like \n$$|I_1 - I_2 |^2 = |I_1|^2 + |I_2|^2 - 2 \\, I_1 \\cdot I_2$$ \nNote that the dot product $I_1 \\cdot I_2$ between two images is largest when the difference $|I_1 - I_2|$ between images is smallest, and vice versa. \n\nFor example, here's a template for each digit:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport cv2\n\ntemplates = []\n\nfor i in range(10):\n img = cv2.imread(\"templates/{}.png\".format(str(i)), cv2.IMREAD_GRAYSCALE)\n if img is None:\n raise Exception(\"Error: Failed to load image {}\".format(i))\n \n templates.append(img)\n \n plt.subplot(2, 5, 1 + i)\n plt.imshow(img, cmap=plt.get_cmap('gray'))\nplt.show() \n",
"_____no_output_____"
]
],
[
[
"We can illustrate template matching by computing the dot products between digit 1 and every other digit. To make the results more robust, we compute the normalized dot product \n$$ \\frac{I_1 \\cdot I_2}{|I_1| |I_2|}$$\n(It's important to normalize the dot product--otherwise brighter images will give stronger matches than darker ones, and that would not make sense.) ",
"_____no_output_____"
]
],
[
[
"img = templates[1]\n\nfor i in range(10):\n template = templates[i]\n print(\" Normalized dot product between 1 and {} = {}\".format(i, \n cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED )[0][0] ))",
" Normalized dot product between 1 and 0 = 0.9185173511505127\n Normalized dot product between 1 and 1 = 1.0\n Normalized dot product between 1 and 2 = 0.9375543594360352\n Normalized dot product between 1 and 3 = 0.9283716678619385\n Normalized dot product between 1 and 4 = 0.9515999555587769\n Normalized dot product between 1 and 5 = 0.9398891925811768\n Normalized dot product between 1 and 6 = 0.9233077168464661\n Normalized dot product between 1 and 7 = 0.9516004323959351\n Normalized dot product between 1 and 8 = 0.918259859085083\n Normalized dot product between 1 and 9 = 0.9280534386634827\n"
]
],
[
[
"We can see that 1 is more strongly correlated to 1 than any other digit. That's the principle behind template matching--it can measure image similarity. \n\nUnfortunately, template matching is not robust to changes in image shapes, sizes, rotations, or partial occlusion. However, neural nets can be very robust to such image defects--that's why they are more powerful.",
"_____no_output_____"
],
[
"## Viewing Neural Network Weights as Templates\n\nIn a neuron inside neural net, inputs $x$ (a vector) are combined with weights $W$ (another vector) to generate an output. Pictorally\n\n<img src=\"figs/neuron.png\" style=\"width: 250px;\">\n\nThe output of the neuron is computed by \n$$ f( W \\cdot x + b) $$ \nwhere $f$ is called the *activation function* and b is called the *bias term*. Most important for this discussion, the dot product $W \\cdot x$ resembles template matching.\n\nAs we will show, in very simple neural nets (sometimes called *linear classifiers*) we can interpret the weights $W$ as templates--the neural net learns how to perform template matching!\n\nWe want to make a linear classifier to recognize digits 0-9. We implement a softmax architecture (shown below) with 10 outputs. For example, if digit 7 is recognized, neuron 7 will have an output close to 1 and the remaining neurons will have outputs close to 0. (FYI, this means we will have to one-hot encode the labels before training.)\nThe input (the image) is $x$, which we draw as a flattened (1d) vector. There are 10 weight vectors $W_0$ - $W_9$ (one for each neuron).\n\n<img src=\"figs/nnet.png\" style=\"width: 400px;\"> \n\nWe write the $i^{\\mathrm th}$ output as \n$$ \\mathrm{output}_i = f( W_{i} \\cdot x + b_i)$$\n\nAs we said, we expect each weight vector $W_i$ learned during training will be a template for digit $i$.\n\nLet's train the neural net on the MNIST data set (a set of 70,000 images of hand-written digits 0-9.) We'll use Keras to implement and train the neural net.",
"_____no_output_____"
]
],
[
[
"#Developed with Keras 2.0.2 and the tensorflow backend\n\n#Load the MNIST data set of handwritten digits 0-9:\nimport numpy as np\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n#Invert the image colors, convert to float, and normalize values:\nx_train = (255 - x_train).astype('float')/255.0\nx_test = (255 - x_test).astype('float')/255.0\n\n# plot first 5 images\nfor i in range(5):\n plt.subplot(1, 5, 1+i)\n plt.imshow(x_train[i], cmap=plt.get_cmap('gray'))\nplt.show()\n\n#Let's flatten the images to 1-d vectors for processing\nimage_shape = (28, 28)\nnum_pixels = 28*28\nx_train = x_train.reshape(x_train.shape[0], num_pixels)\nx_test = x_test.reshape(x_test.shape[0], num_pixels)",
"Using TensorFlow backend.\n"
],
[
"#Now let's one-hot encode the target variable before training\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\n\nnum_classes = y_test.shape[1]",
"_____no_output_____"
]
],
[
[
"We can see that after 1-hot encoding, each digit label becomes a 10-d vector. For example, for the digit 1, there is a 1 in position 1 and 0's in all other positions of the 10-d vector:",
"_____no_output_____"
]
],
[
[
"y_train[3]",
"_____no_output_____"
]
],
[
[
"Now let us create the neural net and train it",
"_____no_output_____"
]
],
[
[
"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import np_utils\nfrom keras.utils import plot_model\n\n# fix random seed for reproducibility\nseed = 123\nnp.random.seed(seed)\n\n# Define the model:\ndef linear_classifier_model():\n \"\"\"single layer, 10 output classes\"\"\"\n \n # create model\n model = Sequential()\n\n # one layer\n model.add(Dense(num_classes, kernel_initializer='normal', \n activation='softmax', input_shape=(num_pixels,)))\n \n # Compile model\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\n#Instantiate model\nmodel = linear_classifier_model()\n\n#Train model\nmodel.fit(x_train, y_train, validation_data=(x_test, y_test), \n epochs=10, batch_size=200, verbose=2)\n\n# Final evaluation of the model\nscores = model.evaluate(x_test, y_test, verbose=0)\nprint(\"Baseline Error: %.2f%%\" % (100-scores[1]*100))",
"Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n0s - loss: 0.9814 - acc: 0.7481 - val_loss: 0.5346 - val_acc: 0.8691\nEpoch 2/10\n0s - loss: 0.4943 - acc: 0.8691 - val_loss: 0.4239 - val_acc: 0.8866\nEpoch 3/10\n0s - loss: 0.4164 - acc: 0.8853 - val_loss: 0.3817 - val_acc: 0.8924\nEpoch 4/10\n0s - loss: 0.3813 - acc: 0.8916 - val_loss: 0.3460 - val_acc: 0.9043\nEpoch 5/10\n0s - loss: 0.3629 - acc: 0.8967 - val_loss: 0.3361 - val_acc: 0.9082\nEpoch 6/10\n0s - loss: 0.3478 - acc: 0.9011 - val_loss: 0.3314 - val_acc: 0.9052\nEpoch 7/10\n0s - loss: 0.3368 - acc: 0.9047 - val_loss: 0.3275 - val_acc: 0.9058\nEpoch 8/10\n0s - loss: 0.3298 - acc: 0.9051 - val_loss: 0.3099 - val_acc: 0.9114\nEpoch 9/10\n0s - loss: 0.3245 - acc: 0.9074 - val_loss: 0.3121 - val_acc: 0.9087\nEpoch 10/10\n0s - loss: 0.3197 - acc: 0.9085 - val_loss: 0.3036 - val_acc: 0.9145\nBaseline Error: 8.55%\n"
]
],
[
[
"Keras lets us easily visualize the model to check that it has the correct architecture",
"_____no_output_____"
]
],
[
[
"plot_model(model, to_file='figs/model.png', show_shapes=True)",
"_____no_output_____"
]
],
[
[
"<img src=\"figs/model.png\">",
"_____no_output_____"
],
[
"Finally, let us grab the weights from layer dense_1, unflatten the shape, and graph them:",
"_____no_output_____"
]
],
[
[
"layer_dense_1 = model.get_layer('dense_1')\n\nweights1 = layer_dense_1.get_weights()[0]\nbias1 = layer_dense_1.get_weights()[1]\n\n#Cast shape to 2d\nweights1 = weights1.reshape(28, 28, 10)\n\n#lot the weights for the first 4 digits\nfor i in range(4):\n plt.subplot(1, 4, 1 + i)\n plt.imshow(weights1[:, :, i], cmap=plt.get_cmap('gray'))\nplt.show()",
"_____no_output_____"
]
],
[
[
"We can see that indeed the learned weights resember digits 0, 1, 2, 3, ... just as we expected of template matching. \n\nFor further details, take a look at [http://cs231n.github.io/linear-classify/](http://cs231n.github.io/linear-classify/)",
"_____no_output_____"
],
[
"## Filters in Convolutional Neural Nets\n\nIn convolutional neural networks, it is common to use small (3x3 or 5x5) sliding convolutional layers instead of large, fully-connected layers. In that case, it may be more helpful to think of the weights as sliding filters to detect low-level features such as edges, textures, and blobs. Indeed, the learned weights often resemble standard image processing filters. Let us try to see this.\n\nFirst, let us reshape (unflatten) the data so the images are again rectangular:",
"_____no_output_____"
]
],
[
[
"from keras import backend as K\nK.set_image_data_format('channels_last') #specify image format\n\nimg_shape = (28, 28, 1)\nx_train = x_train.reshape(x_train.shape[0], 28, 28, 1)\nx_test = x_test.reshape(x_test.shape[0], 28, 28, 1)",
"_____no_output_____"
]
],
[
[
"Now let us define the neural net:",
"_____no_output_____"
]
],
[
[
"from keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.convolutional import MaxPooling2D\n\ndef covnet_model():\n \"\"\"Convolutional neural net\"\"\"\n model = Sequential()\n \n model.add(Convolution2D(32, kernel_size = 7, strides=1, padding='valid', \n input_shape=(28, 28, 1), activation='relu'))\n \n model.add(MaxPooling2D(pool_size=(2, 2)))\n \n model.add(Dropout(0.2))\n \n #flatten 3d tensors into 1d vector. \n model.add(Flatten())\n \n #Add 128 neuron feed forward hidden layer\n model.add(Dense(128, activation='relu'))\n \n #Add output, 10 neurons for 10 target classes, activation is softmax so outputs are \n #probabilities\n model.add(Dense(num_classes, activation='softmax'))\n \n # Compile model\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\nmodel_covnet = covnet_model()",
"_____no_output_____"
]
],
[
[
"Let us plot the network architecture",
"_____no_output_____"
]
],
[
[
"plot_model(model_covnet, to_file='figs/model2.png', show_shapes=True)",
"_____no_output_____"
]
],
[
[
"<img src=\"figs/model2.png\" style=\"width: 350px;\">",
"_____no_output_____"
],
[
"Now let us train the network",
"_____no_output_____"
]
],
[
[
"model_covnet.fit(x_train, y_train, validation_data=(x_test, y_test), \n epochs=10, batch_size=200, verbose=2)\n\n# Final evaluation of the model\nscores = model_covnet.evaluate(x_test, y_test, verbose=0)\nprint(\"Baseline Error: %.2f%%\" % (100-scores[1]*100))",
"Train on 60000 samples, validate on 10000 samples\nEpoch 1/10\n33s - loss: 0.3017 - acc: 0.9151 - val_loss: 0.0875 - val_acc: 0.9747\nEpoch 2/10\n33s - loss: 0.0822 - acc: 0.9762 - val_loss: 0.0568 - val_acc: 0.9818\nEpoch 3/10\n33s - loss: 0.0572 - acc: 0.9827 - val_loss: 0.0497 - val_acc: 0.9840\nEpoch 4/10\n32s - loss: 0.0451 - acc: 0.9862 - val_loss: 0.0354 - val_acc: 0.9883\nEpoch 5/10\n31s - loss: 0.0391 - acc: 0.9880 - val_loss: 0.0348 - val_acc: 0.9883\nEpoch 6/10\n30s - loss: 0.0327 - acc: 0.9896 - val_loss: 0.0317 - val_acc: 0.9890\nEpoch 7/10\n30s - loss: 0.0284 - acc: 0.9909 - val_loss: 0.0304 - val_acc: 0.9901\nEpoch 8/10\n30s - loss: 0.0235 - acc: 0.9923 - val_loss: 0.0339 - val_acc: 0.9888\nEpoch 9/10\n30s - loss: 0.0195 - acc: 0.9938 - val_loss: 0.0371 - val_acc: 0.9887\nEpoch 10/10\n29s - loss: 0.0170 - acc: 0.9945 - val_loss: 0.0306 - val_acc: 0.9902\nBaseline Error: 0.98%\n"
]
],
[
[
"Let us now plot 16 convolutional weights (16 filters) learned in the first convolutional layer:",
"_____no_output_____"
]
],
[
[
"layer_conv2d_4 = model_covnet.get_layer('conv2d_1')\n\nweights2 = layer_conv2d_4.get_weights()[0]\nbias2 = layer_conv2d_4.get_weights()[1]\n\n#Cast shape to 2d\nweights2 = weights2.reshape(7, 7, 32)\n\n#Now plot the weights for the first 16 filters\nplt.figure(figsize=(7,5))\nfor i in range(16):\n plt.subplot(4, 4, 1 + i)\n plt.imshow(weights2[:, :, i], cmap=plt.get_cmap('gray'))\nplt.show()",
"_____no_output_____"
]
],
[
[
"For comparison, let's plot Sobel filters which are used in computer vision to detect horizontal and vertical edges. We see that the neural net weights look similar to Sobel filters.",
"_____no_output_____"
]
],
[
[
"sobelx = np.array([[1, 2, 0, -2, -1], \n [4, 8, 0, -8, -4],\n [6, 12, 0, -12, -6],\n [4, 8, 0, -8, -4],\n [1, 2, 0, -2, -1]]).astype('float32')/12.0\n\nsobely = sobelx.transpose()\n\nplt.figure(figsize=(2, 2))\nplt.subplot(1, 2, 1)\nplt.imshow(sobelx, cmap=plt.get_cmap('gray'))\nplt.subplot(1, 2, 2)\nplt.imshow(sobely, cmap=plt.get_cmap('gray'))\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7ab719eba546e6c4f4ce15f5a66c73d94d635e
| 140,031 |
ipynb
|
Jupyter Notebook
|
docs/examples/driver_examples/Qcodes example with Alazar 9360.ipynb
|
jsaez8/Qcodes
|
74527ae6faf7ec914ae414c6a776307abf158675
|
[
"MIT"
] | 2 |
2019-04-09T09:39:22.000Z
|
2019-10-24T19:07:19.000Z
|
docs/examples/driver_examples/Qcodes example with Alazar 9360.ipynb
|
jsaez8/Qcodes
|
74527ae6faf7ec914ae414c6a776307abf158675
|
[
"MIT"
] | null | null | null |
docs/examples/driver_examples/Qcodes example with Alazar 9360.ipynb
|
jsaez8/Qcodes
|
74527ae6faf7ec914ae414c6a776307abf158675
|
[
"MIT"
] | 1 |
2019-11-19T12:32:29.000Z
|
2019-11-19T12:32:29.000Z
| 80.802654 | 64,673 | 0.71497 |
[
[
[
"# Qcodes example with Alazar ATS 9360",
"_____no_output_____"
]
],
[
[
"# import all necessary things\n%matplotlib nbagg\n\nimport qcodes as qc\nimport qcodes.instrument.parameter as parameter\nimport qcodes.instrument_drivers.AlazarTech.ATS9360 as ATSdriver\nimport qcodes.instrument_drivers.AlazarTech.ATS_acquisition_controllers as ats_contr",
"_____no_output_____"
]
],
[
[
"First lets list all the Alazar boards connected to this machine. In most cases this will probably only be a single one",
"_____no_output_____"
]
],
[
[
"ATSdriver.AlazarTech_ATS.find_boards()",
"_____no_output_____"
],
[
"ats_inst = ATSdriver.AlazarTech_ATS9360(name='Alazar1')\n# Print all information about this Alazar card\nats_inst.get_idn()",
"_____no_output_____"
]
],
[
[
"The Alazar is unusual compared to other instruments as it works together with an acquisition controller. The acquisition controller takes care of post processing and the driver takes care of the communication with the card. At the moment QCoDeS only ships with some very basic acquisition controllers. Here we use a controller that allows us to perform a demodulation of the signal acquired",
"_____no_output_____"
]
],
[
[
"# Instantiate an acquisition controller (In this case we are doing a simple DFT) and \n# provide the name of the name of the alazar card that this controller should control\nacquisition_controller = ats_contr.Demodulation_AcquisitionController(name='acquisition_controller', \n demodulation_frequency=10e6, \n alazar_name='Alazar1')",
"_____no_output_____"
]
],
[
[
"The parameters on the Alazar card are set in a slightly unusual way. As communicating with the card is slow and multiple parameters needs to be set with the same command we use a context manager that takes care of syncing all the paramters to the card after we set them.",
"_____no_output_____"
]
],
[
[
"with ats_inst.syncing():\n ats_inst.clock_source('INTERNAL_CLOCK')\n ats_inst.sample_rate(1_000_000_000)\n ats_inst.clock_edge('CLOCK_EDGE_RISING')\n ats_inst.decimation(1)\n ats_inst.coupling1('DC')\n ats_inst.coupling2('DC')\n ats_inst.channel_range1(.4)\n ats_inst.channel_range2(.4)\n ats_inst.impedance1(50)\n ats_inst.impedance2(50)\n ats_inst.trigger_operation('TRIG_ENGINE_OP_J')\n ats_inst.trigger_engine1('TRIG_ENGINE_J')\n ats_inst.trigger_source1('EXTERNAL')\n ats_inst.trigger_slope1('TRIG_SLOPE_POSITIVE')\n ats_inst.trigger_level1(160)\n ats_inst.trigger_engine2('TRIG_ENGINE_K')\n ats_inst.trigger_source2('DISABLE')\n ats_inst.trigger_slope2('TRIG_SLOPE_POSITIVE')\n ats_inst.trigger_level2(128)\n ats_inst.external_trigger_coupling('DC')\n ats_inst.external_trigger_range('ETR_2V5')\n ats_inst.trigger_delay(0)\n ats_inst.timeout_ticks(0)\n ats_inst.aux_io_mode('AUX_IN_AUXILIARY') # AUX_IN_TRIGGER_ENABLE for seq mode on\n ats_inst.aux_io_param('NONE') # TRIG_SLOPE_POSITIVE for seq mode on",
"_____no_output_____"
]
],
[
[
"This command is specific to this acquisition controller. The kwargs provided here are being forwarded to instrument acquire function\nThis way, it becomes easy to change acquisition specific settings from the ipython notebook",
"_____no_output_____"
]
],
[
[
"acquisition_controller.update_acquisitionkwargs(#mode='NPT',\n samples_per_record=1024,\n records_per_buffer=70,\n buffers_per_acquisition=1,\n #channel_selection='AB',\n #transfer_offset=0,\n #external_startcapture='ENABLED',\n #enable_record_headers='DISABLED',\n #alloc_buffers='DISABLED',\n #fifo_only_streaming='DISABLED',\n #interleave_samples='DISABLED',\n #get_processed_data='DISABLED',\n allocated_buffers=1,\n #buffer_timeout=1000\n)",
"_____no_output_____"
]
],
[
[
"Getting the value of the parameter `acquisition` of the instrument `acquisition_controller` performes the entire acquisition protocol. This again depends on the specific implementation of the acquisition controller",
"_____no_output_____"
]
],
[
[
"acquisition_controller.acquisition()",
"_____no_output_____"
],
[
"# make a snapshot of the 'ats_inst' instrument\nats_inst.snapshot()",
"_____no_output_____"
]
],
[
[
"Finally show that this instrument also works within a loop\n",
"_____no_output_____"
]
],
[
[
"dummy = parameter.ManualParameter(name=\"dummy\")\ndata = qc.Loop(dummy[0:50:1]).each(acquisition_controller.acquisition).run(name='AlazarTest')\nqc.MatPlot(data.acquisition_controller_acquisition)",
"Started at 2018-10-05 15:24:10\nDataSet:\n location = 'data/2018-10-05/#003_AlazarTest_15-24-10'\n <Type> | <array_id> | <array.name> | <array.shape>\n Setpoint | dummy_set | dummy | (50,)\n Measured | acquisition_controller_acquisition | acquisition | (50,)\nFinished at 2018-10-05 15:24:14\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7abbc4124ff2f5768f9825ab9210b9ecf3d358
| 10,828 |
ipynb
|
Jupyter Notebook
|
example/example_olfactory_bulb_dataset.ipynb
|
subhacom/tridesclous
|
e80dc7b82a7661732cff05a7b2064aeb6c0d9326
|
[
"MIT"
] | null | null | null |
example/example_olfactory_bulb_dataset.ipynb
|
subhacom/tridesclous
|
e80dc7b82a7661732cff05a7b2064aeb6c0d9326
|
[
"MIT"
] | null | null | null |
example/example_olfactory_bulb_dataset.ipynb
|
subhacom/tridesclous
|
e80dc7b82a7661732cff05a7b2064aeb6c0d9326
|
[
"MIT"
] | null | null | null | 24.891954 | 254 | 0.517178 |
[
[
[
"# *tridesclous* example with olfactory bulb dataset\n\n",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tridesclous as tdc\n\nfrom tridesclous import DataIO, CatalogueConstructor, Peeler",
"_____no_output_____"
]
],
[
[
"# DataIO = define datasource and working dir\n\ntrideclous provide some datasets than can be downloaded.\n\nNote this dataset contains 2 trials in 2 different files. (the original contains more!)\n\nEach file is considers as a *segment*. *tridesclous* automatically deal with it.\n\nTheses 2 files are in **RawData** format this means binary format with interleaved channels.\n",
"_____no_output_____"
]
],
[
[
"#download dataset\nlocaldir, filenames, params = tdc.download_dataset(name='olfactory_bulb')\nprint(filenames)\nprint(params)\n\nprint()\n#create a DataIO\nimport os, shutil\ndirname = 'tridesclous_olfactory_bulb'\nif os.path.exists(dirname):\n #remove is already exists\n shutil.rmtree(dirname) \ndataio = DataIO(dirname=dirname)\n\n# feed DataIO\ndataio.set_data_source(type='RawData', filenames=filenames, **params)\n\ndataio.add_one_channel_group(channels=range(14))\n\nprint(dataio)\n\n \n ",
"['/home/samuel/Documents/projet/tridesclous/example/olfactory_bulb/OB_file1.raw', '/home/samuel/Documents/projet/tridesclous/example/olfactory_bulb/OB_file2.raw', '/home/samuel/Documents/projet/tridesclous/example/olfactory_bulb/OB_file3.raw']\n{'dtype': 'int16', 'sample_rate': 10000.0, 'total_channel': 16, 'bit_to_microVolt': 0.30517578125}\n\nDataIO <id: 139704555837144> \n workdir: tridesclous_olfactory_bulb\n sample_rate: 10000.0\n total_channel: 16\n channel_groups: 0 [ch0 ch1 ch2 ch3 ... ch10 ch11 ch12 ch13]\n nb_segment: 3\n length: 150000 150000 150000\n durations: 15.0 15.0 15.0 s.\n"
]
],
[
[
"# CatalogueConstructor",
"_____no_output_____"
]
],
[
[
"cc = CatalogueConstructor(dataio=dataio)\nprint(cc)",
"CatalogueConstructor\n chan_grp 0 - ch0 ch1 ch2 ... ch12 ch13\n Signal pre-processing not done yet\n"
]
],
[
[
"## Use automatic parameters and apply the whole chain\n\ntridesclous propose an automatic parameters choice and can apply in one function all the steps.\n",
"_____no_output_____"
]
],
[
[
"from pprint import pprint\nparams = tdc.get_auto_params_for_catalogue(dataio, chan_grp=0)\npprint(params)",
"{'adjacency_radius_um': 400.0,\n 'chunksize': 1000,\n 'clean_cluster': False,\n 'clean_cluster_kargs': {},\n 'clean_waveforms': {'alien_value_threshold': None},\n 'cluster_kargs': {'max_loop': 1000, 'min_cluster_size': 20},\n 'cluster_method': 'pruningshears',\n 'duration': 300.0,\n 'extract_waveforms': {'mode': 'rand',\n 'nb_max': 20000,\n 'wf_left_ms': -1.5,\n 'wf_right_ms': 2.5},\n 'feature_kargs': {'n_components_by_channel': 3},\n 'feature_method': 'pca_by_channel',\n 'mode': 'sparse',\n 'noise_snippet': {'nb_snippet': 300},\n 'peak_detector': {'engine': 'opencl',\n 'method': 'geometrical',\n 'peak_sign': '-',\n 'peak_span_ms': 0.7,\n 'relative_threshold': 5.0},\n 'preprocessor': {'common_ref_removal': False,\n 'engine': 'numpy',\n 'highpass_freq': 300.0,\n 'lostfront_chunksize': -1,\n 'lowpass_freq': 5000.0,\n 'smooth_size': 0},\n 'sparse_threshold': 1.5}\n"
]
],
[
[
"## apply all catalogue steps",
"_____no_output_____"
]
],
[
[
"tdc.apply_all_catalogue_steps(cc, params, verbose=True)",
"estimate_signals_noise 0.1705890859993815\nrun_signalprocessor 0.8053319609998653\nextract_some_waveforms 0.7399420740002824\nclean_waveforms 0.02303425399986736\nextract_some_noise 0.0693022049999854\nproject 0.6348587969996515\nfind_clusters 1.964479604999724\n"
],
[
"print(cc)",
"CatalogueConstructor\n chan_grp 0 - ch0 ch1 ch2 ... ch12 ch13\n nb_peak_by_segment: 4291, 3898, 4534\n some_waveforms.shape: (12720, 40, 14) (sparse 0.21)\n some_features.shape: (12720, 42)\n cluster_labels 13 [-11 -1 0 ... 11 12]\n\n"
]
],
[
[
"## Open CatalogueWindow for visual check\n\nAt the end we can save the catalogue.",
"_____no_output_____"
]
],
[
[
"%gui qt5\nimport pyqtgraph as pg\napp = pg.mkQApp()\nwin = tdc.CatalogueWindow(catalogueconstructor)\nwin.show()\napp.exec_()",
"CatalogueController 0\nconstruct_catalogue 0.598916327000552\n"
],
[
"cc.make_catalogue_for_peeler()",
"make_catalogue 0.07650131300033536\n"
]
],
[
[
"# Peeler\n\nUse automatic parameters.\n",
"_____no_output_____"
]
],
[
[
"peeler_params = tdc.get_auto_params_for_peelers(dataio, chan_grp=0)\npprint(peeler_params)",
"{'argmin_method': 'opencl',\n 'engine': 'geometrical',\n 'inter_sample_oversampling': True,\n 'sparse_threshold_mad': 1.5,\n 'use_sparse_template': True}\n"
],
[
"catalogue = dataio.load_catalogue()\n\npeeler = Peeler(dataio)\npeeler.change_params(catalogue=catalogue, **peeler_params)\n\nt1 = time.perf_counter()\npeeler.run()\nt2 = time.perf_counter()\nprint('peeler.run', t2-t1)\n\nprint()\nfor seg_num in range(dataio.nb_segment):\n spikes = dataio.get_spikes(seg_num)\n print('seg_num', seg_num, 'nb_spikes', spikes.size)\n print(spikes[:3])\n \n",
"100%|██████████| 146/146 [00:05<00:00, 27.26it/s]\n100%|██████████| 146/146 [00:04<00:00, 29.38it/s]\n100%|██████████| 146/146 [00:07<00:00, 17.55it/s]"
]
],
[
[
"## Open PeelerWindow for visual checking",
"_____no_output_____"
]
],
[
[
"%gui qt5\nimport pyqtgraph as pg\napp = pg.mkQApp()\nwin = tdc.PeelerWindow(dataio=dataio, catalogue=initial_catalogue)\nwin.show()\napp.exec_()\n",
"_____no_output_____"
]
],
[
[
"Here a snappshot of PeelerWindow\n\n<img src=\"../doc/img/snapshot_peelerwindow.png\">",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7acfb81b18a2e9dae2c25d01dc42e320c06d81
| 16,933 |
ipynb
|
Jupyter Notebook
|
Alpha_weak_acid.ipynb
|
skotssd/CH234
|
94a3bc6e481af86243c1bce7c34ab833f076bc87
|
[
"BSD-3-Clause"
] | null | null | null |
Alpha_weak_acid.ipynb
|
skotssd/CH234
|
94a3bc6e481af86243c1bce7c34ab833f076bc87
|
[
"BSD-3-Clause"
] | null | null | null |
Alpha_weak_acid.ipynb
|
skotssd/CH234
|
94a3bc6e481af86243c1bce7c34ab833f076bc87
|
[
"BSD-3-Clause"
] | null | null | null | 64.38403 | 818 | 0.546093 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cb7ad131531392a9d81f92a90af1726cb37bbd69
| 29,487 |
ipynb
|
Jupyter Notebook
|
idaes/examples/workshops/Module_0_Welcome/Module_0_Welcome.ipynb
|
dt-schwartz/NGFC
|
9ebbfc2288c9a0b55313998a04e42c80b332db49
|
[
"MIT"
] | 6 |
2020-05-22T03:44:44.000Z
|
2022-01-11T21:32:21.000Z
|
idaes/examples/workshops/Module_0_Welcome/Module_0_Welcome.ipynb
|
dt-schwartz/NGFC
|
9ebbfc2288c9a0b55313998a04e42c80b332db49
|
[
"MIT"
] | 2 |
2020-06-17T18:36:27.000Z
|
2020-06-17T18:36:52.000Z
|
idaes/examples/workshops/Module_0_Welcome/Module_0_Welcome.ipynb
|
dt-schwartz/NGFC
|
9ebbfc2288c9a0b55313998a04e42c80b332db49
|
[
"MIT"
] | 1 |
2021-12-10T18:30:36.000Z
|
2021-12-10T18:30:36.000Z
| 38.646134 | 619 | 0.622003 |
[
[
[
"[//]: #\n<img src=\"idaes_icon.png\" width=\"100\">\n<h1><center>Welcome to the IDAES Stakeholder Workshop</center></h1>",
"_____no_output_____"
],
[
"Welcome and thank you for taking the time to attend today's workshop. Today we will introduce you to the fundamentals of working with the IDAES process modeling toolset, and we will demonstrate how these tools can be applied for optimization applications.\n\nToday's workshop will be conducted using Jupyter Notebooks which provide an online, interactive Python environment for you to use (without the need for installing anything).\n\nBefore we get started on some actual examples, let's make sure that everything is working correctly. The cell below contains a command to run a simple test script that will test that everything we will need for today is working properly.\n\nYou can execute a cell by pressing `Shift+Enter`.",
"_____no_output_____"
]
],
[
[
"run \"notebook_test_script.py\"",
"_____no_output_____"
]
],
[
[
"If everything worked properly, you should see a message saying `All good!` and a summary of all the checks that were run. If you don't see this, please contact someone for assistance.",
"_____no_output_____"
],
[
"## Outline of Workshop\n\nToday's workshop is divided into four modules which will take you through the steps of setting up a flowsheet within the IDAES framework.\n\nWelcome Module (this one):\n\n* Introduction to Jupyter notebooks and Python\n* Introduction to Pyomo\n\nModule 1 will cover:\n\n* how to import models from the core IDAES model library,\n* how to create a model for a single unit operation,\n* how to define feed and operating conditions,\n* how to initialize and solve a single unit model,\n* some ways we can manipulate the model and examine the results.\n\nModule 2 will demonstrate:\n\n* how to combine unit models together to form flowsheets,\n* tools to initialize and solve flowsheets with recycle loops,\n* how to optimize process operating conditions to meet product specifications.\n\nModule 3 will demonstrate:\n\n* how to build new unit models using the IDAES tools,\n* how to include new unit models into flowsheets.\n",
"_____no_output_____"
],
[
"## Introduction to Jupyter Notebooks and Python\n\nIn this short notebook, we will briefly describe the uses of Jupyter notebooks like this one, and provide you with the necessary background in Python for this workshop. We will cover `if` statements, looping, array-like containers called lists and dictionaries, as well as the use of some external packages for working with data. \n\nThere are many additional tutorials online to learn more about the Python syntax.",
"_____no_output_____"
],
[
"In Python, variables do not need to be declared before they are used. You can simply define a new variable using `x = 5`.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nIn the cell below, assign a value of 5 to the variable x. Don't forget to type Shift+Enter to execute the line.</div>",
"_____no_output_____"
],
[
"You can easily see the value of a variable using the built-in `print` function. For example, to print the value of `x` use `print(x)`.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nWrite the code to print the value of x. Don't forget to hit Shift+Enter to execute the cell.\n</div>",
"_____no_output_____"
],
[
"<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nNow change the value of the x variable to 8 and execute the cell.\n</div>",
"_____no_output_____"
],
[
"### Jupyter notebooks and execution order\n\n<div class=\"alert alert-block alert-warning\">\n<b>Note:</b>\nWhen using Jupyter notebooks, it is very important to know that the cells can be executed out of order (intentionally or not). The state of the environment (e.g., values of variables, imports, etc.) is defined by the execution order.\n</div>\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nTo see this concept, select the cell above that contained the print statement and execute the cell again using Shift+Enter.\n</div>\n\nYou should see that the value `8` is now printed. This may seem problematic if you are used to programming in environments where the state is linked to the order of the commands as *written*, not as *executed*.\n\n**Again, notice that the state of the environment is determined by the execution order.**\n\nNote also that the square brackets to the left of the cell show the order that cells were executed. If you scroll to the top, you should see that the code cells show an execution order of `[1]`, `[2]`, `[5]`, and `[4]`, indicating the actual execution order.\n\nThere are some useful menu commands at the top of the Jupyter notebook to help with these problems and make sure you retain the execution order as expected.\n\nSome important commands to remember:\n* You can clear the current state with the menu item `Kernel | Restart & Clear Output`\n* It is often useful to clear the state using the menu command just described, and then execute all the lines **above the currently selected cell** using `Cell | Run All Above`.\n* You can clear all the state and re-run the entire notebook using `Kernel | Restart & Run All`.\n\nTo show the use of these commands, complete the following.\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\n<ul>\n<li>Clear the current state (using Kernel | Restart & Clear Output). You should notice that the square brackets that listed the execution order are all now empty.</li>\n<li>Select the cell immediately below this text\n<li>Re-run all the code up to this point (Cell | Run All Above). You should now see that the square brackets indicate the expected execution order.</li>\n<li>Print the value of x again using the print function. You should see the value 8 printed, while the earlier cell printing x shows the value of 5 as expected.</li>\n</ul>\n</div>\n",
"_____no_output_____"
]
],
[
[
"print(x)",
"_____no_output_____"
]
],
[
[
"### Python `if` statements\n\nIn the code below, we show an example of an `if` statement in Python.\n\n```python\ntemp = 325\n# some other code\nif temp > 320:\n print('temperature is too high')\nelif x < 290:\n print('temperature is too low')\nelse:\n print('temperature is just right')\n```\n\n<div class=\"alert alert-block alert-warning\">\n<b>Note:</b>\nYou will notice that there are no braces to separate blocks in the if-else tree. In Python, indentation is used to delineate blocks of code throughout Python (e.g., if statements, for loops, functions, etc.). The indentation in the above example is not only to improve legibility of the code. It is necessary for the code to run correctly. As well, the number of spaces required to define the indentation is arbitrary, but it must be consistent throughout the code. For example, we could use 3 spaces (instead of the 4 used in the example above, but we could not use 3 for one of the blocks and 4 for another).\n</div>\n\nUsing the syntax above for the `if` statement, write the following code.\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\n<ul>\n <li>set the value of the variable T_degC to 20</li>\n <li>convert this from degrees Celsius to degrees Fahrenheit (use variable name T_degF)</li>\n <li>write an `if` statement that prints a message if the degrees Fahrenheit are below 70</li>\n</ul>\n</div>",
"_____no_output_____"
]
],
[
[
"T_degC = 20\n# some other code\nT_degF = (T_degC * 9.0/5.0) + 32.0\n\n# Todo: put the if statement here\n",
"_____no_output_____"
]
],
[
[
"### Python list containers\n\nNow we will illustrate the use of lists in Python. Lists are similar to vectors or arrays in other languages. A list in Python is indexed by integers from 0 up to the length of the array minus 1. The list can contain standard types (int, float, string), or other objects.\n\nIn the next inline exercise, we will create a list that contains the values from 0 to 50 by steps of 5 using a for loop. Note that the python function `range(n)` can be used to iterate from 0 to (n-1) in a for loop. Also note that lists have an `append` method which adds an entry to the end of the list (e.g., if the list `l` currently has 5 elements, then `l.append('temp')` will add the string \"temp\" as the sixth element). Print the new list after the for loop. If this is done correctly, you should see:\n`[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]` printed after the cell.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nComplete the code block below to create the desired list and print the result.\n</div>",
"_____no_output_____"
]
],
[
[
"# Create a list with the values 0 to 50 with steps of 5.\nxlist = list()\nfor i in range(11):\n # Todo: use the append method of list to append the correct value\n \n\nprint(xlist) # Todo: print the value of xlist to verify the results",
"_____no_output_____"
]
],
[
[
"Python provides a short-hand notation for building lists called *list comprehensions*. An example of a list comprehension that creates all even numbers from 0 to 40 is:\n\n```python\nvalues = [q*2 for q in range(21)]\n```\n\nNote also that list comprehensions can include if clauses. For example, we could also implement the above example with the following code:\n\n```python\nvalues = [q for q in range(41) if q % 2 == 0]\n```\n\nNote that `%` is the modulus operator (it returns the remainder of the division). Therefore, in the above code, `q % 2` returns 0 if the value in `q` is exactly divisible by 2 (i.e., an even number).\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nIn the cell below, create the same xlist that we created previously, but use the list comprehension notation. Verify that this result is correct by printing it.\n</div>\n",
"_____no_output_____"
]
],
[
[
"# Todo: define the list comprehension\n\n\nprint(xlist)",
"_____no_output_____"
]
],
[
[
"You can easily check the length of a list using the python `len(l)` function.\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nPrint the length of `xlist`. It should be 11.\n</div>",
"_____no_output_____"
]
],
[
[
"# Todo: print the len of the list\n\n",
"_____no_output_____"
]
],
[
[
"If you have a list of values or objects, it is easy to iterate through that list in a for loop. In the next inline exercise, we will create another list, `ylist` where each of the values is equal to the corresponding value in `xlist` squared. That is, $y_i = x_i^2$.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nModify the code below to create ylist as described above. Print the values in ylist to check the result.\n</div>",
"_____no_output_____"
]
],
[
[
"ylist = list()\n\n# Todo: define the for loop to add elements to ylist using the values in xlist\n\n\nprint(ylist)",
"_____no_output_____"
]
],
[
[
"This same task could have been done with a list comprehension (using much less code).\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nWrite the list comprehension to compute the values of ylist. Print the values in ylist to check the result.\n</div>",
"_____no_output_____"
]
],
[
[
"# Todo: create ylist using a list comprehension and print the result\n\n",
"_____no_output_____"
]
],
[
[
"### Python dictionary containers\n\nAnother valuable data structure in Python are *dictionaries*. Dictionaries are an associative array; that is, a map from keys to values or objects. The keys can be *almost* anything, including floats, integers, and strings. The code below shows an example of creating a dictionary (here, to store the areas of some of the states).\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nExecute the lines below to see the areas dictionary.\n</div>",
"_____no_output_____"
]
],
[
[
"areas = dict()\nareas['South Dakota'] = 199742 \nareas['Oklahoma'] = 181035\nprint(areas)",
"_____no_output_____"
]
],
[
[
"Dictionaries can contain mixed types (i.e., it is valid to add `areas['Texas'] = 'Really big!'`) but this may lead to unpredictable behavior if the different types are unexpected in other parts of the code.\n\nYou can loop through dictionaries in different ways. For example,\n```python\nd = {'A': 2, 'B': 4, 'D': 16}\nfor k in d.keys():\n # loop through the keys in the dictionary\n # access the value with d[k]\n print('key=', k, 'value=', d[k])\n \nfor v in d.values():\n # loop through the values in the dictionary, ignoring the keys\n print('value=', v)\n \nfor k,v in d.items():\n # loop through the entries in the dictionary, retrieving both\n # the key and the value\n print('key=', k, 'value=', v)\n```\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nThe areas listed above for the two states are in square kilometers. Modify the loop below to create a new dictionary that contains the areas in square miles. Print the new dictionary to verify the correct behavior. Note that 1 kilometer is equal to 0.62137 miles.\n</div>",
"_____no_output_____"
]
],
[
[
"areas_mi = dict()\nfor state_name, area in areas.items():\n # Todo: convert the area to sq. mi and assign to the areas_mi dict.\n \n \nprint(areas_mi)",
"_____no_output_____"
]
],
[
[
"Python also supports dictionary comprehensions much like list comprehensions. For example:\n```python\nd = {'A': 2, 'B': 4, 'D': 16}\nd2 = {k:v**2 for k,v in d.items()}\n```\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nRedo the conversion from square kilometers to square miles using a dictionary comprehension.\n</div>",
"_____no_output_____"
]
],
[
[
"# Todo: define areas_mi using a dictionary comprehension and print the result\n\n",
"_____no_output_____"
]
],
[
[
"### Matplotlib for generating figures\n\nWe will now briefly explore the use of the `matplotlib` package to generate figures. Before we do this, we will introduce some other helpful tools.\n\nAnother effective way to create a list of evenly spaced numbers (e.g., for plotting or other computation) is to use the `linspace` function from the `numpy` package (more information [here](https://www.numpy.org/devdocs/)). Let's import the `numpy` package and use linspace function to create a list of 15 evenly spaced intervals (that is, 16 points) from 0 to 50 and store this in `xlist`. We will also create the `ylist` that corresponds to the square of the values in `xlist`. Note, we must first import the `numpy` package.\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nExecute the next two cells to see the output.\n</div>",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"xlist = list(np.linspace(0,50,16))\nylist = [x**2 for x in xlist]\nprint(xlist)\nprint(ylist)",
"_____no_output_____"
]
],
[
[
"This printed output is not a very effective way to communicate these results. Let's use matplotlib to create a figure of x versus y. A full treatment of the `matplotlib` package is beyond the scope of this tutorial, and further documentation can be found [here](https://matplotlib.org/). For now, we will import the plotting capability and show how to generate a straightforward figure. You can consult the documentation for matplotlib for further details.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nExecute the next two cells to see the output.\n</div>",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"plt.plot(xlist, ylist)\nplt.title('Embedded x vs y figure')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(['data'])\nplt.show()",
"_____no_output_____"
]
],
[
[
"Next, we will use what you have learned so far to create a plot of `sin(x)` for `x` from 0 to $2 \\pi$ with 100 points. Note, you can get the `sin` function and the value for $\\pi$ from the `math` package.\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nExecute the import statement in the next cell, and then complete the missing code in the following cell to create the figure discussed above.\n</div>",
"_____no_output_____"
]
],
[
[
"import math",
"_____no_output_____"
],
[
"x = list(np.linspace(0,2*math.pi, 100))\n\n# Todo: create the list for y\n\n\n# Todo: Generate the figure\n\n\n",
"_____no_output_____"
]
],
[
[
"### Importing and exporting data using Pandas\n\nOften, it is useful to output the data in a general format so it can be imported into other tools or presented in a familiar application. Python makes this easy with many great packages already available. The next code shows how to use the `pandas` package to create a dataframe and export the data to a csv file that we can import to excel. You could also consult [pandas documentation](http://pandas.pydata.org/pandas-docs/stable/) to see how to export the data directly to excel.\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nExecute the code below that shows how to import some data into a DataFrame from the Pandas package and then export this data to a csv file.\n</div>",
"_____no_output_____"
]
],
[
[
"import pandas as pd\ndf_sin = pd.DataFrame({'x': x, 'sin(x) (radians)': y})\nprint(df_sin)\ndf_sin.to_csv('sin_data.csv')",
"_____no_output_____"
]
],
[
[
"If you go back to the browser tab that showed all the Jupyter notebook files and refresh, you will now see that there is a csv file with the x and y data. You can consult the Pandas documentation do learn about the many data analysis and statistical features of the `pandas` package.\n\n### Further Information\n\nFurther information of the packages mentioned above can be found using the following links:\n\n* [numpy](https://www.numpy.org/devdocs/)\n* [matplotlib](https://matplotlib.org/)\n* [pandas](http://pandas.pydata.org/pandas-docs/stable/)\n",
"_____no_output_____"
],
[
"## Introduction to Pyomo\n\n[Pyomo](www.pyomo.org) is an object-oriented, python-based package for equation-oriented (or *algebraic*) modeling and optimization, and the IDAES framework is built upon the Pyomo package. IDAES extends the Pyomo package and defines a class heirarchy for flowsheet based modeling, including definition of property packages, unit models, and flowsheets.\n\nThe use of IDAES does not require extensive knowledge about Pyomo, however, it can be beneficial to have some familiarity with the Pyomo package for certain tasks:\n* IDAES models are open, and you can interrogating the underlying Pyomo model to view the variables, constraints, and objective functions defined in the model.\n* You can use Pyomo components to define your objective function or to create additional constraints.\n* Since IDAES models **are** Pyomo models, any advanced meta-algorithms or analysis tools that can be developed and/or used on a Pyomo model can also be used on an IDAES model.\n\nA full tutorial on Pyomo is beyond the scope of this workshop, however in this section we will briefly cover the commands required to specify an objective function or add a constraint to an existing model.\n\nIn the next cell, we will create a Pyomo model, and add a couple of variables to that model. When using IDAES, you will define a flowsheet and the addition of variables and model equations will be handled by the IDAES framework.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nExecute the following cell to create a Pyomo model with some variables that will be used later.\n</div>",
"_____no_output_____"
]
],
[
[
"from pyomo.environ import ConcreteModel, Var\nmodel = ConcreteModel()\nmodel.x = Var()\nmodel.y = Var()",
"_____no_output_____"
]
],
[
[
"The Pyomo syntax to define a scalar objective function is shown below. This defines the objective function as $x^2$. By default Pyomo models (and IDAES models) seek to *minimize* the objective function.\n```python\nmodel.obj = Objective(expr=model.x**2)\n```\nTo maximize a quantity, include the keyword argument `sense=maximize` as in the following:\n```python\nmodel.obj = Objective(expr=model.y, sense=maximize)\n```\nNote that `Objective` and `maximize` would need to be imported from `pyomo.environ`.\n\nThe Pyomo syntax to define a scalar constraint is shown below. This code defines the equality constraint $x^2 + y^2 = 1$.\n```python\nmodel.on_unit_circle_con = Constraint(expr=model.x**2 + model.y**2 == 1)\n```\nPyomo also supports inequalities. For example, the code for the inequality constraint $x^2 + y^2 \\le 1$ is given as the following.\n```python\nmodel.inside_unit_circle_con = Constraint(expr=model.x**2 + model.y**2 <= 1)\n```\nNote that, as before, we would need to include the appropriate imports. In this case `Constraint` would need to be imported from `pyomo.environ`.\n\nUsing the syntax shown above, we will now add the objective function: $\\min x^2 + y^2$ and the constraint $x + y = 1$.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nComplete the missing code in the cell below. If this is done correctly, after executing the cell, you should see the log output from the solver and the printed solution should show that x, y, and the objective value are all equal to 0.5.\n</div>\n",
"_____no_output_____"
]
],
[
[
"from pyomo.environ import Objective, Constraint, value, SolverFactory\n\n# Todo: add the objective function here\n\n\n# Todo: add the constraint here\n\n\n# now solve the problem\nstatus = SolverFactory('ipopt').solve(model, tee=True) # tee=True shows the solver log\n\n# print the values of x, y, and the objective function at the solution\n# Note that the results are automatically stored in the model variables\nprint('x =', value(model.x))\nprint('y =', value(model.y))\nprint('obj =', value(model.obj))",
"_____no_output_____"
]
],
[
[
"Notice that the code above also imported the `value` function. This is a Pyomo function that should be used to retrieve the value of variables in Pyomo (or IDAES) models. Note that you can display the complete list of all variables, objectives, and constraints (with their expressions) using `model.pprint()`. The `display` method is similar to the `pprint` method except that is shows the *values* of the constraints and objectives instead of the underlying expressions. The `pprint` and `display` methods can also be used on individual components.\n\n<div class=\"alert alert-block alert-info\">\n<b>Inline Exercise:</b>\nExecute the lines of code below to see the output from pprint and display for a Pyomo model.\n</div>",
"_____no_output_____"
]
],
[
[
"print('*** Output from model.pprint():')\nmodel.pprint()\n\nprint()\nprint('*** Output from model.display():')\nmodel.display()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7ad347425cc35c9e172c27e35a90320d1333ba
| 41,425 |
ipynb
|
Jupyter Notebook
|
ml/cc/exercises/feature_crosses.ipynb
|
direkshan-digital/eng-edu
|
52e5e914d8dd6e25b3fb14191610cff7a22a7984
|
[
"Apache-2.0"
] | null | null | null |
ml/cc/exercises/feature_crosses.ipynb
|
direkshan-digital/eng-edu
|
52e5e914d8dd6e25b3fb14191610cff7a22a7984
|
[
"Apache-2.0"
] | null | null | null |
ml/cc/exercises/feature_crosses.ipynb
|
direkshan-digital/eng-edu
|
52e5e914d8dd6e25b3fb14191610cff7a22a7984
|
[
"Apache-2.0"
] | null | null | null | 40.853057 | 711 | 0.552106 |
[
[
[
"#### Copyright 2017 Google LLC.",
"_____no_output_____"
]
],
[
[
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Feature Crosses",
"_____no_output_____"
],
[
"**Learning Objectives:**\n * Improve a linear regression model with the addition of additional synthetic features (this is a continuation of the previous exercise)\n * Use an input function to convert pandas `DataFrame` objects to `Tensors` and invoke the input function in `fit()` and `predict()` operations\n * Use the FTRL optimization algorithm for model training\n * Create new synthetic features through one-hot encoding, binning, and feature crosses",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
],
[
"First, as we've done in previous exercises, let's define the input and create the data-loading code.",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\n\nimport math\n\nfrom IPython import display\nfrom matplotlib import cm\nfrom matplotlib import gridspec\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nimport tensorflow as tf\nfrom tensorflow.python.data import Dataset\n\ntf.logging.set_verbosity(tf.logging.ERROR)\npd.options.display.max_rows = 10\npd.options.display.float_format = '{:.1f}'.format\n\ncalifornia_housing_dataframe = pd.read_csv(\"https://storage.googleapis.com/mledu-datasets/california_housing_train.csv\", sep=\",\")\n\ncalifornia_housing_dataframe = california_housing_dataframe.reindex(\n np.random.permutation(california_housing_dataframe.index))",
"_____no_output_____"
],
[
"def preprocess_features(california_housing_dataframe):\n \"\"\"Prepares input features from California housing data set.\n\n Args:\n california_housing_dataframe: A Pandas DataFrame expected to contain data\n from the California housing data set.\n Returns:\n A DataFrame that contains the features to be used for the model, including\n synthetic features.\n \"\"\"\n selected_features = california_housing_dataframe[\n [\"latitude\",\n \"longitude\",\n \"housing_median_age\",\n \"total_rooms\",\n \"total_bedrooms\",\n \"population\",\n \"households\",\n \"median_income\"]]\n processed_features = selected_features.copy()\n # Create a synthetic feature.\n processed_features[\"rooms_per_person\"] = (\n california_housing_dataframe[\"total_rooms\"] /\n california_housing_dataframe[\"population\"])\n return processed_features\n\ndef preprocess_targets(california_housing_dataframe):\n \"\"\"Prepares target features (i.e., labels) from California housing data set.\n\n Args:\n california_housing_dataframe: A Pandas DataFrame expected to contain data\n from the California housing data set.\n Returns:\n A DataFrame that contains the target feature.\n \"\"\"\n output_targets = pd.DataFrame()\n # Scale the target to be in units of thousands of dollars.\n output_targets[\"median_house_value\"] = (\n california_housing_dataframe[\"median_house_value\"] / 1000.0)\n return output_targets",
"_____no_output_____"
],
[
"# Choose the first 12000 (out of 17000) examples for training.\ntraining_examples = preprocess_features(california_housing_dataframe.head(12000))\ntraining_targets = preprocess_targets(california_housing_dataframe.head(12000))\n\n# Choose the last 5000 (out of 17000) examples for validation.\nvalidation_examples = preprocess_features(california_housing_dataframe.tail(5000))\nvalidation_targets = preprocess_targets(california_housing_dataframe.tail(5000))\n\n# Double-check that we've done the right thing.\nprint(\"Training examples summary:\")\ndisplay.display(training_examples.describe())\nprint(\"Validation examples summary:\")\ndisplay.display(validation_examples.describe())\n\nprint(\"Training targets summary:\")\ndisplay.display(training_targets.describe())\nprint(\"Validation targets summary:\")\ndisplay.display(validation_targets.describe())",
"_____no_output_____"
],
[
"def construct_feature_columns(input_features):\n \"\"\"Construct the TensorFlow Feature Columns.\n\n Args:\n input_features: The names of the numerical input features to use.\n Returns:\n A set of feature columns\n \"\"\"\n return set([tf.feature_column.numeric_column(my_feature)\n for my_feature in input_features])",
"_____no_output_____"
],
[
"def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n \"\"\"Trains a linear regression model.\n \n Args:\n features: pandas DataFrame of features\n targets: pandas DataFrame of targets\n batch_size: Size of batches to be passed to the model\n shuffle: True or False. Whether to shuffle the data.\n num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n Returns:\n Tuple of (features, labels) for next data batch\n \"\"\"\n \n # Convert pandas data into a dict of np arrays.\n features = {key:np.array(value) for key,value in dict(features).items()} \n \n # Construct a dataset, and configure batching/repeating.\n ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n ds = ds.batch(batch_size).repeat(num_epochs)\n \n # Shuffle the data, if specified.\n if shuffle:\n ds = ds.shuffle(10000)\n \n # Return the next batch of data.\n features, labels = ds.make_one_shot_iterator().get_next()\n return features, labels",
"_____no_output_____"
]
],
[
[
"## FTRL Optimization Algorithm\n\nHigh dimensional linear models benefit from using a variant of gradient-based optimization called FTRL. This algorithm has the benefit of scaling the learning rate differently for different coefficients, which can be useful if some features rarely take non-zero values (it also is well suited to support L1 regularization). We can apply FTRL using the [FtrlOptimizer](https://www.tensorflow.org/api_docs/python/tf/train/FtrlOptimizer).",
"_____no_output_____"
]
],
[
[
"def train_model(\n learning_rate,\n steps,\n batch_size,\n feature_columns,\n training_examples,\n training_targets,\n validation_examples,\n validation_targets):\n \"\"\"Trains a linear regression model.\n \n In addition to training, this function also prints training progress information,\n as well as a plot of the training and validation loss over time.\n \n Args:\n learning_rate: A `float`, the learning rate.\n steps: A non-zero `int`, the total number of training steps. A training step\n consists of a forward and backward pass using a single batch.\n feature_columns: A `set` specifying the input feature columns to use.\n training_examples: A `DataFrame` containing one or more columns from\n `california_housing_dataframe` to use as input features for training.\n training_targets: A `DataFrame` containing exactly one column from\n `california_housing_dataframe` to use as target for training.\n validation_examples: A `DataFrame` containing one or more columns from\n `california_housing_dataframe` to use as input features for validation.\n validation_targets: A `DataFrame` containing exactly one column from\n `california_housing_dataframe` to use as target for validation.\n \n Returns:\n A `LinearRegressor` object trained on the training data.\n \"\"\"\n\n periods = 10\n steps_per_period = steps / periods\n\n # Create a linear regressor object.\n my_optimizer = tf.train.FtrlOptimizer(learning_rate=learning_rate)\n my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n linear_regressor = tf.estimator.LinearRegressor(\n feature_columns=feature_columns,\n optimizer=my_optimizer\n )\n \n training_input_fn = lambda: my_input_fn(training_examples, \n training_targets[\"median_house_value\"], \n batch_size=batch_size)\n predict_training_input_fn = lambda: my_input_fn(training_examples, \n training_targets[\"median_house_value\"], \n num_epochs=1, \n shuffle=False)\n predict_validation_input_fn = lambda: my_input_fn(validation_examples, \n validation_targets[\"median_house_value\"], \n num_epochs=1, \n shuffle=False)\n\n # Train the model, but do so inside a loop so that we can periodically assess\n # loss metrics.\n print(\"Training model...\")\n print(\"RMSE (on training data):\")\n training_rmse = []\n validation_rmse = []\n for period in range (0, periods):\n # Train the model, starting from the prior state.\n linear_regressor.train(\n input_fn=training_input_fn,\n steps=steps_per_period\n )\n # Take a break and compute predictions.\n training_predictions = linear_regressor.predict(input_fn=predict_training_input_fn)\n training_predictions = np.array([item['predictions'][0] for item in training_predictions])\n validation_predictions = linear_regressor.predict(input_fn=predict_validation_input_fn)\n validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])\n \n # Compute training and validation loss.\n training_root_mean_squared_error = math.sqrt(\n metrics.mean_squared_error(training_predictions, training_targets))\n validation_root_mean_squared_error = math.sqrt(\n metrics.mean_squared_error(validation_predictions, validation_targets))\n # Occasionally print the current loss.\n print(\" period %02d : %0.2f\" % (period, training_root_mean_squared_error))\n # Add the loss metrics from this period to our list.\n training_rmse.append(training_root_mean_squared_error)\n validation_rmse.append(validation_root_mean_squared_error)\n print(\"Model training finished.\")\n\n \n # Output a graph of loss metrics over periods.\n plt.ylabel(\"RMSE\")\n plt.xlabel(\"Periods\")\n plt.title(\"Root Mean Squared Error vs. Periods\")\n plt.tight_layout()\n plt.plot(training_rmse, label=\"training\")\n plt.plot(validation_rmse, label=\"validation\")\n plt.legend()\n\n return linear_regressor",
"_____no_output_____"
],
[
"_ = train_model(\n learning_rate=1.0,\n steps=500,\n batch_size=100,\n feature_columns=construct_feature_columns(training_examples),\n training_examples=training_examples,\n training_targets=training_targets,\n validation_examples=validation_examples,\n validation_targets=validation_targets)",
"_____no_output_____"
]
],
[
[
"## One-Hot Encoding for Discrete Features\n\nDiscrete (i.e. strings, enumerations, integers) features are usually converted into families of binary features before training a logistic regression model.\n\nFor example, suppose we created a synthetic feature that can take any of the values `0`, `1` or `2`, and that we have a few training points:\n\n| # | feature_value |\n|---|---------------|\n| 0 | 2 |\n| 1 | 0 |\n| 2 | 1 |\n\nFor each possible categorical value, we make a new **binary** feature of **real values** that can take one of just two possible values: 1.0 if the example has that value, and 0.0 if not. In the example above, the categorical feature would be converted into three features, and the training points now look like:\n\n| # | feature_value_0 | feature_value_1 | feature_value_2 |\n|---|-----------------|-----------------|-----------------|\n| 0 | 0.0 | 0.0 | 1.0 |\n| 1 | 1.0 | 0.0 | 0.0 |\n| 2 | 0.0 | 1.0 | 0.0 |",
"_____no_output_____"
],
[
"## Bucketized (Binned) Features\n\nBucketization is also known as binning.\n\nWe can bucketize `population` into the following 3 buckets (for instance):\n- `bucket_0` (`< 5000`): corresponding to less populated blocks\n- `bucket_1` (`5000 - 25000`): corresponding to mid populated blocks\n- `bucket_2` (`> 25000`): corresponding to highly populated blocks\n\nGiven the preceding bucket definitions, the following `population` vector:\n\n [[10001], [42004], [2500], [18000]]\n\nbecomes the following bucketized feature vector:\n\n [[1], [2], [0], [1]]\n\nThe feature values are now the bucket indices. Note that these indices are considered to be discrete features. Typically, these will be further converted in one-hot representations as above, but this is done transparently.\n\nTo define feature columns for bucketized features, instead of using `numeric_column`, we can use [`bucketized_column`](https://www.tensorflow.org/api_docs/python/tf/feature_column/bucketized_column), which takes a numeric column as input and transforms it to a bucketized feature using the bucket boundaries specified in the `boundardies` argument. The following code defines bucketized feature columns for `households` and `longitude`; the `get_quantile_based_boundaries` function calculates boundaries based on quantiles, so that each bucket contains an equal number of elements.",
"_____no_output_____"
]
],
[
[
"def get_quantile_based_boundaries(feature_values, num_buckets):\n boundaries = np.arange(1.0, num_buckets) / num_buckets\n quantiles = feature_values.quantile(boundaries)\n return [quantiles[q] for q in quantiles.keys()]\n\n# Divide households into 7 buckets.\nhouseholds = tf.feature_column.numeric_column(\"households\")\nbucketized_households = tf.feature_column.bucketized_column(\n households, boundaries=get_quantile_based_boundaries(\n california_housing_dataframe[\"households\"], 7))\n\n# Divide longitude into 10 buckets.\nlongitude = tf.feature_column.numeric_column(\"longitude\")\nbucketized_longitude = tf.feature_column.bucketized_column(\n longitude, boundaries=get_quantile_based_boundaries(\n california_housing_dataframe[\"longitude\"], 10))",
"_____no_output_____"
]
],
[
[
"## Task 1: Train the Model on Bucketized Feature Columns\n**Bucketize all the real valued features in our example, train the model and see if the results improve.**\n\nIn the preceding code block, two real valued columns (namely `households` and `longitude`) have been transformed into bucketized feature columns. Your task is to bucketize the rest of the columns, then run the code to train the model. There are various heuristics to find the range of the buckets. This exercise uses a quantile-based technique, which chooses the bucket boundaries in such a way that each bucket has the same number of examples.",
"_____no_output_____"
]
],
[
[
"def construct_feature_columns():\n \"\"\"Construct the TensorFlow Feature Columns.\n\n Returns:\n A set of feature columns\n \"\"\" \n households = tf.feature_column.numeric_column(\"households\")\n longitude = tf.feature_column.numeric_column(\"longitude\")\n latitude = tf.feature_column.numeric_column(\"latitude\")\n housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n median_income = tf.feature_column.numeric_column(\"median_income\")\n rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n \n # Divide households into 7 buckets.\n bucketized_households = tf.feature_column.bucketized_column(\n households, boundaries=get_quantile_based_boundaries(\n training_examples[\"households\"], 7))\n\n # Divide longitude into 10 buckets.\n bucketized_longitude = tf.feature_column.bucketized_column(\n longitude, boundaries=get_quantile_based_boundaries(\n training_examples[\"longitude\"], 10))\n\n #\n # YOUR CODE HERE: bucketize the following columns, following the example above:\n #\n bucketized_latitude = \n bucketized_housing_median_age = \n bucketized_median_income =\n bucketized_rooms_per_person =\n \n feature_columns = set([\n bucketized_longitude,\n bucketized_latitude,\n bucketized_housing_median_age,\n bucketized_households,\n bucketized_median_income,\n bucketized_rooms_per_person])\n \n return feature_columns\n",
"_____no_output_____"
],
[
"_ = train_model(\n learning_rate=1.0,\n steps=500,\n batch_size=100,\n feature_columns=construct_feature_columns(),\n training_examples=training_examples,\n training_targets=training_targets,\n validation_examples=validation_examples,\n validation_targets=validation_targets)",
"_____no_output_____"
]
],
[
[
"### Solution\n\nClick below for a solution.",
"_____no_output_____"
],
[
"You may be wondering how to determine how many buckets to use. That is of course data-dependent. Here, we just selected arbitrary values so as to obtain a not-too-large model.",
"_____no_output_____"
]
],
[
[
"def construct_feature_columns():\n \"\"\"Construct the TensorFlow Feature Columns.\n\n Returns:\n A set of feature columns\n \"\"\" \n households = tf.feature_column.numeric_column(\"households\")\n longitude = tf.feature_column.numeric_column(\"longitude\")\n latitude = tf.feature_column.numeric_column(\"latitude\")\n housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n median_income = tf.feature_column.numeric_column(\"median_income\")\n rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n \n # Divide households into 7 buckets.\n bucketized_households = tf.feature_column.bucketized_column(\n households, boundaries=get_quantile_based_boundaries(\n training_examples[\"households\"], 7))\n\n # Divide longitude into 10 buckets.\n bucketized_longitude = tf.feature_column.bucketized_column(\n longitude, boundaries=get_quantile_based_boundaries(\n training_examples[\"longitude\"], 10))\n \n # Divide latitude into 10 buckets.\n bucketized_latitude = tf.feature_column.bucketized_column(\n latitude, boundaries=get_quantile_based_boundaries(\n training_examples[\"latitude\"], 10))\n\n # Divide housing_median_age into 7 buckets.\n bucketized_housing_median_age = tf.feature_column.bucketized_column(\n housing_median_age, boundaries=get_quantile_based_boundaries(\n training_examples[\"housing_median_age\"], 7))\n \n # Divide median_income into 7 buckets.\n bucketized_median_income = tf.feature_column.bucketized_column(\n median_income, boundaries=get_quantile_based_boundaries(\n training_examples[\"median_income\"], 7))\n \n # Divide rooms_per_person into 7 buckets.\n bucketized_rooms_per_person = tf.feature_column.bucketized_column(\n rooms_per_person, boundaries=get_quantile_based_boundaries(\n training_examples[\"rooms_per_person\"], 7))\n \n feature_columns = set([\n bucketized_longitude,\n bucketized_latitude,\n bucketized_housing_median_age,\n bucketized_households,\n bucketized_median_income,\n bucketized_rooms_per_person])\n \n return feature_columns",
"_____no_output_____"
],
[
"_ = train_model(\n learning_rate=1.0,\n steps=500,\n batch_size=100,\n feature_columns=construct_feature_columns(),\n training_examples=training_examples,\n training_targets=training_targets,\n validation_examples=validation_examples,\n validation_targets=validation_targets)",
"_____no_output_____"
]
],
[
[
"## Feature Crosses\n\nCrossing two (or more) features is a clever way to learn non-linear relations using a linear model. In our problem, if we just use the feature `latitude` for learning, the model might learn that city blocks at a particular latitude (or within a particular range of latitudes since we have bucketized it) are more likely to be expensive than others. Similarly for the feature `longitude`. However, if we cross `longitude` by `latitude`, the crossed feature represents a well defined city block. If the model learns that certain city blocks (within range of latitudes and longitudes) are more likely to be more expensive than others, it is a stronger signal than two features considered individually.\n\nCurrently, the feature columns API only supports discrete features for crosses. To cross two continuous values, like `latitude` or `longitude`, we can bucketize them.\n\nIf we cross the `latitude` and `longitude` features (supposing, for example, that `longitude` was bucketized into `2` buckets, while `latitude` has `3` buckets), we actually get six crossed binary features. Each of these features will get its own separate weight when we train the model.",
"_____no_output_____"
],
[
"## Task 2: Train the Model Using Feature Crosses\n\n**Add a feature cross of `longitude` and `latitude` to your model, train it, and determine whether the results improve.**\n\nRefer to the TensorFlow API docs for [`crossed_column()`](https://www.tensorflow.org/api_docs/python/tf/feature_column/crossed_column) to build the feature column for your cross. Use a `hash_bucket_size` of `1000`.",
"_____no_output_____"
]
],
[
[
"def construct_feature_columns():\n \"\"\"Construct the TensorFlow Feature Columns.\n\n Returns:\n A set of feature columns\n \"\"\" \n households = tf.feature_column.numeric_column(\"households\")\n longitude = tf.feature_column.numeric_column(\"longitude\")\n latitude = tf.feature_column.numeric_column(\"latitude\")\n housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n median_income = tf.feature_column.numeric_column(\"median_income\")\n rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n \n # Divide households into 7 buckets.\n bucketized_households = tf.feature_column.bucketized_column(\n households, boundaries=get_quantile_based_boundaries(\n training_examples[\"households\"], 7))\n\n # Divide longitude into 10 buckets.\n bucketized_longitude = tf.feature_column.bucketized_column(\n longitude, boundaries=get_quantile_based_boundaries(\n training_examples[\"longitude\"], 10))\n \n # Divide latitude into 10 buckets.\n bucketized_latitude = tf.feature_column.bucketized_column(\n latitude, boundaries=get_quantile_based_boundaries(\n training_examples[\"latitude\"], 10))\n\n # Divide housing_median_age into 7 buckets.\n bucketized_housing_median_age = tf.feature_column.bucketized_column(\n housing_median_age, boundaries=get_quantile_based_boundaries(\n training_examples[\"housing_median_age\"], 7))\n \n # Divide median_income into 7 buckets.\n bucketized_median_income = tf.feature_column.bucketized_column(\n median_income, boundaries=get_quantile_based_boundaries(\n training_examples[\"median_income\"], 7))\n \n # Divide rooms_per_person into 7 buckets.\n bucketized_rooms_per_person = tf.feature_column.bucketized_column(\n rooms_per_person, boundaries=get_quantile_based_boundaries(\n training_examples[\"rooms_per_person\"], 7))\n \n # YOUR CODE HERE: Make a feature column for the long_x_lat feature cross\n long_x_lat = \n \n feature_columns = set([\n bucketized_longitude,\n bucketized_latitude,\n bucketized_housing_median_age,\n bucketized_households,\n bucketized_median_income,\n bucketized_rooms_per_person,\n long_x_lat])\n \n return feature_columns",
"_____no_output_____"
],
[
"_ = train_model(\n learning_rate=1.0,\n steps=500,\n batch_size=100,\n feature_columns=construct_feature_columns(),\n training_examples=training_examples,\n training_targets=training_targets,\n validation_examples=validation_examples,\n validation_targets=validation_targets)",
"_____no_output_____"
]
],
[
[
"### Solution\n\nClick below for the solution.",
"_____no_output_____"
]
],
[
[
"def construct_feature_columns():\n \"\"\"Construct the TensorFlow Feature Columns.\n\n Returns:\n A set of feature columns\n \"\"\" \n households = tf.feature_column.numeric_column(\"households\")\n longitude = tf.feature_column.numeric_column(\"longitude\")\n latitude = tf.feature_column.numeric_column(\"latitude\")\n housing_median_age = tf.feature_column.numeric_column(\"housing_median_age\")\n median_income = tf.feature_column.numeric_column(\"median_income\")\n rooms_per_person = tf.feature_column.numeric_column(\"rooms_per_person\")\n \n # Divide households into 7 buckets.\n bucketized_households = tf.feature_column.bucketized_column(\n households, boundaries=get_quantile_based_boundaries(\n training_examples[\"households\"], 7))\n\n # Divide longitude into 10 buckets.\n bucketized_longitude = tf.feature_column.bucketized_column(\n longitude, boundaries=get_quantile_based_boundaries(\n training_examples[\"longitude\"], 10))\n \n # Divide latitude into 10 buckets.\n bucketized_latitude = tf.feature_column.bucketized_column(\n latitude, boundaries=get_quantile_based_boundaries(\n training_examples[\"latitude\"], 10))\n\n # Divide housing_median_age into 7 buckets.\n bucketized_housing_median_age = tf.feature_column.bucketized_column(\n housing_median_age, boundaries=get_quantile_based_boundaries(\n training_examples[\"housing_median_age\"], 7))\n \n # Divide median_income into 7 buckets.\n bucketized_median_income = tf.feature_column.bucketized_column(\n median_income, boundaries=get_quantile_based_boundaries(\n training_examples[\"median_income\"], 7))\n \n # Divide rooms_per_person into 7 buckets.\n bucketized_rooms_per_person = tf.feature_column.bucketized_column(\n rooms_per_person, boundaries=get_quantile_based_boundaries(\n training_examples[\"rooms_per_person\"], 7))\n \n # YOUR CODE HERE: Make a feature column for the long_x_lat feature cross\n long_x_lat = tf.feature_column.crossed_column(\n set([bucketized_longitude, bucketized_latitude]), hash_bucket_size=1000) \n \n feature_columns = set([\n bucketized_longitude,\n bucketized_latitude,\n bucketized_housing_median_age,\n bucketized_households,\n bucketized_median_income,\n bucketized_rooms_per_person,\n long_x_lat])\n \n return feature_columns",
"_____no_output_____"
],
[
"_ = train_model(\n learning_rate=1.0,\n steps=500,\n batch_size=100,\n feature_columns=construct_feature_columns(),\n training_examples=training_examples,\n training_targets=training_targets,\n validation_examples=validation_examples,\n validation_targets=validation_targets)",
"_____no_output_____"
]
],
[
[
"## Optional Challenge: Try Out More Synthetic Features\n\nSo far, we've tried simple bucketized columns and feature crosses, but there are many more combinations that could potentially improve the results. For example, you could cross multiple columns. What happens if you vary the number of buckets? What other synthetic features can you think of? Do they improve the model?",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb7aeaac3074b7e8af258230602f80e64d07811f
| 24,309 |
ipynb
|
Jupyter Notebook
|
SQLite_DataBase_Code_2.0.ipynb
|
Austin-Cyr/Covid_Analysis
|
35d1bd28403952d87efff2e1512c1ab4dce55297
|
[
"MIT"
] | 2 |
2021-11-19T02:45:41.000Z
|
2021-11-19T02:50:23.000Z
|
SQLite_DataBase_Code_2.0.ipynb
|
hzlipscomb5/Covid_Analysis
|
35d1bd28403952d87efff2e1512c1ab4dce55297
|
[
"MIT"
] | null | null | null |
SQLite_DataBase_Code_2.0.ipynb
|
hzlipscomb5/Covid_Analysis
|
35d1bd28403952d87efff2e1512c1ab4dce55297
|
[
"MIT"
] | 1 |
2021-11-19T02:43:26.000Z
|
2021-11-19T02:43:26.000Z
| 30.770886 | 235 | 0.355259 |
[
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"import datetime as dt",
"_____no_output_____"
],
[
"import sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import session, sessionmaker, relationship\nfrom sqlalchemy import create_engine, func",
"_____no_output_____"
],
[
"import sqlite3",
"_____no_output_____"
]
],
[
[
"## Database Creation",
"_____no_output_____"
]
],
[
[
"conn = sqlite3.connect(\"covid_2.db\")",
"_____no_output_____"
],
[
"c = conn.cursor()",
"_____no_output_____"
],
[
"machine_learning_data = pd.read_csv(\"Datasets_HL/ML_Models/2.0_ML_Data.csv\")\nmachine_learning_data.to_sql('machine_learning_data', conn, if_exists='append', index = False,)",
"C:\\Users\\hzlip\\anaconda3\\envs\\mlenv\\lib\\site-packages\\pandas\\core\\generic.py:2789: UserWarning: The spaces in these column names will not be changed. In pandas versions < 0.14, spaces were converted to underscores.\n method=method,\n"
],
[
"# model_machine_learning_data = pd.read_csv('Datasets_HL/ML_Models/Model_Machine_Learning_Data.csv')\n# model_machine_learning_data.to_sql('covid_2.db', conn, if_exists='append', index = False,)",
"_____no_output_____"
],
[
"health_data = pd.read_csv('Datasets_HL/Obesity_and_Health/County_Health_Clean.csv')\nhealth_data.to_sql('health_data', conn, if_exists='append', index = False,)",
"_____no_output_____"
]
],
[
[
"## Database Viewing",
"_____no_output_____"
]
],
[
[
"# SQLAlchemy\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import inspect\n# Pandas\nimport pandas as pd\n\n# Path to sqlite\ndatabase_path = \"covid_2.db\"",
"_____no_output_____"
],
[
"# Create an engine that can talk to the database\nengine = create_engine(f\"sqlite:///{database_path}\")",
"_____no_output_____"
],
[
"# Get the name of the table. \ninspector = inspect(engine)\ninspector.get_table_names()",
"_____no_output_____"
],
[
"# Using the inspector to print the column names within the 'Census_Data' table and its types\ncolumns = inspector.get_columns('health_data')\npd.DataFrame(columns)\n",
"_____no_output_____"
],
[
"# Using the inspector to print the column names within the 'Census_Data' table and its types\ncolumns = inspector.get_columns('machine_learning_data')\npd.DataFrame(columns)",
"_____no_output_____"
],
[
"# Using the inspector to print the column names within the 'Census_Data' table and its types\ncolumns = inspector.get_columns('model_machine_learning_data')\npd.DataFrame(columns)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7aececb16c2c1dcad0622006e8bb481f02ee6c
| 177,546 |
ipynb
|
Jupyter Notebook
|
docs/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb
|
hussainsultan/ibis
|
cc6cfd49ce9ead3e793734b8e56b87040be093fc
|
[
"Apache-2.0"
] | 1 |
2022-03-22T10:39:37.000Z
|
2022-03-22T10:39:37.000Z
|
docs/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb
|
marlenezw/ibis
|
14b9baf3e1021e8698e7f0ae3c0ae5747543431c
|
[
"Apache-2.0"
] | null | null | null |
docs/tutorial/03-Expressions-Lazy-Mode-Logging.ipynb
|
marlenezw/ibis
|
14b9baf3e1021e8698e7f0ae3c0ae5747543431c
|
[
"Apache-2.0"
] | null | null | null | 258.813411 | 60,448 | 0.914203 |
[
[
[
"# Lazy Mode and Logging\n\nSo far, we have seen Ibis in interactive mode. Interactive mode (also known as eager mode) makes Ibis return the\nresults of an operation immediately.\n\nIn most cases, instead of using interactive mode, it makes more sense to use the default lazy mode.\nIn lazy mode, Ibis won't be executing the operations automatically, but instead, will generate an\nexpression to be executed at a later time.\n\nLet's see this in practice, starting with the same example as in previous tutorials - the geography database.",
"_____no_output_____"
]
],
[
[
"!curl -LsS -o $TEMPDIR/geography.db 'https://storage.googleapis.com/ibis-tutorial-data/geography.db'",
"_____no_output_____"
],
[
"import os\nimport tempfile\nimport ibis\n\n\nconnection = ibis.sqlite.connect(os.path.join(tempfile.gettempdir(), 'geography.db'))\ncountries = connection.table('countries')",
"_____no_output_____"
]
],
[
[
"In previous tutorials, we set interactive mode to `True`, and we obtained the result\nof every operation.",
"_____no_output_____"
]
],
[
[
"ibis.options.interactive = True\n\ncountries['name', 'continent', 'population'].limit(3)",
"_____no_output_____"
]
],
[
[
"But now let's see what happens if we leave the `interactive` option to `False` (the default),\nand we operate in lazy mode.",
"_____no_output_____"
]
],
[
[
"ibis.options.interactive = False\n\ncountries['name', 'continent', 'population'].limit(3)",
"_____no_output_____"
]
],
[
[
"What we find is the graph of the expressions that would return the desired result instead of the result itself.\n\nLet's analyze the expressions in the graph:\n\n- We query the `countries` table (all rows and all columns)\n- We select the `name`, `continent` and `population` columns\n- We limit the results to only the first `3` rows\n\nNow consider that the data is in a database, possibly in a different host than the one executing Ibis.\nAlso consider that the results returned to the user need to be moved to the memory of the host executing Ibis.\n\nWhen using interactive (or eager) mode, if we perform one operation at a time, we would do:\n\n- We would move all the rows and columns from the backend (database, big data system, etc.) into memory\n- Once in memory, we would discard all the columns but `name`, `continent` and `population`\n- After that, we would discard all the rows, except the first `3`\n\nThis is not very efficient. If you consider that the table can have millions of rows, backed by a\nbig data system like Spark or Impala, this may not even be possible (not enough memory to load all the data).\n\nThe solution is to use lazy mode. In lazy mode, instead of obtaining the results after each operation,\nwe build an expression (a graph) of all the operations that need to be done. After all the operations\nare recorded, the graph is sent to the backend which will perform the operation in an efficient way - only\nmoving to memory the required data.\n\nYou can think of this as writing a shopping list and requesting someone to go to the supermarket and buy\neverything you need once the list is complete. As opposed as getting someone to bring all the products of\nthe supermarket to your home and then return everything you don't want.\n\nLet's continue with our example, save the expression in a variable `countries_expression`, and check its type.",
"_____no_output_____"
]
],
[
[
"countries_expression = countries['name', 'continent', 'population'].limit(3)\ntype(countries_expression)",
"_____no_output_____"
]
],
[
[
"The type is an Ibis `TableExpr`, since the result is a table (in a broad way, you can consider it a dataframe).\n\nNow we have our query instructions (our expression, fetching only 3 columns and 3 rows) in the variable `countries_expression`.\n\nAt this point, nothing has been requested from the database. We have defined what we want to extract, but we didn't\nrequest it from the database yet. We can continue building our expression if we haven't finished yet. Or once we\nare done, we can simply request it from the database using the method `.execute()`.",
"_____no_output_____"
]
],
[
[
"countries_expression.execute()",
"_____no_output_____"
]
],
[
[
"We can build other types of expressions, for example, one that instead of returning a table,\nreturns a columns.",
"_____no_output_____"
]
],
[
[
"population_in_millions = (countries['population'] / 1_000_000).name('population_in_millions')\npopulation_in_millions",
"_____no_output_____"
]
],
[
[
"If we check its type, we can see how it is a `FloatingColumn` expression.",
"_____no_output_____"
]
],
[
[
"type(population_in_millions)",
"_____no_output_____"
]
],
[
[
"We can combine the previous expression to be a column of a table expression.",
"_____no_output_____"
]
],
[
[
"countries['name', 'continent', population_in_millions].limit(3)",
"_____no_output_____"
]
],
[
[
"Since we are in lazy mode (not interactive), those expressions don't request any data from the database\nunless explicitly requested with `.execute()`.\n\n## Logging queries\n\nFor SQL backends (and for others when it makes sense), the query sent to the database can be logged.\nThis can be done by setting the `verbose` option to `True`.",
"_____no_output_____"
]
],
[
[
"ibis.options.verbose = True\n\ncountries['name', 'continent', population_in_millions].limit(3).execute()",
"SELECT t0.name, t0.continent, t0.population / CAST(? AS REAL) AS population_in_millions \nFROM base.countries AS t0\n LIMIT ? OFFSET ?\n"
]
],
[
[
"By default, the logging is done to the terminal, but we can process the query with a custom function.\nThis allows us to save executed queries to a file, save to a database, send them to a web service, etc.\n\nFor example, to save queries to a file, we can write a custom function that given a query, saves it to a\nlog file.",
"_____no_output_____"
]
],
[
[
"import os\nimport datetime\nimport tempfile\nfrom pathlib import Path\n\n\ndef log_query_to_file(query: str) -> None:\n \"\"\"\n Log queries to `data/tutorial_queries.log`.\n \n Each file is a query. Line breaks in the query are \n represented with the string '\\n'.\n \n A timestamp of when the query is executed is added.\n \"\"\"\n dirname = Path(tempfile.gettempdir())\n fname = dirname / 'tutorial_queries.log'\n query_in_a_single_line = query.replace('\\n', r'\\n')\n with fname.open(mode='a') as f:\n f.write(f'{query_in_a_single_line}\\n')",
"_____no_output_____"
]
],
[
[
"Then we can set the `verbose_log` option to the custom function, execute one query,\nwait one second, and execute another query.",
"_____no_output_____"
]
],
[
[
"import time\n\nibis.options.verbose_log = log_query_to_file\n\ncountries.execute()\ntime.sleep(1.)\ncountries['name', 'continent', population_in_millions].limit(3).execute()",
"_____no_output_____"
]
],
[
[
"This has created a log file in `data/tutorial_queries.log` where the executed queries have been logged.",
"_____no_output_____"
]
],
[
[
"!cat -n data/tutorial_queries.log",
"2020-07-02 17:51:02.760861 - SELECT t0.iso_alpha2, t0.iso_alpha3, t0.iso_numeric, t0.fips, t0.name, t0.capital, t0.area_km2, t0.population, t0.continent \\nFROM base.countries AS t0\\n LIMIT ? OFFSET ?\n2020-07-02 17:51:03.779023 - SELECT t0.name, t0.continent, t0.population / CAST(? AS REAL) AS population_in_millions \\nFROM base.countries AS t0\\n LIMIT ? OFFSET ?\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7af478ba3566bea34f4222c4ace20c16149386
| 213,220 |
ipynb
|
Jupyter Notebook
|
UNSW-NB15/3-Filter-Statistical-Tests/3.1-Mutual-information.ipynb
|
theavila/EmployingFS
|
a2948d9a007eda8d4575a3ce3f093d042b08c7c8
|
[
"Apache-2.0"
] | 1 |
2021-06-20T07:44:45.000Z
|
2021-06-20T07:44:45.000Z
|
UNSW-NB15/3-Filter-Statistical-Tests/3.1-Mutual-information.ipynb
|
theavila/EmployingFS
|
a2948d9a007eda8d4575a3ce3f093d042b08c7c8
|
[
"Apache-2.0"
] | null | null | null |
UNSW-NB15/3-Filter-Statistical-Tests/3.1-Mutual-information.ipynb
|
theavila/EmployingFS
|
a2948d9a007eda8d4575a3ce3f093d042b08c7c8
|
[
"Apache-2.0"
] | null | null | null | 56.90419 | 33,860 | 0.672057 |
[
[
[
"## Mutual information",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_selection import mutual_info_classif, mutual_info_regression\nfrom sklearn.feature_selection import SelectKBest, SelectPercentile",
"_____no_output_____"
]
],
[
[
"## Read Data",
"_____no_output_____"
]
],
[
[
"data = pd.read_csv('../UNSW_Train.csv')\ndata.shape",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
]
],
[
[
"### Train - Test Split",
"_____no_output_____"
]
],
[
[
"# separate train and test sets\n\nX_train, X_test, y_train, y_test = train_test_split(\n data.drop(labels=['is_intrusion'], axis=1),\n data['is_intrusion'],\n test_size=0.2,\n random_state=0)\n\nX_train.shape, X_test.shape",
"_____no_output_____"
]
],
[
[
"### Determine Mutual Information",
"_____no_output_____"
]
],
[
[
"mi = mutual_info_classif(X_test, y_test) \nmi",
"_____no_output_____"
],
[
"# 1. Let's capture the above array in a pandas series\n# 2. Add the variable names in the index\n# 3. Sort the features based on their mutual information value\n# 4. And make a var plot\n\nmi = pd.Series(mi)\nmi.index = X_test.columns\nmi.sort_values(ascending=False).plot.bar(figsize=(20, 6))\nplt.ylabel('Mutual Information')",
"_____no_output_____"
]
],
[
[
"### Select top k features based on MI",
"_____no_output_____"
]
],
[
[
"# select the top 15 features based on their mutual information value\nsel_ = SelectKBest(mutual_info_classif, k=15).fit(X_test, y_test)\n\n# display features\nX_test.columns[sel_.get_support()]",
"_____no_output_____"
],
[
"# to remove the rest of the features:\n\nX_train = sel_.transform(X_train)\nX_test = sel_.transform(X_test)",
"_____no_output_____"
],
[
"X_train.shape, X_test.shape",
"_____no_output_____"
]
],
[
[
"## Standardize Data\n",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import StandardScaler\nscaler = StandardScaler().fit(X_train)\nX_train = scaler.transform(X_train)",
"_____no_output_____"
]
],
[
[
"## Classifiers",
"_____no_output_____"
]
],
[
[
"from sklearn import linear_model\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom catboost import CatBoostClassifier",
"_____no_output_____"
]
],
[
[
"## Metrics Evaluation",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import roc_curve, f1_score\nfrom sklearn import metrics\nfrom sklearn.model_selection import cross_val_score",
"_____no_output_____"
]
],
[
[
"### Logistic Regression",
"_____no_output_____"
]
],
[
[
"%%time\nclf_LR = linear_model.LogisticRegression(n_jobs=-1, random_state=42, C=25).fit(X_train, y_train)",
"CPU times: user 76.1 ms, sys: 197 ms, total: 273 ms\nWall time: 1.95 s\n"
],
[
"pred_y_test = clf_LR.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_test))\n\nf1 = f1_score(y_test, pred_y_test)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_test)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.3403005503436083\nF1 Score: 0.06279116872594694\nFPR: 0.007736083940956784\nTPR: 0.032531587121689125\n"
]
],
[
[
"### Naive Bayes",
"_____no_output_____"
]
],
[
[
"%%time\nclf_NB = GaussianNB(var_smoothing=1e-08).fit(X_train, y_train)",
"CPU times: user 42.1 ms, sys: 10.1 ms, total: 52.1 ms\nWall time: 50.4 ms\n"
],
[
"pred_y_testNB = clf_NB.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_testNB))\n\nf1 = f1_score(y_test, pred_y_testNB)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testNB)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.7638940374689897\nF1 Score: 0.8035680394761815\nFPR: 0.12386626356037703\nTPR: 0.7109096251521638\n"
]
],
[
[
"### Random Forest\n",
"_____no_output_____"
]
],
[
[
"%%time\nclf_RF = RandomForestClassifier(random_state=0,max_depth=100,n_estimators=1000).fit(X_train, y_train)",
"CPU times: user 50 s, sys: 679 ms, total: 50.7 s\nWall time: 50.7 s\n"
],
[
"pred_y_testRF = clf_RF.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_testRF))\n\nf1 = f1_score(y_test, pred_y_testRF, average='weighted', zero_division=0)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testRF)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nFPR: 1.0\nTPR: 1.0\n"
]
],
[
[
"### KNN",
"_____no_output_____"
]
],
[
[
"%%time\nclf_KNN = KNeighborsClassifier(algorithm='ball_tree',leaf_size=1,n_neighbors=5,weights='uniform').fit(X_train, y_train)",
"CPU times: user 6.47 s, sys: 40.5 ms, total: 6.51 s\nWall time: 6.48 s\n"
],
[
"pred_y_testKNN = clf_KNN.predict(X_test)\nprint('accuracy_score:', accuracy_score(y_test, pred_y_testKNN))\n\nf1 = f1_score(y_test, pred_y_testKNN)\nprint('f1:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testKNN)\nprint('fpr:', fpr[1])\nprint('tpr:', tpr[1])",
"accuracy_score: 0.7429068407995666\nf1: 0.8377366640270678\nfpr: 0.7528899164147252\ntpr: 0.9769550434454098\n"
]
],
[
[
"### CatBoost",
"_____no_output_____"
]
],
[
[
"%%time\nclf_CB = CatBoostClassifier(random_state=0,depth=7,iterations=50,learning_rate=0.04).fit(X_train, y_train)",
"0:\tlearn: 0.6539535\ttotal: 64.2ms\tremaining: 3.15s\n1:\tlearn: 0.6177720\ttotal: 69.1ms\tremaining: 1.66s\n2:\tlearn: 0.5842853\ttotal: 76.1ms\tremaining: 1.19s\n3:\tlearn: 0.5532671\ttotal: 85.9ms\tremaining: 988ms\n4:\tlearn: 0.5243632\ttotal: 95.4ms\tremaining: 859ms\n5:\tlearn: 0.4974323\ttotal: 104ms\tremaining: 764ms\n6:\tlearn: 0.4722391\ttotal: 113ms\tremaining: 695ms\n7:\tlearn: 0.4485890\ttotal: 120ms\tremaining: 629ms\n8:\tlearn: 0.4264570\ttotal: 129ms\tremaining: 588ms\n9:\tlearn: 0.4056514\ttotal: 139ms\tremaining: 554ms\n10:\tlearn: 0.3860523\ttotal: 146ms\tremaining: 518ms\n11:\tlearn: 0.3676140\ttotal: 155ms\tremaining: 492ms\n12:\tlearn: 0.3502077\ttotal: 162ms\tremaining: 462ms\n13:\tlearn: 0.3337846\ttotal: 169ms\tremaining: 435ms\n14:\tlearn: 0.3182790\ttotal: 178ms\tremaining: 414ms\n15:\tlearn: 0.3036198\ttotal: 186ms\tremaining: 394ms\n16:\tlearn: 0.2897599\ttotal: 194ms\tremaining: 377ms\n17:\tlearn: 0.2765851\ttotal: 199ms\tremaining: 354ms\n18:\tlearn: 0.2641292\ttotal: 208ms\tremaining: 339ms\n19:\tlearn: 0.2523268\ttotal: 216ms\tremaining: 324ms\n20:\tlearn: 0.2410762\ttotal: 221ms\tremaining: 305ms\n21:\tlearn: 0.2304203\ttotal: 230ms\tremaining: 292ms\n22:\tlearn: 0.2202787\ttotal: 237ms\tremaining: 278ms\n23:\tlearn: 0.2106737\ttotal: 246ms\tremaining: 266ms\n24:\tlearn: 0.2015102\ttotal: 254ms\tremaining: 254ms\n25:\tlearn: 0.1927892\ttotal: 263ms\tremaining: 243ms\n26:\tlearn: 0.1844572\ttotal: 270ms\tremaining: 230ms\n27:\tlearn: 0.1765269\ttotal: 277ms\tremaining: 218ms\n28:\tlearn: 0.1689918\ttotal: 287ms\tremaining: 208ms\n29:\tlearn: 0.1618053\ttotal: 296ms\tremaining: 197ms\n30:\tlearn: 0.1549472\ttotal: 303ms\tremaining: 186ms\n31:\tlearn: 0.1484087\ttotal: 312ms\tremaining: 175ms\n32:\tlearn: 0.1421732\ttotal: 320ms\tremaining: 165ms\n33:\tlearn: 0.1362096\ttotal: 329ms\tremaining: 155ms\n34:\tlearn: 0.1304903\ttotal: 335ms\tremaining: 144ms\n35:\tlearn: 0.1250370\ttotal: 342ms\tremaining: 133ms\n36:\tlearn: 0.1198454\ttotal: 352ms\tremaining: 124ms\n37:\tlearn: 0.1148854\ttotal: 361ms\tremaining: 114ms\n38:\tlearn: 0.1101140\ttotal: 367ms\tremaining: 103ms\n39:\tlearn: 0.1055636\ttotal: 374ms\tremaining: 93.5ms\n40:\tlearn: 0.1012144\ttotal: 382ms\tremaining: 83.8ms\n41:\tlearn: 0.0970736\ttotal: 390ms\tremaining: 74.4ms\n42:\tlearn: 0.0930938\ttotal: 399ms\tremaining: 64.9ms\n43:\tlearn: 0.0892703\ttotal: 404ms\tremaining: 55ms\n44:\tlearn: 0.0856642\ttotal: 412ms\tremaining: 45.8ms\n45:\tlearn: 0.0821772\ttotal: 420ms\tremaining: 36.5ms\n46:\tlearn: 0.0788375\ttotal: 427ms\tremaining: 27.3ms\n47:\tlearn: 0.0756429\ttotal: 435ms\tremaining: 18.1ms\n48:\tlearn: 0.0725849\ttotal: 444ms\tremaining: 9.06ms\n49:\tlearn: 0.0696698\ttotal: 453ms\tremaining: 0us\nCPU times: user 3.66 s, sys: 562 ms, total: 4.22 s\nWall time: 527 ms\n"
],
[
"pred_y_testCB = clf_CB.predict(X_test)\nprint('Accuracy:', accuracy_score(y_test, pred_y_testCB))\n\nf1 = f1_score(y_test, pred_y_testCB, average='weighted', zero_division=0)\nprint('F1 Score:', f1)\n\nfpr, tpr, thresholds = roc_curve(y_test, pred_y_testCB)\nprint('FPR:', fpr[1])\nprint('TPR:', tpr[1])",
"Accuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nFPR: 1.0\nTPR: 1.0\n"
]
],
[
[
"## Model Evaluation\n",
"_____no_output_____"
]
],
[
[
"data = pd.read_csv('../UNSW_Test.csv')\ndata.shape",
"_____no_output_____"
],
[
"# Create feature matrix X and target vextor y\ny_eval = data['is_intrusion']\nX_eval = data.drop(columns=['is_intrusion'])",
"_____no_output_____"
],
[
"X_eval = sel_.transform(X_eval)",
"_____no_output_____"
],
[
"X_eval.shape",
"_____no_output_____"
]
],
[
[
"### Model Evaluation - Logistic Regression\n\n",
"_____no_output_____"
]
],
[
[
"modelLR = linear_model.LogisticRegression(n_jobs=-1, random_state=42, C=25)\nmodelLR.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredLR = modelLR.predict(X_eval)\ny_predLR = modelLR.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreLR = modelLR.score(X_train, y_train)\ntest_scoreLR = modelLR.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreLR)\nprint(\"Testing accuracy is \", test_scoreLR)",
"Training accuracy is 1.0\nTesting accuracy is 0.3403005503436083\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreLR)\nprint('F1 Score:',f1_score(y_test, y_predLR))\nprint('Precision Score:',precision_score(y_test, y_predLR))\nprint('Recall Score:', recall_score(y_test, y_predLR))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predLR))",
"Performance measures for test:\n--------\nAccuracy: 0.3403005503436083\nF1 Score: 0.06279116872594694\nPrecision Score: 0.8990719257540604\nRecall Score: 0.032531587121689125\nConfusion Matrix:\n [[11159 87]\n [23048 775]]\n"
]
],
[
[
"### Cross validation - Logistic Regression\n\n\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelLR, X_eval, y_eval, cv=10, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 0.82946 (+/- 0.08625)\nF1 Score: 0.87260 (+/- 0.05482)\nPrecision: 0.90156 (+/- 0.14756)\nRecall: 0.85509 (+/- 0.13450)\n"
]
],
[
[
"### Model Evaluation - Naive Bayes\n\n\n\n",
"_____no_output_____"
]
],
[
[
"modelNB = GaussianNB(var_smoothing=1e-08)\nmodelNB.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredNB = modelNB.predict(X_eval)\ny_predNB = modelNB.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreNB = modelNB.score(X_train, y_train)\ntest_scoreNB = modelNB.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreNB)\nprint(\"Testing accuracy is \", test_scoreNB)",
"Training accuracy is 1.0\nTesting accuracy is 0.7638940374689897\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreNB)\nprint('F1 Score:',f1_score(y_test, y_predNB))\nprint('Precision Score:',precision_score(y_test, y_predNB))\nprint('Recall Score:', recall_score(y_test, y_predNB))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predNB))",
"Performance measures for test:\n--------\nAccuracy: 0.7638940374689897\nF1 Score: 0.8035680394761815\nPrecision Score: 0.9240002182334006\nRecall Score: 0.7109096251521638\nConfusion Matrix:\n [[ 9853 1393]\n [ 6887 16936]]\n"
]
],
[
[
"### Cross validation - Naive Bayes\n\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelNB, X_eval, y_eval, cv=10, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 0.83509 (+/- 0.17800)\nF1 Score: 0.89274 (+/- 0.09849)\nPrecision: 0.82846 (+/- 0.17068)\nRecall: 0.97471 (+/- 0.02269)\n"
]
],
[
[
"### Model Evaluation - Random Forest\n\n",
"_____no_output_____"
]
],
[
[
"modelRF = RandomForestClassifier(random_state=0,max_depth=100,n_estimators=1000)\nmodelRF.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredRF = modelRF.predict(X_eval)\ny_predRF = modelRF.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreRF = modelRF.score(X_train, y_train)\ntest_scoreRF = modelRF.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreRF)\nprint(\"Testing accuracy is \", test_scoreRF)",
"Training accuracy is 1.0\nTesting accuracy is 0.6793179161082438\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreRF)\nprint('F1 Score:', f1_score(y_test, y_predRF, average='weighted', zero_division=0))\nprint('Precision Score:', precision_score(y_test, y_predRF, average='weighted', zero_division=0))\nprint('Recall Score:', recall_score(y_test, y_predRF, average='weighted', zero_division=0))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predRF))",
"Performance measures for test:\n--------\nAccuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nPrecision Score: 0.4614728311456469\nRecall Score: 0.6793179161082438\nConfusion Matrix:\n [[ 0 11246]\n [ 0 23823]]\n"
]
],
[
[
"### Cross validation - Random Forest\n\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelRF, X_eval, y_eval, cv=10, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 1.00000 (+/- 0.00000)\nF1 Score: 1.00000 (+/- 0.00000)\nPrecision: 1.00000 (+/- 0.00000)\nRecall: 1.00000 (+/- 0.00000)\n"
]
],
[
[
"### Model Evaluation - KNN",
"_____no_output_____"
]
],
[
[
"modelKNN = KNeighborsClassifier(algorithm='ball_tree',leaf_size=1,n_neighbors=5,weights='uniform')\nmodelKNN.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Predict on the new unseen test data\ny_evalpredKNN = modelKNN.predict(X_eval)\ny_predKNN = modelKNN.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreKNN = modelKNN.score(X_train, y_train)\ntest_scoreKNN = modelKNN.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreKNN)\nprint(\"Testing accuracy is \", test_scoreKNN)",
"Training accuracy is 0.9999215809284818\nTesting accuracy is 0.7429068407995666\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreKNN)\nprint('F1 Score:', f1_score(y_test, y_predKNN))\nprint('Precision Score:', precision_score(y_test, y_predKNN))\nprint('Recall Score:', recall_score(y_test, y_predKNN))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predKNN))",
"Performance measures for test:\n--------\nAccuracy: 0.7429068407995666\nF1 Score: 0.8377366640270678\nPrecision Score: 0.7332472196843199\nRecall Score: 0.9769550434454098\nConfusion Matrix:\n [[ 2779 8467]\n [ 549 23274]]\n"
]
],
[
[
"### Cross validation - KNN\n\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='accuracy')\nprint(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\n\nf = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='f1')\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\n\nprecision = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='precision')\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\n\nrecall = cross_val_score(modelKNN, X_eval, y_eval, cv=10, scoring='recall')\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 0.91888 (+/- 0.09863)\nF1 Score: 0.94287 (+/- 0.06320)\nPrecision: 0.93307 (+/- 0.14255)\nRecall: 0.95747 (+/- 0.05023)\n"
]
],
[
[
"### Model Evaluation - CatBoost",
"_____no_output_____"
]
],
[
[
"modelCB = CatBoostClassifier(random_state=0,depth=7,iterations=50,learning_rate=0.04)\nmodelCB.fit(X_train, y_train)",
"0:\tlearn: 0.6539535\ttotal: 5.55ms\tremaining: 272ms\n1:\tlearn: 0.6177720\ttotal: 10.3ms\tremaining: 247ms\n2:\tlearn: 0.5842853\ttotal: 16.2ms\tremaining: 253ms\n3:\tlearn: 0.5532671\ttotal: 24.9ms\tremaining: 286ms\n4:\tlearn: 0.5243632\ttotal: 33.5ms\tremaining: 302ms\n5:\tlearn: 0.4974323\ttotal: 42.8ms\tremaining: 314ms\n6:\tlearn: 0.4722391\ttotal: 51.5ms\tremaining: 316ms\n7:\tlearn: 0.4485890\ttotal: 57.5ms\tremaining: 302ms\n8:\tlearn: 0.4264570\ttotal: 65.7ms\tremaining: 299ms\n9:\tlearn: 0.4056514\ttotal: 73.9ms\tremaining: 295ms\n10:\tlearn: 0.3860523\ttotal: 80.1ms\tremaining: 284ms\n11:\tlearn: 0.3676140\ttotal: 88.8ms\tremaining: 281ms\n12:\tlearn: 0.3502077\ttotal: 95.3ms\tremaining: 271ms\n13:\tlearn: 0.3337846\ttotal: 102ms\tremaining: 261ms\n14:\tlearn: 0.3182790\ttotal: 110ms\tremaining: 256ms\n15:\tlearn: 0.3036198\ttotal: 118ms\tremaining: 252ms\n16:\tlearn: 0.2897599\ttotal: 127ms\tremaining: 246ms\n17:\tlearn: 0.2765851\ttotal: 132ms\tremaining: 235ms\n18:\tlearn: 0.2641292\ttotal: 140ms\tremaining: 229ms\n19:\tlearn: 0.2523268\ttotal: 149ms\tremaining: 223ms\n20:\tlearn: 0.2410762\ttotal: 154ms\tremaining: 213ms\n21:\tlearn: 0.2304203\ttotal: 162ms\tremaining: 207ms\n22:\tlearn: 0.2202787\ttotal: 169ms\tremaining: 198ms\n23:\tlearn: 0.2106737\ttotal: 177ms\tremaining: 192ms\n24:\tlearn: 0.2015102\ttotal: 186ms\tremaining: 186ms\n25:\tlearn: 0.1927892\ttotal: 194ms\tremaining: 179ms\n26:\tlearn: 0.1844572\ttotal: 200ms\tremaining: 170ms\n27:\tlearn: 0.1765269\ttotal: 206ms\tremaining: 162ms\n28:\tlearn: 0.1689918\ttotal: 215ms\tremaining: 155ms\n29:\tlearn: 0.1618053\ttotal: 223ms\tremaining: 149ms\n30:\tlearn: 0.1549472\ttotal: 231ms\tremaining: 141ms\n31:\tlearn: 0.1484087\ttotal: 239ms\tremaining: 135ms\n32:\tlearn: 0.1421732\ttotal: 247ms\tremaining: 127ms\n33:\tlearn: 0.1362096\ttotal: 256ms\tremaining: 120ms\n34:\tlearn: 0.1304903\ttotal: 261ms\tremaining: 112ms\n35:\tlearn: 0.1250370\ttotal: 267ms\tremaining: 104ms\n36:\tlearn: 0.1198454\ttotal: 274ms\tremaining: 96.4ms\n37:\tlearn: 0.1148854\ttotal: 283ms\tremaining: 89.4ms\n38:\tlearn: 0.1101140\ttotal: 288ms\tremaining: 81.4ms\n39:\tlearn: 0.1055636\ttotal: 296ms\tremaining: 74ms\n40:\tlearn: 0.1012144\ttotal: 304ms\tremaining: 66.7ms\n41:\tlearn: 0.0970736\ttotal: 312ms\tremaining: 59.4ms\n42:\tlearn: 0.0930938\ttotal: 320ms\tremaining: 52.1ms\n43:\tlearn: 0.0892703\ttotal: 325ms\tremaining: 44.4ms\n44:\tlearn: 0.0856642\ttotal: 334ms\tremaining: 37.1ms\n45:\tlearn: 0.0821772\ttotal: 342ms\tremaining: 29.7ms\n46:\tlearn: 0.0788375\ttotal: 349ms\tremaining: 22.3ms\n47:\tlearn: 0.0756429\ttotal: 358ms\tremaining: 14.9ms\n48:\tlearn: 0.0725849\ttotal: 366ms\tremaining: 7.47ms\n49:\tlearn: 0.0696698\ttotal: 374ms\tremaining: 0us\n"
],
[
"# Predict on the new unseen test data\ny_evalpredCB = modelCB.predict(X_eval)\ny_predCB = modelCB.predict(X_test)",
"_____no_output_____"
],
[
"train_scoreCB = modelCB.score(X_train, y_train)\ntest_scoreCB = modelCB.score(X_test, y_test)\nprint(\"Training accuracy is \", train_scoreCB)\nprint(\"Testing accuracy is \", test_scoreCB)",
"Training accuracy is 1.0\nTesting accuracy is 0.6793179161082438\n"
],
[
"from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nprint('Performance measures for test:')\nprint('--------')\nprint('Accuracy:', test_scoreCB)\nprint('F1 Score:',f1_score(y_test, y_predCB, average='weighted', zero_division=0))\nprint('Precision Score:',precision_score(y_test, y_predCB, average='weighted', zero_division=0))\nprint('Recall Score:', recall_score(y_test, y_predCB, average='weighted', zero_division=0))\nprint('Confusion Matrix:\\n', confusion_matrix(y_test, y_predCB))",
"Performance measures for test:\n--------\nAccuracy: 0.6793179161082438\nF1 Score: 0.5495955550990522\nPrecision Score: 0.4614728311456469\nRecall Score: 0.6793179161082438\nConfusion Matrix:\n [[ 0 11246]\n [ 0 23823]]\n"
]
],
[
[
"### Cross validation - CatBoost",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn import metrics\n\naccuracy = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='accuracy')\nf = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='f1')\nprecision = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='precision')\nrecall = cross_val_score(modelCB, X_eval, y_eval, cv=10, scoring='recall')",
"0:\tlearn: 0.6539528\ttotal: 6.32ms\tremaining: 310ms\n1:\tlearn: 0.6177707\ttotal: 11.5ms\tremaining: 275ms\n2:\tlearn: 0.5842815\ttotal: 18.3ms\tremaining: 286ms\n3:\tlearn: 0.5532538\ttotal: 27.1ms\tremaining: 311ms\n4:\tlearn: 0.5243420\ttotal: 36.2ms\tremaining: 326ms\n5:\tlearn: 0.4974026\ttotal: 45.3ms\tremaining: 332ms\n6:\tlearn: 0.4722047\ttotal: 54.6ms\tremaining: 336ms\n7:\tlearn: 0.4485551\ttotal: 61.8ms\tremaining: 325ms\n8:\tlearn: 0.4264184\ttotal: 70.9ms\tremaining: 323ms\n9:\tlearn: 0.4056106\ttotal: 79.8ms\tremaining: 319ms\n10:\tlearn: 0.3860123\ttotal: 86.5ms\tremaining: 307ms\n11:\tlearn: 0.3675728\ttotal: 95.9ms\tremaining: 304ms\n12:\tlearn: 0.3501676\ttotal: 103ms\tremaining: 292ms\n13:\tlearn: 0.3337449\ttotal: 109ms\tremaining: 281ms\n14:\tlearn: 0.3182385\ttotal: 118ms\tremaining: 275ms\n15:\tlearn: 0.3035780\ttotal: 127ms\tremaining: 270ms\n16:\tlearn: 0.2897160\ttotal: 136ms\tremaining: 265ms\n17:\tlearn: 0.2765431\ttotal: 142ms\tremaining: 252ms\n18:\tlearn: 0.2640846\ttotal: 150ms\tremaining: 245ms\n19:\tlearn: 0.2522794\ttotal: 160ms\tremaining: 240ms\n20:\tlearn: 0.2410310\ttotal: 165ms\tremaining: 228ms\n21:\tlearn: 0.2303739\ttotal: 174ms\tremaining: 222ms\n22:\tlearn: 0.2202327\ttotal: 182ms\tremaining: 213ms\n23:\tlearn: 0.2106240\ttotal: 191ms\tremaining: 207ms\n24:\tlearn: 0.2014600\ttotal: 200ms\tremaining: 200ms\n25:\tlearn: 0.1927374\ttotal: 209ms\tremaining: 193ms\n26:\tlearn: 0.1844074\ttotal: 215ms\tremaining: 183ms\n27:\tlearn: 0.1764782\ttotal: 222ms\tremaining: 174ms\n28:\tlearn: 0.1689413\ttotal: 231ms\tremaining: 167ms\n29:\tlearn: 0.1617539\ttotal: 240ms\tremaining: 160ms\n30:\tlearn: 0.1548947\ttotal: 248ms\tremaining: 152ms\n31:\tlearn: 0.1483554\ttotal: 257ms\tremaining: 145ms\n32:\tlearn: 0.1421183\ttotal: 266ms\tremaining: 137ms\n33:\tlearn: 0.1361548\ttotal: 276ms\tremaining: 130ms\n34:\tlearn: 0.1304377\ttotal: 281ms\tremaining: 120ms\n35:\tlearn: 0.1249857\ttotal: 288ms\tremaining: 112ms\n36:\tlearn: 0.1197926\ttotal: 297ms\tremaining: 104ms\n37:\tlearn: 0.1148310\ttotal: 306ms\tremaining: 96.6ms\n38:\tlearn: 0.1100617\ttotal: 312ms\tremaining: 87.9ms\n39:\tlearn: 0.1055122\ttotal: 320ms\tremaining: 80ms\n40:\tlearn: 0.1011635\ttotal: 328ms\tremaining: 72.1ms\n41:\tlearn: 0.0970202\ttotal: 337ms\tremaining: 64.3ms\n42:\tlearn: 0.0930409\ttotal: 346ms\tremaining: 56.4ms\n43:\tlearn: 0.0892194\ttotal: 352ms\tremaining: 48ms\n44:\tlearn: 0.0856081\ttotal: 361ms\tremaining: 40.1ms\n45:\tlearn: 0.0821215\ttotal: 369ms\tremaining: 32.1ms\n46:\tlearn: 0.0787825\ttotal: 377ms\tremaining: 24.1ms\n47:\tlearn: 0.0755880\ttotal: 386ms\tremaining: 16.1ms\n48:\tlearn: 0.0725303\ttotal: 395ms\tremaining: 8.07ms\n49:\tlearn: 0.0696130\ttotal: 404ms\tremaining: 0us\n0:\tlearn: 0.6539528\ttotal: 5.38ms\tremaining: 264ms\n1:\tlearn: 0.6177707\ttotal: 10.7ms\tremaining: 256ms\n2:\tlearn: 0.5842815\ttotal: 16.9ms\tremaining: 264ms\n3:\tlearn: 0.5532546\ttotal: 27.4ms\tremaining: 315ms\n4:\tlearn: 0.5243434\ttotal: 36.7ms\tremaining: 330ms\n5:\tlearn: 0.4974066\ttotal: 45.9ms\tremaining: 337ms\n6:\tlearn: 0.4722081\ttotal: 55ms\tremaining: 338ms\n7:\tlearn: 0.4485585\ttotal: 61.6ms\tremaining: 323ms\n8:\tlearn: 0.4264236\ttotal: 70.7ms\tremaining: 322ms\n9:\tlearn: 0.4056153\ttotal: 79.6ms\tremaining: 318ms\n10:\tlearn: 0.3860167\ttotal: 86.3ms\tremaining: 306ms\n11:\tlearn: 0.3675767\ttotal: 95.6ms\tremaining: 303ms\n12:\tlearn: 0.3501712\ttotal: 103ms\tremaining: 292ms\n13:\tlearn: 0.3337483\ttotal: 109ms\tremaining: 281ms\n14:\tlearn: 0.3182437\ttotal: 118ms\tremaining: 276ms\n15:\tlearn: 0.3035827\ttotal: 127ms\tremaining: 270ms\n16:\tlearn: 0.2897194\ttotal: 136ms\tremaining: 265ms\n17:\tlearn: 0.2765463\ttotal: 142ms\tremaining: 252ms\n18:\tlearn: 0.2640885\ttotal: 152ms\tremaining: 248ms\n19:\tlearn: 0.2522834\ttotal: 161ms\tremaining: 242ms\n20:\tlearn: 0.2410347\ttotal: 167ms\tremaining: 230ms\n21:\tlearn: 0.2303782\ttotal: 176ms\tremaining: 224ms\n22:\tlearn: 0.2202366\ttotal: 183ms\tremaining: 215ms\n23:\tlearn: 0.2106264\ttotal: 192ms\tremaining: 208ms\n24:\tlearn: 0.2014624\ttotal: 202ms\tremaining: 202ms\n25:\tlearn: 0.1927403\ttotal: 211ms\tremaining: 195ms\n26:\tlearn: 0.1844102\ttotal: 217ms\tremaining: 185ms\n27:\tlearn: 0.1764815\ttotal: 224ms\tremaining: 176ms\n28:\tlearn: 0.1689450\ttotal: 234ms\tremaining: 169ms\n29:\tlearn: 0.1617582\ttotal: 243ms\tremaining: 162ms\n30:\tlearn: 0.1549000\ttotal: 251ms\tremaining: 154ms\n31:\tlearn: 0.1483606\ttotal: 260ms\tremaining: 146ms\n32:\tlearn: 0.1421241\ttotal: 269ms\tremaining: 138ms\n33:\tlearn: 0.1361606\ttotal: 278ms\tremaining: 131ms\n34:\tlearn: 0.1304432\ttotal: 285ms\tremaining: 122ms\n35:\tlearn: 0.1249908\ttotal: 291ms\tremaining: 113ms\n36:\tlearn: 0.1197981\ttotal: 300ms\tremaining: 105ms\n37:\tlearn: 0.1148366\ttotal: 309ms\tremaining: 97.5ms\n38:\tlearn: 0.1100671\ttotal: 314ms\tremaining: 88.6ms\n39:\tlearn: 0.1055181\ttotal: 322ms\tremaining: 80.5ms\n40:\tlearn: 0.1011691\ttotal: 331ms\tremaining: 72.6ms\n41:\tlearn: 0.0970279\ttotal: 339ms\tremaining: 64.7ms\n42:\tlearn: 0.0930481\ttotal: 348ms\tremaining: 56.6ms\n43:\tlearn: 0.0892263\ttotal: 353ms\tremaining: 48.2ms\n44:\tlearn: 0.0856175\ttotal: 362ms\tremaining: 40.3ms\n45:\tlearn: 0.0821307\ttotal: 371ms\tremaining: 32.2ms\n46:\tlearn: 0.0787914\ttotal: 379ms\tremaining: 24.2ms\n47:\tlearn: 0.0755965\ttotal: 388ms\tremaining: 16.2ms\n48:\tlearn: 0.0725382\ttotal: 398ms\tremaining: 8.12ms\n49:\tlearn: 0.0696218\ttotal: 406ms\tremaining: 0us\n0:\tlearn: 0.6539528\ttotal: 6.59ms\tremaining: 323ms\n1:\tlearn: 0.6177707\ttotal: 12.1ms\tremaining: 291ms\n2:\tlearn: 0.5842815\ttotal: 18.9ms\tremaining: 296ms\n3:\tlearn: 0.5532527\ttotal: 27.8ms\tremaining: 320ms\n4:\tlearn: 0.5243421\ttotal: 36.8ms\tremaining: 331ms\n5:\tlearn: 0.4974279\ttotal: 46.2ms\tremaining: 339ms\n6:\tlearn: 0.4722272\ttotal: 55.5ms\tremaining: 341ms\n7:\tlearn: 0.4485835\ttotal: 63.4ms\tremaining: 333ms\n8:\tlearn: 0.4264476\ttotal: 72ms\tremaining: 328ms\n9:\tlearn: 0.4056377\ttotal: 81.4ms\tremaining: 326ms\n10:\tlearn: 0.3860378\ttotal: 88ms\tremaining: 312ms\n11:\tlearn: 0.3675968\ttotal: 97.5ms\tremaining: 309ms\n12:\tlearn: 0.3501901\ttotal: 105ms\tremaining: 298ms\n13:\tlearn: 0.3337661\ttotal: 112ms\tremaining: 288ms\n14:\tlearn: 0.3182600\ttotal: 121ms\tremaining: 282ms\n15:\tlearn: 0.3035984\ttotal: 130ms\tremaining: 276ms\n16:\tlearn: 0.2897346\ttotal: 139ms\tremaining: 269ms\n17:\tlearn: 0.2765608\ttotal: 144ms\tremaining: 256ms\n18:\tlearn: 0.2641028\ttotal: 153ms\tremaining: 249ms\n19:\tlearn: 0.2522969\ttotal: 161ms\tremaining: 242ms\n20:\tlearn: 0.2410476\ttotal: 167ms\tremaining: 230ms\n21:\tlearn: 0.2303928\ttotal: 176ms\tremaining: 224ms\n22:\tlearn: 0.2202508\ttotal: 183ms\tremaining: 215ms\n23:\tlearn: 0.2106408\ttotal: 193ms\tremaining: 209ms\n24:\tlearn: 0.2014789\ttotal: 203ms\tremaining: 203ms\n25:\tlearn: 0.1927556\ttotal: 212ms\tremaining: 195ms\n26:\tlearn: 0.1844247\ttotal: 217ms\tremaining: 185ms\n27:\tlearn: 0.1764946\ttotal: 225ms\tremaining: 176ms\n28:\tlearn: 0.1689573\ttotal: 234ms\tremaining: 169ms\n29:\tlearn: 0.1617697\ttotal: 243ms\tremaining: 162ms\n30:\tlearn: 0.1549104\ttotal: 250ms\tremaining: 154ms\n31:\tlearn: 0.1483701\ttotal: 260ms\tremaining: 146ms\n32:\tlearn: 0.1421328\ttotal: 269ms\tremaining: 139ms\n33:\tlearn: 0.1361677\ttotal: 278ms\tremaining: 131ms\n34:\tlearn: 0.1304500\ttotal: 283ms\tremaining: 121ms\n35:\tlearn: 0.1249973\ttotal: 290ms\tremaining: 113ms\n36:\tlearn: 0.1198048\ttotal: 299ms\tremaining: 105ms\n37:\tlearn: 0.1148424\ttotal: 308ms\tremaining: 97.4ms\n38:\tlearn: 0.1100744\ttotal: 314ms\tremaining: 88.6ms\n39:\tlearn: 0.1055243\ttotal: 323ms\tremaining: 80.7ms\n40:\tlearn: 0.1011752\ttotal: 331ms\tremaining: 72.8ms\n41:\tlearn: 0.0970327\ttotal: 340ms\tremaining: 64.8ms\n42:\tlearn: 0.0930527\ttotal: 349ms\tremaining: 56.8ms\n43:\tlearn: 0.0892307\ttotal: 354ms\tremaining: 48.3ms\n44:\tlearn: 0.0856217\ttotal: 363ms\tremaining: 40.3ms\n45:\tlearn: 0.0821345\ttotal: 371ms\tremaining: 32.3ms\n46:\tlearn: 0.0787948\ttotal: 379ms\tremaining: 24.2ms\n47:\tlearn: 0.0755955\ttotal: 388ms\tremaining: 16.2ms\n48:\tlearn: 0.0725306\ttotal: 397ms\tremaining: 8.1ms\n49:\tlearn: 0.0696140\ttotal: 406ms\tremaining: 0us\n0:\tlearn: 0.6539528\ttotal: 5.42ms\tremaining: 266ms\n1:\tlearn: 0.6177707\ttotal: 10.9ms\tremaining: 261ms\n2:\tlearn: 0.5842815\ttotal: 17.2ms\tremaining: 269ms\n3:\tlearn: 0.5532525\ttotal: 26.1ms\tremaining: 300ms\n4:\tlearn: 0.5243413\ttotal: 35.2ms\tremaining: 316ms\n5:\tlearn: 0.4974032\ttotal: 44.9ms\tremaining: 329ms\n6:\tlearn: 0.4722052\ttotal: 54.5ms\tremaining: 335ms\n7:\tlearn: 0.4485557\ttotal: 61.4ms\tremaining: 322ms\n8:\tlearn: 0.4264203\ttotal: 70.4ms\tremaining: 321ms\n9:\tlearn: 0.4056124\ttotal: 79.3ms\tremaining: 317ms\n10:\tlearn: 0.3860139\ttotal: 86.1ms\tremaining: 305ms\n11:\tlearn: 0.3675741\ttotal: 95.1ms\tremaining: 301ms\n12:\tlearn: 0.3501687\ttotal: 102ms\tremaining: 291ms\n13:\tlearn: 0.3337459\ttotal: 109ms\tremaining: 280ms\n14:\tlearn: 0.3182415\ttotal: 118ms\tremaining: 275ms\n15:\tlearn: 0.3035807\ttotal: 127ms\tremaining: 269ms\n16:\tlearn: 0.2897186\ttotal: 136ms\tremaining: 264ms\n17:\tlearn: 0.2765456\ttotal: 141ms\tremaining: 251ms\n18:\tlearn: 0.2640885\ttotal: 150ms\tremaining: 245ms\n19:\tlearn: 0.2522846\ttotal: 159ms\tremaining: 238ms\n20:\tlearn: 0.2410359\ttotal: 164ms\tremaining: 227ms\n21:\tlearn: 0.2303789\ttotal: 173ms\tremaining: 221ms\n22:\tlearn: 0.2202375\ttotal: 181ms\tremaining: 212ms\n23:\tlearn: 0.2106279\ttotal: 190ms\tremaining: 206ms\n24:\tlearn: 0.2014469\ttotal: 197ms\tremaining: 197ms\n"
],
[
"print(\"Accuracy: %0.5f (+/- %0.5f)\" % (accuracy.mean(), accuracy.std() * 2))\nprint(\"F1 Score: %0.5f (+/- %0.5f)\" % (f.mean(), f.std() * 2))\nprint(\"Precision: %0.5f (+/- %0.5f)\" % (precision.mean(), precision.std() * 2))\nprint(\"Recall: %0.5f (+/- %0.5f)\" % (recall.mean(), recall.std() * 2))",
"Accuracy: 1.00000 (+/- 0.00000)\nF1 Score: 1.00000 (+/- 0.00000)\nPrecision: 1.00000 (+/- 0.00000)\nRecall: 1.00000 (+/- 0.00000)\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb7affe259ceea69dd24c066bcf20899351645dd
| 741,980 |
ipynb
|
Jupyter Notebook
|
notebooks/43_plotting.ipynb
|
chengsoonong/crowdastro
|
ce14432c36de0574b73d813304365b74446a61f8
|
[
"MIT"
] | 13 |
2015-11-07T15:24:44.000Z
|
2020-04-20T05:29:58.000Z
|
notebooks/43_plotting.ipynb
|
chengsoonong/crowdastro
|
ce14432c36de0574b73d813304365b74446a61f8
|
[
"MIT"
] | 234 |
2016-02-21T23:53:16.000Z
|
2019-06-27T00:26:08.000Z
|
notebooks/43_plotting.ipynb
|
chengsoonong/crowdastro
|
ce14432c36de0574b73d813304365b74446a61f8
|
[
"MIT"
] | 3 |
2015-11-07T00:20:09.000Z
|
2018-10-03T13:37:15.000Z
| 1,055.44808 | 380,346 | 0.941798 |
[
[
[
"# Plotting\n\nIn this notebook, I'll develop a function to plot subjects and their labels.",
"_____no_output_____"
]
],
[
[
"from astropy.coordinates import SkyCoord\nimport astropy.io.fits\nimport astropy.wcs\nimport h5py\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import cm\nimport numpy\nimport skimage.exposure\nimport sklearn.neighbors\nimport sklearn.pipeline\nimport sklearn.preprocessing\n\nCROWDASTRO_H5_PATH = 'data/crowdastro.h5'\nPATCH_DIAMETER = 200\nFITS_CONVENTION = 1\nARCMIN = 1 / 60\nIMAGE_SIZE = 200 * 200\nNORRIS_DAT_PATH = 'data/norris_2006_atlas_classifications_ra_dec_only.dat'\nTRAINING_H5_PATH = 'data/training.h5'\n\nwith h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n N_ASTRO = 5 if f_h5.attrs['ir_survey'] == 'wise' else 6\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## Displaying radio images\n\nRadio images look pretty terrible, so let's run a filter over them to make them a little easier to see. I'll use skimage and try a few different ones.\n\nLet's get an example and look at the basic output.",
"_____no_output_____"
]
],
[
[
"with h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n image = f_h5['/atlas/cdfs/numeric'][250, 2 : 2 + PATCH_DIAMETER ** 2].reshape((PATCH_DIAMETER, PATCH_DIAMETER))",
"_____no_output_____"
],
[
"plt.imshow(image, cmap='gray')\nplt.show()",
"_____no_output_____"
]
],
[
[
"It's hard to make out any features. Now, let's run some filters on it.",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(18, 27))\n\ndef subplot_imshow_hist(i, fig, im, title):\n ax = fig.add_subplot(6, 3, i)\n ax.imshow(im, cmap='gray')\n ax.set_title(title)\n ax.axis('off')\n \n ax = fig.add_subplot(6, 3, i + 3)\n ax.hist(im.ravel(), bins=256, histtype='step', color='black')\n ax.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0))\n\nsubplot_imshow_hist(1, fig, image, 'Default')\n\nsubplot_imshow_hist(2, fig, skimage.exposure.equalize_adapthist(image, clip_limit=0.01), 'Adaptive equalisation')\n\nsubplot_imshow_hist(3, fig, skimage.exposure.equalize_hist(image), 'Histogram equalisation')\n\nsubplot_imshow_hist(7, fig, skimage.exposure.rescale_intensity(image, in_range=tuple(numpy.percentile(image, (0.75, 99.25)))),\n 'Constant stretching 0.75 - 99.25')\n\nsubplot_imshow_hist(8, fig, skimage.exposure.rescale_intensity(image, in_range=tuple(numpy.percentile(image, (1, 99)))),\n 'Constant stretching 1 - 99')\n\nsubplot_imshow_hist(9, fig, skimage.exposure.rescale_intensity(image, in_range=tuple(numpy.percentile(image, (2, 98)))),\n 'Constant stretching 2 - 98')\n\nsubplot_imshow_hist(13, fig, numpy.sqrt(image - image.min()), 'Square root')\n\nsubplot_imshow_hist(14, fig, numpy.log(image - image.min() + 1e-5), 'Logarithm + 1e-5')\n\nsubplot_imshow_hist(15, fig, numpy.log(image + 1), 'Logarithm + 1')\n\n",
"K:\\Languages\\Python35_64\\lib\\site-packages\\skimage\\util\\dtype.py:110: UserWarning: Possible precision loss when converting from float32 to uint16\n \"%s to %s\" % (dtypeobj_in, dtypeobj))\n"
]
],
[
[
"Square root looks good, so let's blitz that over some random images and see how it looks.",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(18, 25))\n\nwith h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n indices = numpy.arange(f_h5['/atlas/cdfs/numeric'].shape[0])\n numpy.random.seed(10000)\n numpy.random.shuffle(indices)\n \n for j, i in enumerate(indices[:3]):\n image = f_h5['/atlas/cdfs/numeric'][i, 2 : 2 + PATCH_DIAMETER ** 2].reshape((PATCH_DIAMETER, PATCH_DIAMETER))\n subplot_imshow_hist(j + 1, fig, numpy.sqrt(image - image.min()), str(i))",
"_____no_output_____"
]
],
[
[
"## Plotting IR objects\n\nThis is an extremely unpleasant operation: We have to find the pixel coordinates of each IR location, which are all specified in RA/DEC.",
"_____no_output_____"
]
],
[
[
"from crowdastro.config import config\n\nwith astropy.io.fits.open(config['data_sources']['atlas_image'],\n ignore_blank=True) as atlas_image:\n wcs = astropy.wcs.WCS(atlas_image[0].header).dropaxis(3).dropaxis(2)\n\ndef ra_dec_to_pixels(subject_coords, coords):\n offset, = wcs.all_world2pix([subject_coords], FITS_CONVENTION)\n # The coords are of the middle of the subject.\n coords = wcs.all_world2pix(coords, FITS_CONVENTION)\n coords -= offset\n \n coords[:, 0] /= config['surveys']['atlas']['mosaic_scale_x'] * 424 / 200\n coords[:, 1] /= config['surveys']['atlas']['mosaic_scale_y'] * 424 / 200\n \n coords += [40, 40]\n \n return coords",
"K:\\Languages\\Python35_64\\lib\\site-packages\\astropy\\io\\fits\\util.py:578: UserWarning: Could not find appropriate MS Visual C Runtime library or library is corrupt/misconfigured; cannot determine whether your file object was opened in append mode. Please consider using a file object opened in write mode instead.\n 'Could not find appropriate MS Visual C Runtime '\nWARNING: FITSFixedWarning: 'spcfix' made the change 'Changed CTYPE3 from 'FREQ-LSR' to 'FREQ''. [astropy.wcs.wcs]\nWARNING: FITSFixedWarning: 'celfix' made the change 'Success'. [astropy.wcs.wcs]\n"
],
[
"with h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n i = 296\n image = f_h5['/atlas/cdfs/numeric'][i, 2 : 2 + PATCH_DIAMETER ** 2].reshape(\n (PATCH_DIAMETER, PATCH_DIAMETER))[60:140, 60:140]\n radio_coords = f_h5['/atlas/cdfs/numeric'][i, :2]\n nearby = f_h5['/atlas/cdfs/numeric'][i, 2 + PATCH_DIAMETER ** 2:] < ARCMIN\n ir_coords = f_h5['/swire/cdfs/numeric'][nearby, :2]\n ir_coords = ra_dec_to_pixels(radio_coords, ir_coords)\n \n plt.imshow(numpy.sqrt(image - image.min()), cmap='gray')\n plt.scatter(ir_coords[:, 0], ir_coords[:, 1])",
"_____no_output_____"
]
],
[
[
"## Displaying classifications\n\nThe simplest thing we can do is to just highlight the host galaxies, so let's load up the Norris et al. classifications and have a look.",
"_____no_output_____"
]
],
[
[
"# Load labels.\n\nwith h5py.File(TRAINING_H5_PATH, 'r') as training_h5:\n crowdsourced_labels = training_h5['labels'].value\n\nwith h5py.File(CROWDASTRO_H5_PATH, 'r') as crowdastro_h5:\n ir_names = crowdastro_h5['/swire/cdfs/string'].value\n ir_positions = crowdastro_h5['/swire/cdfs/numeric'].value[:, :2]\nir_tree = sklearn.neighbors.KDTree(ir_positions)\n\nwith open(NORRIS_DAT_PATH, 'r') as norris_dat:\n norris_coords = [r.strip().split('|') for r in norris_dat]\n\nnorris_labels = numpy.zeros((len(ir_positions)))\nfor ra, dec in norris_coords:\n # Find a neighbour.\n skycoord = SkyCoord(ra=ra, dec=dec, unit=('hourangle', 'deg'))\n ra = skycoord.ra.degree\n dec = skycoord.dec.degree\n ((dist,),), ((ir,),) = ir_tree.query([(ra, dec)])\n if dist < 0.1:\n norris_labels[ir] = 1",
"_____no_output_____"
],
[
"with h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n i = 250\n image = f_h5['/atlas/cdfs/numeric'][i, 2 : 2 + PATCH_DIAMETER ** 2].reshape(\n (PATCH_DIAMETER, PATCH_DIAMETER))[60:140, 60:140]\n radio_coords = f_h5['/atlas/cdfs/numeric'][i, :2]\n nearby = f_h5['/atlas/cdfs/numeric'][i, 2 + PATCH_DIAMETER ** 2:] < ARCMIN\n ir_coords = f_h5['/swire/cdfs/numeric'][nearby, :2]\n ir_coords = ra_dec_to_pixels(radio_coords, ir_coords)\n \n plt.imshow(numpy.sqrt(image - image.min()), cmap='gray')\n plt.scatter(ir_coords[:, 0], ir_coords[:, 1])\n \n labels = norris_labels[nearby].astype(bool)\n nearby_hosts = ir_coords[labels]\n plt.scatter(nearby_hosts[:, 0], nearby_hosts[:, 1], c='red')",
"_____no_output_____"
]
],
[
[
"What about displaying classifications from my classifier?",
"_____no_output_____"
]
],
[
[
"from crowdastro.classifier import RGZClassifier\n\nfrom sklearn.ensemble import RandomForestClassifier",
"_____no_output_____"
],
[
"with h5py.File(TRAINING_H5_PATH, 'r') as f_h5:\n classifier = RGZClassifier(f_h5['features'].value, N_ASTRO)\n \n classifier.train(numpy.arange(f_h5['features'].shape[0]), norris_labels)",
"_____no_output_____"
],
[
"with h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n i = 250\n image = f_h5['/atlas/cdfs/numeric'][i, 2 : 2 + PATCH_DIAMETER ** 2].reshape(\n (PATCH_DIAMETER, PATCH_DIAMETER))[60:140, 60:140]\n radio_coords = f_h5['/atlas/cdfs/numeric'][i, :2]\n nearby = f_h5['/atlas/cdfs/numeric'][i, 2 + PATCH_DIAMETER ** 2:] < ARCMIN\n ir_coords = f_h5['/swire/cdfs/numeric'][nearby, :2]\n ir_coords = ra_dec_to_pixels(radio_coords, ir_coords)\n vec = f_h5['/atlas/cdfs/numeric'][i, :]\n \n probs = classifier.predict_probabilities(vec)[nearby]\n nearby_norris = ir_coords[norris_labels[nearby].astype('bool')]\n nearby_rgz = ir_coords[crowdsourced_labels[nearby].astype('bool')]\n \n plt.figure(figsize=(15, 15))\n base_size = 200\n plt.imshow(numpy.sqrt(image - image.min()), cmap='gray')\n plt.scatter(ir_coords[:, 0], ir_coords[:, 1], s=probs * base_size, c=probs, marker='o', cmap='cool')\n plt.scatter(nearby_norris[:, 0], nearby_norris[:, 1], s=base_size, c='green', marker='*')\n plt.axis('off')\n# plt.scatter(nearby_rgz[:, 0], nearby_rgz[:, 1], s=50, c='cyan', marker='x', alpha=0.5)\n plt.xlim((0, 80))\n plt.ylim((0, 80))",
"_____no_output_____"
]
],
[
[
"## Plotting a committee\n\nIf we have multiple classifiers, how should we output their predictions?",
"_____no_output_____"
]
],
[
[
"with h5py.File(TRAINING_H5_PATH, 'r') as f_h5:\n classifiers = [RGZClassifier(f_h5['features'], N_ASTRO) for _ in range(10)]\n \n for classifier in classifiers:\n subset = numpy.arange(f_h5['features'].shape[0])\n numpy.random.shuffle(subset)\n subset = subset[:len(subset) // 50]\n subset = sorted(subset)\n classifier.train(list(subset), norris_labels[subset])\n \n with h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n i = 250\n image = f_h5['/atlas/cdfs/numeric'][i, 2 : 2 + PATCH_DIAMETER ** 2].reshape(\n (PATCH_DIAMETER, PATCH_DIAMETER))[60:140, 60:140]\n radio_coords = f_h5['/atlas/cdfs/numeric'][i, :2]\n nearby = f_h5['/atlas/cdfs/numeric'][i, 2 + PATCH_DIAMETER ** 2:] < ARCMIN\n ir_coords = f_h5['/swire/cdfs/numeric'][nearby, :2]\n ir_coords = ra_dec_to_pixels(radio_coords, ir_coords)\n vec = f_h5['/atlas/cdfs/numeric'][i, :]\n\n probs = [classifier.predict_probabilities(vec)[nearby] for classifier in classifiers]\n # Set all but the top n predictions to zero.\n n = 1\n for probs_ in probs:\n top_n = sorted(probs_, reverse=True)[:n]\n for j, prob in enumerate(probs_):\n if prob not in top_n:\n probs_[j] = 0",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 10))\nbase_size = 200\nplt.imshow(numpy.sqrt(image - image.min()), cmap='gray')\n\ncolours = cm.rainbow(numpy.linspace(0, 1, 10))\n\nfor colour, probs_ in zip(colours, probs):\n plt.scatter(ir_coords[:, 0] + numpy.random.normal(size=ir_coords.shape[0], scale=0.5),\n ir_coords[:, 1] + numpy.random.normal(size=ir_coords.shape[0], scale=0.5),\n s=probs_ * base_size, marker='x', c=colour, alpha=1)\nplt.axis('off')\nplt.xlim((0, 80))\nplt.ylim((0, 80))",
"_____no_output_____"
]
],
[
[
"These classifiers have really low diversity because of the way I divided up the data, but this should work fine.",
"_____no_output_____"
]
],
[
[
"def plot_points_on_background(points, background, noise=False, base_size=200):\n plt.imshow(background, cmap='gray')\n\n colours = cm.rainbow(numpy.linspace(0, 1, len(points)))\n for colour, (x, y) in zip(colours, points):\n if noise:\n x += numpy.random.normal(scale=0.5)\n y += numpy.random.normal(scale=0.5)\n plt.scatter(x, y, marker='o', c=colour, s=base_size)\n plt.axis('off')\n plt.xlim((0, background.shape[0]))\n plt.ylim((0, background.shape[1]))",
"_____no_output_____"
],
[
"def plot_classifications(atlas_vector, ir_matrix, labels, base_size=200):\n image = atlas_vector[2 : 2 + PATCH_DIAMETER ** 2].reshape((PATCH_DIAMETER, PATCH_DIAMETER)\n )[60:140, 60:140]\n radio_coords = atlas_vector[:2]\n\n nearby = atlas_vector[2 + PATCH_DIAMETER ** 2:] < ARCMIN\n labels = labels[nearby]\n\n ir_coords = ir_matrix[nearby, :2][labels.astype(bool)]\n ir_coords = ra_dec_to_pixels(radio_coords, ir_coords)\n \n plot_points_on_background(ir_coords, image, base_size=base_size)",
"_____no_output_____"
],
[
"with h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n i = 250\n atlas_vector = f_h5['/atlas/cdfs/numeric'][i, :]\n ir_coords = f_h5['/swire/cdfs/numeric']\n plot_classifications(atlas_vector, ir_coords, norris_labels)",
"_____no_output_____"
]
],
[
[
"## Bringing it all together\n\nWe want to plot classifications, RGZ labels, and Norris labels in the same row.",
"_____no_output_____"
]
],
[
[
"def plot_classifications_row(atlas_vector, ir_matrix, classifier_labels, rgz_labels, norris_labels, base_size=200):\n plt.subplot(1, 3, 1)\n plt.title('Classifier')\n plot_classifications(atlas_vector, ir_matrix, classifier_labels, base_size=base_size)\n \n plt.subplot(1, 3, 2)\n plt.title('RGZ')\n plot_classifications(atlas_vector, ir_matrix, rgz_labels, base_size=base_size)\n \n plt.subplot(1, 3, 3)\n plt.title('Norris')\n plot_classifications(atlas_vector, ir_matrix, norris_labels, base_size=base_size)",
"_____no_output_____"
],
[
"with h5py.File(TRAINING_H5_PATH, 'r') as f_h5:\n classifier = RGZClassifier(f_h5['features'].value, N_ASTRO)\n classifier.train(numpy.arange(f_h5['features'].shape[0]), norris_labels)\n\nwith h5py.File(CROWDASTRO_H5_PATH, 'r') as f_h5:\n i = 250\n vec = f_h5['/atlas/cdfs/numeric'][i, :]\n mat = f_h5['/swire/cdfs/numeric']\n probs = classifier.predict_probabilities(vec)\n labels = numpy.zeros(probs.shape)\n labels[probs.argmax()] = 1\n \n plt.figure(figsize=(20, 10))\n plot_classifications_row(vec, mat, labels, crowdsourced_labels, norris_labels, base_size=200)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb7b08ec296b520bd335b7610c80dea75d888a3e
| 17,843 |
ipynb
|
Jupyter Notebook
|
Numpy/Numpy-1.ipynb
|
pywaker/datascience
|
e3e9b55b06489ad1dc10189414311d3d38b840e6
|
[
"CC-BY-4.0"
] | 3 |
2019-03-22T04:15:45.000Z
|
2019-06-29T09:27:06.000Z
|
Numpy/Numpy-1.ipynb
|
learningwithdg/datascience
|
e3e9b55b06489ad1dc10189414311d3d38b840e6
|
[
"CC-BY-4.0"
] | null | null | null |
Numpy/Numpy-1.ipynb
|
learningwithdg/datascience
|
e3e9b55b06489ad1dc10189414311d3d38b840e6
|
[
"CC-BY-4.0"
] | 2 |
2019-05-21T04:26:25.000Z
|
2019-05-21T04:27:15.000Z
| 17.986895 | 227 | 0.423359 |
[
[
[
"### Reading file with Numpy",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"%cat ../Data/dummydata.txt",
"Some sample datafile\n\nYear, Min, Max\n2009, 10, 30\n2010, 12, 29\n2011, 11, 35\n2012, 14, 28\n2013, 10, 32\n"
],
[
"data = np.genfromtxt(\"../Data/dummydata.txt\")",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"data = np.genfromtxt(\"../Data/dummydata.txt\", skip_header=3, delimiter=\",\")",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"type(data)",
"_____no_output_____"
],
[
"data.dtype",
"_____no_output_____"
],
[
"data[2]",
"_____no_output_____"
],
[
"data[2, 0]",
"_____no_output_____"
],
[
"data[0:3]",
"_____no_output_____"
],
[
"data[:3, 0]",
"_____no_output_____"
],
[
"data[:, 0]",
"_____no_output_____"
],
[
"%whos",
"Variable Type Data/Info\n-------------------------------\ndata ndarray 5x3: 15 elems, type `float64`, 120 bytes\nnp module <module 'numpy' from '/us<...>kages/numpy/__init__.py'>\n"
],
[
"temp = data[:, 1]",
"_____no_output_____"
],
[
"temp",
"_____no_output_____"
],
[
"temp.mean()",
"_____no_output_____"
],
[
"date = data[:, 0]",
"_____no_output_____"
],
[
"date",
"_____no_output_____"
],
[
"date.astype(\"int\")",
"_____no_output_____"
],
[
"date = date.astype(\"int\")",
"_____no_output_____"
],
[
"date",
"_____no_output_____"
],
[
"date.dtype",
"_____no_output_____"
],
[
"date.astype(\"int32\")",
"_____no_output_____"
],
[
"diff = np.zeros(len(date))",
"_____no_output_____"
],
[
"diff",
"_____no_output_____"
],
[
"temp_max = data[:, 2]",
"_____no_output_____"
],
[
"temp_min = data[:, 1]",
"_____no_output_____"
],
[
"diff = temp_max - temp_min",
"_____no_output_____"
],
[
"diff",
"_____no_output_____"
],
[
"bad_data = np.zeros(15)",
"_____no_output_____"
],
[
"bad_data",
"_____no_output_____"
],
[
"bad_data[:6] = np.nan",
"_____no_output_____"
],
[
"bad_data",
"_____no_output_____"
],
[
"np.isfinite(bad_data)",
"_____no_output_____"
],
[
"bad_data[np.isfinite(bad_data)]",
"_____no_output_____"
],
[
"np.isinf([np.inf])",
"_____no_output_____"
],
[
"np.isnan([np.nan])",
"_____no_output_____"
],
[
"np.isinf([np.nan, np.inf])",
"_____no_output_____"
],
[
"np.isnan([np.nan, np.inf])",
"_____no_output_____"
],
[
"np.isfinite([np.nan, np.inf])",
"_____no_output_____"
],
[
"np.inf == np.inf",
"_____no_output_____"
],
[
"np.inf > np.inf",
"_____no_output_____"
],
[
"temp",
"_____no_output_____"
],
[
"temp_c = temp / 3",
"_____no_output_____"
],
[
"temp_c",
"_____no_output_____"
],
[
"temp_c.round(0)",
"_____no_output_____"
],
[
"np.unique(temp_c.round(0))",
"_____no_output_____"
],
[
"temp",
"_____no_output_____"
],
[
"new_data = np.vstack((date, temp, temp_c))",
"_____no_output_____"
],
[
"new_data",
"_____no_output_____"
],
[
"new_data = np.transpose(new_data)",
"_____no_output_____"
],
[
"new_data",
"_____no_output_____"
],
[
"np.savetxt('converted.csv', new_data, delimiter=\",\")",
"_____no_output_____"
],
[
"usecols",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7b1540d6c710d5a44fb158e9bb2cf0ef93bbb7
| 202,246 |
ipynb
|
Jupyter Notebook
|
implementation.ipynb
|
zhangir-azerbayev/particle_filtering
|
1391f65bade03457b1d086d44d76d193eb6d27a0
|
[
"MIT"
] | null | null | null |
implementation.ipynb
|
zhangir-azerbayev/particle_filtering
|
1391f65bade03457b1d086d44d76d193eb6d27a0
|
[
"MIT"
] | null | null | null |
implementation.ipynb
|
zhangir-azerbayev/particle_filtering
|
1391f65bade03457b1d086d44d76d193eb6d27a0
|
[
"MIT"
] | null | null | null | 369.736746 | 61,340 | 0.929606 |
[
[
[
"# Particle Filtering for Sequential Bayesian Inference",
"_____no_output_____"
],
[
"## Introduction\nIn this notebook, we produce an implementation of the particle filtering methods discussed in the accompanying article. In particular, we introduce the *bearings-only tracking* problem, a nonlinear non-Gaussian sequential inference problem. Next, we implement sequential importance sampling (SIS) to solve bearings-only tracking and observe the method's limitations. Finally, we achieve a respectable solution to our problem using the bootstrap filter. ",
"_____no_output_____"
],
[
"## The Problem \n### Statement\nThe bearings-only tracking problem is as follows. Suppose a plane begins at $x_0 = (0.01, 0.95)$ with a velocity $v_0=(0.02, -0.013)$ and for $50$ time steps moves according to the following dynamical system. \n\\begin{align}\nv_{t+1} &\\sim \\mathcal{N}(v_t, \\Sigma_v)\\\\\nx_{t+1} & = x_t + v_t\n\\end{align}\n\nwhere $\\Sigma_v = 10^{-6}I_2$. At each time $t$, we receive a noisy measurement of the plane's bearing, that is \n\n\\begin{equation} y_t = \\mathrm{angle}(x_t) + w_t \\end{equation}\n\nwhere $w_t \\sim \\mathcal{N}(0, \\sigma=0.005)$.\n\nOur goal is to infer $p(x_{0:50}, v_{0:50}| y_{1:50})$. ",
"_____no_output_____"
],
[
"### Code\nFirst, we do our imports and set a random seed. ",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport scipy.stats as sp_stats\nimport scipy.special as sp_special\nimport matplotlib.pyplot as plt\nimport matplotlib.patheffects as pe\nimport math\n\nnp.random.seed(3)",
"_____no_output_____"
]
],
[
[
"Next, we parametrize our prior. ",
"_____no_output_____"
]
],
[
[
"# number of time steps\nnum_samples = 50\n# number of particles\nnum_particles = 100\n# Parameters of the prior \nx0 = [0.01, 0.95]\nv0 = [0.02, -0.013]\nvx_var, vy_var = (1.0/1e6, 1.0/1e6)\nv_cov = [[vx_var, 0], [0, vy_var]]\nmeasurement_noise = 0.005",
"_____no_output_____"
]
],
[
[
"The `BearingsData` class performs the following functions \n1. Simulates a ground-truth state $(x_{0:50}, v_{0:50})$ and accompanying measurements $y_{1:50}$. \n2. Provides plotting functions. \n3. Gives us a `__getitem__` function, which allows us to sequentially retrieve datapoints. ",
"_____no_output_____"
]
],
[
[
"class BearingsData(object): \n def __init__(self, num_samples): \n # Simulates velocities \n v_matrix = np.zeros((num_samples, 2))\n v_matrix[0, :] = np.random.multivariate_normal(v0, v_cov)\n for i in range(1, num_samples): \n v_matrix[i, :] = np.random.multivariate_normal(v_matrix[i-1, :], v_cov)\n self.v = v_matrix \n \n # Calculates positions \n x = np.cumsum(v_matrix, axis=0) + x0 - v_matrix # subtract v_matrix because x_t depends on v_{t-1}\n self.x = x\n \n # Calculates bearings \n noise_vector = np.random.multivariate_normal(np.zeros(num_samples),\n (measurement_noise**2) * np.identity(num_samples))\n y = np.arctan(x[:, 1]/x[:, 0]) + noise_vector\n self.y = y \n \n \"\"\"Plots trajectory and bearings\"\"\"\n def plot(self): \n plt.scatter(self.x[:, 0], self.x[:, 1])\n \n y = np.arctan(self.x[:, 1]/self.x[:, 0])\n \n for yt in self.y: \n dx = math.cos(yt) * .5\n dy = math.sin(yt) * .5\n plt.plot([0., dx], [0., dy], color=\"red\", alpha=0.3)\n \n plt.show() \n \n \"\"\"Plots inferences overlayed on ground-truth trajectory and measurements\"\"\"\n def plot_inferences(self, inferences):\n plt.plot(self.x[:, 0], self.x[:, 1], color=\"black\", lw=2, \n path_effects=[pe.Stroke(linewidth=5, foreground='white'), pe.Normal()])\n \n for yt in self.y: \n dx = math.cos(yt) * .5\n dy = math.sin(yt) * .5\n plt.plot([0., dx], [0., dy], color=\"red\", alpha=0.3)\n\n for x in inferences: \n plt.scatter(x[:, 0], x[:, 1])\n plt.show()\n\n \"\"\"Retrieves position, velocity, and measurement at time t\"\"\"\n def __getitem__(self, idx): \n if idx < self.x.shape[0]: \n xt = self.x[idx, :]\n vt = self.v[idx, :]\n yt = self.y[idx]\n return xt, vt, yt\n else: \n raise IndexError('high enough') ",
"_____no_output_____"
]
],
[
[
"Here, we simulate one run of the data-generating process. ",
"_____no_output_____"
]
],
[
[
"data = BearingsData(num_samples)\ndata.plot()",
"_____no_output_____"
]
],
[
[
"## SIS",
"_____no_output_____"
],
[
"In this section, we implement SIS in order to infer the hidden-state given the measurements of the data we generated in the last section. \nThroughout our calculations, we use log probabilities for numerical stability.",
"_____no_output_____"
],
[
"The following defines the Markov transition kernel from state $(x_t, v_t)$ to $(x_{t+1}, v_{t+1})$. Note that the kernel only takes velocities as input: we assume that the deterministic relation $x_{t+1} = x_t + v_t$ is satisfied. ",
"_____no_output_____"
]
],
[
[
"\"\"\"Markov transition kernel\"\"\" \ndef transition_kernel(v1, v2): \n v2_dist = sp_stats.multivariate_normal(mean=v1, cov=v_cov)\n return v2_dist.logpdf(v2)",
"_____no_output_____"
]
],
[
[
"Next, we define the marginal distribution $p(y_t| x_t, v_t)$. Note that $p(y_t|x_t, v_t)$ does not depend on $v_t$. ",
"_____no_output_____"
]
],
[
[
"\"\"\"Probability of measurement y given state xt, vt\"\"\"\ndef measurement_prob(yt, xt): \n error = np.arctan(xt[1]/xt[0]) - yt\n return sp_stats.norm.logpdf(error, scale=measurement_noise)",
"_____no_output_____"
]
],
[
[
"We represent our particles as a dictionary with keys {\"locations\", \"velocities\", \"weight\", \"prior_prob\"}. We store all the particles in a list. \n\nThe following function computes a particle filter step, outputting particles with unnormalized weights. It takes as input particles $\\{(x_{0:t}^{(i)}, v_{0:t}^{(i)})\\}$, draws each $(x_{t+1}^{(i)}, v_{t+1}^{(i)})$, and updates weights and prior probabilities accordingly. Since we reuse this function when implementing the bootstrap filter, we add the `selection` argument that modifies how the weights are updated. ",
"_____no_output_____"
]
],
[
[
"def particle_filter_step(particles, yt, selection=False): \n new_particles = []\n for i in range(len(particles)): \n \n particle = particles[i]\n prev_x = np.squeeze(particle[\"locations\"][-1:, :])\n prev_v = np.squeeze(particle[\"velocities\"][-1:, :])\n \n vt = np.random.multivariate_normal(prev_v, v_cov)\n xt = prev_x + prev_v \n new_particle = {}\n new_particle[\"prior_prob\"] = particle[\"prior_prob\"] + transition_kernel(prev_v, vt)\n if selection: \n new_particle[\"weight\"] = measurement_prob(yt, xt)\n else: \n new_particle[\"weight\"] = particle[\"weight\"] + measurement_prob(yt, xt) \n new_particle[\"locations\"] = np.append(particle[\"locations\"], np.expand_dims(xt, axis=0), axis=0)\n new_particle[\"velocities\"] = np.append(particle[\"velocities\"], np.expand_dims(vt, axis=0), axis=0)\n \n new_particles.append(new_particle)\n \n return new_particles",
"_____no_output_____"
]
],
[
[
"The following function normalizes particle weights. Note that we smooth the probability distribution induced by the weights by a factor of $10^{-10}$. If we do not do so, our algorithm attempts to compute $\\log(0)$ .",
"_____no_output_____"
]
],
[
[
"def normalize_weights(particles): \n log_weights = np.array([particle[\"weight\"] for particle in particles])\n \n # For numerical stability, we smooth the output of softmax by 1e-10\n smoothed_log_weights = np.log(sp_special.softmax(log_weights) + 1e-10)\n normalized_log_weights = np.log(sp_special.softmax(smoothed_log_weights))\n \n for i in range(len(particles)): \n particles[i]['weight'] = normalized_log_weights[i]\n \n return particles",
"_____no_output_____"
]
],
[
[
"The following step combines the functions we have defined so far in order to perform the SIS algorithm. ",
"_____no_output_____"
]
],
[
[
"particles = [{\n \"locations\": np.expand_dims(x0, axis=0), \n \"velocities\": np.expand_dims(v0, axis=0), \n \"weight\": np.log(1.0/num_particles), \n \"prior_prob\": 0\n} for _ in range(num_particles)]\n\nfor _, _, yt in data: \n particles = particle_filter_step(particles, yt)\n particles = normalize_weights(particles)",
"_____no_output_____"
]
],
[
[
"Let's visualize first all 100 particle and then the highest likelihood particle. The ground-truth trajectory is the black line and each colored trajectory is a particle. ",
"_____no_output_____"
]
],
[
[
"data.plot_inferences([particle['locations'] for particle in particles])",
"_____no_output_____"
],
[
"best_idx = np.argmax([particle['weight'] * particle['prior_prob'] for particle in particles])\nprint('particle weight: ', np.exp(particles[best_idx]['weight']))\ndata.plot_inferences([particles[best_idx]['locations']])",
"particle weight: 0.9999999900998796\n"
]
],
[
[
"We can see that SIS correctly identifies a particle that is quite close to the ground-truth trajectory. However, we can also see the two limitations of SIS. \n1. Since we are sampling trajectories from the prior, we end up with many particles that are obviously inconsistent with our measurements. These are a waste of computation. \n2. All but one of the importance weights converge to 0. This means that we effectively only have drawn one sample from $p(x_{0:t}|y_{1:t})$, meaning we only have a very low-resolution picture of the distribution. \nIn the next section, we see that the bootstrap filter addresses these issues. ",
"_____no_output_____"
],
[
"## The Boostrap Filter\nThe following function defines the selection step from the boostrap filter algorithm. ",
"_____no_output_____"
]
],
[
[
"def selection(particles): \n new_particles = []\n probs = [np.exp(particle[\"weight\"]) for particle in particles]\n \n for _ in range(len(particles)): \n idx = np.argmax(np.random.multinomial(1, probs))\n new_particles.append(particles[idx])\n return new_particles",
"_____no_output_____"
]
],
[
[
"This following code snippet performs the boostrap filter algorithm on our data. We have made one modification from the bootstrap filter algorithm described in the accompanying article: instead of applying the selection step at every time step, we only apply it every 10 times steps. The rationale for this is that in our particular case, doing selection at every time step still results in all but one of the importance weights becoming $0$. However, doing selection only every $\\Delta t$ steps scales the variance of the log-importance weights at selection time by $1/{\\Delta t}$. Setting $t=10$ is sufficient to preserve the diversity of particles. ",
"_____no_output_____"
]
],
[
[
"better_particles = [{\n \"locations\": np.expand_dims(x0, axis=0), \n \"velocities\": np.expand_dims(v0, axis=0), \n \"weight\": np.log(1.0/num_particles), \n \"prior_prob\": 0\n} for _ in range(num_particles)]\n\nfor t, (_, _, yt) in enumerate(data): \n if t%10==0: \n better_particles = selection(better_particles)\n better_particles = particle_filter_step(better_particles, yt, selection=True)\n better_particles = normalize_weights(better_particles)\n else: \n better_particles = particle_filter_step(better_particles, yt, selection=False)\n better_particles = normalize_weights(better_particles)",
"_____no_output_____"
],
[
"data.plot_inferences([particle['locations'] for particle in better_particles])",
"_____no_output_____"
]
],
[
[
"As we can see, the bootstrap filter resolves the problems associate with SIS. Namely, \n1. All particles have equal weight. \n2. Since all our particles are informative, we have rich information about $p(x_{0:t}|y_{1:t})$. ",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb7b15a51798347d4fb7394e88e074bbf6273034
| 142,210 |
ipynb
|
Jupyter Notebook
|
ExampleNotebooks/SingleBeamExample.ipynb
|
scienceopen/SimISR
|
f9826c73137113b68dc2b751a735cd96837fceb3
|
[
"MIT"
] | 4 |
2018-10-06T14:15:50.000Z
|
2021-11-28T21:29:07.000Z
|
ExampleNotebooks/SingleBeamExample.ipynb
|
scienceopen/SimISR
|
f9826c73137113b68dc2b751a735cd96837fceb3
|
[
"MIT"
] | 8 |
2016-12-03T23:27:19.000Z
|
2018-06-06T03:04:06.000Z
|
ExampleNotebooks/SingleBeamExample.ipynb
|
scienceopen/SimISR
|
f9826c73137113b68dc2b751a735cd96837fceb3
|
[
"MIT"
] | 3 |
2016-11-18T08:00:53.000Z
|
2021-11-05T13:47:57.000Z
| 197.788595 | 108,214 | 0.875557 |
[
[
[
"# Single Beam\nThis notebook will run the ISR simulator with a set of data created from a function that makes test data. The results along with error bars are plotted below.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport os,inspect\nfrom SimISR import Path\nimport scipy as sp\nfrom SimISR.utilFunctions import readconfigfile,makeconfigfile\nfrom SimISR.IonoContainer import IonoContainer,MakeTestIonoclass\nfrom SimISR.runsim import main as runsim \nfrom SimISR.analysisplots import analysisdump\nimport seaborn as sns",
"/Users/Bodangles/anaconda/lib/python2.7/site-packages/matplotlib/__init__.py:1357: UserWarning: This call to matplotlib.use() has no effect\nbecause the backend has already been chosen;\nmatplotlib.use() must be called *before* pylab, matplotlib.pyplot,\nor matplotlib.backends is imported for the first time.\n\n warnings.warn(_use_error_msg)\n"
]
],
[
[
"## Set up Config Files\nSetting up a configuration files and the directory needed to run the simulation. The simualtor assumes that for each simulation there is a dedicated directory to save out data along the different processing stages. The simulator also assumes that there is a configuration file which is created in the following cell using a default one that comes with the code base. The only parameter the user should have to set is the number of pulses.",
"_____no_output_____"
]
],
[
[
"# set the number of pulses\nnpulses = 2000\ncurloc = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\ntestpath = os.path.join(os.path.split(curloc)[0],'Testdata','Notebookexample1')\nif not os.path.isdir(testpath):\n os.mkdir(testpath)\n\ndefaultpath = os.path.join(os.path.split(curloc)[0],'Test')\ndefcon = os.path.join(defaultpath,'statsbase.ini')\n(sensdict,simparams) = readconfigfile(defcon)\n\ntint = simparams['IPP']*npulses\nratio1 = tint/simparams['Tint']\nsimparams['Tint']=ratio1 * simparams['Tint']\nsimparams['Fitinter'] = ratio1 * simparams['Fitinter']\nsimparams['TimeLim'] = tint\n\nsimparams['startfile']='startfile.h5'\nmakeconfigfile(os.path.join(testpath,'stats.ini'),simparams['Beamlist'],sensdict['Name'],simparams)",
"/Users/Bodangles/anaconda/lib/python2.7/site-packages/numpy/core/numeric.py:190: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n a = empty(shape, dtype, order)\n/Users/Bodangles/Documents/Python/SimISR/SimISR/utilFunctions.py:698: UserWarning: No start file given\n warnings.warn('No start file given',UserWarning)\n"
]
],
[
[
"## Make Input Data\nThis section will create a set of input parmeters that can be used to create ISR Data. It uses a function MakeTestIonoclass which will create a set of plasma parameters that varies with altitude depending on the the function inputs. This data is put into an ionocontainer class, which is used as a container class to move data between the radarData class, fitter class and plotting modules. It has a standard format so any radar data or plasma parameters for the simulator can be saved in this.\n\nA start file is also made which will be used as the starting parameter values used in the fitter. The starting points for the fitter use a nearest neighbor in space to what is found in the start file.",
"_____no_output_____"
]
],
[
[
"\nfinalpath = os.path.join(testpath,'Origparams')\nif not os.path.isdir(finalpath):\n os.mkdir(finalpath)\nz = (50.+sp.arange(120)*5.)\nnz = len(z)\ncoords = sp.column_stack((sp.zeros((nz,2)),z))\nIcont1=MakeTestIonoclass(testv=False,testtemp=True,N_0=1e11,z_0=250.0,H_0=50.0,coords=coords,times =sp.array([[0,1e6]]))\n\nIcontstart = MakeTestIonoclass(testv=False,testtemp=False,N_0=1e11,z_0=250.0,H_0=50.0,coords=coords,times =sp.array([[0,1e6]]))\n\nfinalfile = os.path.join(finalpath,'0 stats.h5')\nIcont1.saveh5(finalfile)\nIcontstart.saveh5(os.path.join(testpath,'startfile.h5'))",
"_____no_output_____"
]
],
[
[
"## Run Simulation\nThe simulation is run through the submodule runsim and its main function, renamed in this as runsim. This function will call all of the neccesary classes and functions to run the simulator. It will save out the data based off of an internal set of file names.\n\nThis function must get a configuration file and a list of functionalities it is to perform. Below the runsim function will create spectra form the plasma parameters, create radar data and then fit it.",
"_____no_output_____"
]
],
[
[
"functlist = ['spectrums','radardata','fitting']\n\nconfig = os.path.join(testpath,'stats.ini')\n\nrunsim(functlist,testpath,config,True)",
"Processing file 0 stats.h5 starting at 2016-12-03 18:17:42.603779\n\n\t Time:0 of 1 Location:0 of 120, now making spectrum.\n\t Time:0 of 1 Location:1 of 120, now making spectrum.\n\t Time:0 of 1 Location:2 of 120, now making spectrum.\n\t Time:0 of 1 Location:3 of 120, now making spectrum.\n\t Time:0 of 1 Location:4 of 120, now making spectrum.\n\t Time:0 of 1 Location:5 of 120, now making spectrum.\n\t Time:0 of 1 Location:6 of 120, now making spectrum.\n\t Time:0 of 1 Location:7 of 120, now making spectrum.\n\t Time:0 of 1 Location:8 of 120, now making spectrum.\n\t Time:0 of 1 Location:9 of 120, now making spectrum.\n\t Time:0 of 1 Location:10 of 120, now making spectrum.\n\t Time:0 of 1 Location:11 of 120, now making spectrum.\n\t Time:0 of 1 Location:12 of 120, now making spectrum.\n\t Time:0 of 1 Location:13 of 120, now making spectrum.\n\t Time:0 of 1 Location:14 of 120, now making spectrum.\n\t Time:0 of 1 Location:15 of 120, now making spectrum.\n\t Time:0 of 1 Location:16 of 120, now making spectrum.\n\t Time:0 of 1 Location:17 of 120, now making spectrum.\n"
]
],
[
[
"## Plotting\nThe data is plotted along with error bars derived from the fitter.",
"_____no_output_____"
]
],
[
[
"sns.set_style(\"whitegrid\")\nsns.set_context(\"notebook\")\nfig1,axmat =plt.subplots(1,3,figsize = (16,7),sharey=True)\naxvec = axmat.flatten()\nfittedfile = os.path.join(testpath,'Fitted','fitteddata.h5')\nfitiono = IonoContainer.readh5(fittedfile)\nparamlist = ['Ne','Te','Ti']\nindlist =[sp.argwhere(ip==fitiono.Param_Names)[0][0] for ip in paramlist]\nn_indlist =[sp.argwhere(('n'+ip)==fitiono.Param_Names)[0][0] for ip in paramlist]\n\naltin =Icont1.Cart_Coords[:,2]\naltfit = fitiono.Cart_Coords[:,2]\n\nin_ind=[[1,0],[1,1],[0,1]]\npbounds = [[1e10,1.2e11],[200.,3000.],[200.,2500.],[-100.,100.]]\nfor i,iax in enumerate(axvec):\n iinind = in_ind[i]\n ifitind = indlist[i]\n n_ifitind = n_indlist[i]\n #plot input\n indata = Icont1.Param_List[:,0,iinind[0],iinind[1]]\n iax.plot(indata,altin)\n #plot fitted data\n fitdata = fitiono.Param_List[:,0,ifitind]\n fit_error = fitiono.Param_List[:,0,n_ifitind]\n ploth=iax.plot(fitdata,altfit)[0]\n iax.set_xlim(pbounds[i])\n iax.errorbar(fitdata,altfit,xerr=fit_error,fmt='-o',color=ploth.get_color())\n iax.set_title(paramlist[i])",
"/Users/Bodangles/anaconda/lib/python2.7/site-packages/numpy/core/numeric.py:482: ComplexWarning: Casting complex values to real discards the imaginary part\n return array(a, dtype, copy=False, order=order)\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7b1ad0a7c9d9c6415985c97c0ffbb302be4bad
| 28,092 |
ipynb
|
Jupyter Notebook
|
3-monte-carlo/mc_agent.ipynb
|
devidduma/reinforcement-learning
|
41691dc4f8c9762c22ba6ee982cc1f2806dbaea4
|
[
"MIT"
] | null | null | null |
3-monte-carlo/mc_agent.ipynb
|
devidduma/reinforcement-learning
|
41691dc4f8c9762c22ba6ee982cc1f2806dbaea4
|
[
"MIT"
] | null | null | null |
3-monte-carlo/mc_agent.ipynb
|
devidduma/reinforcement-learning
|
41691dc4f8c9762c22ba6ee982cc1f2806dbaea4
|
[
"MIT"
] | null | null | null | 39.016667 | 243 | 0.577353 |
[
[
[
"## Monte Carlo on policy evaluation\n\nMonte Carlo on policy evaluation is an important model free policy evaluation algorithm which uses the popular computational method called the Monte Carlo method.\nIt is important since it is usually the first model free algorithm studied in reinforcement learning.\nModel free algorithms are the ones that do not need a full knowledge of all states and transition dynamics.\nThis makes Monte Carlo on policy evaluation very important since it can be applied into a wide range of real-world scenarios.\nIt is also agnostic to the Markov Decision Process setting, i.e. it can be applied into reinforcement learning problems that do not follow the MDP setting.\nIt is guaranteed to converge to a global optima.\nMonte Carlo on policy evaluation can be implemented in three versions, which differ on how they calculate multiple visits of the same state given an episodic (terminating) history: first visit MC, every visit MC and incremental MC.",
"_____no_output_____"
],
[
"### Characteristics of Monte Carlo on policy evaluation:\n\n##### Model free\nMonte Carlo methods are model free, i.e. they do not require full knowledge of all states or transition dynamics.\n\n##### Finite and discrete state and action spaces\nIn order for Monte Carlo on policy evaluation to work, the environment has to have a finite state and action space, because it saves state values in a dictionary internally.\nThe aforementioned is only possible if the state and action spaces are finite and discrete.\n\n##### On policy / Off policy\n - On policy methods attempt to evaluate or improve the policy that is used to make decisions.\n - Off policy methods evaluate or improve a policy different from that used to generate the data.\n Something very positive for off policy methods is that they can figure out the optimal policy **regardless** of the agent’s actions and motivation.\n\nThe Monte Carlo methods we will see here are on policy.\nNevertheless there are also off policy versions of Monte Carlo which we will not show here.\n\n##### Convergence\nMonte Carlo policy evaluation converges to a *global optimum* value function due to the law of large numbers.\n\n##### Sample based\nMonte Carlo methods are sample based.\nMonte Carlo samples many histories for many trajectories which frees us from using a model.\nAs there is no bootstrapping and we need to calculate the return of a state until the end of an episode, one sample in the case of Monte Carlo methods is the full episode.\nThis means that the update rule for the state values only happens after the current episode has been completely sampled.\n\n##### Unbiased estimation of state values\nBecause we are taking an average over the true distribution of returns in Monte Carlo, we obtain an unbiased estimator of the state value at each state.\n\n##### Finite Horizon\nMonte Carlo methods can only be used in a finite horizon setting, i.e. with episodic (terminating) domains only.\nThis is inherent from the fact that Monte Carlo update rule for the state value function only happens at the end of each episode, i.e. they are sample based.\n\n##### Epsilon greedy policy\nEpsilon greedy policies determine how often will the agent explore and how often will the agent exploit.\n\nFurthermore, we want the epsilon greedy policy to be **greedy in the limit of exploration (GLIE)**.\n - all state-action pairs are visited an infinite number of times\n - $\\epsilon_{t} → 0$ as $ t → 0 $, i.e. the policy is greedy in the limit and converges to 0\n\nIn our case, the update rule after each step for our epsilon is the following:\n$ \\epsilon \\gets 1 / ( c_{\\epsilon} \\times f_{\\epsilon})$, where $ c_{\\epsilon} $ is a counter that increments after each episode has ended, whereas $ f_{\\epsilon} $ is a constant factor.\n\n##### Markov Decision Process agnostic\nMonte Carlo methods can be applied in non-MDP settings, i.e. they are MDP agnostic.\n\n##### Discount factor\nThe discount factor must take a value in the range $[0...1]$.\n - setting it to $1$ means that we put as much value to future states as the current state.\n - setting it to $0$ means that we do not value future states at all, only the current state.",
"_____no_output_____"
],
[
"##### Initialization\nFor Monte Carlo on policy evaluation we keep track of the following:\n - state value functions, initially set to $0$\n - for internal calculations we keep track of total reward up to a specific state as well as the number of times that state was visited\n - samples array contains the latest sampled episode. It is initially set to an empty array and it is cleared after each episode.\n- `self.discount_factor` is set to $1$.\n - we set `self.decaying_epsilon_mul_factor` to a value of $0.2$.\n This is done to allow the agent to explore longer.\n `self.epsilon` starts from $5$ and decreases with each episode.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport random\nfrom collections import defaultdict\nfrom environment import Env\n\n# Monte Carlo Agent which learns every episode from the sample\nclass MCAgent:\n def __init__(self, actions):\n self.width = 5\n self.height = 5\n self.actions = actions\n self.discount_factor = 0.9\n self.decaying_epsilon_counter = 1\n self.decaying_epsilon_mul_factor = 0.2\n self.epsilon = None\n self.samples = []\n self.value_table = defaultdict(VisitState)\n\n# class containing information for visited states\nclass VisitState:\n def __init__(self, total_G = 0, N = 0, V = 0):\n self.total_G = total_G\n self.N = N\n self.V = V",
"_____no_output_____"
]
],
[
[
"### Monte Carlo on policy evaluation\n\nMonte Carlo methods sample an episode *first* and only after that do they update the V value function.\nThe class `MCAgent` is a parent class for the three versions of Monte Carlo on policy evaluation: first visit Monte Carlo, every visit Monte Carlo and incremental Monte Carlo.\n\n##### Calculating the discounted returns\n\nAt the end of an episode, we start by calculating the discounted returns for each visited state.\nWe implement the method `preprocess_visited_states()` that calculates the discounted future sum of rewards $G_t$ for each state.\nNotice that the calculation of $G_t$ for each visited state is a common process for any version of Monte Carlo methods.\nDuring the calculations, the sample is reversed since it simplifies the calculations, i.e. the discount factor can be applied more easily to the $G_t$ sums in reverse and we do not need to calculate high powers of the discount factor.\nIn the end it returns the states and their discounted sums in the correct order.",
"_____no_output_____"
]
],
[
[
"class MCAgent(MCAgent):\n # for each episode calculate discounted returns and return info\n def preprocess_visited_states(self):\n # state name and G for each state as appeared in the episode\n all_states = []\n G = 0\n for reward in reversed(self.samples):\n state_name = str(reward[0])\n G = reward[1] + self.discount_factor * G\n all_states.append([state_name, G])\n all_states.reverse()\n\n self.decaying_epsilon_counter = self.decaying_epsilon_counter + 1\n\n return all_states",
"_____no_output_____"
]
],
[
[
"##### Abstract methods\n\nWe define the following two abstract methods:\n - `mc()`\n - `update_global_value_table()`\n\nThese have to be implemented from the specific version of Monte Carlo method.",
"_____no_output_____"
]
],
[
[
"class MCAgent(MCAgent):\n # to be defined in children classes\n def mc(self):\n pass\n\n # update visited states for first visit or every visit MC\n def update_global_value_table(self, state_name, G_t):\n pass",
"_____no_output_____"
]
],
[
[
"#### First Visit Monte Carlo\n\nFirst visit Monte Carlo is a Monte Carlo method that considers only the first visits to a state *in one episode*.\nNotice that we can consider multiple visits to a state, but not on the same episode.\n\nWe define a child class for the First Visit Monte Carlo agent.\n - in the method `mc()` we first call the `preprocess_visited_states()` method that will give us an array of visited states and their returns.\n - we make sure to check whether a state has already been visited or not.\n If it had been visited, we do not consider that state, we do not update the V values with it.\n - in the method `update_global_value_table()` we update the V values according to textbook update formulas.\n Notice that the visited states are saved in a dictionary.\n\n##### Update rule\n\nThe update rule for V values in the First Visit Monte Carlo is the following:\n\n$ V^{\\pi}(s_t) \\gets G_{total}(s_t) / N(s_t) $ where:\n - $ N(s_t) $ - the number of times the state has been visited during multiple episodes.\n Notice that although we are in the first visit case, the number of times a state has been visited can be more than 1.\n That same state could have been visited multiple times in *different episodes*.\n - $ G_{total}(s_t) $ - cumulative return of multiple visits to that state",
"_____no_output_____"
]
],
[
[
"from mc_agent import MCAgent, VisitState\nfrom environment import Env\n\nclass FVMCAgent(MCAgent):\n def __init__(self, actions):\n super(FVMCAgent, self).__init__(actions)\n\n # for every episode, update V values of visited states\n def mc(self):\n all_states = super(FVMCAgent, self).preprocess_visited_states()\n visit_state = []\n for state in all_states:\n if state[0] not in visit_state:\n visit_state.append(state[0])\n self.update_global_value_table(state[0], state[1])\n\n # update V values of visited states for first visit or every visit MC\n def update_global_value_table(self, state_name, G_t):\n updated = False\n if state_name in self.value_table:\n state = self.value_table[state_name]\n state.total_G = state.total_G + G_t\n state.N = state.N + 1\n state.V = state.total_G / state.N\n updated = True\n if not updated:\n self.value_table[state_name] = VisitState(total_G=G_t, N=1, V=G_t)",
"_____no_output_____"
]
],
[
[
"#### Every Visit Monte Carlo\n\nEvery Visit Monte Carlo is a Monte Carlo method that does not differentiate if the state has been visited multiple times or not during an episode.\n\nWe define a child class for the Every Visit Monte Carlo agent.\n - in the method `mc()` we first call the `preprocess_visited_states()` method that will give us an array of visited states and their returns.\n - this time we do not check whether that state has already been visited or not. We update our V values with every state in the array.\n - in the method `update_global_value_table()` we update the V values according to textbook update formulas.\n Notice that the visited states are saved in a dictionary.\n\n##### Update rule\n\nThe update rule for V values in the Every Visit Monte Carlo is the following:\n\n$ V^{\\pi}(s_t) = G_{total}(s_t) / N(s_t) $ where:\n - $ N(s_t) $ - the number of times the state has been visited during multiple episodes.\n One state can be visited multiple times in the same episode or in different episodes.\n - $ G_{total}(s_t) $ - cumulative return of multiple visits to that state.",
"_____no_output_____"
]
],
[
[
"from mc_agent import MCAgent, VisitState\nfrom environment import Env\n\n\nclass EVMCAgent(MCAgent):\n def __init__(self, actions):\n super(EVMCAgent, self).__init__(actions)\n\n # for every episode, update V values of visited states\n def mc(self):\n all_states = super(EVMCAgent, self).preprocess_visited_states()\n for state in all_states:\n self.update_global_value_table(state[0], state[1])\n\n # update V values of visited states for first visit or every visit MC\n def update_global_value_table(self, state_name, G_t):\n updated = False\n if state_name in self.value_table:\n state = self.value_table[state_name]\n state.total_G = state.total_G + G_t\n state.N = state.N + 1\n state.V = state.total_G / state.N\n updated = True\n if not updated:\n self.value_table[state_name] = VisitState(total_G=G_t, N=1, V=G_t)",
"_____no_output_____"
]
],
[
[
"#### Incremental Monte Carlo\n\nIncremental Monte Carlo is a Monte Carlo method that introduces a new update rule. It has the following key characteristics:\n - most importantly, it introduces the notion of a **learning rate**, which we will see below.\n - it can take two versions: Incremental First Visit Monte Carlo and Incremental Every Visit Monte Carlo.\n We will see the latter one, although the first one can be easily derived.\n\nWe define a child class for the Incremental Monte Carlo agent.\n - in the method `mc()` we first call the `preprocess_visited_states()` method that will give us an array of visited states and their returns.\n - We do not check whether that state has already been visited or not. We update our V values with every state in the array.\n - in the method `update_global_value_table()` we update the V values according to textbook update formulas.\n Notice that the visited states are saved in a dictionary.\n - `update_global_value_table()` is different for Incremental Monte Carlo.\n\n##### Update rule\n\nThe update rule for V values in the Incremental Monte Carlo is the following:\n\n$ V^{\\pi}(s_t) \\gets V^{\\pi}(s_t) + \\alpha [ G(s_t) - V^{\\pi}(s_t) ] $ where:\n - $V^{\\pi}(s_t)$ - state value of current state following the policy $\\pi$\n - $ \\alpha $ - it is called the **learning rate**.\n In our case, we use a **decaying, step-based learning rate** which takes the value of $ \\alpha = 0.5 * 1 / N(s_t) $\n - $ N(s_t) $ - the number of times the state has been visited during multiple episodes.\n Notice that although we are in the first visit case, the number of times a state has been visited can be more than 1.\n That same state could have been visited multiple times in *different episodes*.\n - $ G(s_t) $ - return until the end of the episode of current state.\n\n##### Setting the learning rate\n\nIncremental Monte Carlo can be thought of as a general case of the previous two methods.\n - setting $\\alpha = 1 / N(s_t)$ recovers the original Monte Carlo on policy evaluation algorithms.\n - setting $\\alpha < 1 / N(s_t)$ gives a higher weight to older data\n - setting $\\alpha > 1 / N(s_t)$ gives a higher weight to newer data, which can help learning in non-stationary domains.\n\nIf we are in a truly Markovian domain, Every Visit Monte Carlo will be more data efficient, because we update our average return for a state every time we visit the state.",
"_____no_output_____"
]
],
[
[
"from mc_agent import MCAgent, VisitState\nfrom environment import Env\n\nclass IMCAgent(MCAgent):\n def __init__(self, actions):\n super(IMCAgent, self).__init__(actions)\n\n # for every episode, update V values of visited states\n def mc(self):\n all_states = super(IMCAgent, self).preprocess_visited_states()\n for state in all_states:\n self.update_global_visit_state(state[0], state[1])\n\n # redefined V value update of visited states for incremental MC\n def update_global_visit_state(self, state_name, G_t):\n updated = False\n if state_name in self.value_table:\n state = self.value_table[state_name]\n state.N = state.N + 1\n learning_rate = 0.5 * 1 / state.N\n state.V = state.V + learning_rate * (G_t - state.V)\n updated = True\n if not updated:\n self.value_table[state_name] = VisitState(total_G=G_t, N=1, V=G_t)",
"_____no_output_____"
]
],
[
[
"### Other methods\n\n##### Helper methods",
"_____no_output_____"
]
],
[
[
"class MCAgent(MCAgent):\n # get action for the state according to the v function table\n # agent pick action of epsilon-greedy policy\n def get_action(self, state):\n self.update_epsilon()\n if np.random.rand() < self.epsilon:\n # take random action\n action = np.random.choice(self.actions)\n else:\n # take action according to the v function table\n next_state = self.possible_next_state(state)\n action = self.arg_max(next_state)\n return int(action)\n\n def update_epsilon(self):\n self.epsilon = 1 / (self.decaying_epsilon_counter * self.decaying_epsilon_mul_factor)",
"_____no_output_____"
],
[
"class MCAgent(MCAgent):\n # append sample to memory(state, reward, done)\n def save_sample(self, state, reward, done):\n self.samples.append([state, reward, done])\n\n # compute arg_max if multiple candidates exit, pick one randomly\n @staticmethod\n def arg_max(next_state):\n max_index_list = []\n max_value = next_state[0]\n for index, value in enumerate(next_state):\n if value > max_value:\n max_index_list.clear()\n max_value = value\n max_index_list.append(index)\n elif value == max_value:\n max_index_list.append(index)\n return random.choice(max_index_list)",
"_____no_output_____"
],
[
"class MCAgent(MCAgent):\n # get the possible next states\n def possible_next_state(self, state):\n col, row = state\n next_state = [0.0] * 4\n\n if row != 0:\n next_state[0] = self.value_table[str([col, row - 1])].V\n else:\n next_state[0] = self.value_table[str(state)].V\n if row != self.height - 1:\n next_state[1] = self.value_table[str([col, row + 1])].V\n else:\n next_state[1] = self.value_table[str(state)].V\n if col != 0:\n next_state[2] = self.value_table[str([col - 1, row])].V\n else:\n next_state[2] = self.value_table[str(state)].V\n if col != self.width - 1:\n next_state[3] = self.value_table[str([col + 1, row])].V\n else:\n next_state[3] = self.value_table[str(state)].V\n\n return next_state",
"_____no_output_____"
]
],
[
[
"##### Main loop\n\nSince all Monte Carlo methods are closely related, we define a common function called `mainloop()` in the parent class `MCAgent`.\nAll children MC agents inherit this method and can execute it in their static main functions.",
"_____no_output_____"
]
],
[
[
"class MCAgent(MCAgent):\n # to be called in a main loop\n def mainloop(self, env, verbose=False):\n for episode in range(1000):\n state = env.reset()\n action = self.get_action(state)\n\n while True:\n env.render()\n\n # forward to next state. reward is number and done is boolean\n next_state, reward, done = env.step(action)\n self.save_sample(next_state, reward, done)\n\n # get next action\n action = self.get_action(next_state)\n\n # at the end of each episode, update the v function table\n if done:\n if(verbose):\n print(\"episode : \", episode, \"\\t[3, 2]: \", round(self.value_table[\"[3, 2]\"].V, 2),\n \"\\t[2, 3]:\", round(self.value_table[\"[2, 3]\"].V, 2),\n \"\\t[2, 2]:\", round(self.value_table[\"[2, 2]\"].V, 2),\n \"\\t\\tepsilon: \", round(self.epsilon, 2))\n self.mc()\n self.samples.clear()\n break",
"_____no_output_____"
]
],
[
[
"Implementing the main functions for the three Monte Carlo agents is pretty straightforward now.\n\n##### First Visit Monte Carlo agent",
"_____no_output_____"
]
],
[
[
"if __name__ == \"__main__\":\n env = Env()\n agent = FVMCAgent(actions=list(range(env.n_actions)))\n try:\n agent.mainloop(env)\n except:\n pass",
"_____no_output_____"
]
],
[
[
"##### Every Visit Monte Carlo agent",
"_____no_output_____"
]
],
[
[
"if __name__ == \"__main__\":\n env = Env()\n agent = EVMCAgent(actions=list(range(env.n_actions)))\n try:\n agent.mainloop(env)\n except:\n pass",
"_____no_output_____"
]
],
[
[
"##### Incremental Monte Carlo agent",
"_____no_output_____"
]
],
[
[
"if __name__ == \"__main__\":\n env = Env()\n agent = IMCAgent(actions=list(range(env.n_actions)))\n try:\n agent.mainloop(env)\n except:\n pass",
"_____no_output_____"
]
],
[
[
"### Results\n\nAll Monte Carlo agents will converge to an optimal policy usually within 40 iterations.\nThe most effective agents to solve our problem seem to be the following:\n - First Visit Monte Carlo - In First Visit Monte Carlo, we discard states visited multiple times inside an episode that have high returns in their late visits.\n Basically, we only consider the first return of that state, which is of course much less (more discounted) than the returns of late visits.\n This in turn seems to encourage our agent not to waste time going back and forth in order to avoid being penalized by the triangles.\n\nVery important for making Incremental Monte Carlo on policy evaluation converge to an optimal policy in Grid World is the **decaying learning rate**, that decays with increasing number of episodes.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"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"
]
] |
cb7b20dc0c07663be5871cfc46e16e0dada6ccd0
| 213,690 |
ipynb
|
Jupyter Notebook
|
avatar_image.ipynb
|
adonath/avatar
|
76b0010754ea4a151230e440331748b23517780e
|
[
"BSD-3-Clause"
] | null | null | null |
avatar_image.ipynb
|
adonath/avatar
|
76b0010754ea4a151230e440331748b23517780e
|
[
"BSD-3-Clause"
] | null | null | null |
avatar_image.ipynb
|
adonath/avatar
|
76b0010754ea4a151230e440331748b23517780e
|
[
"BSD-3-Clause"
] | null | null | null | 1,582.888889 | 210,532 | 0.951285 |
[
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Circle",
"_____no_output_____"
],
[
"from scipy.misc import imread\nfrom skimage.color import rgb2gray\nfrom skimage.transform import rescale\nfrom scipy.ndimage import convolve\n\nfrom astropy.convolution import Tophat2DKernel\n\nfrom gammapy.stats import significance",
"_____no_output_____"
],
[
"np.random.seed(10)\ndata = imread('/home/hfm/adonath/Desktop/AxelSchwarz.jpg')\ndata_gray = rgb2gray(data)\ndata_gray = 4 * rescale(data_gray, 0.2)\nsignal = np.pad(data_gray, ((100,100), (100, 100)), mode='constant', constant_values=0)\nbackground = 3 * np.ones_like(signal)\ndata = np.random.poisson(background + signal)",
"_____no_output_____"
],
[
"tophat = Tophat2DKernel(5)\ntophat.normalize('peak')\n\n\nn_on = convolve(data, tophat.array)\nn_off = convolve(background, tophat.array)\n\nsig = significance(n_on, n_off)\n\nfig = plt.figure(figsize=(5, 5), facecolor='none')\nax = fig.add_axes([0, 0, 1, 1])\nim = ax.imshow(sig, cmap='inferno', vmax=20, interpolation='bicubic')\n\ny_center, x_center = 305, 257\nradius = 200\npatch = Circle((x_center, y_center), radius=radius, transform=ax.transData)\nim.set_clip_path(patch)\n\nax.set_xlim(x_center - radius, x_center + radius)\nax.set_ylim(y_center + radius, y_center - radius)\nplt.axis('off')\nplt.savefig('adonath_avatar.png', dpi=51, transparent=True)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code"
]
] |
cb7b224f1df9ccc5b4a88679dd8ed1eebe24a197
| 10,059 |
ipynb
|
Jupyter Notebook
|
homework/day_2/Jasmine-day2-homework.ipynb
|
msse-2020-bootcamp/team1-project
|
f7b83c067734e03e80b8a1feec18679fdac8b857
|
[
"BSD-3-Clause"
] | null | null | null |
homework/day_2/Jasmine-day2-homework.ipynb
|
msse-2020-bootcamp/team1-project
|
f7b83c067734e03e80b8a1feec18679fdac8b857
|
[
"BSD-3-Clause"
] | 14 |
2020-08-11T20:47:51.000Z
|
2020-08-19T20:59:14.000Z
|
homework/day_2/Jasmine-day2-homework.ipynb
|
msse-2020-bootcamp/team1-project
|
f7b83c067734e03e80b8a1feec18679fdac8b857
|
[
"BSD-3-Clause"
] | null | null | null | 24.180288 | 139 | 0.479471 |
[
[
[
"# Monte Carlo Simulation \n\nToday, we will work with the Lennard Jones equation. \n\n$$ U(r) = 4 \\epsilon \\left[\\left(\\frac{\\sigma}{r}\\right)^{12} -\\left(\\frac{\\sigma}{r}\\right)^{6} \\right] $$\n\nReduced Units:\n\n$$ U^*\\left(r_{ij} \\right) = 4 \\left[\\left(\\frac{1}{r^*_{ij}}\\right)^{12} -\\left(\\frac{1}{r^*_{ij}}\\right)^{6} \\right] $$\n",
"_____no_output_____"
]
],
[
[
"import math\nimport os\n\ndef calculate_LJ(r_ij): \n \"\"\"\n The LJ interaction energy between two particles.\n \n Computes the pairwise Lennard jones interaction energy based on the separation distance in reduced units.\n \n Parameters\n ----------\n r_ij : float\n The distance between the particles in reduced units.\n \n Returns\n -------\n pairwise_energy : float\n The pairwise Lennard Jones interaction energy in reduced units.\n \n \"\"\"\n r6_term = math.pow(1/r_ij, 6)\n r12_term = math.pow(r6_term, 2)\n \n pairwise_energy = 4 * (r12_term - r6_term)\n \n return pairwise_energy\n",
"_____no_output_____"
],
[
"#Defining a function for the tail correction\n\ndef calculate_tail_correction(particles, volume, r_cutoff):\n \"\"\"\n This function calculates the tail correction\n \n Parameters\n ----------\n particles : int\n The number of particles in the sample\n \n volume : float\n The volume of the sample\n \n r_cutoff : float\n The cutoff radius\n \n Returns\n -------\n tail_correction_factor: float\n The tail correction factor in reduced units\n \n \"\"\"\n r3_term = math.pow(1/r_cutoff, 3)\n r9_term = math.pow(r3_term, 3)\n \n tail_correction_factor = ((8* math.pi * (particles ** 2)) / (3 * volume) ) * (((1/3) * (r9_term)) - r3_term)\n \n return tail_correction_factor\n\n\n",
"_____no_output_____"
],
[
"tail_correction_factor = calculate_tail_correction(800, 10**3, 3)",
"_____no_output_____"
],
[
"assert math.isclose(tail_correction_factor, -1.9849E+02, rel_tol=0.00001)\n",
"_____no_output_____"
],
[
"calculate_LJ(1)",
"_____no_output_____"
],
[
"calculate_LJ(math.pow(2,(1/6)))",
"_____no_output_____"
],
[
"assert 1 == 1",
"_____no_output_____"
],
[
"#If we assert something that is not True (otherwise known as False), we will get an assert error\n# assert 1 == 0",
"_____no_output_____"
],
[
"assert calculate_LJ(1) == 0\nassert calculate_LJ(math.pow(2, (1/6))) == -1",
"_____no_output_____"
],
[
"def calculate_distance(coord1, coord2):\n \"\"\"\n Calculate the distance between two 3D coordinates.\n \n Parameters\n ----------\n coord1, coord2 : list\n The atomic coordinates [x, y, z]\n \n Returns\n -------\n distance: float\n The distance between the two atoms\n \n \"\"\"\n sum_square_diff = 0\n \n for i in range(len(coord1)):\n sum_square_diff += (coord1[i] - coord2[i])**2\n \n distance = math.sqrt(sum_square_diff)\n \n return distance",
"_____no_output_____"
],
[
"point_1 = [0, 0, 0]\npoint_2 = [1, 0, 0]\n\ndist1 = calculate_distance(point_1, point_2)\n\nassert dist1 == 1",
"_____no_output_____"
],
[
"point_3 = [0, 0, 0]\npoint_4 = [0, 1, 1]\n\ndist2 = calculate_distance(point_3, point_4)\nassert math.sqrt(2) == dist2",
"_____no_output_____"
],
[
"atomic_coordinates = [[0, 0, 0], [0, math.pow(2, 1/6), 0], [0, 2*math.pow(2, 1/6), 0]]",
"_____no_output_____"
],
[
"def calculate_total_energy(coordinates, cutoff):\n \"\"\"\n Calculate the total Lennard Jonest energy of a system of particles.\n \n Parameters\n ----------\n coordinates : list\n Nested list containing particle coordinates.\n \n Returns\n -------\n total_energy : float\n The total pairwise Lennard jonest energy of the system of particles.\n \"\"\"\n \n total_energy = 0\n \n num_atoms = len(coordinates)\n \n for i in range(num_atoms):\n for j in range(i+1, num_atoms):\n dist_ij = calculate_distance(coordinates[i], coordinates[j])\n \n if dist_ij < cutoff:\n interaction_energy = calculate_LJ(dist_ij)\n total_energy += interaction_energy\n \n return total_energy\n ",
"_____no_output_____"
],
[
"def read_xyz(filepath):\n \"\"\"\n Reads coordinates from an xyz file.\n \n Parameters\n ----------\n filepath : str\n The path to the xyz file to be processed.\n \n Returns\n -------\n atomic_coordinates : list\n A two dimensional list containing atomic coordinates\n \"\"\"\n \n with open(filepath) as f:\n box_length = float(f.readline().split()[0])\n num_atoms = float(f.readline())\n coordinates = f.readlines()\n \n atomic_coordinates = []\n \n for atom in coordinates:\n split_atoms = atom.split()\n \n float_coords = []\n \n # We split this way to get rid of the atom label.\n for coord in split_atoms[1:]:\n float_coords.append(float(coord))\n \n atomic_coordinates.append(float_coords)\n \n \n return atomic_coordinates, box_length",
"_____no_output_____"
],
[
"import os\n",
"_____no_output_____"
],
[
"os.getcwd()\n#os.chdir('/home/jasminehakim/msse-bootcamp/team1-project/homework/day_2')\n",
"_____no_output_____"
],
[
"file_path = os.path.join('lj_sample_configurations', 'lj_sample_config_periodic1.txt')\n\ncoordinates, box_length = read_xyz(file_path)",
"_____no_output_____"
],
[
"box_length",
"_____no_output_____"
],
[
"len(coordinates)",
"_____no_output_____"
],
[
"calculate_total_energy(coordinates)",
"_____no_output_____"
],
[
"\n ",
"_____no_output_____"
],
[
"assert tail_correction_factor == -1.9849E+02",
"_____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"
]
] |
cb7b35a74f0cf625e3f1be085dc67e0f1cd95755
| 6,744 |
ipynb
|
Jupyter Notebook
|
docs/tutorials/mixture.ipynb
|
0x0L/tinygp
|
918c0bb8f7a0adbe9ca06df4667a3c15b9f92cec
|
[
"MIT"
] | null | null | null |
docs/tutorials/mixture.ipynb
|
0x0L/tinygp
|
918c0bb8f7a0adbe9ca06df4667a3c15b9f92cec
|
[
"MIT"
] | null | null | null |
docs/tutorials/mixture.ipynb
|
0x0L/tinygp
|
918c0bb8f7a0adbe9ca06df4667a3c15b9f92cec
|
[
"MIT"
] | null | null | null | 31.367442 | 333 | 0.562426 |
[
[
[
"try:\n import tinygp\nexcept ImportError:\n %pip install -q tinygp\n\ntry:\n import jaxopt\nexcept ImportError:\n %pip install -q jaxopt",
"_____no_output_____"
]
],
[
[
"(mixture)=\n\n# Mixture of Kernels",
"_____no_output_____"
],
[
"It can be useful to model a dataset using a mixture of GPs.\nFor example, the data might have both systematic effects and a physical signal that can be modeled using a GP.\nI know of a few examples where this method has been used in the context of time series analysis for the discovery of transiting exoplanets (for example, [Aigrain et al. 2016](https://arxiv.org/abs/1603.09167) and [Luger et al. 2016](https://arxiv.org/abs/1607.00524)), but I'm sure that these aren't the earliest references.\nThe idea is pretty simple: if your model is a mixture of two GPs (with covariance matrices $K_1$ and $K_2$ respectively), this is equivalent to a single GP where the kernel is the sum of two kernels, one for each component ($K = K_1 + K_2$).\nIn this case, the equation for the predictive mean conditioned on a dataset $\\boldsymbol{y}$ is\n\n$$\n\\boldsymbol{\\mu} = (K_1 + K_2)\\,(K_1 + K_2 + N)^{-1} \\, \\boldsymbol{y}\n$$\n\nwhere $N$ is the (possibly diagonal) matrix describing the measurement uncertainties.\nIt turns out that the equation for computing the predictive mean for component 1 is simply\n\n$$\n\\boldsymbol{\\mu}_1 = K_1\\,(K_1 + K_2 + N)^{-1} \\, \\boldsymbol{y}\n$$\n\nand the equivalent expression can be written for component 2.\n\nThis can be implemented in `tinygp` using the new `kernel` keyword argument in the `predict` method.\nTo demonstrate this, let's start by generating a synthetic dataset.\nComponent 1 is a systematic signal that depends on two input parameters ($t$ and $\\theta$ following Aigrain) and component 2 is a quasiperiodic oscillation that is the target of our analysis.",
"_____no_output_____"
]
],
[
[
"import jax\nimport jax.numpy as jnp\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tinygp import GaussianProcess, kernels, transforms\n\nfrom jax.config import config\n\nconfig.update(\"jax_enable_x64\", True)\n\nrandom = np.random.default_rng(123)\nN = 256\nt = np.sort(random.uniform(0, 10, N))\ntheta = random.uniform(-np.pi, np.pi, N)\nX = np.vstack((t, theta)).T\n\n\ndef build_gp(params):\n kernel1 = jnp.exp(params[\"log_amp1\"]) * transforms.Linear(\n jnp.exp(params[\"log_scale1\"]), kernels.Matern32()\n )\n kernel2 = jnp.exp(params[\"log_amp2\"]) * transforms.Subspace(\n 0,\n kernels.ExpSquared(jnp.exp(params[\"log_scale2\"]))\n * kernels.ExpSineSquared(\n scale=jnp.exp(params[\"log_period\"]),\n gamma=jnp.exp(params[\"log_gamma\"]),\n ),\n )\n kernel = kernel1 + kernel2\n return GaussianProcess(kernel, X, diag=jnp.exp(params[\"log_diag\"]))\n\n\ntrue_params = {\n \"log_amp1\": np.log(2.0),\n \"log_scale1\": np.log([2.0, 0.8]),\n \"log_amp2\": np.log(2.0),\n \"log_scale2\": np.log(3.5),\n \"log_period\": np.log(2.0),\n \"log_gamma\": np.log(10.0),\n \"log_diag\": np.log(0.5),\n}\ngp = build_gp(true_params)\ny = gp.sample(jax.random.PRNGKey(5678))\n\nplt.plot(t, y, \".k\")\nplt.ylim(-6.5, 6.5)\nplt.xlim(0, 10)\nplt.xlabel(\"t\")\nplt.ylabel(\"y\");",
"_____no_output_____"
]
],
[
[
"The physical (oscillatory) component is not obvious in this dataset because it is swamped by the systematics.\nNow, we'll find the maximum likelihood hyperparameters by numerically minimizing the negative log-likelihood function.",
"_____no_output_____"
]
],
[
[
"import jaxopt\n\n\[email protected]\ndef loss(params):\n return -build_gp(params).log_probability(y)\n\n\nsolver = jaxopt.ScipyMinimize(fun=loss)\nsoln = solver.run(true_params)\nprint(\"Maximum likelihood parameters:\")\nprint(soln.params)",
"_____no_output_____"
]
],
[
[
"Now let's use the trick from above to compute the prediction of component 1 and remove it to see the periodic signal.",
"_____no_output_____"
]
],
[
[
"# Compute the predictive means - note the \"kernel\" argument\ngp = build_gp(soln.params)\nmu1 = gp.condition(y, kernel=gp.kernel.kernel1).gp.loc\nmu2 = gp.condition(y, kernel=gp.kernel.kernel2).gp.loc\n\nplt.plot(t, y, \".k\", mec=\"none\", alpha=0.3)\nplt.plot(t, y - mu1, \".k\")\nplt.plot(t, mu2)\n\nplt.ylim(-6.5, 6.5)\nplt.xlim(0, 10)\nplt.xlabel(\"t\")\nplt.ylabel(\"y\");",
"_____no_output_____"
]
],
[
[
"In this plot, the original dataset is plotted in light gray points and the \"de-trended\" data with component 1 removed is plotted as black points.\nThe prediction of the GP model for component 2 is shown as a blue line.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7b45d532a407fa9ad417957621d1637fde2490
| 11,002 |
ipynb
|
Jupyter Notebook
|
examples/XEntropy-example1-dihedral_entropy.ipynb
|
liedllab/X-Entropy
|
64faa7d70378d12157edaf66a59e87ef27b3a06a
|
[
"MIT"
] | 14 |
2021-03-15T14:28:22.000Z
|
2021-11-02T14:13:11.000Z
|
examples/XEntropy-example1-dihedral_entropy.ipynb
|
liedllab/X-Entropy
|
64faa7d70378d12157edaf66a59e87ef27b3a06a
|
[
"MIT"
] | 9 |
2021-04-08T12:44:10.000Z
|
2021-10-20T09:04:12.000Z
|
examples/XEntropy-example1-dihedral_entropy.ipynb
|
liedllab/X-Entropy
|
64faa7d70378d12157edaf66a59e87ef27b3a06a
|
[
"MIT"
] | 1 |
2021-04-06T01:44:42.000Z
|
2021-04-06T01:44:42.000Z
| 22.271255 | 113 | 0.51936 |
[
[
[
"import numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"from xentropy import dihedrals",
"_____no_output_____"
],
[
"from astropy import units as au",
"_____no_output_____"
]
],
[
[
"# single Gaussian distro",
"_____no_output_____"
],
[
"## create artificial data",
"_____no_output_____"
]
],
[
[
"data= np.random.randn(100000)*30",
"_____no_output_____"
]
],
[
[
"## perform kde",
"_____no_output_____"
]
],
[
[
"dih_ent = dihedrals.dihedralEntropy(data=data,verbose=True)\ndih_ent.calculate()",
"_____no_output_____"
]
],
[
[
"## plot normalized histogram and kde",
"_____no_output_____"
]
],
[
[
"f,axs = plt.subplots(ncols=2,figsize=(12,6))\n\n\naxs[0].hist(data,180,density=True, label=\"histogram\")\nxs, ys = dih_ent.pdf_x_deg,dih_ent.pdf_deg\naxs[0].plot(xs,ys, lw=5,alpha=.7, label=\"XEntropy KDE\\nS = {:.3f} J/(mol*K)\".format(dih_ent.entropy))\n\naxs[0].set(xlabel=\"artif. dihedrals / degree\", ylabel=\"prob. density / degree$^{-1}$\")\n\n\naxs[1].hist(data/180*np.pi,180,density=True, label=\"histogram\")\nxs, ys = dih_ent.pdf_x,dih_ent.pdf\naxs[1].plot(xs,ys, lw=5,alpha=.7, label=\"XEntropy KDE\\nS = {:.3f} J/(mol*K)\".format(dih_ent.entropy))\n\naxs[1].set(xlabel=\"artif. dihedrals / radian\", ylabel=\"prob. density / radian$^{-1}$\")\n\n\nfor ax in axs:\n ax.legend(loc=\"upper right\")",
"_____no_output_____"
]
],
[
[
"# Gaussians of variable width",
"_____no_output_____"
],
[
"## create artificial data",
"_____no_output_____"
]
],
[
[
"data= [np.random.randn(100000)*20,\n np.random.randn(100000)*30,\n np.random.randn(100000)*40,\n np.random.randn(100000)*50]",
"_____no_output_____"
]
],
[
[
"## perform kde",
"_____no_output_____"
]
],
[
[
"dih_ent = dihedrals.dihedralEntropy(data=data,verbose=True,input_unit=\"degree\")\n\ndih_ent.calculate()",
"_____no_output_____"
]
],
[
[
"## plot normalized histogram and kde",
"_____no_output_____"
]
],
[
[
"f,axs = plt.subplots(2,2,figsize=(12,12),sharex=True,sharey=True)\n\n\nfor ax,dat,xs,ys,S in zip(axs.flatten(),data,dih_ent.pdf_x_deg,dih_ent.pdf_deg, dih_ent.entropy):\n ax.hist(dat,180,density=True, label=\"histogram\")\n ax.plot(xs,ys, lw=5,alpha=.7, label=\"XEntropy KDE\\nS = {:.3f} J/(mol*K)\".format(S))\n \n ax.set(xlabel=\"artificial dihedrals\", ylabel=\"probability density\")\n ax.legend()\nf.tight_layout()",
"_____no_output_____"
]
],
[
[
"# binodal distributions",
"_____no_output_____"
],
[
"## create artificial data",
"_____no_output_____"
]
],
[
[
"def binodal_data(n_samples=1001,w1=10,w2=10):\n n1 = n_samples//2\n n2 = n_samples-n1\n p1 = np.random.randn(n1)*w1-90\n p2 = np.random.randn(n2)*w2+90\n\n return np.concatenate([p1,p2])",
"_____no_output_____"
],
[
"data= [binodal_data(100000,5,25),\n binodal_data(100000,15,25),\n binodal_data(100000,25,25),\n binodal_data(100000,35,25)]",
"_____no_output_____"
]
],
[
[
"## perform kde",
"_____no_output_____"
]
],
[
[
"dih_ent = dihedrals.dihedralEntropy(data=data, verbose=False, input_unit=\"degree\")\n\ndih_ent.calculate()",
"_____no_output_____"
]
],
[
[
"## plot normalized histogram and kde",
"_____no_output_____"
]
],
[
[
"f,axs = plt.subplots(2,2,figsize=(12,12),sharex=True,sharey=True)\n\n\nfor ax,dat,xs,ys,S in zip(axs.flatten(), data,dih_ent.pdf_x_deg, dih_ent.pdf_deg, dih_ent.entropy):\n ax.hist(dat,180,density=True, label=\"histogram\")\n ax.plot(xs,ys, lw=5,alpha=.7, label=\"XEntropy KDE\\nS = {:.3f} J/(mol*K)\".format(S))\n \n ax.set(xlabel=\"artificial dihedrals\", ylabel=\"probability density\")\n ax.legend()\nf.tight_layout()",
"_____no_output_____"
]
],
[
[
"# shifted binodal distributions",
"_____no_output_____"
],
[
"## create artificial data",
"_____no_output_____"
]
],
[
[
"def binodal_data(n_samples=1001,w1=10,w2=10):\n n1 = n_samples//2\n n2 = n_samples-n1\n p1 = np.random.randn(n1)*w1\n p2 = np.random.randn(n2)*w2+180\n\n return np.divmod(np.concatenate([p1,p2]),360)[1]-180",
"_____no_output_____"
],
[
"data= [binodal_data(100000,5,25),\n binodal_data(100000,15,25),\n binodal_data(100000,25,25),\n binodal_data(100000,35,25)]",
"_____no_output_____"
]
],
[
[
"## perform kde",
"_____no_output_____"
]
],
[
[
"dih_ent = dihedrals.dihedralEntropy(data=data, verbose=False, input_unit=\"degree\")\n\ndih_ent.calculate()",
"_____no_output_____"
]
],
[
[
"## plot normalized histogram and kde",
"_____no_output_____"
]
],
[
[
"f,axs = plt.subplots(2,2,figsize=(12,12),sharex=True,sharey=True)\n\n\nfor ax,dat,xs,ys,S in zip(axs.flatten(),data,dih_ent.pdf_x_deg,dih_ent.pdf_deg, dih_ent.entropy):\n ax.hist(dat,180,density=True, label=\"histogram\")\n ax.plot(xs,ys, lw=5,alpha=.7, label=\"XEntropy KDE\\nS = {:.3f} J/(mol*K)\".format(S))\n \n ax.set(xlabel=\"artificial dihedrals\", ylabel=\"probability density\")\n ax.legend()\nf.tight_layout()",
"_____no_output_____"
]
],
[
[
"# trinodal distributions (butane-like)",
"_____no_output_____"
],
[
"## create artificial data",
"_____no_output_____"
]
],
[
[
"def trinodal_data(n_samples=1001,w1=20,w2=20,w3=20):\n n1 = int(n_samples*2/5)\n n2 = int((n_samples-n1)/2)\n n3 = n_samples-n1-n2\n p1 = np.random.randn(n1)*w1\n p2 = np.random.randn(n2)*w2-120\n p3 = np.random.randn(n3)*w3+120\n\n return np.concatenate([p1,p2,p3])",
"_____no_output_____"
],
[
"data= trinodal_data(100000)",
"_____no_output_____"
]
],
[
[
"## perform kde",
"_____no_output_____"
]
],
[
[
"dih_ent = dihedrals.dihedralEntropy(data=data, verbose=False, input_unit=\"degree\")\n\ndih_ent.calculate()",
"_____no_output_____"
]
],
[
[
"## plot normalized histogram and kde",
"_____no_output_____"
]
],
[
[
"f,axs = plt.subplots()\n\nxs, ys = dih_ent.pdf_x_deg,dih_ent.pdf_deg\naxs.hist(data,180,density=True, label=\"histogram\")\n\n\naxs.plot(xs,ys, lw=5,alpha=.7, label=\"XEntropy KDE\\nS = {:.3f} J/(mol*K)\".format(dih_ent.entropy))\naxs.set(xlabel=\"artificial dihedrals\", ylabel=\"probability density\")\n\naxs.legend()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7b49f6213f377bce1a87f5be99d94368000360
| 241,206 |
ipynb
|
Jupyter Notebook
|
src/.ipynb_checkpoints/jf-model-1-checkpoint.ipynb
|
joaquinfontela/Machine-Learning
|
733284fe82e6c128358fe2e7721d887e2683da9f
|
[
"MIT"
] | null | null | null |
src/.ipynb_checkpoints/jf-model-1-checkpoint.ipynb
|
joaquinfontela/Machine-Learning
|
733284fe82e6c128358fe2e7721d887e2683da9f
|
[
"MIT"
] | null | null | null |
src/.ipynb_checkpoints/jf-model-1-checkpoint.ipynb
|
joaquinfontela/Machine-Learning
|
733284fe82e6c128358fe2e7721d887e2683da9f
|
[
"MIT"
] | 1 |
2021-07-30T20:53:53.000Z
|
2021-07-30T20:53:53.000Z
| 69.632217 | 97,656 | 0.586789 |
[
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nfrom matplotlib import style\nimport matplotlib.ticker as ticker\nimport seaborn as sns",
"_____no_output_____"
],
[
"from sklearn.datasets import load_boston\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import plot_confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import f1_score\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import RepeatedKFold\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import ParameterGrid\nfrom sklearn.inspection import permutation_importance\nimport multiprocessing",
"_____no_output_____"
],
[
"labels = pd.read_csv('../csv/train_labels.csv')\nlabels.head()",
"_____no_output_____"
],
[
"values = pd.read_csv('../csv/train_values.csv')\nvalues.head(10).T",
"_____no_output_____"
],
[
"values.isnull().values.any()",
"_____no_output_____"
],
[
"labels.isnull().values.any()",
"_____no_output_____"
],
[
"values.dtypes ",
"_____no_output_____"
],
[
"values[\"building_id\"].count() == values[\"building_id\"].drop_duplicates().count()",
"_____no_output_____"
],
[
"values.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 260601 entries, 0 to 260600\nData columns (total 39 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 building_id 260601 non-null int64 \n 1 geo_level_1_id 260601 non-null int64 \n 2 geo_level_2_id 260601 non-null int64 \n 3 geo_level_3_id 260601 non-null int64 \n 4 count_floors_pre_eq 260601 non-null int64 \n 5 age 260601 non-null int64 \n 6 area_percentage 260601 non-null int64 \n 7 height_percentage 260601 non-null int64 \n 8 land_surface_condition 260601 non-null object\n 9 foundation_type 260601 non-null object\n 10 roof_type 260601 non-null object\n 11 ground_floor_type 260601 non-null object\n 12 other_floor_type 260601 non-null object\n 13 position 260601 non-null object\n 14 plan_configuration 260601 non-null object\n 15 has_superstructure_adobe_mud 260601 non-null int64 \n 16 has_superstructure_mud_mortar_stone 260601 non-null int64 \n 17 has_superstructure_stone_flag 260601 non-null int64 \n 18 has_superstructure_cement_mortar_stone 260601 non-null int64 \n 19 has_superstructure_mud_mortar_brick 260601 non-null int64 \n 20 has_superstructure_cement_mortar_brick 260601 non-null int64 \n 21 has_superstructure_timber 260601 non-null int64 \n 22 has_superstructure_bamboo 260601 non-null int64 \n 23 has_superstructure_rc_non_engineered 260601 non-null int64 \n 24 has_superstructure_rc_engineered 260601 non-null int64 \n 25 has_superstructure_other 260601 non-null int64 \n 26 legal_ownership_status 260601 non-null object\n 27 count_families 260601 non-null int64 \n 28 has_secondary_use 260601 non-null int64 \n 29 has_secondary_use_agriculture 260601 non-null int64 \n 30 has_secondary_use_hotel 260601 non-null int64 \n 31 has_secondary_use_rental 260601 non-null int64 \n 32 has_secondary_use_institution 260601 non-null int64 \n 33 has_secondary_use_school 260601 non-null int64 \n 34 has_secondary_use_industry 260601 non-null int64 \n 35 has_secondary_use_health_post 260601 non-null int64 \n 36 has_secondary_use_gov_office 260601 non-null int64 \n 37 has_secondary_use_use_police 260601 non-null int64 \n 38 has_secondary_use_other 260601 non-null int64 \ndtypes: int64(31), object(8)\nmemory usage: 77.5+ MB\n"
],
[
"to_be_categorized = [\"land_surface_condition\", \"foundation_type\", \"roof_type\",\\\n \"position\", \"ground_floor_type\", \"other_floor_type\",\\\n \"plan_configuration\", \"legal_ownership_status\"]\nfor row in to_be_categorized:\n values[row] = values[row].astype(\"category\")\nvalues.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 260601 entries, 0 to 260600\nData columns (total 39 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 building_id 260601 non-null int64 \n 1 geo_level_1_id 260601 non-null int64 \n 2 geo_level_2_id 260601 non-null int64 \n 3 geo_level_3_id 260601 non-null int64 \n 4 count_floors_pre_eq 260601 non-null int64 \n 5 age 260601 non-null int64 \n 6 area_percentage 260601 non-null int64 \n 7 height_percentage 260601 non-null int64 \n 8 land_surface_condition 260601 non-null category\n 9 foundation_type 260601 non-null category\n 10 roof_type 260601 non-null category\n 11 ground_floor_type 260601 non-null category\n 12 other_floor_type 260601 non-null category\n 13 position 260601 non-null category\n 14 plan_configuration 260601 non-null category\n 15 has_superstructure_adobe_mud 260601 non-null int64 \n 16 has_superstructure_mud_mortar_stone 260601 non-null int64 \n 17 has_superstructure_stone_flag 260601 non-null int64 \n 18 has_superstructure_cement_mortar_stone 260601 non-null int64 \n 19 has_superstructure_mud_mortar_brick 260601 non-null int64 \n 20 has_superstructure_cement_mortar_brick 260601 non-null int64 \n 21 has_superstructure_timber 260601 non-null int64 \n 22 has_superstructure_bamboo 260601 non-null int64 \n 23 has_superstructure_rc_non_engineered 260601 non-null int64 \n 24 has_superstructure_rc_engineered 260601 non-null int64 \n 25 has_superstructure_other 260601 non-null int64 \n 26 legal_ownership_status 260601 non-null category\n 27 count_families 260601 non-null int64 \n 28 has_secondary_use 260601 non-null int64 \n 29 has_secondary_use_agriculture 260601 non-null int64 \n 30 has_secondary_use_hotel 260601 non-null int64 \n 31 has_secondary_use_rental 260601 non-null int64 \n 32 has_secondary_use_institution 260601 non-null int64 \n 33 has_secondary_use_school 260601 non-null int64 \n 34 has_secondary_use_industry 260601 non-null int64 \n 35 has_secondary_use_health_post 260601 non-null int64 \n 36 has_secondary_use_gov_office 260601 non-null int64 \n 37 has_secondary_use_use_police 260601 non-null int64 \n 38 has_secondary_use_other 260601 non-null int64 \ndtypes: category(8), int64(31)\nmemory usage: 63.6 MB\n"
],
[
"datatypes = dict(values.dtypes)\nfor row in values.columns:\n if datatypes[row] != \"int64\" and datatypes[row] != \"int32\" and \\\n datatypes[row] != \"int16\" and datatypes[row] != \"int8\":\n continue\n if values[row].nlargest(1).item() > 32767 and values[row].nlargest(1).item() < 2**31:\n values[row] = values[row].astype(np.int32)\n elif values[row].nlargest(1).item() > 127:\n values[row] = values[row].astype(np.int16)\n else:\n values[row] = values[row].astype(np.int8)\nvalues.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 260601 entries, 0 to 260600\nData columns (total 39 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 building_id 260601 non-null int32 \n 1 geo_level_1_id 260601 non-null int8 \n 2 geo_level_2_id 260601 non-null int16 \n 3 geo_level_3_id 260601 non-null int16 \n 4 count_floors_pre_eq 260601 non-null int8 \n 5 age 260601 non-null int16 \n 6 area_percentage 260601 non-null int8 \n 7 height_percentage 260601 non-null int8 \n 8 land_surface_condition 260601 non-null category\n 9 foundation_type 260601 non-null category\n 10 roof_type 260601 non-null category\n 11 ground_floor_type 260601 non-null category\n 12 other_floor_type 260601 non-null category\n 13 position 260601 non-null category\n 14 plan_configuration 260601 non-null category\n 15 has_superstructure_adobe_mud 260601 non-null int8 \n 16 has_superstructure_mud_mortar_stone 260601 non-null int8 \n 17 has_superstructure_stone_flag 260601 non-null int8 \n 18 has_superstructure_cement_mortar_stone 260601 non-null int8 \n 19 has_superstructure_mud_mortar_brick 260601 non-null int8 \n 20 has_superstructure_cement_mortar_brick 260601 non-null int8 \n 21 has_superstructure_timber 260601 non-null int8 \n 22 has_superstructure_bamboo 260601 non-null int8 \n 23 has_superstructure_rc_non_engineered 260601 non-null int8 \n 24 has_superstructure_rc_engineered 260601 non-null int8 \n 25 has_superstructure_other 260601 non-null int8 \n 26 legal_ownership_status 260601 non-null category\n 27 count_families 260601 non-null int8 \n 28 has_secondary_use 260601 non-null int8 \n 29 has_secondary_use_agriculture 260601 non-null int8 \n 30 has_secondary_use_hotel 260601 non-null int8 \n 31 has_secondary_use_rental 260601 non-null int8 \n 32 has_secondary_use_institution 260601 non-null int8 \n 33 has_secondary_use_school 260601 non-null int8 \n 34 has_secondary_use_industry 260601 non-null int8 \n 35 has_secondary_use_health_post 260601 non-null int8 \n 36 has_secondary_use_gov_office 260601 non-null int8 \n 37 has_secondary_use_use_police 260601 non-null int8 \n 38 has_secondary_use_other 260601 non-null int8 \ndtypes: category(8), int16(3), int32(1), int8(27)\nmemory usage: 11.2 MB\n"
],
[
"labels.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 260601 entries, 0 to 260600\nData columns (total 2 columns):\n # Column Non-Null Count Dtype\n--- ------ -------------- -----\n 0 building_id 260601 non-null int64\n 1 damage_grade 260601 non-null int64\ndtypes: int64(2)\nmemory usage: 4.0 MB\n"
],
[
"labels[\"building_id\"] = labels[\"building_id\"].astype(np.int32)\nlabels[\"damage_grade\"] = labels[\"damage_grade\"].astype(np.int8)\nlabels.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 260601 entries, 0 to 260600\nData columns (total 2 columns):\n # Column Non-Null Count Dtype\n--- ------ -------------- -----\n 0 building_id 260601 non-null int32\n 1 damage_grade 260601 non-null int8 \ndtypes: int32(1), int8(1)\nmemory usage: 1.2 MB\n"
]
],
[
[
"# Primer Modelo",
"_____no_output_____"
]
],
[
[
"important_values = values\\\n .merge(labels, on=\"building_id\")\nimportant_values.drop(columns=[\"building_id\"], inplace = True)\nimportant_values[\"geo_level_1_id\"] = important_values[\"geo_level_1_id\"].astype(\"category\")",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(important_values.drop(columns = 'damage_grade'),\n important_values['damage_grade'], test_size = 0.2, random_state = 123)",
"_____no_output_____"
],
[
"def encode_and_bind(original_dataframe, feature_to_encode):\n dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])\n res = pd.concat([original_dataframe, dummies], axis=1)\n res = res.drop([feature_to_encode], axis=1)\n return(res) \n\nfeatures_to_encode = [\"geo_level_1_id\", \"land_surface_condition\", \"foundation_type\", \"roof_type\",\\\n \"position\", \"ground_floor_type\", \"other_floor_type\",\\\n \"plan_configuration\", \"legal_ownership_status\"]\nfor feature in features_to_encode:\n X_train = encode_and_bind(X_train, feature)",
"_____no_output_____"
],
[
"rf_model = RandomForestClassifier(n_estimators = 150, max_depth = 15, criterion = \"gini\", verbose=True)\nrf_model.fit(X_train, y_train)",
"[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n[Parallel(n_jobs=1)]: Done 150 out of 150 | elapsed: 25.2s finished\n"
],
[
"rf_model.score(X_train, y_train)",
"[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n[Parallel(n_jobs=1)]: Done 150 out of 150 | elapsed: 3.6s finished\n"
],
[
"rf_model.feature_importances_",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize = (20,20))\nplt.bar(X_train.columns, rf_model.feature_importances_)\nplt.xlabel(\"Features\")\nplt.xticks(rotation = 90)\nplt.ylabel(\"Importance\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Obtenemos un grafico que indica la importancia de cada columna para el modelo recien generado.",
"_____no_output_____"
]
],
[
[
"important_columns = [col for col in values.columns if col.startswith('has_superstructure')]\nimportant_values = values[important_columns + \\\n ['building_id', 'geo_level_1_id', 'foundation_type', 'ground_floor_type', 'age', 'area_percentage']]\\\n .merge(labels, on=\"building_id\")\nimportant_values.drop(columns=[\"building_id\"], inplace = True)\nimportant_values[\"geo_level_1_id\"] = important_values[\"geo_level_1_id\"].astype(\"category\")\nimportant_values",
"_____no_output_____"
],
[
"X_train, X_test, y_train, y_test = train_test_split(important_values.drop(columns = 'damage_grade'),\n important_values['damage_grade'], test_size = 0.2, random_state = 123)",
"_____no_output_____"
],
[
"def encode_and_bind(original_dataframe, feature_to_encode):\n dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])\n res = pd.concat([original_dataframe, dummies], axis=1)\n res = res.drop([feature_to_encode], axis=1)\n return(res) \n\nfeatures_to_encode = [\"geo_level_1_id\", \"foundation_type\", \"ground_floor_type\"]\nfor feature in features_to_encode:\n X_train = encode_and_bind(X_train, feature)\n X_test = encode_and_bind(X_test, feature)",
"_____no_output_____"
],
[
"rf_model = RandomForestClassifier(n_estimators = 100, max_depth = 15, max_features = 45, criterion = \"gini\", verbose=True)\nrf_model.fit(X_train, y_train)",
"[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n[Parallel(n_jobs=1)]: Done 100 out of 100 | elapsed: 42.9s finished\n"
],
[
"rf_model.score(X_train, y_train)",
"[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n[Parallel(n_jobs=1)]: Done 100 out of 100 | elapsed: 2.3s finished\n"
],
[
"y_preds = rf_model.predict(X_test)\nf1_score(y_test, y_preds, average='micro')",
"[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n[Parallel(n_jobs=1)]: Done 100 out of 100 | elapsed: 0.6s finished\n"
],
[
"rf_model.feature_importances_",
"_____no_output_____"
],
[
"test_values = pd.read_csv('../csv/test_values.csv', index_col = \"building_id\")\ntest_values",
"_____no_output_____"
],
[
"important_columns = [col for col in test_values.columns if col.startswith('has_superstructure')]\ntest_values_subset = test_values[important_columns + \\\n ['geo_level_1_id', 'foundation_type', 'ground_floor_type', 'age', 'area_percentage']]\ntest_values_subset[\"geo_level_1_id\"] = test_values_subset[\"geo_level_1_id\"].astype(\"category\")\ntest_values_subset",
"<ipython-input-178-5613ea823212>:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n test_values_subset[\"geo_level_1_id\"] = test_values_subset[\"geo_level_1_id\"].astype(\"category\")\n"
],
[
"def encode_and_bind(original_dataframe, feature_to_encode):\n dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])\n res = pd.concat([original_dataframe, dummies], axis=1)\n res = res.drop([feature_to_encode], axis=1)\n return(res) \n\nfeatures_to_encode = [\"geo_level_1_id\", \"foundation_type\", \"ground_floor_type\"]\nfor feature in features_to_encode:\n test_values_subset = encode_and_bind(test_values_subset, feature)\ntest_values_subset",
"_____no_output_____"
],
[
"preds = rf_model.predict(test_values_subset)",
"[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n[Parallel(n_jobs=1)]: Done 100 out of 100 | elapsed: 0.9s finished\n"
],
[
"submission_format = pd.read_csv('../csv/submission_format.csv', index_col = \"building_id\")",
"_____no_output_____"
],
[
"my_submission = pd.DataFrame(data=preds,\n columns=submission_format.columns,\n index=submission_format.index)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7b4aebbf10500dc55b34941b58926de049e68d
| 29,699 |
ipynb
|
Jupyter Notebook
|
docs/tutorials/2_environments_tutorial.ipynb
|
UofT-EcoSystem/rlscope_agents
|
49b1f2b32fbfee82c4d9eaa04f436b6058caf39a
|
[
"Apache-2.0"
] | null | null | null |
docs/tutorials/2_environments_tutorial.ipynb
|
UofT-EcoSystem/rlscope_agents
|
49b1f2b32fbfee82c4d9eaa04f436b6058caf39a
|
[
"Apache-2.0"
] | null | null | null |
docs/tutorials/2_environments_tutorial.ipynb
|
UofT-EcoSystem/rlscope_agents
|
49b1f2b32fbfee82c4d9eaa04f436b6058caf39a
|
[
"Apache-2.0"
] | null | null | null | 38.075641 | 422 | 0.559749 |
[
[
[
"##### Copyright 2018 The TF-Agents Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Environments\n\n<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/agents/tutorials/2_environments_tutorial\">\n <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/agents/blob/master/docs/tutorials/2_environments_tutorial.ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/agents/blob/master/docs/tutorials/2_environments_tutorial.ipynb\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/agents/docs/tutorials/2_environments_tutorial.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"## Introduction",
"_____no_output_____"
],
[
"The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return.\n\nIn TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand, and debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow.\n\nLet us look at Python environments first. TensorFlow environments follow a very similar API.",
"_____no_output_____"
],
[
"## Setup\n",
"_____no_output_____"
],
[
"If you haven't installed tf-agents or gym yet, run:",
"_____no_output_____"
]
],
[
[
"!pip install --pre tf-agents[reverb]\n!pip install 'gym==0.10.11'",
"_____no_output_____"
],
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport tensorflow as tf\nimport numpy as np\n\nfrom tf_agents.environments import py_environment\nfrom tf_agents.environments import tf_environment\nfrom tf_agents.environments import tf_py_environment\nfrom tf_agents.environments import utils\nfrom tf_agents.specs import array_spec\nfrom tf_agents.environments import wrappers\nfrom tf_agents.environments import suite_gym\nfrom tf_agents.trajectories import time_step as ts\n\ntf.compat.v1.enable_v2_behavior()",
"_____no_output_____"
]
],
[
[
"## Python Environments",
"_____no_output_____"
],
[
"Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step:\n1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step.\n2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps.\n3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence.\n4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step.\n\nThese are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`.\n\nThe interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are:",
"_____no_output_____"
]
],
[
[
"class PyEnvironment(object):\n\n def reset(self):\n \"\"\"Return initial_time_step.\"\"\"\n self._current_time_step = self._reset()\n return self._current_time_step\n\n def step(self, action):\n \"\"\"Apply action and return new time_step.\"\"\"\n if self._current_time_step is None:\n return self.reset()\n self._current_time_step = self._step(action)\n return self._current_time_step\n\n def current_time_step(self):\n return self._current_time_step\n\n def time_step_spec(self):\n \"\"\"Return time_step_spec.\"\"\"\n\n @abc.abstractmethod\n def observation_spec(self):\n \"\"\"Return observation_spec.\"\"\"\n\n @abc.abstractmethod\n def action_spec(self):\n \"\"\"Return action_spec.\"\"\"\n\n @abc.abstractmethod\n def _reset(self):\n \"\"\"Return initial_time_step.\"\"\"\n\n @abc.abstractmethod\n def _step(self, action):\n \"\"\"Apply action and return new time_step.\"\"\"\n self._current_time_step = self._step(action)\n return self._current_time_step",
"_____no_output_____"
]
],
[
[
"In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time.\n\nNote that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`.\n\nThe `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively.\n\nIn TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions.",
"_____no_output_____"
],
[
"### Using Standard Environments\n\nTF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec.",
"_____no_output_____"
]
],
[
[
"environment = suite_gym.load('CartPole-v0')\nprint('action_spec:', environment.action_spec())\nprint('time_step_spec.observation:', environment.time_step_spec().observation)\nprint('time_step_spec.step_type:', environment.time_step_spec().step_type)\nprint('time_step_spec.discount:', environment.time_step_spec().discount)\nprint('time_step_spec.reward:', environment.time_step_spec().reward)\n",
"_____no_output_____"
]
],
[
[
"So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode.",
"_____no_output_____"
]
],
[
[
"action = np.array(1, dtype=np.int32)\ntime_step = environment.reset()\nprint(time_step)\nwhile not time_step.is_last():\n time_step = environment.step(action)\n print(time_step)",
"_____no_output_____"
]
],
[
[
"### Creating your own Python Environment\n\nFor many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python.\n\nLet's say we want to train an agent to play the following (Black Jack inspired) card game:\n\n1. The game is played using an infinite deck of cards numbered 1...10.\n2. At every turn the agent can do 2 things: get a new random card, or stop the current round.\n3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over.\n\nAn environment that represents the game could look like this:\n\n1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round.\n2. Observations: Sum of the cards in the current round.\n3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round:\n sum_of_cards - 21 if sum_of_cards <= 21, else -21\n",
"_____no_output_____"
]
],
[
[
"class CardGameEnv(py_environment.PyEnvironment):\n\n def __init__(self):\n self._action_spec = array_spec.BoundedArraySpec(\n shape=(), dtype=np.int32, minimum=0, maximum=1, name='action')\n self._observation_spec = array_spec.BoundedArraySpec(\n shape=(1,), dtype=np.int32, minimum=0, name='observation')\n self._state = 0\n self._episode_ended = False\n\n def action_spec(self):\n return self._action_spec\n\n def observation_spec(self):\n return self._observation_spec\n\n def _reset(self):\n self._state = 0\n self._episode_ended = False\n return ts.restart(np.array([self._state], dtype=np.int32))\n\n def _step(self, action):\n\n if self._episode_ended:\n # The last action ended the episode. Ignore the current action and start\n # a new episode.\n return self.reset()\n\n # Make sure episodes don't go on forever.\n if action == 1:\n self._episode_ended = True\n elif action == 0:\n new_card = np.random.randint(1, 11)\n self._state += new_card\n else:\n raise ValueError('`action` should be 0 or 1.')\n\n if self._episode_ended or self._state >= 21:\n reward = self._state - 21 if self._state <= 21 else -21\n return ts.termination(np.array([self._state], dtype=np.int32), reward)\n else:\n return ts.transition(\n np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0)",
"_____no_output_____"
]
],
[
[
"Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong.\n\nTo validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs.",
"_____no_output_____"
]
],
[
[
"environment = CardGameEnv()\nutils.validate_py_environment(environment, episodes=5)",
"_____no_output_____"
]
],
[
[
"Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round.",
"_____no_output_____"
]
],
[
[
"get_new_card_action = np.array(0, dtype=np.int32)\nend_round_action = np.array(1, dtype=np.int32)\n\nenvironment = CardGameEnv()\ntime_step = environment.reset()\nprint(time_step)\ncumulative_reward = time_step.reward\n\nfor _ in range(3):\n time_step = environment.step(get_new_card_action)\n print(time_step)\n cumulative_reward += time_step.reward\n\ntime_step = environment.step(end_round_action)\nprint(time_step)\ncumulative_reward += time_step.reward\nprint('Final Reward = ', cumulative_reward)",
"_____no_output_____"
]
],
[
[
"### Environment Wrappers\n\nAn environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together.\n\nSome common wrappers can be found in `environments/wrappers.py`. For example:\n\n1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space.\n2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc.\n3. `TimeLimit`: Terminates the episode after a fixed number of steps.\n",
"_____no_output_____"
],
[
"#### Example 1: Action Discretize Wrapper",
"_____no_output_____"
],
[
"InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-2, 2]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping:",
"_____no_output_____"
]
],
[
[
"env = suite_gym.load('Pendulum-v0')\nprint('Action Spec:', env.action_spec())\n\ndiscrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5)\nprint('Discretized Action Spec:', discrete_action_env.action_spec())",
"_____no_output_____"
]
],
[
[
"The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment.\n",
"_____no_output_____"
],
[
"## TensorFlow Environments",
"_____no_output_____"
],
[
"The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways:\n\n* They generate tensor objects instead of arrays\n* TF environments add a batch dimension to the tensors generated when compared to the specs. \n\nConverting the python environments into TFEnvs allows tensorflow to parellalize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow.",
"_____no_output_____"
]
],
[
[
"class TFEnvironment(object):\n\n def time_step_spec(self):\n \"\"\"Describes the `TimeStep` tensors returned by `step()`.\"\"\"\n\n def observation_spec(self):\n \"\"\"Defines the `TensorSpec` of observations provided by the environment.\"\"\"\n\n def action_spec(self):\n \"\"\"Describes the TensorSpecs of the action expected by `step(action)`.\"\"\"\n\n def reset(self):\n \"\"\"Returns the current `TimeStep` after resetting the Environment.\"\"\"\n return self._reset()\n\n def current_time_step(self):\n \"\"\"Returns the current `TimeStep`.\"\"\"\n return self._current_time_step()\n\n def step(self, action):\n \"\"\"Applies the action and returns the new `TimeStep`.\"\"\"\n return self._step(action)\n\n @abc.abstractmethod\n def _reset(self):\n \"\"\"Returns the current `TimeStep` after resetting the Environment.\"\"\"\n\n @abc.abstractmethod\n def _current_time_step(self):\n \"\"\"Returns the current `TimeStep`.\"\"\"\n\n @abc.abstractmethod\n def _step(self, action):\n \"\"\"Applies the action and returns the new `TimeStep`.\"\"\"",
"_____no_output_____"
]
],
[
[
"The `current_time_step()` method returns the current time_step and initializes the environment if needed.\n\nThe `reset()` method forces a reset in the environment and returns the current_step.\n\nIf the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode.\n\nFor now, let us look at how `TFEnvironments` are created.",
"_____no_output_____"
],
[
"### Creating your own TensorFlow Environment\n\nThis is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below).",
"_____no_output_____"
],
[
"### Wrapping a Python Environment in TensorFlow",
"_____no_output_____"
],
[
"We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper.",
"_____no_output_____"
]
],
[
[
"env = suite_gym.load('CartPole-v0')\ntf_env = tf_py_environment.TFPyEnvironment(env)\n\nprint(isinstance(tf_env, tf_environment.TFEnvironment))\nprint(\"TimeStep Specs:\", tf_env.time_step_spec())\nprint(\"Action Specs:\", tf_env.action_spec())",
"_____no_output_____"
]
],
[
[
"Note the specs are now of type: `(Bounded)TensorSpec`.",
"_____no_output_____"
],
[
"### Usage Examples",
"_____no_output_____"
],
[
"#### Simple Example",
"_____no_output_____"
]
],
[
[
"env = suite_gym.load('CartPole-v0')\n\ntf_env = tf_py_environment.TFPyEnvironment(env)\n# reset() creates the initial time_step after resetting the environment.\ntime_step = tf_env.reset()\nnum_steps = 3\ntransitions = []\nreward = 0\nfor i in range(num_steps):\n action = tf.constant([i % 2])\n # applies the action and returns the new TimeStep.\n next_time_step = tf_env.step(action)\n transitions.append([time_step, action, next_time_step])\n reward += next_time_step.reward\n time_step = next_time_step\n\nnp_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions)\nprint('\\n'.join(map(str, np_transitions)))\nprint('Total reward:', reward.numpy())",
"_____no_output_____"
]
],
[
[
"#### Whole Episodes",
"_____no_output_____"
]
],
[
[
"env = suite_gym.load('CartPole-v0')\ntf_env = tf_py_environment.TFPyEnvironment(env)\n\ntime_step = tf_env.reset()\nrewards = []\nsteps = []\nnum_episodes = 5\n\nfor _ in range(num_episodes):\n episode_reward = 0\n episode_steps = 0\n while not time_step.is_last():\n action = tf.random.uniform([1], 0, 2, dtype=tf.int32)\n time_step = tf_env.step(action)\n episode_steps += 1\n episode_reward += time_step.reward.numpy()\n rewards.append(episode_reward)\n steps.append(episode_steps)\n time_step = tf_env.reset()\n\nnum_steps = np.sum(steps)\navg_length = np.mean(steps)\navg_reward = np.mean(rewards)\n\nprint('num_episodes:', num_episodes, 'num_steps:', num_steps)\nprint('avg_length', avg_length, 'avg_reward:', avg_reward)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7b5965891ce8765ab8205438cbfbd544af0a9a
| 15,170 |
ipynb
|
Jupyter Notebook
|
notebooks_dev/.ipynb_checkpoints/hyper_para_search_genetic-checkpoint.ipynb
|
TianyuDu/AnnEconForecast
|
648bb05498f333811021c07b04000d5f81ddc7f8
|
[
"MIT"
] | 7 |
2018-12-26T07:54:43.000Z
|
2020-03-27T04:35:48.000Z
|
notebooks_dev/.ipynb_checkpoints/hyper_para_search_genetic-checkpoint.ipynb
|
TianyuDu/EFANN
|
648bb05498f333811021c07b04000d5f81ddc7f8
|
[
"MIT"
] | null | null | null |
notebooks_dev/.ipynb_checkpoints/hyper_para_search_genetic-checkpoint.ipynb
|
TianyuDu/EFANN
|
648bb05498f333811021c07b04000d5f81ddc7f8
|
[
"MIT"
] | 2 |
2019-06-09T21:10:56.000Z
|
2021-03-20T13:13:48.000Z
| 35.27907 | 121 | 0.542848 |
[
[
[
"\"\"\"\nThis notebook contains codes to run hyper-parameter tuning using a genetic algorithm.\nUse another notebook if you wish to use *grid search* instead.\n# Under development.\n\"\"\"\nimport os, sys\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom pprint import pprint\nfrom typing import Dict, List\nimport datetime",
"_____no_output_____"
],
[
"import sys\nsys.path.append(\"../\")\n# If this notebook file is not placed under in /notebook/ directory,\n# adding directory \"../\" might not correly add the project directory.\n# If adding \"../\" does not solve the importing problem, we need to setup \n# the directory mannually.\ntry:\n import constants\nexcept ModuleNotFoundError:\n core_dir = input(\"Directory of core files >>> \")\n if not core_dir.endswith(\"/\"):\n core_dir += \"/\"\n sys.path.append(core_dir)\n import constants",
"_____no_output_____"
],
[
"from core.tools.metrics import *\nimport core.tools.visualize as visualize\nfrom core.tools.time_series import *\nfrom core.tools.data_import import *\nimport core.tools.rnn_prepare as rnn_prepare\nimport core.tools.param_set_generator as param_set_generator\nimport core.ga.genetic_hpt as genetic_hpt\n\nimport core.models.stacked_lstm as stacked_lstm\n\nimport core.training.hps_methods as hps_methods",
"_____no_output_____"
],
[
"# data preparation phase.\npprint(constants.DATA_DIR)\nchoice = None\nwhile choice is None or choice not in constants.DATA_DIR.keys():\n if choice is not None:\n print(\"Invalid data location received, try again...\")\n choice = input(\"Select Dataset >>> \")\n# choice = \"a\"\n\nFILE_DIR = constants.DATA_DIR[choice]\n\nprint(f\"Dataset chosen: {FILE_DIR}\")\n\nprint(\"Avaiable configuration files found: \")\nfor cf in os.listdir(\"../hps_configs\"):\n if cf.endswith(\"config.py\"):\n print(\"\\t\" + cf)\n\nconfig_name = input(\"Select config file >>> \")\nif config_name.endswith(\".py\"):\n config_name = config_name[:-3]\n# config_name = \"mac_config\"\n\nexec(f\"import hps_configs.{config_name} as config\")\n\n# print(\"Reading configuration file...\")\n# for att in dir(config):\n# if att.endswith(\"_config\"):\n# print(f\"\\tLoading: {att}\")\n# exec(f\"globals().update(config.{att})\")",
"{'a': '/Users/tianyudu/Documents/Academics/EconForecasting/AnnEconForecast/data/UNRATE.csv',\n 'b': '/home/ec2-user/AnnEconForecast/data/UNRATE.csv',\n 'c': '/home/ec2-user/AnnEconForecast/data/DEXCAUS.csv'}\nSelect Dataset >>> b\nDataset chosen: /home/ec2-user/AnnEconForecast/data/UNRATE.csv\nAvaiable configuration files found: \n\tec2_config.py\n\tmac_config.py\nSelect config file >>> ec2_config\n"
],
[
"def obj_func(param) -> float:\n df_ready = rnn_prepare.prepare_dataset(\n file_dir=FILE_DIR,\n periods=int(param[\"PERIODS\"]),\n order=int(param[\"ORDER\"]),\n remove=None,\n verbose=False\n )\n\n # Split dataset.\n (X_train, X_val, X_test,\n y_train, y_val, y_test) = rnn_prepare.split_dataset(\n raw=df_ready,\n train_ratio=param[\"TRAIN_RATIO\"],\n val_ratio=param[\"VAL_RATIO\"],\n lags=param[\"LAGS\"]\n )\n\n # The gross dataset excluding the test set.\n # Excluding the test set for isolation purpose.\n data_feed = {\n \"X_train\": X_train,\n \"X_val\": X_val,\n \"y_train\": y_train,\n \"y_val\": y_val,\n }\n ep = param[\"epochs\"]\n ckpts = range(int(ep * 0.95), ep) # Take the final 5% epochs.\n tf.reset_default_graph()\n model = stacked_lstm.StackedLSTM(\n param=param,\n prediction_checkpoints=ckpts,\n verbose=False\n )\n \n ret_pack = model.fit(data=data_feed, ret=[\"mse_val\"])\n return float(np.mean(list(ret_pack[\"mse_val\"].values())))",
"_____no_output_____"
],
[
"total_gen = 30\ninit_size = 10\nignore_set = (\n \"PERIODS\", \"ORDER\", \"TRAIN_RATIO\", \"VAL_RATIO\", \"num_outputs\", \"num_inputs\", \"report_periods\",\n \"tensorboard_path\", \"model_path\", \"fig_path\"\n)",
"_____no_output_____"
],
[
"optimizer = genetic_hpt.GeneticHPT(\n gene_pool=config.main,\n pop_size=init_size,\n eval_func=obj_func,\n mode=\"min\",\n retain=0.5,\n shot_prob=0.05,\n mutate_prob=0.05,\n verbose=False,\n ignore=ignore_set\n)",
"_____no_output_____"
],
[
"# sample_param = {'LAGS': 6,\n# 'ORDER': 1,\n# 'PERIODS': 1,\n# 'TRAIN_RATIO': 0.8,\n# 'VAL_RATIO': 0.1,\n# 'clip_grad': None,\n# 'epochs': 500,\n# 'fig_path': '/Volumes/Intel/debug/model_figs/',\n# 'learning_rate': 0.1,\n# 'model_path': '/Volumes/Intel/debug/saved_models/',\n# 'num_inputs': 1,\n# 'num_neurons': (32, 64),\n# 'num_outputs': 1,\n# 'num_time_steps': None,\n# 'report_periods': 10,\n# 'tensorboard_path': '/Volumes/Intel/debug/tensorboard/'}",
"_____no_output_____"
],
[
"class HiddenPrints:\n def __enter__(self):\n self._original_stdout = sys.stdout\n sys.stdout = open(os.devnull, 'w')\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n sys.stdout.close()\n sys.stdout = self._original_stdout",
"_____no_output_____"
],
[
"start_time = datetime.datetime.now()",
"_____no_output_____"
],
[
"# Training\nbest_rec = list()\nworst_rec = list()\nprint(\"Initial evaluation gen=0...\")\noptimizer.evaluate(verbose=True)\nprint(f\"\\nBest fitted entity validatiton MSE: {optimizer.population[0][1]: 0.7f}\\\n\\nWorst fitted entity validation MSE: {optimizer.population[-1][1]: 0.7f}\")\nfor gen in range(total_gen):\n print(f\"Generation: [{gen + 1}/{total_gen}]\")\n optimizer.select()\n optimizer.evolve()\n optimizer.evaluate(verbose=True)\n print(f\"\\nBest fitted entity validation MSE: {optimizer.population[0][1]: 0.7f}\\\n \\nWorst fitted entity validation MSE: {optimizer.population[-1][1]: 0.7f}\")\n best_rec.append(optimizer.population[0][1])\n worst_rec.append(optimizer.population[-1][1])\nprint(f\"Final generation best fitted entity: {optimizer.population[0][0]}\\\n\\nwith valudation set MSE (fitness): {optimizer.population[0][1]}\")",
"Initial evaluation gen=0...\n #################### Evaluating population[10/10, 100.00%]\nBest fitted entity validation MSE: 0.0241276\nWorst fitted entity validation MSE: 0.0702762\nGeneration: [1/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0250522 \nWorst fitted entity validation MSE: 0.0429758\nGeneration: [2/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0257155 \nWorst fitted entity validation MSE: 34072.1835938\nGeneration: [3/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0251317 \nWorst fitted entity validation MSE: 28.7871838\nGeneration: [4/30]\n #################### Evaluating population[10/10, 100.00%]\nBest fitted entity validation MSE: 0.0255463 \nWorst fitted entity validation MSE: 0.0309619\nGeneration: [5/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0237283 \nWorst fitted entity validation MSE: 0.0301053\nGeneration: [6/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0236307 \nWorst fitted entity validation MSE: 0.0294730\nGeneration: [7/30]\n #################### Evaluating population[10/10, 100.00%]\nBest fitted entity validation MSE: 0.0232075 \nWorst fitted entity validation MSE: 1172.3624268\nGeneration: [8/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0225821 \nWorst fitted entity validation MSE: 0.0407270\nGeneration: [9/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0227762 \nWorst fitted entity validation MSE: 0.0263290\nGeneration: [10/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0227003 \nWorst fitted entity validation MSE: 0.0262675\nGeneration: [11/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0226677 \nWorst fitted entity validation MSE: 0.0304239\nGeneration: [12/30]\n #################### Evaluating population[10/10, 100.00%]\nBest fitted entity validation MSE: 0.0230436 \nWorst fitted entity validation MSE: 16373.0742188\nGeneration: [13/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0228544 \nWorst fitted entity validation MSE: 0.0254180\nGeneration: [14/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0226873 \nWorst fitted entity validation MSE: 1162.0667725\nGeneration: [15/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0227074 \nWorst fitted entity validation MSE: 44308.7539062\nGeneration: [16/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0226993 \nWorst fitted entity validation MSE: 0.0256101\nGeneration: [17/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0227305 \nWorst fitted entity validation MSE: 2065.1970215\nGeneration: [18/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0226183 \nWorst fitted entity validation MSE: 0.0262335\nGeneration: [19/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0226900 \nWorst fitted entity validation MSE: 5187.5346680\nGeneration: [20/30]\n #################### Evaluating population[10/10, 100.00%]\nBest fitted entity validation MSE: 0.0228980 \nWorst fitted entity validation MSE: 5170.0634766\nGeneration: [21/30]\n #################### Evaluating population[10/10, 100.00%]\nBest fitted entity validation MSE: 0.0227659 \nWorst fitted entity validation MSE: 21959.7695312\nGeneration: [22/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0227334 \nWorst fitted entity validation MSE: 3281.9970703\nGeneration: [23/30]\n #################### Evaluating population[11/11, 100.00%]\nBest fitted entity validation MSE: 0.0220784 \nWorst fitted entity validation MSE: 161492.1718750\nGeneration: [24/30]\n #######------------- Evaluating population[4/11, 36.36%]"
],
[
"end_time = datetime.datetime.now()\nprint(f\"Time taken: {str(end_time - start_time)}\")",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7b5d182994e7cb688e95dc2ea89f26a985f477
| 11,385 |
ipynb
|
Jupyter Notebook
|
Demo_of_RISE_for_slides_with_Jupyter_notebooks__Python.ipynb
|
Naereen/notebooks
|
eaf0dd147c10dfd5fa7806833705f3a6eac41e0e
|
[
"MIT"
] | 102 |
2016-06-25T09:30:00.000Z
|
2022-03-24T21:02:49.000Z
|
Demo_of_RISE_for_slides_with_Jupyter_notebooks__Python.ipynb
|
Naereen/notebooks
|
eaf0dd147c10dfd5fa7806833705f3a6eac41e0e
|
[
"MIT"
] | 34 |
2016-06-26T12:21:30.000Z
|
2021-04-06T09:19:49.000Z
|
Demo_of_RISE_for_slides_with_Jupyter_notebooks__Python.ipynb
|
Naereen/notebooks
|
eaf0dd147c10dfd5fa7806833705f3a6eac41e0e
|
[
"MIT"
] | 44 |
2017-05-13T23:54:56.000Z
|
2021-07-17T15:34:24.000Z
| 30.039578 | 2,241 | 0.549056 |
[
[
[
"<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Demo-of-RISE-for-slides-with-Jupyter-notebooks-(Python)\" data-toc-modified-id=\"Demo-of-RISE-for-slides-with-Jupyter-notebooks-(Python)-1\"><span class=\"toc-item-num\">1 </span>Demo of RISE for slides with Jupyter notebooks (Python)</a></span><ul class=\"toc-item\"><li><span><a href=\"#Title-2\" data-toc-modified-id=\"Title-2-1.1\"><span class=\"toc-item-num\">1.1 </span>Title 2</a></span><ul class=\"toc-item\"><li><span><a href=\"#Title-3\" data-toc-modified-id=\"Title-3-1.1.1\"><span class=\"toc-item-num\">1.1.1 </span>Title 3</a></span><ul class=\"toc-item\"><li><span><a href=\"#Title-4\" data-toc-modified-id=\"Title-4-1.1.1.1\"><span class=\"toc-item-num\">1.1.1.1 </span>Title 4</a></span></li></ul></li></ul></li><li><span><a href=\"#Text\" data-toc-modified-id=\"Text-1.2\"><span class=\"toc-item-num\">1.2 </span>Text</a></span></li><li><span><a href=\"#Maths\" data-toc-modified-id=\"Maths-1.3\"><span class=\"toc-item-num\">1.3 </span>Maths</a></span></li><li><span><a href=\"#And-code\" data-toc-modified-id=\"And-code-1.4\"><span class=\"toc-item-num\">1.4 </span>And code</a></span></li></ul></li><li><span><a href=\"#More-demo-of-Markdown-code\" data-toc-modified-id=\"More-demo-of-Markdown-code-2\"><span class=\"toc-item-num\">2 </span>More demo of Markdown code</a></span><ul class=\"toc-item\"><li><span><a href=\"#Lists\" data-toc-modified-id=\"Lists-2.1\"><span class=\"toc-item-num\">2.1 </span>Lists</a></span><ul class=\"toc-item\"><li><ul class=\"toc-item\"><li><span><a href=\"#Images\" data-toc-modified-id=\"Images-2.1.0.1\"><span class=\"toc-item-num\">2.1.0.1 </span>Images</a></span></li><li><span><a href=\"#And-Markdown-can-include-raw-HTML\" data-toc-modified-id=\"And-Markdown-can-include-raw-HTML-2.1.0.2\"><span class=\"toc-item-num\">2.1.0.2 </span>And Markdown can include raw HTML</a></span></li></ul></li></ul></li></ul></li><li><span><a href=\"#End-of-this-demo\" data-toc-modified-id=\"End-of-this-demo-3\"><span class=\"toc-item-num\">3 </span>End of this demo</a></span></li></ul></div>",
"_____no_output_____"
],
[
"# Demo of RISE for slides with Jupyter notebooks (Python)\n\n- This document is an example of a slideshow, written in a [Jupyter notebook](https://www.jupyter.org/) with the [RISE extension](https://github.com/damianavila/RISE).\n\n> By [Lilian Besson](http://perso.crans.org/besson/), Sept.2017.",
"_____no_output_____"
],
[
"---\n## Title 2\n### Title 3\n#### Title 4\n##### Title 5\n##### Title 6",
"_____no_output_____"
],
[
"## Text\nWith text, *emphasis*, **bold**, ~~striked~~, `inline code` and\n\n> *Quote.*\n>\n> -- By a guy.",
"_____no_output_____"
],
[
"## Maths\nWith inline math $\\sin(x)^2 + \\cos(x)^2 = 1$ and equations:\n$$\\sin(x)^2 + \\cos(x)^2 = \\left(\\frac{\\mathrm{e}^{ix} - \\mathrm{e}^{-ix}}{2i}\\right)^2 + \\left(\\frac{\\mathrm{e}^{ix} + \\mathrm{e}^{-ix}}{2}\\right)^2 = \\frac{-\\mathrm{e}^{2ix}-\\mathrm{e}^{-2ix}+2 \\; ++\\mathrm{e}^{2ix}+\\mathrm{e}^{-2ix}+2}{4} = 1.$$",
"_____no_output_____"
],
[
"## And code\nIn Markdown:\n```python\nfrom sys import version\nprint(version)\n```\n\nAnd in a executable cell (with Python 3 kernel) :",
"_____no_output_____"
]
],
[
[
"from sys import version\nprint(version)",
"3.6.9 (default, Oct 8 2020, 12:12:24) \n[GCC 8.4.0]\n"
]
],
[
[
"# More demo of Markdown code",
"_____no_output_____"
],
[
"## Lists\n\n- Unordered\n- lists\n- are easy.\n\nAnd\n\n1. and ordered also ! Just\n2. start lines by `1.`, `2.` etc\n3. or simply `1.`, `1.`, ...",
"_____no_output_____"
],
[
"#### Images\nWith a HTML `<img/>` tag or the `` Markdown code:\n<img width=\"100\" src=\"agreg/images/dooku.jpg\"/>\n\n",
"_____no_output_____"
]
],
[
[
"# https://gist.github.com/dm-wyncode/55823165c104717ca49863fc526d1354\n\"\"\"Embed a YouTube video via its embed url into a notebook.\"\"\"\nfrom functools import partial\n\nfrom IPython.display import display, IFrame\n\nwidth, height = (560, 315, )\n\ndef _iframe_attrs(embed_url):\n \"\"\"Get IFrame args.\"\"\"\n return (\n ('src', 'width', 'height'), \n (embed_url, width, height, ),\n )\n\ndef _get_args(embed_url):\n \"\"\"Get args for type to create a class.\"\"\"\n iframe = dict(zip(*_iframe_attrs(embed_url)))\n attrs = {\n 'display': partial(display, IFrame(**iframe)),\n }\n return ('YouTubeVideo', (object, ), attrs, )\n\ndef youtube_video(embed_url):\n \"\"\"Embed YouTube video into a notebook.\n\n Place this module into the same directory as the notebook.\n\n >>> from embed import youtube_video\n >>> youtube_video(url).display()\n \"\"\"\n YouTubeVideo = type(*_get_args(embed_url)) # make a class\n return YouTubeVideo() # return an object\n",
"_____no_output_____"
]
],
[
[
"#### And Markdown can include raw HTML\n\n<center><span style=\"color: green;\">This is a centered span, colored in green.</span></center>\n\nIframes are disabled by default, but by using the IPython internals we can include let say a YouTube video:",
"_____no_output_____"
]
],
[
[
"youtube_video(\"https://www.youtube.com/embed/FNg5_2UUCNU\").display()",
"_____no_output_____"
],
[
"print(2**2021)",
"240780458385579342400393461351617812815637161357071131707208942081962936661153218844512115504763375697200879163458183553026017242301187821441055479544760906104973534996069938628004474568289906582206917095065620305216254432816950650228843795794816095162791355341943390986975847866692139272448065870433527123346286515814575123941041341323886584452213168407427683905346733773730890398535581783579726464034446453496393589067919979673611753823620422962335479358086639875375670825770647896268644196740771259886611570273762180917307714137084771977480688440721015151914970095703226362506437887288273484956889253937152\n"
]
],
[
[
"# End of this demo\n\n- See [here for more notebooks](https://github.com/Naereen/notebooks/)!\n- This document, like my other notebooks, is distributed [under the MIT License](https://lbesson.mit-license.org/).",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cb7b6696b99ecf04159d72edf459a78d3e37ac07
| 267,817 |
ipynb
|
Jupyter Notebook
|
notebooks/BO_stats.ipynb
|
tangkong/ls_be
|
f0ea81a2e9e7b6ff487fde31eeb24a6d7aa667e9
|
[
"MIT"
] | null | null | null |
notebooks/BO_stats.ipynb
|
tangkong/ls_be
|
f0ea81a2e9e7b6ff487fde31eeb24a6d7aa667e9
|
[
"MIT"
] | null | null | null |
notebooks/BO_stats.ipynb
|
tangkong/ls_be
|
f0ea81a2e9e7b6ff487fde31eeb24a6d7aa667e9
|
[
"MIT"
] | null | null | null | 463.351211 | 85,278 | 0.819179 |
[
[
[
"import numpy as np\nimport pickle\nimport time\n\nfrom src.data.make_dataset import generate_dataset\nfrom src.models.train_model import BO_loop, grid_search, dist_loop\nfrom src.models.acquisition import Random, MaxVariance\n\nfrom functools import partial",
"_____no_output_____"
],
[
"# run trig basis tests\niters = 5\nrng = np.random.default_rng(seed = 42)\ndata_seeds = rng.integers(low=0, high=10000, size=iters)\n\nds_cfg = {'n_cpts': 5, 'supply_truth':False, 'basis':'trig'}\nbo_cfg = {'pca_cpts': 4, 'bo_iters':200}\n\nmv_bo_loop = partial(BO_loop, acq_func=MaxVariance )\nmv_bo_loop.__name__='mv_bo_loop'\nrand_bo_loop = partial(BO_loop, acq_func=Random )\nrand_bo_loop.__name__='rand_bo_loop'\nloops = [grid_search, dist_loop, mv_bo_loop, rand_bo_loop]",
"_____no_output_____"
],
[
"for s in data_seeds:\n face_image, data, x_vals = generate_dataset(n_cpts=ds_cfg['n_cpts'], \n seed=s, supply_truth=ds_cfg['supply_truth'],\n xanes=ds_cfg['basis'])\n for loop in [mv_bo_loop]:\n # run test\n ts = time.time()\n _, varis, errs, info_dict = loop(data, n_cpts=bo_cfg['pca_cpts'], \n n_iters=bo_cfg['bo_iters'])\n\n # construct results dictionary and save\n results = {'max_variances': varis,\n 'errors': errs,\n 'info_dict': info_dict,\n 'bo_cfg': bo_cfg,\n 'ds_cfg': ds_cfg,\n 'loop_type': loop.__name__,\n 'start_time': ts\n }\n break\n\n # with open(f'results_{ds_cfg[\"basis\"]}_{s}_{loop.__name__}.pkl', 'wb') as f:\n # pickle.dump(results, f) \n break",
"=== iter 0, ((10, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 1, ((11, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 2, ((12, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 3, ((13, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 4, ((14, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 5, ((15, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 6, ((16, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 7, ((17, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 8, ((18, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 9, ((19, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 10, ((20, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 11, ((21, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 12, ((22, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 13, ((23, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 14, ((24, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 15, ((25, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 16, ((26, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 17, ((27, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 18, ((28, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 19, ((29, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 20, ((30, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 21, ((31, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 22, ((32, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 23, ((33, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 24, ((34, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 25, ((35, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 26, ((36, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 27, ((37, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 28, ((38, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 29, ((39, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 30, ((40, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 31, ((41, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 32, ((42, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 33, ((43, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 34, ((44, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 35, ((45, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 36, ((46, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 37, ((47, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 38, ((48, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 39, ((49, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 40, ((50, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 41, ((51, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 42, ((52, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 43, ((53, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 44, ((54, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 45, ((55, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 46, ((56, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 47, ((57, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 48, ((58, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 49, ((59, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 50, ((60, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 51, ((61, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 52, ((62, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 53, ((63, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 54, ((64, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 55, ((65, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 56, ((66, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 57, ((67, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 58, ((68, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 59, ((69, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 60, ((70, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 61, ((71, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 62, ((72, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 63, ((73, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 64, ((74, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 65, ((75, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 66, ((76, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 67, ((77, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 68, ((78, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 69, ((79, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 70, ((80, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 71, ((81, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 72, ((82, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 73, ((83, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 74, ((84, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 75, ((85, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 76, ((86, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 77, ((87, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 78, ((88, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 79, ((89, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 80, ((90, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 81, ((91, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 82, ((92, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 83, ((93, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 84, ((94, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 85, ((95, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 86, ((96, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 87, ((97, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 88, ((98, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 89, ((99, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 90, ((100, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 91, ((101, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 92, ((102, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 93, ((103, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 94, ((104, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 95, ((105, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 96, ((106, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 97, ((107, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 98, ((108, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 99, ((109, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 100, ((110, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 101, ((111, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 102, ((112, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 103, ((113, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 104, ((114, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 105, ((115, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 106, ((116, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 107, ((117, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 108, ((118, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 109, ((119, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 110, ((120, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 111, ((121, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 112, ((122, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 113, ((123, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 114, ((124, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 115, ((125, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 116, ((126, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 117, ((127, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 118, ((128, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 119, ((129, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 120, ((130, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 121, ((131, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 122, ((132, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 123, ((133, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 124, ((134, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 125, ((135, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 126, ((136, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 127, ((137, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 128, ((138, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 129, ((139, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 130, ((140, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 131, ((141, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 132, ((142, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 133, ((143, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 134, ((144, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 135, ((145, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 136, ((146, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 137, ((147, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 138, ((148, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 139, ((149, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 140, ((150, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 141, ((151, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 142, ((152, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 143, ((153, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 144, ((154, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 145, ((155, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 146, ((156, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 147, ((157, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 148, ((158, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 149, ((159, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 150, ((160, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 151, ((161, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 152, ((162, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 153, ((163, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 154, ((164, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 155, ((165, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 156, ((166, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 157, ((167, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 158, ((168, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 159, ((169, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 160, ((170, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 161, ((171, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 162, ((172, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 163, ((173, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 164, ((174, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 165, ((175, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 166, ((176, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 167, ((177, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 168, ((178, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 169, ((179, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 170, ((180, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 171, ((181, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 172, ((182, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 173, ((183, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 174, ((184, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 175, ((185, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 176, ((186, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 177, ((187, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 178, ((188, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 179, ((189, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 180, ((190, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 181, ((191, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 182, ((192, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 183, ((193, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 184, ((194, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 185, ((195, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 186, ((196, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 187, ((197, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 188, ((198, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 189, ((199, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 190, ((200, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 191, ((201, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 192, ((202, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 193, ((203, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 194, ((204, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 195, ((205, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 196, ((206, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 197, ((207, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 198, ((208, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n=== iter 199, ((209, 4)) -- cpt 0 -- cpt 1 -- cpt 2 -- cpt 3 \n"
],
[
"plot_component_comp(data, info_dict['curr_cpt_weights'], \n torch.Tensor(info_dict['train_x']), info_dict['test_x'], \n varis, errs['spec_mse_avg'])",
"Iter 10/2000: 0.6835506558418274\nIter 20/2000: 0.6473759412765503\n"
],
[
"# reading and coallating data\nfrom pathlib import Path\npkl_path = Path.cwd().parent / 'reports' / 'results_xanes_400'\nprint(pkl_path)\n",
"c:\\Users\\roberttk\\Desktop\\SLAC_RA\\machine-learning\\ls_be\\reports\\results_xanes_400\n"
],
[
"\nnewdist = {n.__name__:[] for n in loops}\nfor p in (pkl_path.parent / 'results_newdist_400').glob('*.pkl'):\n with open(p, 'rb') as f:\n a = pickle.load(f)\n newdist[a['loop_type']].append(a['errors']['spec_mse_avg'])",
"_____no_output_____"
],
[
"spec_mse_err = {n.__name__:[] for n in loops}\nfor p in pkl_path.glob('*.pkl'):\n with open(p, 'rb') as f:\n a = pickle.load(f)\n spec_mse_err[a['loop_type']].append(a['errors']['spec_mse_avg'])",
"_____no_output_____"
],
[
"plt.figure(figsize=(5,5))\nnew_name = {'grid_search': 'grid search', 'mv_bo_loop': 'max variance', \n 'rand_bo_loop': 'random search', 'dist_loop': 'distance' }\n\ncolor_code = ['k', 'r', 'b', 'g']\nfor i, loop_name in enumerate(['grid_search', 'rand_bo_loop', 'dist_loop', 'mv_bo_loop']):\n if loop_name == 'dist_loop':\n continue\n\n arr = np.array(spec_mse_err[loop_name])\n mean = np.mean(arr, axis=0).flatten()\n std = np.std(np.log(arr), axis=0).flatten()\n\n plt.plot(np.log(mean), color_code[i], label=new_name[loop_name])\n # plt.plot(arr.T)\n plt.fill_between(range(len(mean)), np.log(mean)-std, \n np.log(mean)+std, color=color_code[i], alpha=0.2)\n\narr = np.array(newdist['dist_loop'])\nmean = np.mean(arr, axis=0).flatten()\nstd = np.std(np.log(arr), axis=0).flatten()\n\nplt.plot(np.log(mean), 'b', label='distance' )\nplt.fill_between(range(len(mean)), np.log(mean)-std, np.log(mean)+std, color='b', alpha=0.2)\n\n\nplt.legend()\n# plt.ylim(0.000005, 0.001)\nplt.ylabel('Log(Reconstruction Error)')\nplt.xlabel('iteration')\nprint(f'statistics over {arr.shape[0]} tests')\nplt.savefig('xanes_recon_err.png')",
"statistics over 40 tests\n"
],
[
"np.shape(spec_mse_err['grid_search'])",
"_____no_output_____"
],
[
"from src.visualization.visualize import plot_component_comp\nimport torch\nimport re\n\npickle_list = list(pkl_path.glob('*.pkl'))\ni=40\nfp = pickle_list[i]\nwith open(fp, 'rb') as f:\n print(fp)\n a = pickle.load(f)\n\n# grab numbers\ns = int(re.search('\\d+',fp.name).group())\nprint(s)\n\nface_image, data, x_vals = generate_dataset(n_cpts=a['ds_cfg']['n_cpts'], \n seed=s, supply_truth=a['ds_cfg']['supply_truth'],\n xanes='trig')\n\nplot_component_comp(data, a['info_dict']['curr_cpt_weights'], \n torch.Tensor(a['info_dict']['train_x']), a['info_dict']['test_x'], \n a['max_variances'], a['errors']['spec_mse_avg'])",
"c:\\Users\\roberttk\\Desktop\\SLAC_RA\\machine-learning\\ls_be\\reports\\results_trig_400\\results_trig_3670_dist_loop.pkl\n3670\nIter 10/2000: 0.3550422489643097\nIter 20/2000: 0.3241519033908844\nIter 30/2000: 0.3084942698478699\nIter 40/2000: 0.30387988686561584\n"
],
[
"xanes = 'xanes'\n\nif (xanes is None) or (xanes == 'xanes'):\n print('xanes detected')\nif xanes == 'trig':\n print('trig detected')\n",
"xanes detected\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7b80318d97d4312a83ee03f551e06b3c810d51
| 1,358 |
ipynb
|
Jupyter Notebook
|
docs/_build/doctrees/nbsphinx/examples/quickstart.ipynb
|
morrislab/damuta
|
48e3146b610397e1c3020b26f0d010b38901452b
|
[
"MIT"
] | 2 |
2021-11-02T19:56:02.000Z
|
2022-01-20T19:15:48.000Z
|
docs/_build/html/examples/quickstart.ipynb
|
morrislab/damuta
|
48e3146b610397e1c3020b26f0d010b38901452b
|
[
"MIT"
] | null | null | null |
docs/_build/html/examples/quickstart.ipynb
|
morrislab/damuta
|
48e3146b610397e1c3020b26f0d010b38901452b
|
[
"MIT"
] | 1 |
2022-03-29T01:13:51.000Z
|
2022-03-29T01:13:51.000Z
| 16.361446 | 42 | 0.472018 |
[
[
[
"# Quickstart",
"_____no_output_____"
]
],
[
[
"import damuta as da",
"_____no_output_____"
],
[
"\n\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
]
] |
cb7b8770a8d84cbb8b5768fc1edc4356809580ee
| 9,801 |
ipynb
|
Jupyter Notebook
|
valve_cv.ipynb
|
santiago-salas-v/walas
|
65c1a86f9f2aaf6757d139aa6ce658ab1c750f0d
|
[
"MIT"
] | null | null | null |
valve_cv.ipynb
|
santiago-salas-v/walas
|
65c1a86f9f2aaf6757d139aa6ce658ab1c750f0d
|
[
"MIT"
] | null | null | null |
valve_cv.ipynb
|
santiago-salas-v/walas
|
65c1a86f9f2aaf6757d139aa6ce658ab1c750f0d
|
[
"MIT"
] | null | null | null | 56.653179 | 437 | 0.585859 |
[
[
[
"# Unit conversion for the valve coefficient\n\n## Friction losses in energy balance\n\nThe contribution of friction losses is considered as a head loss in the enrgy balance.\n\nEB   $0~m=\\frac{\\Delta p}{\\rho g}+\\Delta z+\\frac{\\Delta w^2}{2 g}+\\Delta H_{v}+\\frac{\\dot Q}{\\rho g \\dot V}+\\frac{C_v\\Delta T}{g}+\\frac{-\\dot W_{Welle}}{\\rho g \\dot V}$\n\nAnlagenkennlinie $H_{Anlage}=\\underbrace{\\Delta z+\\frac{p_{aus}-p_{ein}}{\\rho g}}_{\\text{stat. Förderhöhe, }f(\\Delta z)}+\\underbrace{\\frac{w_{aus}^2-w_{ein}^2}{2g}+\\sum H_{Verluste}}_{\\text{dyn. Förderhöhe, }f(\\dot V)}$\n\nPumpenkennlinie $H_{Pumpe}=H(\\dot V)$ \n\nWhere $p$ is pressure, $\\rho$ is density, $g$ is the local acceleration due to gravy, $z$ is elevation, $w$ is linear velocity, $H_{Verluste}$ are head losses due to friction, $\\dot Q$ is heat flow into the system, $\\dot V$ is volume flow, $C_v\\Delta T$ is change in internal energy due solely to temperature change of incompressible fluid, $\\dot W_{Welle}$ is power given by shaft work. $H$ are pressure heads as heights. \n\nThe pump curve gives a decreasing dynamic head $H_{Pumpe}$ with increasing volume flow $\\dot V$. The plant curve $H_{Anlage}$ consists of a static head dependent on plant conditions like height, inlet and outlet pressure (independent of flow), and a dynamic head incresing with volume flow $\\dot V$. Pump must be able to meet the dynamic + static head of the plant at a given flow.\n\n## Definition of valve flow coefficients\n\nSee [1] and [2]. Note that below, as in ref. [1] volume flow is $Q$. \n\n### Resistance coefficient $\\zeta$ - dimensionless\n\nFriction loss attributable to a pipe, valve, fitting, etc. in the pipeline, in terms of velocity head or velocity pressure. aka Widerstandsbeiwert.\n\n$\\Delta H=\\zeta \\frac{w^2}{2g}$\n\nExpressed as pressure loss, $\\Delta H=\\frac{\\Delta p_{Verlust}}{\\rho g}$, or $\\Delta p_{Verlust}=\\zeta \\frac{\\rho w^2}{2}$.\n\nThe total head losses are composed of the sum of all resistances given by pipes and fittings:\n\nLosses $\\sum H_{Verlust}=\\zeta_{ges}\\cdot\\frac{w^2}{2g}$\n\n$\\zeta_{ges}$ is the total resistance coefficient. \n\n$\\zeta_{ges}=\\zeta_{Rohr}+\\zeta_{Ventile}+\\zeta_{Einbauten}+...$\n\nFor a pipe, the resistance coefficient is related to the length (L) to diameter (d) ratio, to give the *Widerstandszahl* (aka Darcy-Weisbach friction factor $f_D=\\lambda$).\n\n$\\lambda=\\zeta\\frac{d}{L}=\\frac{\\Delta p}{\\rho g}\\frac{2g}{w^2}\\frac{d}{L}$\n\nMore precisely, the pressure loss through the pipe is proportional to the length and inversely proportional to the diameter, by the Darcy-Weisbach friction factor. \n\n$\\frac{\\Delta p}{L}=\\lambda\\frac{\\rho}{d}\\frac{w^2}{2}$\n\nThe Nikuradse-diagram (Nikuradse-Colebrook-Moody) shows $\\lambda$ as a function of the Reynolds-number $Re=\\frac{w d_{i}\\rho}{\\eta}=\\frac{w d_i}{\\nu}$ and the surface relative roughness $k_s/d_i$ (or $\\epsilon/d_i$). For laminar flow ($Re<3000$), the friction factor converges to the Poiseuille analytical solution of the momentum balance. \n\n$\\lambda_{laminar}=\\frac{64}{Re}$\n\nIn turbulent flow, an approximate calculation is given by Blasius [2], not considering roughness.\n\n$\\lambda_{turb}\\approx(100 Re)^{-1/4} \\qquad 3000<Re<10^5$\n\nor by Prandtl /. Kasman considering roughness [2,3].\n\n$\\frac{1}{\\sqrt{\\lambda}}=2\\cdot ln\\left(\\frac{d_i}{k}\\right)+1,14$\n\n### *US* Flow coefficient $C_v$ - dimensions $\\frac{US_{gal}}{min}$\n\n$C_v=Q\\sqrt{\\frac{\\Delta p_0}{\\Delta p}\\frac{\\rho}{\\rho_0}}$\n\nQ    flow in US gal/min\n\n$\\Delta p_0$   reference differential pressure = 1lb/in²\n\n$\\Delta p_0$   operating differential pressure in lb/in²\n\n$\\rho_0$     density of reference fluid water = 62.4 lg/ft³\n\n$\\rho$     density of operating fluid in lb/ft³\n \n\n### *Metric* flow coefficient $K_v$ - dimensions $\\frac{m^3}{h}$\n\n$K_v=Q\\sqrt{\\frac{\\Delta p_0}{\\Delta p}\\frac{\\rho}{\\rho_0}}$\n\nQ    flow in m³/h\n\n$\\Delta p_0$   reference differential pressure = 1bar\n\n$\\Delta p_0$   operating differential pressure in bar\n\n$\\rho_0$     density of reference fluid water = 1000 kg/m³\n\n$\\rho$     density of operating fluid in kg/m³\n\n### *Metric* flow coefficient Av - dimensions $m^2$\n\n$A_v=Q\\sqrt{\\frac{\\rho}{\\Delta p}}$\n\nQ    flow in m³/s\n\n$\\Delta p_0$   operating differential pressure in Pa\n\n$\\rho$     density of Newtonian liquid in kg/m³\n\nThis coefficient is derived from the dimensionless resistance coefficient $\\zeta$, following from its definition in pressure loss form:\n\n$\\Delta p_{Verlust}=\\zeta \\frac{\\rho w^2}{2g}$\n\n$\\Rightarrow Q=A\\cdot w=\\underbrace{A\\cdot \\sqrt{\\frac{2}{\\zeta}}}_{A_v}\\cdot\\sqrt{\\frac{\\Delta p}{\\rho}}$\n\nThe definition of $A_v$ then follows, as a coefficient proportional to the orifice diameter cross section at complete opening $A$, by the factor $\\left(\\frac{2}{\\zeta}\\right)^{1/2}$.\n \n## Interconversions\n\nDue to prevailing historic use of the *imperial* unit system [4], it is unavoidable to carry out units intervonversions. In order to build the relationship between flow coefficients with units, it is necessary to do this in dimensionless form, as follows:\n\n$\\begin{align}\n\\frac{C_v/(US_{gal}/min)}{K_v/(m^3/h)}&=\\frac{\\left(\\frac{Q}{US_{gal}/min}\\right)}{\\left(\\frac{Q}{m^3/h}\\right)}\\cdot\\frac{\\sqrt{\\frac{1\\frac{lb_f}{in^2}}{\\Delta p}\\cdot\\frac{\\rho}{62.4\\frac{lb_m}{ft^3}}}}{\\sqrt{\\frac{1~bar}{\\Delta p}\\cdot\\frac{\\rho}{1000\\frac{kg}{m^3}}}}\\\\\n&=\\frac{m^3/h}{US_{gal}/min}\\cdot\\sqrt{\\frac{1\\frac{lb_f}{in^2}}{1~bar}\\cdot\\frac{1000\\frac{kg}{m^3}}{62.4\\frac{lb_m}{ft^3}}}\\cdot\\frac{\\frac{1~h}{60~min}}{3.7854\\cdot 10^{-3}\\frac{m^3}{US_{gal}}}\\\\\n&=4.4029\\cdot\\sqrt{\\frac{1\\frac{lb_f}{in^2}\\cdot\\frac{4.4482~N}{lb_f}\\cdot\\left(\\frac{1~in}{2.54\\cdot 10^{-2}~m}\\right)^2}{1~bar\\cdot\\frac{10^5~N/m^2}{bar}}\\cdot\\frac{1000\\frac{kg}{m^3}}{62.4\\frac{lb_m}{ft^3}\\cdot\\frac{1~kg}{2.2042~lb_m}\\cdot\\left(\\frac{1~ft}{30.48\\cdot 10^{-2}~m}\\right)^3}}\\\\\n&=4.4029\\cdot\\sqrt{\\frac{6894.72}{10^5}\\cdot \\frac{1000}{999.74}}\\\\\n&=1.1562\n\\end{align}$\n\nThis result is equal to $1/(865\\cdot10^{-3})$, which is listed in ref. [1] as \"$K_v/C_v=865 \\times 10^{-3}$\".\n\nSimilarly, the relationship of $C_v$ to $A_v$ is built in dimensionless form.\n\n$\\begin{align}\n\\frac{A_v/(m^2)}{C_v/(US_{gal}/min)}&=\\frac{\\left(\\frac{Q}{m^3/s}\\right)}{\\left(\\frac{Q}{US_{gal}/min}\\right)}\\cdot\\frac{\\sqrt{\\frac{\\rho}{\\Delta p}}}{\\sqrt{\\frac{1\\frac{lb_f}{in^2}}{\\Delta p}\\cdot\\frac{\\rho}{62.4\\frac{lb_m}{ft^3}}}}\\\\\n&=\\frac{US_{gal}/min}{m^3/s}\\cdot\\sqrt{\\frac{62.4\\frac{lb_m}{ft^3}}{1\\frac{lb_f}{in^2}}}\\cdot 3.7854\\cdot 10^{-3}\\frac{m^3}{US_{gal}}\\frac{1~min}{60~s}\\\\\n&=6.309\\cdot 10^{-5}\\sqrt{\\frac{62.4\\frac{lb_m}{ft^3}}{1\\frac{lb_f}{in^2}}\\cdot\\frac{\\frac{1~kg/m^3}{2.2042\\cdot(30.48\\cdot 10^{-2})^3 lb_m/ft^3}}{\\frac{\\frac{4.4482}{(2.54\\cdot 10^{-2})^2}\\frac{kg m}{s^2 m^2}}{lb_f/in^2}}}\\\\\n&=6.309\\cdot 10^{-5}\\cdot\\sqrt{\\frac{999.744}{6894.72}}\\frac{s}{m}\\\\\n&=24.027\\cdot 10^{-6}\\frac{s}{m}\n\\end{align}$\n\nThis is listed in ref. [1] as $A_v/C_v=23.8\\times 10^{-6}$.\n\nFrom these two, the relationship from $A_v$ to $K_v$ is:\n\n$\\frac{A_v/(m^2)}{K_v/(m^3/h)}=\\frac{A_v/(m^2)}{C_v/(US_{gal}/min)}\\cdot\\frac{C_v/(US_{gal}/min)}{K_v/(m^3/h)}=1.1562\\cdot 24.027\\cdot 10^{-6}\\frac{s}{m}=27.78\\cdot 10^{-6}\\frac{s}{m}$\n\nReferences: \n1. Smith, P., & Zappe, R. W. (2004). Valve selection handbook: engineering fundamentals for selecting the right valve design for every industrial flow application. Elsevier.\n2. PAT notes\n3. Stephan, P. u.a. (2013). Vdi-Wärmeatlas. 11., bearb. und erw. Aufl. Berlin, Heidelberg: Springer-Verlag.\n4. Christen, D. S. (2009). Praxiswissen der chemischen verfahrenstechnik: handbuch für chemiker und verfahrensingenieure. Springer-Verlag.",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown"
]
] |
cb7b8c3729b6d89cffaea6d1f69a19513d41931e
| 1,263 |
ipynb
|
Jupyter Notebook
|
test/py/.ipynb_checkpoints/Preciprec-checkpoint.ipynb
|
Crop2ML-Catalog/STICS_SNOW
|
26ed2a9a30e068d72d5589b1dc64916c1b07fa09
|
[
"MIT"
] | null | null | null |
test/py/.ipynb_checkpoints/Preciprec-checkpoint.ipynb
|
Crop2ML-Catalog/STICS_SNOW
|
26ed2a9a30e068d72d5589b1dc64916c1b07fa09
|
[
"MIT"
] | null | null | null |
test/py/.ipynb_checkpoints/Preciprec-checkpoint.ipynb
|
Crop2ML-Catalog/STICS_SNOW
|
26ed2a9a30e068d72d5589b1dc64916c1b07fa09
|
[
"MIT"
] | null | null | null | 20.704918 | 58 | 0.490103 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cb7bb12bb860ee763e9a1f434f2143ac672077f3
| 1,780 |
ipynb
|
Jupyter Notebook
|
Python-Assignment-2/pattern-checkpoint.ipynb
|
MihirMore/Ineuron-Assignments
|
2668abc8f517ca50b501dd165d671b082bd255ab
|
[
"MIT"
] | 3 |
2021-04-06T07:46:12.000Z
|
2021-12-07T01:44:21.000Z
|
Python-Assignment-2/pattern.ipynb
|
MihirMore/Ineuron-Assignments
|
2668abc8f517ca50b501dd165d671b082bd255ab
|
[
"MIT"
] | null | null | null |
Python-Assignment-2/pattern.ipynb
|
MihirMore/Ineuron-Assignments
|
2668abc8f517ca50b501dd165d671b082bd255ab
|
[
"MIT"
] | null | null | null | 18.350515 | 82 | 0.377528 |
[
[
[
"## Create the below pattern using nested for loop in Python.\n'''\n*\n* *\n* * *\n* * * *\n* * * * *\n* * * *\n* * *\n* *\n*\n'''",
"_____no_output_____"
],
[
"for rows in range(0 , 5):\n for columns in range( 0 , rows + 1):\n print(\"*\",end=\"\")\n print() \nfor row in range (5 , 0 , -1):\n for column in range(0 , row - 1):\n print(\"*\",end=\"\")\n print() ",
"*\n**\n***\n****\n*****\n****\n***\n**\n*\n\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cb7bb896ba5a809f12b2bfba0512bd27ade37749
| 17,135 |
ipynb
|
Jupyter Notebook
|
notebooks/DataExplore2.ipynb
|
garybake/cuisine_prediction
|
6dcee12d8ffded8ac1168d06bb55bd0a7c7fdc7b
|
[
"MIT"
] | null | null | null |
notebooks/DataExplore2.ipynb
|
garybake/cuisine_prediction
|
6dcee12d8ffded8ac1168d06bb55bd0a7c7fdc7b
|
[
"MIT"
] | 1 |
2021-03-23T19:17:39.000Z
|
2021-03-23T19:17:39.000Z
|
notebooks/DataExplore2.ipynb
|
garybake/cuisine_prediction
|
6dcee12d8ffded8ac1168d06bb55bd0a7c7fdc7b
|
[
"MIT"
] | null | null | null | 26.361538 | 463 | 0.461978 |
[
[
[
"https://towardsdatascience.com/a-production-ready-multi-class-text-classifier-96490408757",
"_____no_output_____"
]
],
[
[
"import os\nimport re\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.multiclass import OneVsRestClassifier\n\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"data_path = 'data'\n\nrows = []\nfor root, _, file in os.walk(data_path):\n for filename in file:\n if '.txt' in filename:\n cuisine = os.path.splitext(filename)[0]\n text_file = open(os.path.join(data_path, filename), \"r\")\n lines = text_file.readlines()\n for line in lines:\n row = {\n 'cuisine': cuisine,\n 'ingredients': line\n }\n rows.append(row)\n text_file.close()\n\ndf = pd.DataFrame.from_dict(rows)\ndf = df.sample(frac=1).reset_index(drop=True)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"df.groupby('cuisine').count()",
"_____no_output_____"
],
[
"#pre-processing\nimport re \ndef clean_str(string):\n \"\"\"\n Tokenization/string cleaning for dataset\n Every dataset is lower cased except\n \"\"\"\n string = re.sub(r\"\\n\", \"\", string) \n string = re.sub(r\"\\r\", \"\", string) \n string = re.sub(r\"[0-9]\", \"digit\", string)\n string = re.sub(r\"\\'\", \"\", string) \n string = re.sub(r\"\\\"\", \"\", string) \n return string.strip().lower()",
"_____no_output_____"
],
[
"X = []\nfor i in range(df.shape[0]):\n X.append(clean_str(df.iloc[i][1]))\ny = np.array(df[\"cuisine\"])",
"_____no_output_____"
],
[
"y.size",
"_____no_output_____"
],
[
"#train test split\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=5)",
"_____no_output_____"
],
[
"#pipeline of feature engineering and model\n\nmodel = Pipeline([\n ('vectorizer', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', OneVsRestClassifier(LinearSVC(class_weight=\"balanced\")))\n])\n#the class_weight=\"balanced\" option tries to remove the biasedness of model towards majority sample",
"_____no_output_____"
],
[
"#parameter selection\nfrom sklearn.model_selection import GridSearchCV\nparameters = {'vectorizer__ngram_range': [(1, 1), (1, 2),(2,2)],\n 'tfidf__use_idf': (True, False)}",
"_____no_output_____"
],
[
"gs_clf_svm = GridSearchCV(model, parameters, n_jobs=-1)\ngs_clf_svm = gs_clf_svm.fit(X, y)\nprint(gs_clf_svm.best_score_)\nprint(gs_clf_svm.best_params_)",
"/usr/local/lib/python3.6/dist-packages/sklearn/model_selection/_split.py:2053: FutureWarning: You should specify a value for 'cv' instead of relying on the default value. The default value will change from 3 to 5 in version 0.22.\n warnings.warn(CV_WARNING, FutureWarning)\n"
],
[
"#preparing the final pipeline using the selected parameters\nmodel = Pipeline([('vectorizer', CountVectorizer(ngram_range=(1,2))),\n ('tfidf', TfidfTransformer(use_idf=True)),\n ('clf', OneVsRestClassifier(LinearSVC(class_weight=\"balanced\")))])",
"_____no_output_____"
],
[
"#fit model with training data\nmodel.fit(X_train, y_train)",
"_____no_output_____"
],
[
"#evaluation on test data\npred = model.predict(X_test)",
"_____no_output_____"
],
[
"model.classes_",
"_____no_output_____"
],
[
"from sklearn.metrics import confusion_matrix, accuracy_score\nconfusion_matrix(pred, y_test)",
"_____no_output_____"
],
[
"accuracy_score(y_test, pred)",
"_____no_output_____"
],
[
"#save the model\nfrom sklearn.externals import joblib\njoblib.dump(model, 'model_cuisine_ingredients.pkl', compress=1)",
"_____no_output_____"
],
[
"from sklearn.externals import joblib\nmodel = joblib.load('model_cuisine_ingredients.pkl')",
"_____no_output_____"
],
[
"test_recipe = \"1 2 1/2 to 3 pound boneless pork shoulder or butt, trimmed and cut in half 1 small butternut squash (about 1 1/2 pounds)—peeled, seeded, and cut into 1 inch pieces 1 14.5 ounce can diced tomatoes 1 jalapeño pepper, seeded and chopped 2 cloves garlic, chopped 1 tablespoon chili powder kosher salt 4 6 inch corn tortillas, cut into 1/2 inch wide strips 1 tablespoon canola oil sliced radishes, cilantro sprigs, and lime wedges, for serving\"",
"_____no_output_____"
],
[
"model.predict([test_recipe])[0]",
"_____no_output_____"
],
[
"steak_hache = \"1 tbsp vegetable oil 4 shallots , very finely chopped 600g freshly ground beef (ask the butcher for something with roughly 15% fat - we used chuck) 8 thyme sprigs, leaves picked and chopped 2 tsp Dijon mustard 2 tbsp plain flour 200ml crème fraîche 1 egg yolk 6 tarragon sprigs, leaves picked and finely chopped dressed green salad, to serve\"",
"_____no_output_____"
],
[
"model.predict([steak_hache])[0]",
"_____no_output_____"
],
[
"toad_in_the_hole = \"140g plain flour 3 eggs 300ml milk 2 tsp Dijon mustard 2 tbsp vegetable oil 8 Cumberland sausages 8 sage leaves 4 rosemary sprigs\"",
"_____no_output_____"
],
[
"model.predict([toad_in_the_hole])[0]",
"_____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"
]
] |
cb7bbbe0d6da6fcb2d1623d72868c3fd4b5332d1
| 740,343 |
ipynb
|
Jupyter Notebook
|
EnsembleTechniquesJanASolution.ipynb
|
ABPande/MyPythonRepo
|
51de39aee6c99b6ea2eb47fb199925ee63ca3750
|
[
"Apache-2.0"
] | null | null | null |
EnsembleTechniquesJanASolution.ipynb
|
ABPande/MyPythonRepo
|
51de39aee6c99b6ea2eb47fb199925ee63ca3750
|
[
"Apache-2.0"
] | null | null | null |
EnsembleTechniquesJanASolution.ipynb
|
ABPande/MyPythonRepo
|
51de39aee6c99b6ea2eb47fb199925ee63ca3750
|
[
"Apache-2.0"
] | null | null | null | 281.178504 | 416,936 | 0.915639 |
[
[
[
"# Problem statement\n\nWe have data from a Portuguese bank on details of customers related to selling a term deposit\nThe objective of the project is to help the marketing team identify potential customers who are relatively more likely to subscribe to the term deposit and this increase the hit ratio",
"_____no_output_____"
],
[
"# Data dictionary\n\n**Bank client data**\n* 1 - age \n* 2 - job : type of job \n* 3 - marital : marital status\n* 4 - education \n* 5 - default: has credit in default? \n* 6 - housing: has housing loan? \n* 7 - loan: has personal loan?\n* 8 - balance in account\n\n**Related to previous contact**\n* 8 - contact: contact communication type\n* 9 - month: last contact month of year\n* 10 - day_of_week: last contact day of the week\n* 11 - duration: last contact duration, in seconds*\n\n**Other attributes**\n* 12 - campaign: number of contacts performed during this campaign and for this client\n* 13 - pdays: number of days that passed by after the client was last contacted from a previous campaign\n* 14 - previous: number of contacts performed before this campaign and for this client\n* 15 - poutcome: outcome of the previous marketing campaign\n\n**Output variable (desired target):has the client subscribed a term deposit?**\n\n",
"_____no_output_____"
]
],
[
[
"# To enable plotting graphs in Jupyter notebook\n%matplotlib inline \n\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\n# calculate accuracy measures and confusion matrix\nfrom sklearn import metrics\n\n\n",
"c:\\python\\lib\\site-packages\\sklearn\\ensemble\\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release.\n from numpy.core.umath_tests import inner1d\n"
],
[
"#Load the file from local directory using pd.read_csv which is a special form of read_table\n#while reading the data, supply the \"colnames\" list\n\nbank_df = pd.read_csv(\"bank-full.csv\")\n",
"_____no_output_____"
],
[
"bank_df.head()",
"_____no_output_____"
],
[
"bank_df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 45211 entries, 0 to 45210\nData columns (total 17 columns):\nage 45211 non-null int64\njob 45211 non-null object\nmarital 45211 non-null object\neducation 45211 non-null object\ndefault 45211 non-null object\nbalance 45211 non-null int64\nhousing 45211 non-null object\nloan 45211 non-null object\ncontact 45211 non-null object\nday 45211 non-null int64\nmonth 45211 non-null object\nduration 45211 non-null int64\ncampaign 45211 non-null int64\npdays 45211 non-null int64\nprevious 45211 non-null int64\npoutcome 45211 non-null object\nTarget 45211 non-null object\ndtypes: int64(7), object(10)\nmemory usage: 5.9+ MB\n"
],
[
"#### this attribute highly affects the output target (e.g., if duration=0 then y='no'). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model\n\nbank_df.drop(['duration'], inplace=True, axis=1)",
"_____no_output_____"
]
],
[
[
"#### Certain variables are more relevant if they are categorical variable than numerical variables. We will convert such categorical variables to numeric variabes",
"_____no_output_____"
]
],
[
[
"bank_df['day']=bank_df['day'].astype('category')\nbank_df['Target']=bank_df['Target'].astype('category')",
"_____no_output_____"
]
],
[
[
"# Exploratory data analysis",
"_____no_output_____"
],
[
"## Univariate analysis - boxplot / histogram for numerical variables",
"_____no_output_____"
]
],
[
[
"sns.boxplot(x=bank_df['age'], data=bank_df)",
"_____no_output_____"
]
],
[
[
"**Age column has some outliers. The median age is about 40 years. There are some customers above 90 years of age. This data might have to be checked**",
"_____no_output_____"
]
],
[
[
"#histograms from the pair plots\nsns.pairplot(bank_df)",
"_____no_output_____"
]
],
[
[
"**The distribution of all numerical variables other than age is highly skewed - hence we might want to transform or bin some of these variables**",
"_____no_output_____"
],
[
"**On similar lines, please perform univariate analysis of other numerical variables**",
"_____no_output_____"
],
[
"## Univariate analysis - countplot / value count for categorical variables",
"_____no_output_____"
]
],
[
[
"bank_df['job'].value_counts()",
"_____no_output_____"
],
[
"sns.countplot(bank_df['marital'])",
"_____no_output_____"
],
[
"sns.countplot(bank_df['education'])",
"_____no_output_____"
],
[
"sns.countplot(bank_df['default'])",
"_____no_output_____"
]
],
[
[
"**default - yes is a very small % - we can consider deleting this column**",
"_____no_output_____"
]
],
[
[
"sns.countplot(bank_df['housing'])",
"_____no_output_____"
],
[
"sns.countplot(bank_df['loan'])",
"_____no_output_____"
],
[
"sns.countplot(bank_df['contact'])",
"_____no_output_____"
],
[
"sns.countplot(bank_df['poutcome'])",
"_____no_output_____"
],
[
"sns.countplot(bank_df['Target'])",
"_____no_output_____"
],
[
"bank_df['Target'].value_counts(normalize=True)",
"_____no_output_____"
]
],
[
[
"### The response rate is only 11.6%. Hence the Y variable has a high class imbalance. Hence accuracy will not be a reliable model performance measure. \n\n### FN is very critical for this business case because a false negative is a customer who will potentially subscribe for a loan but who has been classified as 'will not subscribe'. Hence the most relevant model performance measure is recall",
"_____no_output_____"
],
[
"## Bivariate analysis",
"_____no_output_____"
]
],
[
[
"#Group numerical variables by mean for the classes of Y variable\nnp.round(bank_df.groupby([\"Target\"]).mean() ,1)",
"_____no_output_____"
]
],
[
[
"#### The mean balance is higher for customers who subscribe to the term deposit compared to those who dont\n\n\n#### number of days that passed by after the client was last contacted from a previous campaign is higher for people who have subscribed\n\n#### number of contacts performed before this campaign is also higher for customers who subscribe\n",
"_____no_output_____"
],
[
"### All of the above facts indicate that customers with a higher balance and those who have been contacted frequently before the campaign tend to subscribe for the term deposit",
"_____no_output_____"
],
[
"### Bivariate analysis using crosstab",
"_____no_output_____"
]
],
[
[
"pd.crosstab(bank_df['job'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )",
"_____no_output_____"
]
],
[
[
"#### The highest conversion is for students (28%) and lowest is for blue-collar(7%",
"_____no_output_____"
]
],
[
[
"pd.crosstab(bank_df['marital'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )",
"_____no_output_____"
],
[
"pd.crosstab(bank_df['education'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )",
"_____no_output_____"
],
[
"print(pd.crosstab(bank_df['default'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False ))\nprint(bank_df['default'].value_counts(normalize=True))",
"Target no yes\ndefault \nno 0.882039 0.117961\nyes 0.936196 0.063804\nno 0.981973\nyes 0.018027\nName: default, dtype: float64\n"
]
],
[
[
"### Since default - yes is only 2% of the data and the conversion is also comparitively lower for default - yes, we can remove this column",
"_____no_output_____"
]
],
[
[
"bank_df.drop(['default'], axis=1, inplace=True)",
"_____no_output_____"
],
[
"bank_df.columns",
"_____no_output_____"
],
[
"pd.crosstab(bank_df['housing'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )",
"_____no_output_____"
],
[
"pd.crosstab(bank_df['loan'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )",
"_____no_output_____"
],
[
"pd.crosstab(bank_df['contact'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )",
"_____no_output_____"
],
[
"pd.crosstab(bank_df['day'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )[0:10]",
"_____no_output_____"
],
[
"pd.crosstab(bank_df['month'], bank_df['Target'], normalize='index').sort_values(by='yes',ascending=False )",
"_____no_output_____"
]
],
[
[
"### List out the high level findings from bivariate analysis that could provide pointers to feature selection\n\n\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"#Binning:\ndef binning(col, cut_points, labels=None):\n #Define min and max values:\n minval = col.min()\n maxval = col.max()\n\n #create list by adding min and max to cut_points\n break_points = [minval] + cut_points + [maxval]\n\n #if no labels provided, use default labels 0 ... (n-1)\n if not labels:\n labels = range(len(cut_points)+1)\n\n #Binning using cut function of pandas\n colBin = pd.cut(col,bins=break_points,labels=labels,include_lowest=True)\n return colBin",
"_____no_output_____"
],
[
"#Binning balance\ncut_points = [0,500,1000, 1500,2000]\nlabels = [\"very low\",\"low\",\"medium\",\"high\", \"very high\", \"highest\"]\nbank_df['balance_range'] = binning(bank_df['balance'], cut_points, labels)\nbank_df['balance_range'].value_counts()\n",
"_____no_output_____"
],
[
"#Binning campaign\ncut_points = [2,3,4]\nlabels = [\"<=2\",\"3\",\"4\",\">4\"]\nbank_df['campaign_range'] = binning(bank_df['campaign'], cut_points, labels)\nbank_df['campaign_range'].value_counts()\n",
"_____no_output_____"
],
[
"bank_df.drop(['balance', 'campaign'], axis=1, inplace=True)\nbank_df.columns",
"_____no_output_____"
],
[
"X = bank_df.drop(\"Target\" , axis=1)\ny = bank_df[\"Target\"] # select all rows and the 17 th column which is the classification \"Yes\", \"No\"\nX = pd.get_dummies(X, drop_first=True)",
"_____no_output_____"
],
[
"test_size = 0.30 # taking 70:30 training and test set\nseed = 7 # Random numbmer seeding for reapeatability of the code\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=seed)",
"_____no_output_____"
],
[
"X_train.shape,X_test.shape",
"_____no_output_____"
],
[
"#instantiating decision tree as the default model\ndt_model = DecisionTreeClassifier()\ndt_model.fit(X_train, y_train)",
"_____no_output_____"
],
[
"# Is the model an overfit model? \ny_pred = dt_model.predict(X_test)\nprint(dt_model.score(X_train, y_train))\nprint(dt_model.score(X_test , y_test))",
"0.9987360571302177\n0.8359628428192274\n"
],
[
"# Note: - Decision Tree is a non-parametric algorithm and hence prone to overfitting easily. This is evident from the difference\n# in scores in training and testing\n\n# In ensemble techniques, we want multiple instances (each different from the other) and each instance to be overfit!!! \n# hopefully, the different instances will do different mistakes in classification and when we club them, their\n# errors will get cancelled out giving us the benefit of lower bias and lower overall variance errors.\n\n",
"_____no_output_____"
],
[
"#Confusion matrix\n\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, recall_score\n\nprint(confusion_matrix(y_test, y_pred))\n\nprint(accuracy_score(y_test, y_pred))\n\n\nprint(recall_score(y_test, y_pred,average=\"binary\", pos_label=\"yes\"))\n\n\n",
"[[10845 1185]\n [ 1040 494]]\n0.8359628428192274\n0.3220338983050847\n"
]
],
[
[
"#### The recall score is relatively low and this has to be improves in the model",
"_____no_output_____"
]
],
[
[
"clf_pruned = DecisionTreeClassifier(criterion = \"entropy\", random_state = 100, max_depth=3, min_samples_leaf=5)\nclf_pruned.fit(X_train, y_train)",
"_____no_output_____"
]
],
[
[
"## Visualizing the tree",
"_____no_output_____"
]
],
[
[
"from sklearn.tree import export_graphviz\nfrom sklearn.externals.six import StringIO \nfrom IPython.display import Image \nimport pydotplus\nimport graphviz\n\n\nfeature_cols = X_train.columns\ndot_data = StringIO()\nexport_graphviz(clf_pruned, out_file=dot_data, \n filled=True, rounded=True,\n special_characters=True,feature_names = feature_cols,class_names=['0','1'])\ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \ngraph.write_png('bank_pruned.png')\nImage(graph.create_png())",
"_____no_output_____"
],
[
"## Calculating feature importance\n\nfeat_importance = clf_pruned.tree_.compute_feature_importances(normalize=False)\n\n\nfeat_imp_dict = dict(zip(feature_cols, clf_pruned.feature_importances_))\nfeat_imp = pd.DataFrame.from_dict(feat_imp_dict, orient='index')\nfeat_imp.sort_values(by=0, ascending=False)[0:10] #Top 10 features",
"_____no_output_____"
],
[
"preds_pruned = clf_pruned.predict(X_test)\npreds_pruned_train = clf_pruned.predict(X_train)\n",
"_____no_output_____"
],
[
"acc_DT = accuracy_score(y_test, preds_pruned)\nrecall_DT = recall_score(y_test, preds_pruned, average=\"binary\", pos_label=\"yes\")",
"_____no_output_____"
],
[
"#Store the accuracy results for each model in a dataframe for final comparison\nresultsDf = pd.DataFrame({'Method':['Decision Tree'], 'accuracy': acc_DT, 'recall': recall_DT})\nresultsDf = resultsDf[['Method', 'accuracy', 'recall']]\nresultsDf",
"_____no_output_____"
]
],
[
[
"### Overfitting is reduced after pruning, but recall has drastically reduced",
"_____no_output_____"
]
],
[
[
"## Apply the Random forest model and print the accuracy of Random forest Model\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nrfcl = RandomForestClassifier(n_estimators = 50)\nrfcl = rfcl.fit(X_train, y_train)\n\n\n\n\n",
"_____no_output_____"
],
[
"pred_RF = rfcl.predict(X_test)\nacc_RF = accuracy_score(y_test, pred_RF)\nrecall_RF = recall_score(y_test, pred_RF, average=\"binary\", pos_label=\"yes\")",
"_____no_output_____"
],
[
"tempResultsDf = pd.DataFrame({'Method':['Random Forest'], 'accuracy': [acc_RF], 'recall': [recall_RF]})\nresultsDf = pd.concat([resultsDf, tempResultsDf])\nresultsDf = resultsDf[['Method', 'accuracy', 'recall']]\nresultsDf\nresultsDf",
"_____no_output_____"
],
[
"## Apply Adaboost Ensemble Algorithm for the same data and print the accuracy.\n\n\nfrom sklearn.ensemble import AdaBoostClassifier\nabcl = AdaBoostClassifier( n_estimators= 200, learning_rate=0.1, random_state=22)\nabcl = abcl.fit(X_train, y_train)\n\n\n\n\n",
"_____no_output_____"
],
[
"pred_AB =abcl.predict(X_test)\nacc_AB = accuracy_score(y_test, pred_AB)\nrecall_AB = recall_score(y_test, pred_AB, pos_label='yes')",
"_____no_output_____"
],
[
"tempResultsDf = pd.DataFrame({'Method':['Adaboost'], 'accuracy': [acc_AB], 'recall':[recall_AB]})\nresultsDf = pd.concat([resultsDf, tempResultsDf])\nresultsDf = resultsDf[['Method', 'accuracy', 'recall']]\nresultsDf\nresultsDf",
"_____no_output_____"
],
[
"## Apply Bagging Classifier Algorithm and print the accuracy\n\n\nfrom sklearn.ensemble import BaggingClassifier\n\nbgcl = BaggingClassifier(n_estimators=100, max_samples= .7, bootstrap=True, oob_score=True, random_state=22)\nbgcl = bgcl.fit(X_train, y_train)\n\n\n\n\n\n",
"_____no_output_____"
],
[
"pred_BG =bgcl.predict(X_test)\nacc_BG = accuracy_score(y_test, pred_BG)\nrecall_BG = recall_score(y_test, pred_BG, pos_label='yes')",
"_____no_output_____"
],
[
"tempResultsDf = pd.DataFrame({'Method':['Bagging'], 'accuracy': [acc_BG], 'recall':[recall_BG]})\nresultsDf = pd.concat([resultsDf, tempResultsDf])\nresultsDf = resultsDf[['Method', 'accuracy', 'recall']]\nresultsDf\nresultsDf",
"_____no_output_____"
],
[
"from sklearn.ensemble import GradientBoostingClassifier\ngbcl = GradientBoostingClassifier(n_estimators = 200, learning_rate = 0.1, random_state=22)\ngbcl = gbcl.fit(X_train, y_train)\n\n\n\n\n",
"_____no_output_____"
],
[
"pred_GB =gbcl.predict(X_test)\nacc_GB = accuracy_score(y_test, pred_GB)\nrecall_GB = recall_score(y_test, pred_GB, pos_label='yes')\n",
"_____no_output_____"
],
[
"tempResultsDf = pd.DataFrame({'Method':['Gradient Boost'], 'accuracy': [acc_GB], 'recall':[recall_GB]})\nresultsDf = pd.concat([resultsDf, tempResultsDf])\nresultsDf = resultsDf[['Method', 'accuracy', 'recall']]\nresultsDf\nresultsDf",
"_____no_output_____"
]
],
[
[
"### Bagging gives overall best model performance. However, please note that the recall is still very low and will have to be improved",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb7bbbe76b759e1d30a929c12bac98a992c6395e
| 7,437 |
ipynb
|
Jupyter Notebook
|
ntbk_fl-en_GenerateEvaluationData.ipynb
|
redperiabras/FILIPINEU
|
833fd8d44c9d4de94d3433ca810a4a17831343ff
|
[
"MIT"
] | null | null | null |
ntbk_fl-en_GenerateEvaluationData.ipynb
|
redperiabras/FILIPINEU
|
833fd8d44c9d4de94d3433ca810a4a17831343ff
|
[
"MIT"
] | 1 |
2017-10-30T12:02:44.000Z
|
2017-10-30T12:02:44.000Z
|
ntbk_fl-en_GenerateEvaluationData.ipynb
|
redperiabras/FILIPINEU
|
833fd8d44c9d4de94d3433ca810a4a17831343ff
|
[
"MIT"
] | 1 |
2020-11-16T07:56:58.000Z
|
2020-11-16T07:56:58.000Z
| 30.604938 | 1,170 | 0.572812 |
[
[
[
"import pickle\nimport math\n\nfrom nltk import word_tokenize\nfrom nltk.translate.bleu_score import modified_precision, closest_ref_length, brevity_penalty, SmoothingFunction, sentence_bleu\n\nfrom collections import Counter\n\nfrom fractions import Fraction\n\nfrom modules.sentence import tokenizer, read, detokenize\nfrom modules.model import NMT",
"WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n"
],
[
"nbest = 0\nweights = (0.25, 0.25, 0.25, 0.25)",
"_____no_output_____"
],
[
"from models import fl_en\nmodel = fl_en",
"_____no_output_____"
],
[
"source_tokenizer = tokenizer(model.config['source_tokenizer'], lowercase=model.config['source_lowercase'])\nsource_eval = read('models/fl_en/source.data.test', source_tokenizer, model.config['backwards'])",
"_____no_output_____"
],
[
"target_tokenizer = tokenizer('word', lowercase=model.config['target_lowercase'])\nreferences = read('models/fl_en/source.data.test', target_tokenizer, model.config['backwards'])\nprint(references)",
"_____no_output_____"
],
[
"output_file = open('models/fl_en/result.data.test', 'w', encoding='utf-8')\n\nhypotheses = []\n\nfor i, sent in enumerate(model.translate(source_eval, encode=True, nbest=nbest)):\n print(sent, file=output_file, flush=True)\n hypotheses.append(word_tokenize(sent))\n \noutput_file.close()",
"_____no_output_____"
],
[
"evaluation_file = open('models/fl_en/scores.data.eval.csv','w', encoding='utf-8')\n\np_numerators = Counter()\np_denominators = Counter()\nhyp_lengths, ref_lengths = 0, 0\n\nfor reference, hypothesis in zip(references, hypotheses):\n \n hyp_len = len(hypothesis)\n ref_len = closest_ref_length([reference], hyp_len)\n \n hyp_lengths += hyp_len\n ref_lengths += ref_len\n \n set_data = '%d,%d' % (ref_len, hyp_len)\n \n for i, _ in enumerate(weights, start=1):\n p_i = modified_precision(reference, hypothesis, i)\n p_numerators[i] += p_i.numerator\n p_denominators[i] += p_i.denominator\n set_data += ',%d,%d' % (p_i.numerator, p_i.denominator)\n \n set_data += ',%f' % sentence_bleu([reference], hypothesis)\n \n print(set_data, file=evaluation_file, flush=True)\n \nevaluation_file.close()",
"_____no_output_____"
],
[
"bp = brevity_penalty(ref_lengths, hyp_lengths)\nprint(bp)",
"0.920491284044873\n"
],
[
"p_n = [Fraction(p_numerators[i], p_denominators[i], _normalize=False)\n for i, _ in enumerate(weights, start=1)]",
"_____no_output_____"
],
[
"smoothing_function = SmoothingFunction().method0\n\np_n = smoothing_function(p_n, references=references, hypothesis=hypothesis,\n hyp_len=hyp_len, emulate_multibleu=False)\n\ns = (w * math.log(p_i) for i, (w, p_i) in enumerate(zip(weights, p_n)))\n\nprint(math.exp(math.fsum(s)))",
"0.01839351702653491\n"
],
[
"from nltk.translate.bleu_score import corpus_bleu\n\ncorpus_bleu(references, hypotheses)",
"/mnt/c/ubuntu-bash/filipineu/venv/lib/python3.5/site-packages/nltk/translate/bleu_score.py:490: UserWarning: \nCorpus/Sentence contains 0 counts of 3-gram overlaps.\nBLEU scores might be undesirable; use SmoothingFunction().\n warnings.warn(_msg)\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7bca4d605fa9165966ee3459a74d8701ea001b
| 77,605 |
ipynb
|
Jupyter Notebook
|
notebooks/EDA.ipynb
|
HeegyuKim/RecSys-MovieLens100k
|
aa3a272e6045d8230ecbabbf94a6f68170a26c9e
|
[
"MIT"
] | null | null | null |
notebooks/EDA.ipynb
|
HeegyuKim/RecSys-MovieLens100k
|
aa3a272e6045d8230ecbabbf94a6f68170a26c9e
|
[
"MIT"
] | null | null | null |
notebooks/EDA.ipynb
|
HeegyuKim/RecSys-MovieLens100k
|
aa3a272e6045d8230ecbabbf94a6f68170a26c9e
|
[
"MIT"
] | null | null | null | 32.883475 | 114 | 0.293319 |
[
[
[
"# EDA\n",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2\nimport sys\nsys.path.append(\"../src\")",
"_____no_output_____"
],
[
"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport scipy\nfrom collections import Counter",
"_____no_output_____"
]
],
[
[
"## Data Preparation",
"_____no_output_____"
]
],
[
[
"ds_links = pd.read_csv(\"../ml-latest-small/links.csv\")\nds_movies = pd.read_csv(\"../ml-latest-small/movies.csv\")\nds_ratings = pd.read_csv(\"../ml-latest-small/ratings.csv\")\nds_tags = pd.read_csv(\"../ml-latest-small/tags.csv\")",
"_____no_output_____"
]
],
[
[
"## Ratings",
"_____no_output_____"
]
],
[
[
"ds_movies",
"_____no_output_____"
],
[
"ratings_mean_count = ds_ratings.groupby(\"movieId\").agg({\"rating\": [\"mean\", \"count\"]})\nratings_mean_count.columns = [\"ratings_mean\", \"ratings_count\"]\nratings_mean_count",
"_____no_output_____"
]
],
[
[
"## User-Item Matrix",
"_____no_output_____"
]
],
[
[
"def create_user_item_matrix(ratings) -> pd.DataFrame:\n mat = ratings.pivot(index=\"userId\", columns=\"movieId\", values=\"rating\")\n mat[~mat.isna()] = 1\n mat.fillna(0, inplace=True)\n return mat\n\ndef create_user_item_ranking_matrix(ratings) -> pd.DataFrame:\n return ratings.pivot(index=\"userId\", columns=\"movieId\", values=\"rating\")\n\nuser_item_matrix = create_user_item_ranking_matrix(ds_ratings)\nuser_item_matrix.head()",
"_____no_output_____"
]
],
[
[
"유저마다 시간별로 rating 매긴걸 정렬한 다음\n일정 비율로 나눠서 이전에 매긴 rating을 바탕으로 이후에 매긴 rating을 예측할 수 있는\n모델을 만들고자 함",
"_____no_output_____"
]
],
[
[
"def create_user_item_matrix_train(ds_ratings, train_size=0.5):\n users = ds_ratings.userId.unique()\n train_sets = []\n for user in users:\n ratings = ds_ratings[ds_ratings.userId == user].sort_values(\"timestamp\")\n q_value = ratings.timestamp.quantile(q=train_size, interpolation='nearest')\n train_set = ratings[ratings.timestamp <= q_value]\n train_sets.append(train_set)\n\n train_set = pd.concat(train_sets, axis=0)\n return train_set\n\ntrain_set = create_user_item_matrix_train(ds_ratings, 0.5)\ntrain_set = create_user_item_ranking_matrix(train_set)\ntrain_set",
"_____no_output_____"
],
[
"train_set.to_csv(\"../data/user_item_matrix_X_0.5.csv\")\ncreate_user_item_matrix(ds_ratings).to_csv(\"../data/user_item_matrix_Y_0.5.csv\")",
"_____no_output_____"
]
],
[
[
"## Tag 정보 EDA",
"_____no_output_____"
]
],
[
[
"tag_counts = ds_tags.tag.value_counts()\ntag_counts[tag_counts >= 5]",
"_____no_output_____"
]
],
[
[
"## Movie EDA",
"_____no_output_____"
]
],
[
[
"from sklearn.feature_extraction.text import CountVectorizer\n# ds_movies.genres.str.split(\"|\")\ncv = CountVectorizer()\ngenres = cv.fit_transform(ds_movies.genres)\ngenres = pd.DataFrame(\n genres.toarray(),\n columns=list(sorted(cv.vocabulary_.keys(), key=lambda x: cv.vocabulary_[x]))\n)\ngenres",
"_____no_output_____"
]
],
[
[
"title 에서 연도를 지울 경우 중복되는게 있는지 확인해봤고, 282개 있음",
"_____no_output_____"
]
],
[
[
"titles = ds_movies.title.str[:-7]\ntitles.value_counts()",
"_____no_output_____"
],
[
"ds_movies[ds_movies.title.str.contains(\"Hamlet\")]",
"_____no_output_____"
]
],
[
[
"## 학습에 필요한 결과물 저장",
"_____no_output_____"
]
],
[
[
"movie_genre_matrix = pd.concat(\n [ds_movies.drop(columns=\"genres\"), genres],\n axis=1\n).drop(columns=\"movieId\")\nmovie_genre_matrix.index = ds_movies.movieId\nmovie_genre_matrix = pd.concat([movie_genre_matrix, ratings_mean_count], axis=1)\nmovie_genre_matrix[\"years\"] = movie_genre_matrix.title.str.strip().str[-5:-1]\nmovie_genre_matrix.years = movie_genre_matrix.years.apply(lambda x: int(x) if x.isdigit() else 0)\n\nmovie_genre_matrix.to_csv(\"../data/movies.csv\")\nmovie_genre_matrix",
"_____no_output_____"
],
[
"movie_genre_matrix.columns[1:25]",
"_____no_output_____"
]
],
[
[
"영화 점보와 평점 정보를 pandas를 이용해서 불러옵니다",
"_____no_output_____"
]
],
[
[
"ds_movies = pd.read_csv(\"../ml-latest-small/movies.csv\", index_col=0)\nds_ratings = pd.read_csv(\"../ml-latest-small/ratings.csv\")",
"_____no_output_____"
]
],
[
[
"영화 평점과 평가 수를 집계한 후 영화 제목을 데이터프레임에 추가합니다.",
"_____no_output_____"
]
],
[
[
"\nmovie_ratings = ds_ratings.groupby(\"movieId\") \\\n .agg({\"rating\": [\"count\", \"mean\"]})\nmovie_ratings[\"title\"] = ds_movies.title\nmovie_ratings",
"_____no_output_____"
]
],
[
[
"평점이 50개 이상한 영화 중 가장 평점이 좋은 영화 10개를 가져옵니다.<br/>\n평점이 같다면 평가 수가 많은 영화 순으로 정렬합니다.",
"_____no_output_____"
]
],
[
[
"\nmovie_ratings[movie_ratings[(\"rating\", \"count\")] >= 50] \\\n .sort_values([(\"rating\", \"mean\"), (\"rating\", \"count\")], ascending=[False, False]) \\\n .head(10)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7bcc314abd65b90f80e6ef75f2038e22a642ad
| 14,530 |
ipynb
|
Jupyter Notebook
|
docs/notebooks/Strength_Analysis.ipynb
|
IanViotti/composipy
|
87866ce908358d895d9a04a3a243a46ff7cda3a7
|
[
"MIT"
] | null | null | null |
docs/notebooks/Strength_Analysis.ipynb
|
IanViotti/composipy
|
87866ce908358d895d9a04a3a243a46ff7cda3a7
|
[
"MIT"
] | null | null | null |
docs/notebooks/Strength_Analysis.ipynb
|
IanViotti/composipy
|
87866ce908358d895d9a04a3a243a46ff7cda3a7
|
[
"MIT"
] | null | null | null | 29.294355 | 1,761 | 0.520096 |
[
[
[
"# Composipy for strength analysis of a laminate",
"_____no_output_____"
],
[
"In this exemple we will use the exercise 6-7 from *Analysis and Performance of Fiber Composites by B. Agarwal* pg. 244. \n\n",
"_____no_output_____"
]
],
[
[
"from composipy import Ply, Laminate, Load, Strength",
"_____no_output_____"
]
],
[
[
"Fist, lets consider the following laminate\n\n$[45_{ply1}/0_{ply2}/45_{ply1}]$\n\nWhere $ply_1$ is $3 mm$ thick and $ply_2$ is $6mm$ thick with the following Elastic and strength characteristics\n\n- E1 = 19745 MPa\n- E2 = 1980 MPa\n- $\\nu_{12}$ = 0.35\n- G = 700 MPa\n- $\\sigma_1^T$ = 400 Mpa\n- $\\sigma_1^C$ = -250 Mpa\n- $\\sigma_2^T$ = 150 Mpa\n- $\\sigma_2^C$ = -200 Mpa\n- $\\tau_{12}$ = 25 Mpa",
"_____no_output_____"
],
[
"### Setting the laminate",
"_____no_output_____"
]
],
[
[
"ply_1 = Ply(19745 , 1980, 0.35, 700, 3, 400, -250, 150, -200, 25, name='3mm Unidirection Fiber Composite') \nply_2 = Ply(19745 , 1980, 0.35, 700, 6, 400, -250, 150, -200, 25, name='6mm Unidirection Fiber Composite')",
"_____no_output_____"
]
],
[
[
"Now, defining the laminate",
"_____no_output_____"
]
],
[
[
"layup_1 = [\n (45, ply_1),\n (0, ply_2),\n (45, ply_1)\n ]\n\nlaminate_1 = Laminate(layup_1)\n\n\nprint(ply_1,'\\n',ply_2)\n\nprint('==============================================')\n\nprint(laminate_1)",
"Ply(6mm Unidirection Carbon Fiber, E1 = 19745, E2 = 1980, \n v12 = 0.35, G12 = 700, thickness = 3, \n T1 = 400, C1 = -250, T2 = 150, C2 = -200, S = 25) \n Ply(6mm Unidirection Carbon Fiber, E1 = 19745, E2 = 1980, \n v12 = 0.35, G12 = 700, thickness = 6, \n T1 = 400, C1 = -250, T2 = 150, C2 = -200, S = 25)\n==============================================\n6mm Unidirection Carbon Fiber 45 ///// \n6mm Unidirection Carbon Fiber 0 ===== \n6mm Unidirection Carbon Fiber 45 ///// \n\n"
]
],
[
[
"The $ABD'$ matrix can be called by the `ABD_p` atribute",
"_____no_output_____"
]
],
[
[
"laminate_1.ABD_p",
"_____no_output_____"
]
],
[
[
"### Setting the loads",
"_____no_output_____"
],
[
"In the exemple, the element is subjected to the following loads\n\n- Nx = 1000 N/mm\n- Ny = 200 N/m\n- Nxy = 0\n- Mx = 0\n- My = 0\n- Mxy = 0",
"_____no_output_____"
],
[
"We will input the loads by using the `Load` class.",
"_____no_output_____"
]
],
[
[
"loads_1 = Load(1000,200,0,0,0,0)\n\nloads_1",
"_____no_output_____"
]
],
[
[
"### Checking the strength and elastic parameters of the laminate under load",
"_____no_output_____"
],
[
"Now we can analyse the strain and strees in the laminate using the `Strength` class.",
"_____no_output_____"
]
],
[
[
"analysis = Strength(laminate_1,loads_1)",
"_____no_output_____"
]
],
[
[
"Let's see the the mid-plane strain in the load direction (*xy*) by calling the `mid_strain_xy` atribute",
"_____no_output_____"
]
],
[
[
"analysis.mid_strain_xy",
"_____no_output_____"
]
],
[
[
"Or, in the laminate coordinates (*12*), by calling `mid_strain_12`.",
"_____no_output_____"
]
],
[
[
"analysis.mid_strain_12",
"_____no_output_____"
]
],
[
[
"Just like that, we can get the stress in all plies for both *xy* and *12* directions by calling `stress_xy` or `stress_12`.",
"_____no_output_____"
]
],
[
[
"analysis.stress_xy ",
"_____no_output_____"
],
[
"analysis.stress_12",
"_____no_output_____"
]
],
[
[
"From the stresses in the laminate coordinates, we can calculate the Tsai-Wu failure index for all plies by calling `TW_i`.",
"_____no_output_____"
]
],
[
[
"analysis.TW_i",
"_____no_output_____"
]
],
[
[
"Because the Tsai-Wu index is below 1 for all plies, the laminate is still undamaged. ",
"_____no_output_____"
],
[
"We can discover in what load the first ply will fail based on the Tsai-Wu failure criterion by using the `FPF` parameter.",
"_____no_output_____"
]
],
[
[
"analysis.FPF",
"FPF Load: \n [[2548.05698026]\n [ 509.61139605]\n [ 0. ]\n [ 0. ]\n [ 0. ]\n [ 0. ]]\nFailed Ply(ies): \n [2]\nLaminate Tsai-Wu Index in FPF: \n [0.12933910070551077, 1.0199433489695386, 0.12933910070551077]\nStrength Ratio for FPF: \n 2.573537550058799\n"
]
],
[
[
"By this, we now know that the second ply will fail under $Nx = 2548.06 N/mm; Ny=509.61N/mm$ and that the Strenth Ratio for the FPF is $2.57$.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7bcd066a3810416f599ae0681d5fcd23ccfa81
| 1,478 |
ipynb
|
Jupyter Notebook
|
DICTIONARY__________Convert into tuple.ipynb
|
MaximilianFreitag/JupyterNotebooks
|
18a5e9fbea976e15b6cc9e997792b19259f6a118
|
[
"MIT"
] | 3 |
2021-08-04T15:31:32.000Z
|
2021-12-22T21:00:11.000Z
|
DICTIONARY__________Convert into tuple.ipynb
|
MaximilianFreitag/JupyterNotebooks
|
18a5e9fbea976e15b6cc9e997792b19259f6a118
|
[
"MIT"
] | null | null | null |
DICTIONARY__________Convert into tuple.ipynb
|
MaximilianFreitag/JupyterNotebooks
|
18a5e9fbea976e15b6cc9e997792b19259f6a118
|
[
"MIT"
] | null | null | null | 17.807229 | 55 | 0.449256 |
[
[
[
"dict = { 'Geeks': 10, 'for': 12, 'Geek': 31 } \n\nlist = [(k, v) for k, v in dict.items()] \n\nprint(list)\n",
"[('Geeks', 10), ('for', 12), ('Geek', 31)]\n"
],
[
"my_dict = {\"date\": \"1.1.2020\"}\n \ntuple(map(int,'1.1.2020'.split('.'))) ",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cb7bfc8a54e8a5ef86ab1cd2af68d6c06ecbd5fa
| 972,824 |
ipynb
|
Jupyter Notebook
|
Idalia/ParticleTracking.ipynb
|
SalishSeaCast/analysis
|
5964628f08ca1f36121a5d8430ad5b4ae7756c7a
|
[
"Apache-2.0"
] | null | null | null |
Idalia/ParticleTracking.ipynb
|
SalishSeaCast/analysis
|
5964628f08ca1f36121a5d8430ad5b4ae7756c7a
|
[
"Apache-2.0"
] | null | null | null |
Idalia/ParticleTracking.ipynb
|
SalishSeaCast/analysis
|
5964628f08ca1f36121a5d8430ad5b4ae7756c7a
|
[
"Apache-2.0"
] | null | null | null | 1,105.481818 | 205,799 | 0.942974 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cb7c242c00077334c27f6adf21ee021b1208af86
| 1,911 |
ipynb
|
Jupyter Notebook
|
Untitled.ipynb
|
matthewmiller01/2019-CS109A
|
941cb07b32baacf7caccd49e94e3dfe3ef910f91
|
[
"MIT"
] | null | null | null |
Untitled.ipynb
|
matthewmiller01/2019-CS109A
|
941cb07b32baacf7caccd49e94e3dfe3ef910f91
|
[
"MIT"
] | null | null | null |
Untitled.ipynb
|
matthewmiller01/2019-CS109A
|
941cb07b32baacf7caccd49e94e3dfe3ef910f91
|
[
"MIT"
] | null | null | null | 23.024096 | 108 | 0.52381 |
[
[
[
"import scipy\nfrom scipy.integrate import quad",
"_____no_output_____"
],
[
"# https://stackoverflow.com/questions/5965583/use-scipy-integrate-quad-to-integrate-complex-numbers\ndef complex_quadrature(func, a, b, **kwargs):\n def real_func(x):\n return scipy.real(func(x))\n def imag_func(x):\n return scipy.imag(func(x))\n real_integral = quad(real_func, a, b, **kwargs)\n imag_integral = quad(imag_func, a, b, **kwargs)\n return (real_integral[0] + 1j*imag_integral[0], real_integral[1:], imag_integral[1:])",
"_____no_output_____"
],
[
"complex_quadrature(lambda x: 1/((x**2)-4), 1, 1)\n#complex_quadrature(lambda x: 1/((x**2)-4), 1, 2)\n#complex_quadrature(lambda x: 1/((x**2)-4), 3, 1)\n#complex_quadrature(lambda x: 1/((x**2)-4), 3, 2)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
cb7c27e3f2802deae69bf8175ef58981bb317767
| 130,862 |
ipynb
|
Jupyter Notebook
|
notebooks/ad_analysis.ipynb
|
snad-space/zwad
|
fe1759d72c6d01d96246cf66898eecbfcc778af4
|
[
"MIT"
] | 11 |
2020-12-04T01:51:09.000Z
|
2022-01-16T16:23:40.000Z
|
notebooks/ad_analysis.ipynb
|
snad-space/zwad
|
fe1759d72c6d01d96246cf66898eecbfcc778af4
|
[
"MIT"
] | 30 |
2020-12-12T15:14:46.000Z
|
2021-10-20T14:45:26.000Z
|
notebooks/ad_analysis.ipynb
|
snad-space/zwad
|
fe1759d72c6d01d96246cf66898eecbfcc778af4
|
[
"MIT"
] | 3 |
2021-03-16T20:03:54.000Z
|
2021-05-12T16:27:35.000Z
| 34.601269 | 121 | 0.324296 |
[
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom zwad.ad.postprocess import *\n\nfrom IPython.display import display, HTML\npd.set_option('display.max_rows', 2000)\nplt.rcParams['figure.max_open_warning'] = 100",
"_____no_output_____"
]
],
[
[
"# Table of contents\n* [M31](#M31)\n* [Deep](#Deep)\n* [Disk](#Disk)",
"_____no_output_____"
]
],
[
[
"data_dir = '../data/'\n\n\ndef load_ad_results(filenames):\n table = load_ad_tables_by_patterns([os.path.join(data_dir, fname)\n for fname in filenames])\n # Sort the table\n table = table.loc[table.isna().sum(axis=1).sort_values(kind='mergesort').index].reset_index(drop=True)\n\n return table\n\n\ndef result_comparison(ad_filenames, expert_filename): \n table = load_ad_results(ad_filenames)\n expert_table = load_expert_table(expert_filename)\n subtable = pd.merge(table, expert_table, on='oid', how='left')\n return subtable",
"_____no_output_____"
]
],
[
[
"# M31",
"_____no_output_____"
]
],
[
[
"subtable = result_comparison(\n [os.path.join(data_dir, name) for name in ['m31_iso.csv', 'm31_gmm.csv', 'm31_lof.csv', 'm31_svm.csv']],\n os.path.join(data_dir, 'm31_maria.csv'))\n\ndisplay(subtable)",
"_____no_output_____"
]
],
[
[
"# Deep",
"_____no_output_____"
]
],
[
[
"result_comparison(\n [os.path.join(data_dir, name) for name in ['deep_iso.csv', 'deep_gmm.csv', 'deep_lof.csv', 'deep_svm.csv']],\n os.path.join(data_dir, 'deep_maria.csv'))",
"_____no_output_____"
]
],
[
[
"# Disk",
"_____no_output_____"
]
],
[
[
"result_comparison(\n [os.path.join(data_dir, name) for name in ['disk_iso.csv', 'disk_gmm.csv', 'disk_lof.csv', 'disk_svm.csv']],\n os.path.join(data_dir, 'disk_maria.csv'))",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7c2e212e1eb2c7953a847189f511cada221912
| 29,634 |
ipynb
|
Jupyter Notebook
|
dataloader/Parser.ipynb
|
KhurramPirov/Twins-recognition
|
f99ba1128afb3674a49db6a4b19afd5108c3fdf9
|
[
"MIT"
] | null | null | null |
dataloader/Parser.ipynb
|
KhurramPirov/Twins-recognition
|
f99ba1128afb3674a49db6a4b19afd5108c3fdf9
|
[
"MIT"
] | null | null | null |
dataloader/Parser.ipynb
|
KhurramPirov/Twins-recognition
|
f99ba1128afb3674a49db6a4b19afd5108c3fdf9
|
[
"MIT"
] | null | null | null | 38.737255 | 2,683 | 0.525646 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport warnings\nimport time\nimport os\nimport copy\nfrom PIL import Image\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torchvision\nfrom torchvision import datasets, models, transforms\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision.utils import make_grid\n\n% matplotlib inline\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"path=os.getcwd()",
"_____no_output_____"
],
[
"df=pd.read_csv(path+'/twins_aligned_cropped_resized/df/pairs_test.csv')",
"_____no_output_____"
],
[
"df1=pd.read_csv(path+'/twins_aligned_cropped_resized/df/pairs_train.csv')",
"_____no_output_____"
],
[
"def check_overlap(df1,df):\n t=0\n print(df1.shape[0])\n print(df.shape[0])\n for i in range(df1.shape[0]):\n for j in range(df.shape[0]):\n if (df1['id_1'].iloc[i]==df['id_1'].iloc[j] and df1['id_2'].iloc[i]==df['id_2'].iloc[j]) or (df1['id_2'].iloc[i]==df['id_1'].iloc[j] and df1['id_2'].iloc[i]==df['id_1'].iloc[j]): t+=1\n print(t)\n return t",
"_____no_output_____"
],
[
"check_overlap(df1,df)",
"646\n208\n58\n"
]
],
[
[
"## Splitting",
"_____no_output_____"
]
],
[
[
"df=pd.read_csv(path+'/twins_aligned_cropped_resized/df/pairs.csv')",
"_____no_output_____"
],
[
"df['label'].unique()",
"_____no_output_____"
],
[
"df.groupby(['label']).count()",
"_____no_output_____"
],
[
"df[(df['label']=='Sibling') ]",
"_____no_output_____"
],
[
"#{'id_1':[0],'id_2':[0],'label':[0]}\ntrain=pd.DataFrame({})\ntest=pd.DataFrame({})\n\nsame=df[df['label']=='Same']\nident=df[(df['label']=='Identical')| (df['label']=='IdenticalMirror')\n | (df['label']=='UnknownTwinType') |(df['label']=='Fraternal')|(df['label']=='Sibling')]\n\nother=df[(df['label']=='IdenticalTriplet') ]#| (df['label']=='Sibling')\n\nprint(same.shape)\nprint(ident.shape)\nprint(other.shape)",
"(432, 3)\n(416, 3)\n(6, 3)\n"
],
[
"train=train.append(other)",
"_____no_output_____"
],
[
"def inverse(a):\n copy=a.copy()\n #print(a)\n a['id_1']=str(copy['id_2'])\n a['id_2']=str(copy['id_1'])\n #print(a)\n return a\n\nwhile ident.shape[0]>0:\n prob=np.random.randint(0,11)\n t=ident.iloc[np.random.randint(ident.shape[0])]\n if prob>=8:\n test=test.append(t)\n test=test.append(inverse(t))\n else:\n train=train.append(t)\n train=train.append(inverse(t))\n ident=ident[(ident['id_1']!=t['id_1']) & (str(ident['id_2'])!=str(t['id_2'])) ]\n ident=ident[(ident['id_1']!=inverse(t)['id_1']) &(ident['id_2']!=inverse(t)['id_2']) ]\nprint(test.shape)\nprint(train.shape)\ncheck_overlap(test,train)",
"_____no_output_____"
],
[
"while same.shape[0]>0:\n t=same.iloc[np.random.randint(same.shape[0])] \n if t['id_1'] in train['id_1'].tolist():\n train=train.append(t)\n else:\n test=test.append(t)\n same=same[(same['id_1']!=t['id_1']) &(same['id_2']!=t['id_2']) ]\nprint(test.shape)\nprint(train.shape)\ncheck_overlap(test,train)",
"(431, 3)\n(9, 3)\n431\n9\n0\n"
],
[
"print(test.shape)\nprint(train.shape)\ncheck_overlap(test,train)",
"(431, 3)\n(9, 3)\n431\n9\n0\n"
],
[
"train.to_csv(path+'/twins_aligned_cropped_resized/df/pairs_train_fedor.csv',index =False)\ntest.to_csv(path+'/twins_aligned_cropped_resized/df/pairs_test_fedor.csv',index =False)",
"_____no_output_____"
]
],
[
[
"## Read",
"_____no_output_____"
]
],
[
[
"train=pd.read_csv(path+'/twins_aligned_cropped_resized/df/pairs_train_fedor.csv')\ntest=pd.read_csv(path+'/twins_aligned_cropped_resized/df/pairs_test_fedor.csv')",
"_____no_output_____"
],
[
"test.head()",
"_____no_output_____"
],
[
"test['id_1']=test['id_1'].apply(int)\ntest['id_2']=test['id_2'].apply(int)\ntrain['id_1']=train['id_1'].apply(int)\ntrain['id_2']=train['id_2'].apply(int)",
"_____no_output_____"
],
[
"test.head()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cb7c38d7352a963d84c69b779a6da1a7914628e6
| 30,894 |
ipynb
|
Jupyter Notebook
|
Test Notebooks/SP Chatbot Test/chatbot_test.ipynb
|
Asienwald/SmartPoly-AI-Chatbot
|
c54c2e95f619743e5b85dd96cad64ee7b7b357ae
|
[
"MIT"
] | null | null | null |
Test Notebooks/SP Chatbot Test/chatbot_test.ipynb
|
Asienwald/SmartPoly-AI-Chatbot
|
c54c2e95f619743e5b85dd96cad64ee7b7b357ae
|
[
"MIT"
] | null | null | null |
Test Notebooks/SP Chatbot Test/chatbot_test.ipynb
|
Asienwald/SmartPoly-AI-Chatbot
|
c54c2e95f619743e5b85dd96cad64ee7b7b357ae
|
[
"MIT"
] | 2 |
2021-04-13T12:54:16.000Z
|
2021-10-30T13:17:32.000Z
| 57.853933 | 367 | 0.672169 |
[
[
[
"# <font color='cyan'>AI Chatbot Test</font>",
"_____no_output_____"
]
],
[
[
"import nltk\nimport numpy as np\nimport random\nimport string # process standard python strings",
"_____no_output_____"
]
],
[
[
"### Read the raw txt file",
"_____no_output_____"
]
],
[
[
"f = open('chatbot.txt', 'r', errors = 'ignore')",
"_____no_output_____"
],
[
"raw = f.read()\nraw = raw.lower()",
"_____no_output_____"
],
[
"# 1st time use only\n# nltk.download('punkt')\n# nltk.download('wordnet')",
"_____no_output_____"
]
],
[
[
"### Tokenize the raw data",
"_____no_output_____"
]
],
[
[
"# converts to list of sentences\nsent_tokens = nltk.sent_tokenize(raw)\n# converts to list of words\nword_tokens = nltk.word_tokenize(raw)",
"_____no_output_____"
],
[
"sent_tokens",
"_____no_output_____"
],
[
"word_tokens[:2]",
"_____no_output_____"
]
],
[
[
"### Pre-processing the Raw Text",
"_____no_output_____"
]
],
[
[
"'''\ndefine function called LemTokens which will\ntake in the tokens as inputs\n& return normalised tokens\n'''",
"_____no_output_____"
],
[
"lemmer = nltk.stem.WordNetLemmatizer()\n# Wordnet is a semantically-oriented dictionary of English included \n# in NLTK",
"_____no_output_____"
],
[
"def LemTokens(tokens):\n return [lemmer.lemmatize(token) for token in tokens]\n\nremove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)",
"_____no_output_____"
],
[
"def LemNormalize(text):\n return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))",
"_____no_output_____"
]
],
[
[
"### Keyword Matching",
"_____no_output_____"
]
],
[
[
"'''\ndefine function for greeting by bot\nEg. If user input greeting, bot reply with greeting\nELIZA uses simple keyword matching for greetings\n'''",
"_____no_output_____"
],
[
"GREETING_INPUTS = ('hello', 'hi', 'greetings', 'sup', \"what's up\", 'hey')\nGREETING_RESPONSES = ['hi', 'hey', '*nods', 'hi there', 'hello', \n \"I'm glad! You're talking to me!\"]",
"_____no_output_____"
],
[
"def greeting(sentence):\n for word in sentence.split():\n if word.lower() in GREETING_INPUTS:\n return random.choice(GREETING_RESPONSES)",
"_____no_output_____"
]
],
[
[
"### Generating Response",
"_____no_output_____"
]
],
[
[
"'''\nTo generate response from our bot for input qns,\nconcept of codument similarity used\nWe'll begin by importing the necessary modules\n'''",
"_____no_output_____"
],
[
"# From scikit learn libary, import TFidf vectorizer to convert collection of \n# raw documents to matrix of TF-IDF features\nfrom sklearn.feature_extraction.text import TfidfVectorizer",
"_____no_output_____"
],
[
"# import cosine similary module from scikit learn lib\nfrom sklearn.metrics.pairwise import cosine_similarity\n# used to find similarity between words entered by user & owrds in corpus\n# This is the simplest implementation of a chatbot",
"_____no_output_____"
],
[
"# define function response which searches user's utterance for >1 known keywords\n# & returns several possible responses\n# if no matches, return \"I'm sorry! Don't understand you!\"\n\ndef response(user_resp):\n robo_response = ''\n sent_tokens.append(user_resp)\n \n tfidf_vec = TfidfVectorizer(tokenizer = LemNormalize, stop_words = 'english')\n tfidf = tfidf_vec.fit_transform(sent_tokens)\n \n vals = cosine_similarity(tfidf[-1], tfidf)\n idx = vals.argsort()[0][-2]\n \n flat = vals.flatten()\n flat.sort()\n \n req_tfidf = flat[-2]\n \n robo_response += \"Sorry! Don't understand\" if (req_tfidf == 0) else sent_tokens[idx]\n return robo_response",
"_____no_output_____"
],
[
"# feed lines we want our bot to say while starting & ending conversation\n# depending on user's input\n\nflag = True\nprint('BOI: Howdy. Ask me Anything :)')\nrobo_text: str = ''\n\nwhile flag:\n user_resp = input('>>>').lower()\n \n if user_resp not in ['bye', 'exit']:\n if user_resp in ['thanks', 'thank you']:\n flag = False\n robo_text = 'No Problem'\n else:\n if greeting(user_resp) != None:\n robo_text = greeting(user_resp)\n else:\n print(response(user_resp))\n sent_tokens.remove(user_resp)\n else:\n flag = False\n robo_text = 'Cya!'\n \n print(f\"BOI: {robo_text}\")",
"BOI: Howdy. Ask me Anything :)\n>>>what is an ai\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb7c38f735480ddd5b7d81d2b35e3f375d7a9cd7
| 10,272 |
ipynb
|
Jupyter Notebook
|
main.ipynb
|
andriidem308/demchenko_nikiforov_labwork
|
a6d11fdecb85ce27acb1a0a9c9e37dbdce389573
|
[
"MIT"
] | 1 |
2020-10-13T11:51:10.000Z
|
2020-10-13T11:51:10.000Z
|
main.ipynb
|
andriidem308/demchenko_nikiforov_labwork
|
a6d11fdecb85ce27acb1a0a9c9e37dbdce389573
|
[
"MIT"
] | null | null | null |
main.ipynb
|
andriidem308/demchenko_nikiforov_labwork
|
a6d11fdecb85ce27acb1a0a9c9e37dbdce389573
|
[
"MIT"
] | null | null | null | 40.924303 | 1,703 | 0.567368 |
[
[
[
"***Лабораторна робота<br>***\n*Виконали студенти 3 курсу<br>\nгрупи \"Комп'ютерна математика\"<br>\nДемченко Андрій та Нікіфоров Олександр<br>*",
"_____no_output_____"
],
[
"( 1 ) Імпортуємо потрібні бібліотеки та допоміжні файли",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport utils",
"_____no_output_____"
]
],
[
[
"( 2 ) Читаємо дані із бази данних та виводимо їх",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(\"heart_failure_clinical_records_dataset.csv\")\nprint(df.head())\n",
" age anaemia creatinine_phosphokinase diabetes ejection_fraction \\\n0 75.0 0 582 0 20 \n1 55.0 0 7861 0 38 \n2 65.0 0 146 0 20 \n3 50.0 1 111 0 20 \n4 65.0 1 160 1 20 \n\n high_blood_pressure platelets serum_creatinine serum_sodium sex \\\n0 1 265000.00 1.9 130 1 \n1 0 263358.03 1.1 136 1 \n2 0 162000.00 1.3 129 1 \n3 0 210000.00 1.9 137 1 \n4 0 327000.00 2.7 116 0 \n\n smoking time DEATH_EVENT \n0 0 4 1 \n1 0 6 1 \n2 1 7 1 \n3 0 7 1 \n4 0 8 1 \n"
]
],
[
[
"( 3 ) Визначаємо змінні, які будем тренувати",
"_____no_output_____"
]
],
[
[
"features = ['age', 'ejection_fraction', 'serum_creatinine', 'serum_sodium', 'time']\nX_init = df[features]\nY_init = df[\"DEATH_EVENT\"]\n\nX = utils.normalize(X_init)\nY = np.asarray(Y_init).copy()",
"_____no_output_____"
]
],
[
[
"( 4 ) Тут будуть глобальні змінні\n",
"_____no_output_____"
]
],
[
[
"BATCH_SIZE = 32\nFEATURES_NUM = len(features)\nALPHA = 0.1\nBETA = 0.9\nGRAD_TOL = 0.001\nEPOCHS = 150\nTEST_BEGIN, TEST_END = 180, 220\n",
"_____no_output_____"
]
],
[
[
"( 5 ) Створюємо та тренуємо модель",
"_____no_output_____"
]
],
[
[
"model = utils.Model(num_features=FEATURES_NUM)\nmodel.fit(X, Y, batch_size=BATCH_SIZE, grad_tol=GRAD_TOL, epochs=EPOCHS)",
"_____no_output_____"
]
],
[
[
"( 6 ) Тестуємо модель",
"_____no_output_____"
]
],
[
[
"x_test = X[TEST_BEGIN:TEST_END]\ny_test = Y[TEST_BEGIN:TEST_END]\ny_predicted = model.predict_proba(x_test)\n\nprint(f\" - - - Predicted Y - - - \\n{y_predicted}\")\nprint(f\"\\n - - - Real Y - - - \\n{y_test}\")\n\n",
"_____no_output_____"
]
]
] |
[
"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"
]
] |
cb7c3adc0e10bcd854a488927143ecc82f274ee6
| 259,278 |
ipynb
|
Jupyter Notebook
|
local-experiments.ipynb
|
OliverDudgeon/QSync
|
34adbcf37d501b803aa000b0421ce22fb7934e9b
|
[
"MIT"
] | null | null | null |
local-experiments.ipynb
|
OliverDudgeon/QSync
|
34adbcf37d501b803aa000b0421ce22fb7934e9b
|
[
"MIT"
] | null | null | null |
local-experiments.ipynb
|
OliverDudgeon/QSync
|
34adbcf37d501b803aa000b0421ce22fb7934e9b
|
[
"MIT"
] | null | null | null | 870.060403 | 149,616 | 0.951191 |
[
[
[
"import os\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport qiskit.ignis.mitigation.measurement as mc\r\nfrom dotenv import load_dotenv\r\nfrom numpy import pi\r\nfrom qiskit import (IBMQ, Aer, ClassicalRegister, QuantumCircuit,\r\n QuantumRegister, transpile)\r\nfrom qiskit.ignis.verification.tomography import (StateTomographyFitter,\r\n state_tomography_circuits)\r\nfrom qiskit.providers.aer import AerSimulator, noise\r\nfrom qiskit.providers.ibmq.managed import IBMQJobManager\r\nfrom qiskit.quantum_info import partial_trace\r\nfrom qutip import Bloch, Bloch3d, Qobj\r\nfrom tqdm import tqdm\r\nfrom tqdm.contrib import tenumerate\r\n\r\nfrom sync_calcs import dm2bloch, spin_husimi_qfunc, spin_S_measure\r\nfrom sync_gates import add_tomography\r\nfrom sync_plots import *\r\n\r\nload_dotenv()\r\n\r\nimport logging\r\n\r\nlogging.getLogger('qiskit.providers.ibmq').setLevel(logging.ERROR)\r\n",
"_____no_output_____"
],
[
"backend = Aer.get_backend('statevector_simulator')",
"_____no_output_____"
]
],
[
[
"# Parameters",
"_____no_output_____"
]
],
[
[
"# Simulation Steps\r\nSIM_STEPS = 5000\r\n\r\n# Qubits of physical device to use\r\n# Ordered from zero\r\nmain = 0\r\nancilla = 1\r\n\r\ngain_amp = 1\r\nloss_amp = 0.1\r\nm = min(loss_amp, gain_amp)\r\n\r\ndetuning = 3 * m\r\nsignal_strength = 2 * m\r\ndt = 0.5",
"_____no_output_____"
],
[
"# Plotting constants\r\nn = 20 # angle array size scale\r\n\r\ntheta = np.linspace(0, np.pi, n)\r\nphi = np.linspace(-np.pi, np.pi, 2 * n).reshape(-1, 1) # 1D vector -> 2D column vector",
"_____no_output_____"
]
],
[
[
"# Circuit",
"_____no_output_____"
]
],
[
[
"def generate_circuit(time_steps, detuning, signal_strength, steps, main, ancilla):\r\n qreg_q = QuantumRegister(max(main, ancilla) + 1, \"q\")\r\n creg_c = ClassicalRegister(2, \"c\")\r\n\r\n qc = QuantumCircuit(qreg_q, creg_c)\r\n\r\n for i in range(steps):\r\n if hasattr(time_steps, \"__iter__\"):\r\n dt = time_steps[i]\r\n else:\r\n dt = time_steps\r\n theta_d = 2 * np.arcsin(np.sqrt(loss_amp * dt))\r\n theta_g = 2 * np.arcsin(np.sqrt(gain_amp * dt))\r\n\r\n theta = signal_strength * dt\r\n phi = pi - detuning * dt / 2\r\n lam = pi - detuning * dt / 2\r\n\r\n qc.u(theta, phi, lam, qreg_q[main])\r\n\r\n # Loss CU\r\n # qc.cu(theta_d, 0, 0, 0, qreg_q[main], qreg_q[ancilla])\r\n # qc.cx(qreg_q[ancilla], qreg_q[main])\r\n # qc.measure(qreg_q[ancilla], creg_c[0])\r\n # qc.reset(qreg_q[ancilla])\r\n\r\n # Loss 2xCX\r\n qc.u(pi / 2, -pi, 0, qreg_q[main])\r\n qc.u(-theta_d / 2, -pi / 2, pi, qreg_q[ancilla])\r\n qc.cx(qreg_q[ancilla], qreg_q[main])\r\n qc.u(pi / 2, -pi / 2, 0, qreg_q[main])\r\n qc.u(-theta_d / 2, pi, pi / 2, qreg_q[ancilla])\r\n qc.cx(qreg_q[ancilla], qreg_q[main])\r\n qc.u(0, 0, -pi / 2, qreg_q[main])\r\n qc.u(0, 0, -pi / 2, qreg_q[ancilla])\r\n qc.measure(qreg_q[ancilla], creg_c[0])\r\n qc.reset(qreg_q[ancilla])\r\n\r\n # # Gain\r\n qc.u(-pi, 0, 0, qreg_q[main])\r\n qc.cx(qreg_q[main], qreg_q[ancilla])\r\n qc.cu(theta_g, 0, 0, 0, qreg_q[main], qreg_q[ancilla])\r\n qc.cx(qreg_q[main], qreg_q[ancilla])\r\n qc.u(pi, 0, 0, qreg_q[main])\r\n qc.measure(qreg_q[ancilla], creg_c[0])\r\n qc.reset(qreg_q[ancilla])\r\n\r\n return qc\r\n",
"_____no_output_____"
],
[
"gain_amp=0.1\r\nloss_amp=1\r\nDR = 1\r\ndetunings = np.linspace(-DR, DR, n)",
"_____no_output_____"
],
[
"S = np.zeros([2*n, n])\r\n\r\nfor i, D in enumerate(detunings):\r\n circuit = generate_circuit(dt, D, loss_amp, SIM_STEPS, main, ancilla)\r\n circuit = transpile(circuit, backend)\r\n job = backend.run(circuit)\r\n prod_state = job.result().get_statevector(0)\r\n state = partial_trace(prod_state, [1])\r\n s = state.data\r\n s[0,0], s[1,1] = s[1,1], s[0,0]\r\n s[0,1], s[1,0] = s[1,0], s[0,1]\r\n state = Qobj(s)\r\n Q = spin_husimi_qfunc(state, theta, phi)\r\n s = spin_S_measure(theta, Q)\r\n\r\n S[:, i] = s",
"_____no_output_____"
],
[
"# circuit = generate_circuit(dt, 0.1, loss_amp, 1000, main, ancilla)\r\n# circuit = transpile(circuit, backend)\r\n# job = backend.run(circuit)\r\n# prod_state = job.result().get_statevector(0)\r\n# state = partial_trace(prod_state, [1])\r\n# s = state.data\r\n# # s[0,0], s[1,1] = s[1,1], s[0,0]\r\n# # s[0,1], s[1,0] = s[1,0], s[0,1]\r\n# state = Qobj(s)\r\n# state",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=set_size(DOCUMENT_WIDTH * 2))\r\n\r\nDETUNING, PHI = np.meshgrid(detunings / loss_amp, phi)\r\n\r\ncquad = ax.contourf(PHI, DETUNING, S, 100)\r\nfor c in cquad.collections:\r\n c.set_edgecolor(\"face\")\r\nax.set_xlabel(r'$\\varphi$')\r\nax.set_ylabel(r'$\\Delta/\\Gamma_d$')\r\n\r\ncbar = fig.colorbar(cquad)\r\ncbar.set_label(r\"$S(\\varphi\\,|\\,\\hat\\rho)$\", rotation=270, labelpad=20)\r\ncbar.ax.yaxis.set_major_locator(MultipleLocator(base=0.02))\r\ncbar.ax.yaxis.set_major_formatter(FuncFormatter(lambda v, pos: f\"{v:.2f}\"))\r\nangle_xaxis(ax)\r\n\r\n",
"_____no_output_____"
],
[
"calc_and_plot_Q_and_S(Qobj(state.data))\r\n\r\nb = Bloch()\r\n\r\nb.add_states(state)\r\n\r\nb.show()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7c3cb36561f967791c5909d9e253c1d8e36a17
| 6,311 |
ipynb
|
Jupyter Notebook
|
examples/notebooks/models_training/vaegan_training.ipynb
|
clementchadebec/benchmark_VAE
|
943e231f9e5dfa40b4eec14d4536f1c229ad9be1
|
[
"Apache-2.0"
] | 143 |
2021-10-17T08:43:33.000Z
|
2022-03-31T11:10:53.000Z
|
examples/notebooks/models_training/vaegan_training.ipynb
|
louis-j-vincent/benchmark_VAE
|
943e231f9e5dfa40b4eec14d4536f1c229ad9be1
|
[
"Apache-2.0"
] | 6 |
2022-01-21T17:40:09.000Z
|
2022-03-16T13:09:22.000Z
|
examples/notebooks/models_training/vaegan_training.ipynb
|
louis-j-vincent/benchmark_VAE
|
943e231f9e5dfa40b4eec14d4536f1c229ad9be1
|
[
"Apache-2.0"
] | 18 |
2021-12-16T15:17:08.000Z
|
2022-03-15T01:30:13.000Z
| 23.117216 | 115 | 0.548091 |
[
[
[
"# If you run on colab uncomment the following line\n#!pip install git+https://github.com/clementchadebec/benchmark_VAE.git",
"_____no_output_____"
],
[
"import torch\nimport torchvision.datasets as datasets\n\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"mnist_trainset = datasets.MNIST(root='../../data', train=True, download=True, transform=None)\n\ntrain_dataset = mnist_trainset.data[:-10000].reshape(-1, 1, 28, 28) / 255.\neval_dataset = mnist_trainset.data[-10000:].reshape(-1, 1, 28, 28) / 255.",
"_____no_output_____"
],
[
"from pythae.models import VAEGAN, VAEGANConfig\nfrom pythae.trainers import CoupledOptimizerAdversarialTrainer, CoupledOptimizerAdversarialTrainerConfig\nfrom pythae.pipelines.training import TrainingPipeline\nfrom pythae.models.nn.benchmarks.mnist import Encoder_VAE_MNIST, Decoder_AE_MNIST, LayeredDiscriminator_MNIST",
"_____no_output_____"
],
[
"config = CoupledOptimizerAdversarialTrainerConfig(\n output_dir='my_model',\n learning_rate=1e-4,\n batch_size=100,\n num_epochs=100,\n)\n\n\nmodel_config = VAEGANConfig(\n input_dim=(1, 28, 28),\n latent_dim=16,\n adversarial_loss_scale=0.8,\n reconstruction_layer= 3,\n margin=0.4,\n equilibrium= 0.68\n\n)\n\nmodel = VAEGAN(\n model_config=model_config,\n encoder=Encoder_VAE_MNIST(model_config), \n decoder=Decoder_AE_MNIST(model_config) \n)",
"_____no_output_____"
],
[
"pipeline = TrainingPipeline(\n training_config=config,\n model=model\n)",
"_____no_output_____"
],
[
"pipeline(\n train_data=train_dataset,\n eval_data=eval_dataset\n)",
"_____no_output_____"
],
[
"import os",
"_____no_output_____"
],
[
"last_training = sorted(os.listdir('my_model'))[-1]\ntrained_model = VAEGAN.load_from_folder(os.path.join('my_model', last_training, 'final_model'))",
"_____no_output_____"
],
[
"from pythae.samplers import NormalSampler",
"_____no_output_____"
],
[
"# create normal sampler\nnormal_samper = NormalSampler(\n model=trained_model\n)",
"_____no_output_____"
],
[
"# sample\ngen_data = normal_samper.sample(\n num_samples=25\n)",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# show results with normal sampler\nfig, axes = plt.subplots(nrows=5, ncols=5, figsize=(10, 10))\n\nfor i in range(5):\n for j in range(5):\n axes[i][j].imshow(gen_data[i*5 +j].cpu().squeeze(0), cmap='gray')\n axes[i][j].axis('off')\nplt.tight_layout(pad=0.)",
"_____no_output_____"
],
[
"from pythae.samplers import GaussianMixtureSampler, GaussianMixtureSamplerConfig",
"_____no_output_____"
],
[
"# set up gmm sampler config\ngmm_sampler_config = GaussianMixtureSamplerConfig(\n n_components=10\n)\n\n# create gmm sampler\ngmm_sampler = GaussianMixtureSampler(\n sampler_config=gmm_sampler_config,\n model=trained_model\n)\n\n# fit the sampler\ngmm_sampler.fit(train_dataset)",
"_____no_output_____"
],
[
"# sample\ngen_data = gmm_sampler.sample(\n num_samples=25\n)",
"_____no_output_____"
],
[
"# show results with gmm sampler\nfig, axes = plt.subplots(nrows=5, ncols=5, figsize=(10, 10))\n\nfor i in range(5):\n for j in range(5):\n axes[i][j].imshow(gen_data[i*5 +j].cpu().squeeze(0), cmap='gray')\n axes[i][j].axis('off')\nplt.tight_layout(pad=0.)",
"_____no_output_____"
]
],
[
[
"## ... the other samplers work the same",
"_____no_output_____"
]
]
] |
[
"code",
"markdown"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb7c401770916d9067366be8a0fddc284bd7e914
| 5,953 |
ipynb
|
Jupyter Notebook
|
notebooks/.ipynb_checkpoints/sampling-checkpoint.ipynb
|
samiraabnar/awd-lstm-lm
|
c800038ed257f0ff033ea550c3ef5e670aff2fa2
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/.ipynb_checkpoints/sampling-checkpoint.ipynb
|
samiraabnar/awd-lstm-lm
|
c800038ed257f0ff033ea550c3ef5e670aff2fa2
|
[
"BSD-3-Clause"
] | null | null | null |
notebooks/.ipynb_checkpoints/sampling-checkpoint.ipynb
|
samiraabnar/awd-lstm-lm
|
c800038ed257f0ff033ea550c3ef5e670aff2fa2
|
[
"BSD-3-Clause"
] | null | null | null | 43.772059 | 1,380 | 0.572316 |
[
[
[
"###############################################################################\n# Language Modeling on Penn Tree Bank\n#\n# This file generates new sentences sampled from the language model\n#\n###############################################################################\n\nimport argparse\n\nimport torch\nfrom torch.autograd import Variable\n\nimport data\n\nparser = argparse.ArgumentParser(description='PyTorch PTB Language Model')\n\n# Model parameters.\nparser.add_argument('--data', type=str, default='./data/penn',\n help='location of the data corpus')\nparser.add_argument('--model', type=str, default='LSTM',\n help='type of recurrent net (LSTM, QRNN)')\nparser.add_argument('--checkpoint', type=str, default='./model.pt',\n help='model checkpoint to use')\nparser.add_argument('--outf', type=str, default='generated.txt',\n help='output file for generated text')\nparser.add_argument('--words', type=int, default='1000',\n help='number of words to generate')\nparser.add_argument('--seed', type=int, default=1111,\n help='random seed')\nparser.add_argument('--cuda', action='store_true',\n help='use CUDA')\nparser.add_argument('--temperature', type=float, default=1.0,\n help='temperature - higher will increase diversity')\nparser.add_argument('--log-interval', type=int, default=100,\n help='reporting interval')\nparser.add_argument('-f')\nargs = parser.parse_args()",
"_____no_output_____"
],
[
"# Set the random seed manually for reproducibility.\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available():\n if not args.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n else:\n torch.cuda.manual_seed(args.seed)\n\nif args.temperature < 1e-3:\n parser.error(\"--temperature has to be greater or equal 1e-3\")\n\nargs.checkpoint = \"../pwc_bs64_concat.pt\"\nwith open(args.checkpoint, 'rb') as f:\n model = torch.load(f)\n \nmodel.eval()\nif args.model == 'QRNN':\n model.reset()\n\nif args.cuda:\n model.cuda()\nelse:\n model.cpu()",
"WARNING: You have a CUDA device, so you should probably run with --cuda\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cb7c48cf1de2f62b3adec4af66185f50e8bdb56d
| 7,000 |
ipynb
|
Jupyter Notebook
|
Jupyter Notebook/Iris Jupyternotebook.ipynb
|
hafidh561/Machine-Learning-Predict-Iris-Species
|
6561f290326cf3f0d184da6e6f8d08a2ebc67d54
|
[
"MIT"
] | null | null | null |
Jupyter Notebook/Iris Jupyternotebook.ipynb
|
hafidh561/Machine-Learning-Predict-Iris-Species
|
6561f290326cf3f0d184da6e6f8d08a2ebc67d54
|
[
"MIT"
] | null | null | null |
Jupyter Notebook/Iris Jupyternotebook.ipynb
|
hafidh561/Machine-Learning-Predict-Iris-Species
|
6561f290326cf3f0d184da6e6f8d08a2ebc67d54
|
[
"MIT"
] | null | null | null | 24.822695 | 94 | 0.434571 |
[
[
[
"from sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"df = pd.read_csv('iris.csv')\ndf['species'] = df['species'].map({\n 'setosa': 0,\n 'versicolor': 1,\n 'virginica': 2\n})\ndf.head()",
"_____no_output_____"
],
[
"x = df.iloc[:, 0:-1]\ny = df['species']\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=3)",
"_____no_output_____"
],
[
"from tensorflow import keras\nfrom tensorflow.keras import layers\n\nmodel = keras.Sequential([\n layers.Dense(units=512, activation='relu', input_shape=[4]),\n layers.Dense(units=512, activation='relu'),\n layers.Dense(units=512, activation='relu'),\n layers.Dense(units=3, activation='softmax')\n])\n\nmodel.compile(\n optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy']\n)\n\nhistory = model.fit(\n x_train, y_train,\n validation_data=(x_test, y_test),\n batch_size=512,\n epochs=50,\n verbose=0\n)",
"_____no_output_____"
],
[
"history_df = pd.DataFrame(history.history)\nprint(history_df['val_accuracy'].max())\nprint(history_df['accuracy'].max())",
"0.9777777791023254\n0.9904761910438538\n"
],
[
"model.save('iris_model.h5')",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7c4c12e6c8a699b0c64bee37d3c734218ac441
| 2,201 |
ipynb
|
Jupyter Notebook
|
Metody Numeryczne 2021/13. ODE/lecture_part1.ipynb
|
piotrbullet/public_lectures
|
aa0c9d71a4e87e11a99be01fe18ebe1df2b89208
|
[
"CC-BY-4.0"
] | null | null | null |
Metody Numeryczne 2021/13. ODE/lecture_part1.ipynb
|
piotrbullet/public_lectures
|
aa0c9d71a4e87e11a99be01fe18ebe1df2b89208
|
[
"CC-BY-4.0"
] | null | null | null |
Metody Numeryczne 2021/13. ODE/lecture_part1.ipynb
|
piotrbullet/public_lectures
|
aa0c9d71a4e87e11a99be01fe18ebe1df2b89208
|
[
"CC-BY-4.0"
] | null | null | null | 19.13913 | 91 | 0.468878 |
[
[
[
"%%HTML\n<style>\n.rendered_html table, .rendered_html th, .rendered_html tr, .rendered_html td {\n font-size: 100%;\n}\n</style>",
"_____no_output_____"
]
],
[
[
"# Metody Numeryczne\n\n## Rozwiązywanie równań różniczkowych zwyczajnych\n\n\n\n### dr hab. inż. Jerzy Baranowski, Prof.AGH",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport numpy as np\n%matplotlib inline\ndef normalize_vector(v):\n v=np.array(v)\n return v/np.linalg.norm(v)\nimport matplotlib as mpl\nplt.style.context('seaborn-white')\nmpl.rcParams['figure.dpi']= 200",
"_____no_output_____"
]
],
[
[
"## Równanie różniczkowe pierwszego rzędu\n\n$$\n\\begin{aligned}\n\\dot{y}={}&f(x,y)\\\\\ny(x_0) = y_0\n\\end{aligned}\n$$\n\n",
"_____no_output_____"
],
[
"## Równanie różniczkowe drugiego rzędu\n\n$$\n\\begin{aligned}\n\\dot{y}={}&f(x,y)\\\\\ny(x_0) = y_0\n\\end{aligned}\n\n\\Rightarrow\n\n\n$$\n",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb7c6717033bd6ba0c7a5b0fa0011c061c9b67e3
| 64,221 |
ipynb
|
Jupyter Notebook
|
Segmentation/PointRend - Image Segmentation as Rendering/PointRend-Paper.ipynb
|
koreaunitas/Deep-Learning-Paper-Reviews_
|
72a256935fd5154cfcef60fdf5dad447dd1e5c87
|
[
"MIT"
] | 2 |
2022-01-03T07:21:47.000Z
|
2022-01-03T08:07:58.000Z
|
Segmentation/PointRend - Image Segmentation as Rendering/PointRend-Paper.ipynb
|
koreaunitas/Deep-Learning-Paper-Reviews_
|
72a256935fd5154cfcef60fdf5dad447dd1e5c87
|
[
"MIT"
] | null | null | null |
Segmentation/PointRend - Image Segmentation as Rendering/PointRend-Paper.ipynb
|
koreaunitas/Deep-Learning-Paper-Reviews_
|
72a256935fd5154cfcef60fdf5dad447dd1e5c87
|
[
"MIT"
] | 1 |
2022-01-15T23:14:48.000Z
|
2022-01-15T23:14:48.000Z
| 62.109284 | 311 | 0.543654 |
[
[
[
"# **PointRend - Image Segmentation as Rendering**\n\n**Authors: Alexander Kirillov, Yuxin Wu, Kaiming H,e Ross Girshick - Facebook AI Research (FAIR)**\n\n**Official Github**: https://github.com/facebookresearch/detectron2/tree/main/projects/PointRend\n\n---\n\n**Edited By Su Hyung Choi (Key Summary & Code Practice)**\n\nIf you have any issues on this scripts, please PR to the repository below.\n\n**[Github: @JonyChoi - Computer Vision Paper Reviews]** https://github.com/jonychoi/Computer-Vision-Paper-Reviews\n\nEdited Jan 10 2022\n\n---",
"_____no_output_____"
],
[
"### **Abstract**\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n <i>We present a new method for efficient high-quality\n image segmentation of objects and scenes. By analogizing\n classical computer graphics methods for efficient rendering\n with over- and undersampling challenges faced in pixel\n labeling tasks, we develop a unique perspective of image\n segmentation as a rendering problem. From this vantage,\n we present the PointRend (Point-based Rendering) neural\n network module: a module that performs point-based\n segmentation predictions at adaptively selected locations\n based on an iterative subdivision algorithm. PointRend\n can be flexibly applied to both instance and semantic\n segmentation tasks by building on top of existing state-ofthe-art models. While many concrete implementations of\n the general idea are possible, we show that a simple design\n already achieves excellent results. Qualitatively, PointRend\n outputs crisp object boundaries in regions that are oversmoothed by previous methods. Quantitatively, PointRend\n yields significant gains on COCO and Cityscapes, for both\n instance and semantic segmentation. PointRend’s efficiency\n enables output resolutions that are otherwise impractical\n in terms of memory or computation compared to existing\n approaches. Code has been made available at https://\n github.com/facebookresearch/detectron2/\n tree/master/projects/PointRend.</i>\n </p>\n </td>\n </tr>\n </tbody>\n</table>",
"_____no_output_____"
],
[
"### **Introduction**\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n Image segmentation tasks involve mapping pixels sampled on a regular grid to a label map, or a set of label maps,\n on the same grid. For semantic segmentation, the label map\n indicates the predicted category at each pixel. In the case of\n instance segmentation, a binary foreground vs. background\n map is predicted for each detected object. The modern tools\n of choice for these tasks are built on convolutional neural\n networks (CNNs) [27, 26].\n </p>\n \n<table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/figure1.png\" width=\"300\" />\n </td>\n <td>\n <img src=\"./imgs/figure1_description.png\" width=\"350\" />\n </td>\n </tr>\n </tbody>\n</table>\n <p>\n CNNs for image segmentation typically operate on regular grids: the input image is a regular grid of pixels, their\n hidden representations are feature vectors on a regular grid,\n and their outputs are label maps on a regular grid. Regular grids are convenient, but not necessarily computationally ideal for image segmentation. The label maps predicted by these networks should be mostly smooth, i.e.,\n neighboring pixels often take the same label, because highfrequency regions are restricted to the sparse boundaries between objects. A regular grid will unnecessarily oversample\n the smooth areas while simultaneously undersampling object boundaries. The result is excess computation in smooth\n regions and blurry contours (Fig. 1, upper-left). Image segmentation methods often predict labels on a low-resolution\n regular grid, e.g., 1/8-th of the input [35] for semantic segmentation, or 28×28 [19] for instance segmentation, as a\n compromise between undersampling and oversampling.\n </p>\n <p>\n Analogous sampling issues have been studied for\n decades in computer graphics. For example, a renderer\n maps a model (e.g., a 3D mesh) to a rasterized image, i.e. a regular grid of pixels. While the output is on a regular grid,\n computation is not allocated uniformly over the grid. Instead, a common graphics strategy is to compute pixel values at an irregular subset of adaptively selected points in the\n image plane. The classical subdivision technique of [48], as\n an example, yields a quadtree-like sampling pattern that efficiently renders an anti-aliased, high-resolution image.\n </p>\n <p>\n The central idea of this paper is to view image segmentation as a rendering problem and to adapt classical\n ideas from computer graphics to efficiently “render” highquality label maps (see Fig. 1, bottom-left). We encapsulate this computational idea in a new neural network\n module, called PointRend, that uses a subdivision strategy\n to adaptively select a non-uniform set of points at which\n to compute labels. PointRend can be incorporated into\n popular meta-architectures for both instance segmentation\n (e.g., Mask R-CNN [19]) and semantic segmentation (e.g.,\n FCN [35]). Its subdivision strategy efficiently computes\n high-resolution segmentation maps using an order of magnitude fewer floating-point operations than direct, dense\n computation.\n </p>\n <img src=\"./imgs/figure2.png\" />\n <p>\n PointRend is a general module that admits many possible implementations. Viewed abstractly, a PointRend\n module accepts one or more typical CNN feature maps\n f(xi, yi) that are defined over regular grids, and outputs\n high-resolution predictions p(x0i, y0i) over a finer grid. Instead of making excessive predictions over all points on the\n output grid, PointRend makes predictions only on carefully\n selected points. To make these predictions, it extracts a\n point-wise feature representation for the selected points by\n interpolating f, and uses a small point head subnetwork to\n predict output labels from the point-wise features. We will\n present a simple and effective PointRend implementation.\n </p>\n <p>\n We evaluate PointRend on instance and semantic segmentation tasks using the COCO [29] and Cityscapes [9]\n benchmarks. Qualitatively, PointRend efficiently computes\n sharp boundaries between objects, as illustrated in Fig. 2\n and Fig. 8. We also observe quantitative improvements even\n though the standard intersection-over-union based metrics\n for these tasks (mask AP and mIoU) are biased towards\n object-interior pixels and are relatively insensitive to boundary improvements. PointRend improves strong Mask RCNN and DeepLabV3 [5] models by a significant margin.\n </p>\n </td>\n </tr>\n </tbody>\n</table>",
"_____no_output_____"
],
[
"### **2. Related Work**\n\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n <strong>Rendering</strong> algorithms in computer graphics output a regular grid of pixels. However, they usually compute these\n pixel values over a non-uniform set of points. Efficient procedures like subdivision [48] and adaptive sampling [38, 42]\n refine a coarse rasterization in areas where pixel values\n have larger variance. Ray-tracing renderers often use oversampling [50], a technique that samples some points more\n densely than the output grid to avoid aliasing effects. Here,\n we apply classical subdivision to image segmentation.\n </p>\n <p>\n Non-uniform grid representations. Computation on regular grids is the dominant paradigm for 2D image analysis, but this is not the case for other vision tasks. In 3D\n shape recognition, large 3D grids are infeasible due to cubic scaling. Most CNN-based approaches do not go beyond coarse 64×64×64 grids [12, 8]. Instead, recent works\n consider more efficient non-uniform representations such as\n meshes [47, 14], signed distance functions [37], and octrees [46]. Similar to a signed distance function, PointRend\n can compute segmentation values at any point.\n </p>\n <p>\n Recently, Marin et al. [36] propose an efficient semantic\n segmentation network based on non-uniform subsampling\n of the input image prior to processing with a standard semantic segmentation network. PointRend, in contrast, focuses on non-uniform sampling at the output. It may be\n possible to combine the two approaches, though [36] is currently unproven for instance segmentation.\n </p>\n <p>\n <strong>Instance segmentation</strong> methods based on the Mask RCNN meta-architecture [19] occupy top ranks in recent\n challenges [32, 3]. These region-based architectures typically predict masks on a 28×28 grid irrespective of object size. This is sufficient for small objects, but for large\n objects it produces undesirable “blobby” output that oversmooths the fine-level details of large objects (see Fig. 1,\n top-left). Alternative, bottom-up approaches group pixels\n to form object masks [31, 1, 25]. These methods can produce more detailed output, however, they lag behind regionbased approaches on most instance segmentation benchmarks [29, 9, 40]. TensorMask [7], an alternative slidingwindow method, uses a sophisticated network design to\n predict sharp high-resolution masks for large objects, but\n its accuracy also lags slightly behind. In this paper, we\n show that a region-based segmentation model equipped\n with PointRend can produce masks with fine-level details\n while improving the accuracy of region-based approaches.\n </p>\n <p>\n <strong>Semantic segmentation.</strong> Fully convolutional networks\n (FCNs) [35] are the foundation of modern semantic segmentation approaches. They often predict outputs that have\n lower resolution than the input grid and use bilinear upsampling to recover the remaining 8-16× resolution. Results\n may be improved with dilated/atrous convolutions that replace some subsampling layers [4, 5] at the expense of more\n memory and computation.\n </p> \n <table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/figure3.png\" width=\"300\" />\n </td>\n <td>\n <img src=\"./imgs/figure3_description.png\" width=\"290\" />\n </td>\n </tr>\n </tbody>\n</table>\n <p>\n Alternative approaches include encoder-decoder achitectures [6, 24, 44, 45] that subsample the grid representation\n in the encoder and then upsample it in the decoder, using\n skip connections [44] to recover filtered details. Current\n approaches combine dilated convolutions with an encoderdecoder structure [6, 30] to produce output on a 4× sparser\n grid than the input grid before applying bilinear interpolation. In our work, we propose a method that can efficiently\n predict fine-level details on a grid as dense as the input grid.\n </p>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **3. Method**\n\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n We analogize image segmentation (of objects and/or\n scenes) in computer vision to image rendering in computer\n graphics. Rendering is about displaying a model (e.g., a\n 3D mesh) as a regular grid of pixels, i.e., an image. While\n the output representation is a regular grid, the underlying\n physical entity (e.g., the 3D model) is continuous and its\n physical occupancy and other attributes can be queried at\n any real-value point on the image plane using physical and\n geometric reasoning, such as ray-tracing.\n </p>\n <p>\n Analogously, in computer vision, we can think of an image segmentation as the occupancy map of an underlying\n continuous entity, and the segmentation output, which is a\n regular grid of predicted labels, is “rendered” from it. The\n entity is encoded in the network’s feature maps and can be\n accessed at any point by interpolation. A parameterized\n function, that is trained to predict occupancy from these interpolated point-wise feature representations, is the counterpart to physical and geometric reasoning.\n </p>\n <p>\n Based on this analogy, we propose PointRend (Pointbased Rendering) as a methodology for image segmentation using point representations. A PointRend module accepts one or more typical CNN feature maps of C channels f ∈ R\n C×H×W , each defined over a regular grid (that\n is typically 4× to 16× coarser than the image grid), and outputs predictions for the K class labels p ∈ R\n K×H0×W0\n over a regular grid of different (and likely higher) resolution. A PointRend module consists of three main components: (i) A point selection strategy chooses a small number\n of real-value points to make predictions on, avoiding excessive computation for all pixels in the high-resolution output\n grid. (ii) For each selected point, a point-wise feature representation is extracted. Features for a real-value point are\n computed by bilinear interpolation of f, using the point’s 4\n nearest neighbors that are on the regular grid of f. As a result, it is able to utilize sub-pixel information encoded in the\n channel dimension of f to predict a segmentation that has\n higher resolution than f. (iii) A point head: a small neural network trained to predict a label from this point-wise\n feature representation, independently for each point.\n </p>\n <p>\n The PointRend architecture can be applied to instance\n segmentation (e.g., on Mask R-CNN [19]) and semantic\n segmentation (e.g., on FCNs [35]) tasks. For instance segmentation, PointRend is applied to each region. It computes masks in a coarse-to-fine fashion by making predictions over a set of selected points (see Fig. 3). For semantic segmentation, the whole image can be considered as a\n single region, and thus without loss of generality we will\n describe PointRend in the context of instance segmentation.\n We discuss the three main components in more detail next.\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **3.1. Point Selection for Inference and Training**\n\n<table>\n <thead>\n <tr>\n <th>\n Point Selection for Inference and Training\n </th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <p>\n At the core of our method is the idea of flexibly and\n adaptively selecting points in the image plane at which to\n predict segmentation labels. Intuitively, these points should\n be located more densely near high-frequency areas, such as\n object boundaries, analogous to the anti-aliasing problem in\n ray-tracing. We develop this idea for inference and training.\n </p>\n <p>\n <strong>Inference.</strong> Our selection strategy for inference is inspired\n by the classical technique of adaptive subdivision [48] in\n computer graphics. The technique is used to efficiently render high resolutions images (e.g., via ray-tracing) by computing only at locations where there is a high chance that\n the value is significantly different from its neighbors; for all\n other locations the values are obtained by interpolating already computed output values (starting from a coarse grid).\n </p>\n <p>\n For each region, we iteratively “render” the output mask\n in a coarse-to-fine fashion. The coarsest level prediction is\n made on the points on a regular grid (e.g., by using a standard coarse segmentation prediction head). In each iteration, PointRend upsamples its previously predicted segmentation using bilinear interpolation and then selects the N\n most uncertain points (e.g., those with probabilities closest\n to 0.5 for a binary mask) on this denser grid. PointRend then\n computes the point-wise feature representation (described\n shortly in §3.2) for each of these N points and predicts their\n labels. This process is repeated until the segmentation is upsampled to a desired resolution. One step of this procedure is illustrated on a toy example in Fig. 4.\n </p>\n <table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/figure4.png\" width=\"400\"/>\n </td>\n <td>\n <img src=\"./imgs/figure5.png\" width=\"380\"/>\n </td>\n </tr>\n </tbody>\n</table>\n <p>\n With a desired output resolution of M×M pixels and a\n starting resolution of M0×M0, PointRend requires no more\n than N log2\n M\n M0\n point predictions. This is much smaller\n than M×M, allowing PointRend to make high-resolution\n predictions much more effectively. For example, if M0 is\n 7 and the desired resolutions is M=224, then 5 subdivision\n steps are preformed. If we select N=282 points at each\n step, PointRend makes predictions for only 282\n ·4.25 points,\n which is 15 times smaller than 2242\n . Note that fewer than\n N log2\n M\n M0\n points are selected overall because in the first\n subdivision step only 142 points are available.\n </p>\n <p>\n <strong>Training.</strong> During training, PointRend also needs to select\n points at which to construct point-wise features for training the point head. In principle, the point selection strategy\n can be similar to the subdivision strategy used in inference.\n However, subdivision introduces sequential steps that are\n less friendly to training neural networks with backpropagation. Instead, for training we use a non-iterative strategy\n based on random sampling.\n </p>\n <p>\n The sampling strategy selects N points on a feature map to train on.1\n It is designed to bias selection towards uncertain regions, while also retaining\n some degree of uniform coverage, using three principles.\n (i) Over generation: we over-generate candidate points by randomly sampling kN points (k>1) from a uniform distribution. (ii) Importance sampling: we focus on points with\n uncertain coarse predictions by interpolating the coarse\n prediction values at all kN points and computing a taskspecific uncertainty estimate (defined in §4 and §5). The\n most uncertain βN points (β ∈ [0, 1]) are selected from\n the kN candidates. (iii) Coverage: the remaining (1 − β)N\n points are sampled from a uniform distribution. We illustrate this procedure with different settings, and compare it\n to regular grid selection, in Fig. 5.\n </p>\n <p>\n At training time, predictions and loss functions are only\n computed on the N sampled points (in addition to the coarse\n segmentation), which is simpler and more efficient than\n backpropagation through subdivision steps. This design is\n similar to the parallel training of RPN + Fast R-CNN in a\n Faster R-CNN system [13], whose inference is sequential.\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **3.2. Point-wise Representation and Point Head**\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n PointRend constructs point-wise features at selected\n points by combining (e.g., concatenating) two feature types,\n fine-grained and coarse prediction features, described next.\n </p>\n <p>\n <strong>Fine-grained features.</strong> To allow PointRend to render fine\n segmentation details we extract a feature vector at each sampled point from CNN feature maps. Because a point is a\n real-value 2D coordinate, we perform bilinear interpolation\n on the feature maps to compute the feature vector, following standard practice [22, 19, 10]. Features can be extracted\n from a single feature map (e.g., res2 in a ResNet); they can\n also be extracted from multiple feature maps (e.g., res2 to\n res5, or their feature pyramid [28] counterparts) and concatenated, following the Hypercolumn method [17].\n </p>\n <p>\n <strong>Coarse prediction features.</strong> The fine-grained features enable resolving detail, but are also deficient in two regards.\n First, they do not contain region-specific information and\n thus the same point overlapped by two instances’ bounding boxes will have the same fine-grained features. Yet, the\n point can only be in the foreground of one instance. Therefore, for the task of instance segmentation, where different\n regions may predict different labels for the same point, additional region-specific information is needed.\n </p>\n <p>\n Second, depending on which feature maps are used for\n the fine-grained features, the features may contain only relatively low-level information (e.g., we will use res2 with\n DeepLabV3). In this case, a feature source with more contextual and semantic information can be helpful. This issue\n affects both instance and semantic segmentation.\n </p>\n <p>\n Based on these considerations, the second feature type is\n a coarse segmentation prediction from the network, i.e., a\n K-dimensional vector at each point in the region (box) representing a K-class prediction. The coarse resolution, by\n design, provides more globalized context, while the channels convey the semantic classes. These coarse predictions are similar to the outputs made by the existing architectures,\n and are supervised during training in the same way as existing models. For instance segmentation, the coarse prediction can be, for example, the output of a lightweight 7×7\n resolution mask head in Mask R-CNN. For semantic segmentation, it can be, for example, predictions from a stride\n 16 feature map.\n </p>\n <p>\n <strong>Point head.</strong> Given the point-wise feature representation\n at each selected point, PointRend makes point-wise segmentation predictions using a simple multi-layer perceptron (MLP). This MLP shares weights across all points (and\n all regions), analogous to a graph convolution [23] or a\n PointNet [43]. Since the MLP predicts a segmentation label for each point, it can be trained by standard task-specific\n segmentation losses (described in §4 and §5).\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **4. Experiments: Instance Segmentation**\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n <strong>Datasets.</strong> We use two standard instance segmentation\n datasets: COCO [29] and Cityscapes [9]. We report the\n standard mask AP metric [29] using the median of 3 runs\n for COCO and 5 for Cityscapes (it has higher variance).\n </p>\n <p>\n COCO has 80 categories with instance-level annotation.\n We train on train2017 (∼118k images) and report results\n on val2017 (5k images). As noted in [16], the COCO\n ground-truth is often coarse and AP for the dataset may not\n fully reflect improvements in mask quality. Therefore we\n supplement COCO results with AP measured using the 80\n COCO category subset of LVIS [16], denoted by AP*.\n </p>\n <p>\n The LVIS annotations have significantly higher quality. Note\n that for AP? we use the same models trained on COCO\n and simply re-evaluate their predictions against the higherquality LVIS annotations using the LVIS evaluation API.\n Cityscapes is an ego-centric street-scene dataset with\n 8 categories, 2975 train images, and 500 validation images. The images are higher resolution compared to COCO\n (1024×2048 pixels) and have finer, more pixel-accurate\n ground-truth instance segmentations.\n </p>\n <p>\n <strong>Architecture.</strong> Our experiments use Mask R-CNN with a\n ResNet-50 [20] + FPN [28] backbone. The default mask\n head in Mask R-CNN is a region-wise FCN, which we denote by “4× conv”.2 We use this as our baseline for comparison. For PointRend, we make appropriate modifications\n to this baseline, as described next.\n </p>\n <p>\n <strong>Lightweight, coarse mask prediction head.</strong> To compute\n the coarse prediction, we replace the 4× conv mask head\n with a lighter weight design that resembles Mask R-CNN’s\n box head and produces a 7×7 mask prediction. Specifically, for each bounding box, we extract a 14×14 feature map from the P2 level of the FPN using bilinear interpolation. The features are computed on a regular grid inside the\n bounding box (this operation can seen as a simple version of\n RoIAlign). Next, we use a stride-two 2×2 convolution layer\n with 256 output channels followed by ReLU [39], which\n reduces the spatial size to 7×7. Finally, similar to Mask\n R-CNN’s box head, an MLP with two 1024-wide hidden\n layers is applied to yield a 7×7 mask prediction for each of\n the K classes. ReLU is used on the MLP’s hidden layers\n and the sigmoid activation function is applied to its outputs. \n </p>\n <p>\n <strong>PointRend.</strong> At each selected point, a K-dimensional feature vector is extracted from the coarse prediction head’s\n output using bilinear interpolation. PointRend also interpolates a 256-dimensional feature vector from the P2 level of\n the FPN. This level has a stride of 4 w.r.t. the input image.\n These coarse prediction and fine-grained feature vectors are\n concatenated. We make a K-class prediction at selected\n points using an MLP with 3 hidden layers with 256 channels. In each layer of the MLP, we supplement the 256 output channels with the K coarse prediction features to make\n the input vector for the next layer. We use ReLU inside the\n MLP and apply sigmoid to its output.\n </p>\n <p>\n <strong>Training.</strong> We use the standard 1× training schedule and\n data augmentation from Detectron2 [49] by default (full details are in the appendix). For PointRend, we sample 142\n points using the biased sampling strategy described in the\n §3.1 with k=3 and β=0.75. We use the distance between\n 0.5 and the probability of the ground truth class interpolated from the coarse prediction as the point-wise uncertainty measure. For a predicted box with ground-truth class\n c, we sum the binary cross-entropy loss for the c-th MLP\n output over the 142 points. The lightweight coarse prediction head uses the average cross-entropy loss for the mask\n predicted for class c, i.e., the same loss as the baseline 4×\n conv head. We sum all losses without any re-weighting.\n </p>\n <p>\n During training, Mask R-CNN applies the box and mask\n heads in parallel, while during inference they run as a cascade. We found that training as a cascade does not improve\n the baseline Mask R-CNN, but PointRend can benefit from\n it by sampling points inside more accurate boxes, slightly\n improving overall performance (∼0.2% AP, absolute).\n </p>\n <p>\n <strong>Inference.</strong> For inference on a box with predicted class c,\n unless otherwise specified, we use the adaptive subdivision\n technique to refine the coarse 7×7 prediction for class c to\n the 224×224 in 5 steps. At each step, we select and update\n (at most) the N=282 most uncertain points based on the\n absolute difference between the predictions and 0.5.\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n\n",
"_____no_output_____"
],
[
"### **4.1. Main Results**\n\n<table>\n <tbody>\n <tr>\n <td>\n <table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/table1.png\" width=\"520\" />\n </td>\n <td>\n <img src=\"./imgs/figure6.png\" width=\"470\" /> \n </td>\n </tr>\n </tbody>\n</table>\n <table width=\"500\">\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/table2.png\" width=\"500\" />\n <img src=\"./imgs/table2_description.png\" width=\"500\" />\n </td>\n </tr>\n </tbody>\n </table>\n <p>\n We compare PointRend to the default 4× conv head in\n Mask R-CNN in Table 1. PointRend outperforms the default head on both datasets. The gap is larger when evaluating the COCO categories using the LVIS annotations (AP*)\n and for Cityscapes, which we attribute to the superior annotation quality in these datasets. Even with the same output\n resolution PointRend outperforms the baseline. The difference between 28×28 and 224×224 is relatively small because AP uses intersection-over-union [11] and, therefore,\n is heavily biased towards object-interior pixels and less sensitive to the boundary quality. Visually, however, the difference in boundary quality is obvious, see Fig. 6.\n </p>\n <p>\n Subdivision inference allows PointRend to yield a high\n resolution 224×224 prediction using more than 30 times\n less compute (FLOPs) and memory than the default 4×\n conv head needs to output the same resolution (based on\n taking a 112×112 RoIAlign input), see Table 2. PointRend\n makes high resolution output feasible in the Mask R-CNN\n framework by ignoring areas of an object where a coarse prediction is sufficient (e.g., in the areas far away from object boundaries). In terms of wall-clock runtime, our unoptimized implementation outputs 224×224 masks at ∼13 fps,\n which is roughly the same frame-rate as a 4× conv head\n modified to output 56×56 masks (by doubling the default\n RoIAlign size), a design that actually has lower COCO AP\n compared to the 28×28 4× conv head (34.5% vs. 35.2%).\n </p>\n <table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/table3.png\" width=\"400\" />\n </td>\n <td>\n <img src=\"./imgs/figure7.png\" width=\"390\" />\n </td>\n </tr>\n </tbody>\n</table>\n <p>\n Table 3 shows PointRend subdivision inference with different output resolutions and number of points selected at\n each subdivision step. Predicting masks at a higher resolution can improve results. Though AP saturates, visual\n improvements are still apparent when moving from lower\n (e.g., 56×56) to higher (e.g., 224×224) resolution outputs,\n see Fig. 7. AP also saturates with the number of points sampled in each subdivision step because points are selected in\n the most ambiguous areas first. Additional points may make\n predictions in the areas where a coarse prediction is already\n sufficient. For objects with complex boundaries, however,\n using more points may be beneficial.\n </p>\n <table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/table4.png\" width=\"400\" />\n </td>\n <td>\n <img src=\"./imgs/table5.png\" width=\"400\" />\n </td>\n </tr>\n </tbody>\n</table>\n </td>\n </tr>\n </tbody>\n</table>",
"_____no_output_____"
],
[
"### **4.2. Ablation Experiments**\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n We conduct a number of ablations to analyze PointRend.\n In general we note that it is robust to the exact design of the\n point head MLP. Changes of its depth or width do not show\n any significant difference in our experiments.\n </p>\n <p>\n <strong>Point selection during training.</strong> During training we select\n 142 points per object following the biased sampling strategy (§3.1). Sampling only 142 points makes training computationally and memory efficient and we found that using\n more points does not improve results. Surprisingly, sampling only 49 points per box still maintains AP, though we\n observe an increased variance in AP.\n </p>\n <p>\n Table 4 shows PointRend performance with different selection strategies during training. Regular grid selection\n achieves similar results to uniform sampling. Whereas biasing sampling toward ambiguous areas improves AP. However, a sampling strategy that is biased too heavily towards\n boundaries of the coarse prediction (k>10 and β close to\n 1.0) decreases AP. Overall, we find a wide range of parameters 2<k<5 and 0.75<β<1.0 delivers similar results.\n </p>\n <p>\n <strong>Larger models, longer training.</strong> Training ResNet-50 +\n FPN (denoted R50-FPN) with the 1× schedule under-fits\n on COCO. In Table 5 we show that the PointRend improvements over the baseline hold with both longer training\n schedule and larger models (see the appendix for details).\n </p>\n <img src=\"./imgs/figure8.png\" />\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **5. Experiments: Semantic Segmentation**\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n PointRend is not limited to instance segmentation and\n can be extended to other pixel-level recognition tasks. Here,\n we demonstrate that PointRend can benefit two semantic\n segmentation models: DeeplabV3 [5], which uses dilated\n convolutions to make prediction on a denser grid, and SemanticFPN [24], a simple encoder-decoder architecture.\n </p>\n <p>\n <strong>Dataset.</strong> We use the Cityscapes [9] semantic segmentation\n set with 19 categories, 2975 training images, and 500 validation images. We report the median mIoU of 5 trials.\n </p>\n <p>\n <strong>Implementation details.</strong> We reimplemented DeeplabV3\n and SemanticFPN following their respective papers. SemanticFPN uses a standard ResNet-101 [20], whereas\n DeeplabV3 uses the ResNet-103 proposed in [5].3 We follow the original papers’ training schedules and data augmentation (details are in the appendix).\n </p>\n <p>\n We use the same PointRend architecture as for instance segmentation. Coarse prediction features come from\n the (already coarse) output of the semantic segmentation\n model. Fine-grained features are interpolated from res2 for\n DeeplabV3 and from P2 for SemanticFPN. During training\n we sample as many points as there are on a stride 16 feature map of the input (2304 for deeplabV3 and 2048 for SemanticFPN). We use the same k=3, β=0.75 point selection\n strategy. During inference, subdivision uses N=8096 (i.e.,\n the number of points in the stride 16 map of a 1024×2048\n image) until reaching the input image resolution. To measure prediction uncertainty we use the same strategy during training and inference: the difference between the most\n confident and second most confident class probabilities.\n </p>\n <table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/table6.png\" width=\"500\" />\n </td>\n <td>\n <img src=\"./imgs/figure9.png\" width=\"400\" />\n </td>\n </tr>\n </tbody>\n</table>\n\n<table>\n <tbody>\n <tr>\n <td>\n <img src=\"./imgs/table7.png\" width=\"500\" />\n </td>\n </tr>\n </tbody>\n</table>\n <p>\n <strong>DeeplabV3.</strong> In Table 6 we compare DeepLabV3 to\n DeeplabV3 with PointRend. The output resolution can also\n be increased by 2× at inference by using dilated convolutions in res4 stage, as described in [5]. Compared to both, PointRend has higher mIoU. Qualitative improvements are\n also evident, see Fig. 8. By sampling points adaptively,\n PointRend reaches 1024×2048 resolution (i.e. 2M points)\n by making predictions for only 32k points, see Fig. 9.\n </p>\n <p>\n <strong>SemanticFPN.</strong> Table 7 shows that SemanticFPN with\n PointRend improves over both 8× and 4× output stride\n variants without PointRend.\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **Appendix A. Instance Segmentation Details**\n\n<table>\n <thead>\n <tr>\n <th>\n Appendix A. Instance Segmentation Details\n </th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\n <p>\n We use SGD with 0.9 momentum; a linear learning rate\n warmup [15] over 1000 updates starting from a learning rate\n of 0.001 is applied; weight decay 0.0001 is applied; horizontal flipping and scale train-time data augmentation; the\n batch normalization (BN) [21] layers from the ImageNet\n pre-trained models are frozen (i.e., BN is not used); no testtime augmentation is used.\n </p>\n <p>\n <strong>COCO [29]:</strong> 16 images per mini-batch; the training schedule is 60k / 20k / 10k updates at learning rates of 0.02 / 0.002 / 0.0002 respectively; training images are resized randomly\n to a shorter edge from 640 to 800 pixels with a step of 32\n pixels and inference images are resized to a shorter edge\n size of 800 pixels.\n </p>\n <p>\n <strong>Cityscapes [9]:</strong> 8 images per mini-batch the training\n schedule is 18k / 6k updates at learning rates of 0.01 /\n 0.001 respectively; training images are resized randomly to\n a shorter edge from 800 to 1024 pixels with a step of 32 pixels and inference images are resized to a shorter edge size\n of 1024 pixels.\n </p>\n <p>\n <strong>Longer schedule:</strong> The 3× schedule for COCO is 210k /\n 40k / 20k updates at learning rates of 0.02 / 0.002 / 0.0002,\n respectively; all other details are the same as the setting described above.\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **Appendix B. Semantic Segmentation Details**\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n <strong>DeeplabV3 [5]:</strong> We use SGD with 0.9 momentum with 16\n images per mini-batch cropped to a fixed 768×768 size;\n the training schedule is 90k updates with a poly learning\n rate [34] update strategy, starting from 0.01; a linear learning rate warmup [15] over 1000 updates starting from a\n learning rate of 0.001 is applied; the learning rate for ASPP\n and the prediction convolution are multiplied by 10; weight\n decay of 0.0001 is applied; random horizontal flipping and\n scaling of 0.5× to 2.0× with a 32 pixel step is used as training data augmentation; BN is applied to 16 images minibatches; no test-time augmentation is used;\n </p>\n <p>\n <strong>SemanticFPN [24]:</strong> We use SGD with 0.9 momentum\n with 32 images per mini-batch cropped to a fixed 512×1024\n size; the training schedule is 40k / 15k / 10k updates at\n learning rates of 0.01 / 0.001 / 0.0001 respectively; a linear\n learning rate warmup [15] over 1000 updates starting from\n a learning rate of 0.001 is applied; weight decay 0.0001 is\n applied; horizontal flipping, color augmentation [33], and\n crop bootstrapping [2] are used during training; scale traintime data augmentation resizes an input image from 0.5×\n to 2.0× with a 32 pixel step; BN layers are frozen (i.e., BN\n is not used); no test-time augmentation is used.\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **Appendix C. AP* Computation**\n\n\n<table>\n <tbody>\n <tr>\n <td>\n <p>\n The first version (v1) of this paper on arXiv has an error in COCO mask AP evaluated against the LVIS annotations [16] (AP*\n ). The old version used an incorrect list of\n the categories not present in each evaluation image, which\n resulted in lower AP* values.\n </p>\n </td>\n </tr>\n </tbody>\n</table>\n",
"_____no_output_____"
],
[
"### **References**\n\n- [1] Anurag Arnab and Philip HS Torr. Pixelwise instance\nsegmentation with a dynamically instantiated network. In\nCVPR, 2017. 3\n- [2] Samuel Rota Bulo, Lorenzo Porzi, and Peter Kontschieder. `\nIn-place activated batchnorm for memory-optimized training\nof DNNs. In CVPR, 2018. 9\n- [3] Kai Chen, Jiangmiao Pang, Jiaqi Wang, Yu Xiong, Xiaoxiao Li, Shuyang Sun, Wansen Feng, Ziwei Liu, Jianping Shi,\nWanli Ouyang, et al. Hybrid task cascade for instance segmentation. In CVPR, 2019. 3\n- [4] Liang-Chieh Chen, George Papandreou, Iasonas Kokkinos,\nKevin Murphy, and Alan L Yuille. DeepLab: Semantic image segmentation with deep convolutional nets, atrous convolution, and fully connected CRFs. PAMI, 2018. 3\n- [5] Liang-Chieh Chen, George Papandreou, Florian Schroff, and\nHartwig Adam. Rethinking atrous convolution for semantic\nimage segmentation. arXiv:1706.05587, 2017. 2, 3, 8, 9\n- [6] Liang-Chieh Chen, Yukun Zhu, George Papandreou, Florian\nSchroff, and Hartwig Adam. Encoder-decoder with atrous\nseparable convolution for semantic image segmentation. In\nECCV, 2018. 3\n- [7] Xinlei Chen, Ross Girshick, Kaiming He, and Piotr Dollar. ´\nTensorMask: A foundation for dense object segmentation. In\nICCV, 2019. 3\n- [8] Christopher B Choy, Danfei Xu, JunYoung Gwak, Kevin\nChen, and Silvio Savarese. 3D-R2N2: A unified approach\nfor single and multi-view 3D object reconstruction. In\nECCV, 2016. 3\n- [9] Marius Cordts, Mohamed Omran, Sebastian Ramos, Timo\nRehfeld, Markus Enzweiler, Rodrigo Benenson, Uwe\nFranke, Stefan Roth, and Bernt Schiele. The Cityscapes\ndataset for semantic urban scene understanding. In CVPR, 2016. 2, 3, 5, 8, 9\n- [10] Jifeng Dai, Haozhi Qi, Yuwen Xiong, Yi Li, Guodong\nZhang, Han Hu, and Yichen Wei. Deformable convolutional networks. In ICCV, 2017. 5\n- [11] Mark Everingham, SM Ali Eslami, Luc Van Gool, Christopher KI Williams, John Winn, and Andrew Zisserman. The\nPASCAL visual object classes challenge: A retrospective.\nIJCV, 2015. 6\n- [12] Rohit Girdhar, David F Fouhey, Mikel Rodriguez, and Abhinav Gupta. Learning a predictable and generative vector\nrepresentation for objects. In ECCV, 2016. 3\n- [13] Ross Girshick. Fast R-CNN. In ICCV, 2015. 5\n- [14] Georgia Gkioxari, Jitendra Malik, and Justin Johnson. Mesh\nR-CNN. In ICCV, 2019. 3\n9\n- [15] Priya Goyal, Piotr Dollar, Ross Girshick, Pieter Noord- ´\nhuis, Lukasz Wesolowski, Aapo Kyrola, Andrew Tulloch,\nYangqing Jia, and Kaiming He. Accurate, large minibatch\nsgd: Training imagenet in 1 hour. arXiv:1706.02677, 2017.\n9\n- [16] Agrim Gupta, Piotr Dollar, and Ross Girshick. LVIS: A\ndataset for large vocabulary instance segmentation. In ICCV, 2019. 5, 6, 7, 9\n- [17] Bharath Hariharan, Pablo Arbelaez, Ross Girshick, and Ji- ´\ntendra Malik. Hypercolumns for object segmentation and\nfine-grained localization. In CVPR, 2015. 5\n- [18] Kaiming He, Ross Girshick, and Piotr Dollar. Rethinking ´\nimagenet pre-training. In ICCV, 2019. 7\n- [19] Kaiming He, Georgia Gkioxari, Piotr Dollar, and Ross Gir- ´\nshick. Mask R-CNN. In ICCV, 2017. 1, 2, 3, 4, 5, 6\n- [20] Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun.\nDeep residual learning for image recognition. In CVPR, 2016. 2, 5, 8\n- [21] Sergey Ioffe and Christian Szegedy. Batch normalization:\nAccelerating deep network training by reducing internal covariate shift. In ICML, 2015. 9\n- [22] Max Jaderberg, Karen Simonyan, Andrew Zisserman, and\nKoray Kavukcuoglu. Spatial transformer networks. In NIPS, 2015. 5\n- [23] Thomas N Kipf and Max Welling. Semi-supervised classification with graph convolutional networks. ICLR, 2017. 5\n- [24] Alexander Kirillov, Ross Girshick, Kaiming He, and Piotr\nDollar. Panoptic feature pyramid networks. In ´ CVPR, 2019.\n3, 8, 9\n- [25] Alexander Kirillov, Evgeny Levinkov, Bjoern Andres, Bogdan Savchynskyy, and Carsten Rother. InstanceCut: from\nedges to instances with multicut. In CVPR, 2017. 3\n- [26] Alex Krizhevsky, Ilya Sutskever, and Geoff Hinton. ImageNet classification with deep convolutional neural networks. In NIPS, 2012. 1\n- [27] Yann LeCun, Bernhard Boser, John S Denker, Donnie\nHenderson, Richard E Howard, Wayne Hubbard, and\nLawrence D Jackel. Backpropagation applied to handwritten zip code recognition. Neural computation, 1989. 1\n- [28] Tsung-Yi Lin, Piotr Dollar, Ross Girshick, Kaiming He, ´\nBharath Hariharan, and Serge Belongie. Feature pyramid\nnetworks for object detection. In CVPR, 2017. 2, 5\n- [29] Tsung-Yi Lin, Michael Maire, Serge Belongie, James Hays,\nPietro Perona, Deva Ramanan, Piotr Dollar, and C Lawrence ´\nZitnick. Microsoft COCO: Common objects in context. In\nECCV, 2014. 2, 3, 5, 9\n- [30] Chenxi Liu, Liang-Chieh Chen, Florian Schroff, Hartwig\nAdam, Wei Hua, Alan L Yuille, and Li Fei-Fei. Autodeeplab: Hierarchical neural architecture search for semantic\nimage segmentation. In CVPR, 2019. 3\n- [31] Shu Liu, Jiaya Jia, Sanja Fidler, and Raquel Urtasun. SGN:\nSequential grouping networks for instance segmentation. In\nCVPR, 2017. 3\n- [32] Shu Liu, Lu Qi, Haifang Qin, Jianping Shi, and Jiaya Jia.\nPath aggregation network for instance segmentation. In\nCVPR, 2018. 3\n- [33] Wei Liu, Dragomir Anguelov, Dumitru Erhan, Christian\nSzegedy, Scott Reed, Cheng-Yang Fu, and Alexander C\nBerg. SSD: Single shot multibox detector. In ECCV, 2016.\n9\n- [34] Wei Liu, Andrew Rabinovich, and Alexander C Berg.\nParsenet: Looking wider to see better. arXiv:1506.04579, 2015. 9\n- [35] Jonathan Long, Evan Shelhamer, and Trevor Darrell. Fully\nconvolutional networks for semantic segmentation. In\nCVPR, 2015. 1, 2, 3, 4\n- [36] Dmitrii Marin, Zijian He, Peter Vajda, Priyam Chatterjee,\nSam Tsai, Fei Yang, and Yuri Boykov. Efficient segmentation: Learning downsampling near semantic boundaries. In\nICCV, 2019. 3\n- [37] Lars Mescheder, Michael Oechsle, Michael Niemeyer, Sebastian Nowozin, and Andreas Geiger. Occupancy networks:\nLearning 3d reconstruction in function space. In CVPR, s2019. 3\n- [38] Don P Mitchell. Generating antialiased images at low sampling densities. ACM SIGGRAPH Computer Graphics, 1987. 2\n- [39] Vinod Nair and Geoffrey E Hinton. Rectified linear units\nimprove restricted boltzmann machines. In ICML, 2010. 6\n- [40] Gerhard Neuhold, Tobias Ollmann, Samuel Rota Bulo, and `\nPeter Kontschieder. The mapillary vistas dataset for semantic\nunderstanding of street scenes. In CVPR, 2017. 3\n- [41] Paphio. Jo-Wilfried Tsonga - [19]. CC BY-NC-SA\n2.0. https://www.flickr.com/photos/paphio/\n2855627782/, 2008. 1\n- [42] Matt Pharr, Wenzel Jakob, and Greg Humphreys. Physically\nbased rendering: From theory to implementation, chapter 7.\nMorgan Kaufmann, 2016. 2\n- [43] Charles R Qi, Hao Su, Kaichun Mo, and Leonidas J Guibas.\nPointNet: Deep learning on point sets for 3D classification\nand segmentation. In CVPR, 2017. 5\n- [44] Olaf Ronneberger, Philipp Fischer, and Thomas Brox. UNet: Convolutional networks for biomedical image segmentation. In MICCAI, 2015. 3\n- [45] Ke Sun, Yang Zhao, Borui Jiang, Tianheng Cheng, Bin Xiao,\nDong Liu, Yadong Mu, Xinggang Wang, Wenyu Liu, and\nJingdong Wang. High-resolution representations for labeling\npixels and regions. arXiv:1904.04514, 2019. 3\n- [46] Maxim Tatarchenko, Alexey Dosovitskiy, and Thomas Brox.\nOctree generating networks: Efficient convolutional architectures for high-resolution 3D outputs. In ICCV, 2017. 3\n- [47] Nanyang Wang, Yinda Zhang, Zhuwen Li, Yanwei Fu, Wei\nLiu, and Yu-Gang Jiang. Pixel2Mesh: Generating 3D mesh\nmodels from single RGB images. In ECCV, 2018. 3\n- [48] Turner Whitted. An improved illumination model for shaded\ndisplay. In ACM SIGGRAPH Computer Graphics, 1979. 2, 4\n- [49] Yuxin Wu, Alexander Kirillov, Francisco Massa, Wan-Yen\nLo, and Ross Girshick. Detectron2. https://github.\ncom/facebookresearch/detectron2, 2019. 6\n[50] Kun Zhou, Qiming Hou, Rui Wang, and Baining Guo. Realtime kd-tree construction on graphics hardware. In ACM\nTransactions on Graphics (TOG), 2008. 2",
"_____no_output_____"
]
]
] |
[
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb7c8219c9abecf210fc9f43b2de3674a8241c0b
| 6,156 |
ipynb
|
Jupyter Notebook
|
notebooks/Workshops/2017_Baku_STCU_IRIS_ObsPy_course/05_Event_metadata_exercise.ipynb
|
krischer/seismo_live_build
|
e4e8e59d9bf1b020e13ac91c0707eb907b05b34f
|
[
"CC-BY-3.0"
] | 3 |
2020-07-11T10:01:39.000Z
|
2020-12-16T14:26:03.000Z
|
notebooks/Workshops/2017_Baku_STCU_IRIS_ObsPy_course/05_Event_metadata.ipynb
|
krischer/seismo_live_build
|
e4e8e59d9bf1b020e13ac91c0707eb907b05b34f
|
[
"CC-BY-3.0"
] | null | null | null |
notebooks/Workshops/2017_Baku_STCU_IRIS_ObsPy_course/05_Event_metadata.ipynb
|
krischer/seismo_live_build
|
e4e8e59d9bf1b020e13ac91c0707eb907b05b34f
|
[
"CC-BY-3.0"
] | 3 |
2020-11-11T05:05:41.000Z
|
2022-03-12T09:36:24.000Z
| 6,156 | 6,156 | 0.642788 |
[
[
[
"<div style='background-image: url(\"share/baku.jpg\") ; padding: 0px ; background-size: cover ; border-radius: 15px ; height: 250px; background-position: 0% 80%'>\n <div style=\"float: right ; margin: 50px ; padding: 20px ; background: rgba(255 , 255 , 255 , 0.9) ; width: 50% ; height: 150px\">\n <div style=\"position: relative ; top: 50% ; transform: translatey(-50%)\">\n <div style=\"font-size: xx-large ; font-weight: 900 ; color: rgba(0 , 0 , 0 , 0.9) ; line-height: 100%\">ObsPy Tutorial</div>\n <div style=\"font-size: large ; padding-top: 20px ; color: rgba(0 , 0 , 0 , 0.7)\">Handling Event Metadata</div>\n </div>\n </div>\n</div>\nimage: User:Abbaszade656 / Wikimedia Commons / <a href=\"http://creativecommons.org/licenses/by-sa/4.0/\">CC-BY-SA-4.0</a>",
"_____no_output_____"
],
[
"## Workshop for the \"Training in Network Management Systems and Analytical Tools for Seismic\"\n### Baku, October 2018\n\nSeismo-Live: http://seismo-live.org\n\n##### Authors:\n* Lion Krischer ([@krischer](https://github.com/krischer))\n* Tobias Megies ([@megies](https://github.com/megies))\n---",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nplt.rcParams['figure.figsize'] = 12, 8",
"_____no_output_____"
]
],
[
[
"- for event metadata, the de-facto standard is [QuakeML (an xml document structure)](https://quake.ethz.ch/quakeml/)\n- QuakeML files can be read using **`read_events()`**",
"_____no_output_____"
]
],
[
[
"import obspy\n\ncatalog = obspy.read_events(\"./data/south_napa_with_some_aftershocks.xml\")\nprint(catalog)",
"_____no_output_____"
]
],
[
[
"- **`read_events()`** function returns a **`Catalog`** object, which is\na collection of **`Event`** objects.",
"_____no_output_____"
]
],
[
[
"print(type(catalog))\nprint(type(catalog[0]))",
"_____no_output_____"
],
[
"event = catalog[0]\nprint(event)",
"_____no_output_____"
]
],
[
[
"- Event objects are again collections of other resources.\n- the nested ObsPy Event class structure (Catalog/Event/Origin/Magnitude/FocalMechanism/...) is closely modelled after QuakeML\n<img src=\"images/Event.svg\" width=90%>",
"_____no_output_____"
]
],
[
[
"print(type(event.origins))\nprint(type(event.origins[0]))\nprint(event.origins[0])",
"_____no_output_____"
],
[
"print(type(event.magnitudes))\nprint(type(event.magnitudes[0]))\nprint(event.magnitudes[0])",
"_____no_output_____"
],
[
"# try event.<Tab> to get an idea what \"children\" elements event has",
"_____no_output_____"
]
],
[
[
"- The Catalog object contains some convenience methods to make\nworking with events easier.\n- for example, the included events can be filtered with various keys.",
"_____no_output_____"
]
],
[
[
"largest_magnitude_events = catalog.filter(\"magnitude >= 4.0\")\nprint(largest_magnitude_events)",
"_____no_output_____"
]
],
[
[
"- There is a basic preview plot using the matplotlib basemap module.",
"_____no_output_____"
]
],
[
[
"catalog.plot(projection=\"local\", resolution=\"i\", label=\"magnitude\");",
"_____no_output_____"
]
],
[
[
"- a (modified) Catalog can be output to file in a number of different formats.",
"_____no_output_____"
]
],
[
[
"largest_magnitude_events.write(\"/tmp/large_events.xml\", format=\"QUAKEML\")\n!ls -l /tmp/large_events.xml",
"_____no_output_____"
]
],
[
[
"- the event type classes can be used to build up Events/Catalogs/Picks/.. from scratch in custom processing work flows and to share them with other researchers in the de facto standard format QuakeML",
"_____no_output_____"
]
],
[
[
"from obspy import UTCDateTime\nfrom obspy.core.event import Catalog, Event, Origin, Magnitude\nfrom obspy.geodetics import FlinnEngdahl\n\ncat = Catalog()\ncat.description = \"Just a fictitious toy example catalog built from scratch\"\n\ne = Event()\ne.event_type = \"not existing\"\n\no = Origin()\no.time = UTCDateTime(2014, 2, 23, 18, 0, 0)\no.latitude = 47.6\no.longitude = 12.0\no.depth = 10000\no.depth_type = \"operator assigned\"\no.evaluation_mode = \"manual\"\no.evaluation_status = \"preliminary\"\no.region = FlinnEngdahl().get_region(o.longitude, o.latitude)\n\nm = Magnitude()\nm.mag = 7.2\nm.magnitude_type = \"Mw\"\n\nm2 = Magnitude()\nm2.mag = 7.4\nm2.magnitude_type = \"Ms\"\n\n# also included could be: custom picks, amplitude measurements, station magnitudes,\n# focal mechanisms, moment tensors, ...\n\n# make associations, put everything together\ncat.append(e)\ne.origins = [o]\ne.magnitudes = [m, m2]\nm.origin_id = o.resource_id\nm2.origin_id = o.resource_id\n\nprint(cat)\ncat.write(\"/tmp/my_custom_events.xml\", format=\"QUAKEML\")\n!cat /tmp/my_custom_events.xml",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7c83d24ab7478fd432ab7c54e8c0bd827b6fff
| 205,838 |
ipynb
|
Jupyter Notebook
|
Africa Finance/Africa Aid Analysis.ipynb
|
Frightera/Exploratory-Data-Analysis
|
22168933ad12cbba27c21432fa5cda5ca74de5bf
|
[
"MIT"
] | 10 |
2020-10-04T19:47:02.000Z
|
2022-03-06T15:37:25.000Z
|
Africa Finance/Africa Aid Analysis.ipynb
|
Frightera/Exploratory-Data-Analysis
|
22168933ad12cbba27c21432fa5cda5ca74de5bf
|
[
"MIT"
] | null | null | null |
Africa Finance/Africa Aid Analysis.ipynb
|
Frightera/Exploratory-Data-Analysis
|
22168933ad12cbba27c21432fa5cda5ca74de5bf
|
[
"MIT"
] | 2 |
2020-12-25T02:48:46.000Z
|
2022-01-28T14:33:53.000Z
| 39.282061 | 535 | 0.405173 |
[
[
[
"# Simple Analysis with Pandas and Numpy",
"_____no_output_____"
],
[
"***ABSTRACT***\n* If a donor gives aid for a project that the recipient government would have undertaken anyway, then the aid is financing some expenditure other than the intended project. The notion that aid in this sense may be \"fungible,\" while long recognized, has recently been receiving some empirical support. The paper \"What Does Aid to Africa Finance?\" focuses on Sub-Saharan Africa—the region with the largest GDP share of aid—and presents results that indicate that aid may be partially fungible, and suggests some reasons why.\n\nThis database contains data used for the analysis.",
"_____no_output_____"
],
[
"#### Import Libraries & Load the data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n\nprint('OK')",
"OK\n"
],
[
"df = pd.read_csv('data.csv')\ndf.head(-5)",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 301 entries, 0 to 300\nData columns (total 50 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 countryc 301 non-null object \n 1 year 301 non-null int64 \n 2 agrgdp 301 non-null object \n 3 popn 297 non-null float64\n 4 infmort 301 non-null object \n 5 schprim 301 non-null object \n 6 schsec 301 non-null object \n 7 grtdsbp 301 non-null object \n 8 grlndsbp 301 non-null object \n 9 aiddsbp 301 non-null object \n 10 totexpp 301 non-null object \n 11 agexpp 301 non-null object \n 12 enexpp 301 non-null object \n 13 indexpp 301 non-null object \n 14 tacexpp 301 non-null object \n 15 eduexpp 301 non-null object \n 16 hthexpp 301 non-null object \n 17 prirepp 301 non-null object \n 18 curexpp 301 non-null object \n 19 capexpp 301 non-null object \n 20 gdnpp 301 non-null object \n 21 d0 301 non-null object \n 22 cnlnagp 301 non-null object \n 23 cnlnenp 301 non-null object \n 24 cnlninp 301 non-null object \n 25 cnlntacp 301 non-null object \n 26 cnlnedup 301 non-null object \n 27 cnlnhthp 301 non-null object \n 28 cnlnothp 301 non-null object \n 29 dgrtdsbp 301 non-null object \n 30 dgrlndsbp 301 non-null object \n 31 daiddsbp 301 non-null object \n 32 dtotexpp 301 non-null object \n 33 dagexpp 301 non-null object \n 34 denexpp 301 non-null object \n 35 dindexpp 301 non-null object \n 36 dtacexpp 301 non-null object \n 37 deduexpp 301 non-null object \n 38 dhthexpp 301 non-null object \n 39 dothexpp 301 non-null object \n 40 dcurexpp 301 non-null object \n 41 dcapexpp 301 non-null object \n 42 dprirepp 301 non-null object \n 43 dcnlnagp 301 non-null object \n 44 dcnlnenp 301 non-null object \n 45 dcnlninp 301 non-null object \n 46 dcnlntacp 301 non-null object \n 47 dcnlnedup 301 non-null object \n 48 dcnlnhthp 301 non-null object \n 49 dcnlnothp 301 non-null object \ndtypes: float64(1), int64(1), object(48)\nmemory usage: 117.7+ KB\n"
],
[
"df_new = df.copy()\n\ndf1 = df_new.sample(frac = 0.25, random_state = 0)\ndf_new = df_new.drop(df1.index)\n\ndf1.head(3)",
"_____no_output_____"
],
[
"df2 = df_new.sample(frac = 0.25, random_state = 0)\ndf_new = df_new.drop(df2.index)\n\ndf2.head(3)",
"_____no_output_____"
],
[
"df3 = df_new.sample(frac = 0.25, random_state = 0)\n\ndf3.head(3)",
"_____no_output_____"
],
[
"df4 = df_new.drop(df3.index) # since all subsets' indexes were dropped\ndf4.head(3)",
"_____no_output_____"
]
],
[
[
"### Missing Values",
"_____no_output_____"
],
[
"* **Interpolation** is a type of estimation, a method of constructing new data points within the range of a discrete set of known data points while **imputation** is replacing the missing data of the mean of the column.",
"_____no_output_____"
]
],
[
[
"df3.isnull().sum()",
"_____no_output_____"
],
[
"df3[df3['popn'].isnull() == True]",
"_____no_output_____"
],
[
"df3['popn'].fillna(df3['popn'].mean(), inplace = True) # that's called imputation\ndf3.isnull().sum()",
"_____no_output_____"
],
[
"df1.isna().sum()",
"_____no_output_____"
],
[
"df1['popn'].fillna(df1['popn'].interpolate(), inplace = True)\ndf1.isna().sum()",
"_____no_output_____"
]
],
[
[
"##### When to use interpolation or imputation?\n* Data has linear relationship = Interpolation otherwise imputation.",
"_____no_output_____"
],
[
"### Combine Data",
"_____no_output_____"
]
],
[
[
"df5 = df1.join(df2, lsuffix = '_left') # _left indicates columns from left hand side\ndf5 # NaN = df1 is larger than df2",
"_____no_output_____"
],
[
"# Concat\ndf6 = pd.concat([df1,df2], axis = 0) # 0 indicates rows\ndf6",
"_____no_output_____"
]
],
[
[
"#### Inner Join",
"_____no_output_____"
],
[
"<img src=\"https://cdn.sqltutorial.org/wp-content/uploads/2016/03/SQL-INNER-JOIN.png\"/>",
"_____no_output_____"
]
],
[
[
"df7 = pd.merge(df1,df2, on = 'year')\ndf7",
"_____no_output_____"
]
],
[
[
"#### Full Outer Inclusive Join\n<img src=\"https://cdn.sqltutorial.org/wp-content/uploads/2016/07/SQL-FULL-OUTER-JOIN.png\"/>",
"_____no_output_____"
]
],
[
[
"df8 = pd.merge(df1,df2, how = 'outer')\ndf8",
"_____no_output_____"
]
],
[
[
"#### Left Inclusive Join\n<img src=\"https://cdn.sqltutorial.org/wp-content/uploads/2016/03/SQL-LEFT-JOIN.png\"/>",
"_____no_output_____"
]
],
[
[
"df9 = pd.merge(df1,df2, how = 'left')\ndf9",
"_____no_output_____"
]
],
[
[
"#### Right Inclusive Join\n<img src=\"https://www.dofactory.com/img/sql/sql-right-join.png\"/>",
"_____no_output_____"
]
],
[
[
"df10 = pd.merge(df1,df2, how = 'right')\ndf10.head(5)",
"_____no_output_____"
]
],
[
[
"### Sorting Data",
"_____no_output_____"
]
],
[
[
"df1.sort_values(by = ['agrgdp'], ascending = True)\ndf1",
"_____no_output_____"
],
[
"df1.sort_index(axis = 0, ascending =True)",
"_____no_output_____"
]
],
[
[
"### Selecting and Slicing Data",
"_____no_output_____"
]
],
[
[
"df1[['countryc', 'year']]",
"_____no_output_____"
],
[
"df1.iloc[:,1:8].head()",
"_____no_output_____"
]
],
[
[
"### Grouping & Aggregating",
"_____no_output_____"
]
],
[
[
"df1.groupby(['year', 'infmort']).agg(np.mean)",
"_____no_output_____"
],
[
"df1.groupby(['schsec']).groups",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cb7c8923085ee7c34ee10ba9f4b472eace6bf298
| 11,536 |
ipynb
|
Jupyter Notebook
|
word_vectors.ipynb
|
Shail2512/Aspect-Based-Document-Similarity
|
357ab67b8bf218c12405f5f70e1748b4861711e5
|
[
"MIT"
] | 47 |
2020-10-14T09:28:39.000Z
|
2022-03-01T01:54:32.000Z
|
word_vectors.ipynb
|
Shail2512/Aspect-Based-Document-Similarity
|
357ab67b8bf218c12405f5f70e1748b4861711e5
|
[
"MIT"
] | 2 |
2021-11-21T20:07:10.000Z
|
2022-02-10T09:25:40.000Z
|
word_vectors.ipynb
|
stjordanis/aspect-document-similarity
|
ca17e0a8730caa224b0efe8909b1e5a87bb456ea
|
[
"MIT"
] | 8 |
2020-11-07T08:43:01.000Z
|
2022-02-15T05:45:13.000Z
| 32.404494 | 389 | 0.474861 |
[
[
[
"# Word vectors (FastText) for Baseline\n\n#### Create Spacy model from word vectors\n\n```bash\npython -m spacy init-model en output/cord19_docrel/spacy/en_cord19_fasttext_300d --vectors-loc output/cord19_docrel/cord19.fasttext.w2v.txt\npython -m spacy init-model en output/acl_docrel/spacy/en_acl_fasttext_300d --vectors-loc output/acl_docrel/acl.fasttext.w2v.txt\n```\n",
"_____no_output_____"
]
],
[
[
"import gensim\nimport json\nimport os\nimport requests\nimport pickle\nimport pandas as pd\nimport logging\nfrom pathlib import Path\nfrom tqdm import tqdm_notebook as tqdm\nfrom smart_open import open\nfrom nlp import load_dataset\nimport nlp\nimport acl.utils\nfrom trainer_cli import ExperimentArguments",
"wandb: WARNING W&B installed but not logged in. Run `wandb login` or set the WANDB_API_KEY env variable.\n"
]
],
[
[
"## CORD19",
"_____no_output_____"
]
],
[
[
"data_dir = Path('./output/cord19_docrel')\n\nexperiment_args = ExperimentArguments(\n nlp_dataset='./datasets/cord19_docrel/cord19_docrel.py',\n nlp_cache_dir='./data/nlp_cache',\n doc_id_col='doi',\n doc_a_col='from_doi',\n doc_b_col='to_doi',\n cv_fold=1,\n)\n\ndocs_ds = load_dataset(experiment_args.nlp_dataset,\n name='docs',\n cache_dir=experiment_args.nlp_cache_dir,\n split=nlp.Split('docs'))",
"_____no_output_____"
],
[
"# Extract tokens from each document and create token file.\ntokens_count = 0\nwith open(data_dir / 'tokens.txt', 'w') as f:\n for idx, doc in docs_ds.data.to_pandas().iterrows():\n text = acl.utils.get_text_from_doc(doc) \n for token in gensim.utils.simple_preprocess(text, min_len=2, max_len=15):\n f.write(token + ' ')\n tokens_count += 1\n f.write('\\n')\nprint(f'Total tokens: {tokens_count:,}')\n",
"Total tokens: 16,181,414\n"
],
[
"import fasttext\n\nmodel = fasttext.train_unsupervised(str(data_dir / 'tokens.txt'), \n model='skipgram', \n lr=0.05, # learning rate [0.05]\n dim=300, # size of word vectors [100]\n ws=5, # size of the context window [5]\n epoch=5, # number of epochs [5]\n thread=4, # number of threads [number of cpus]\n )",
"_____no_output_____"
],
[
"model.save_model(str(data_dir / 'cord19.fasttext.bin'))",
"_____no_output_____"
],
[
"from gensim.models.wrappers import FastText\n\nft_model = FastText.load_fasttext_format(str(data_dir / 'cord19.fasttext.bin'))\nft_model.wv.save_word2vec_format(data_dir / 'cord19.fasttext.w2v.txt')",
"_____no_output_____"
],
[
"# Unset\ndel ft_model\ndel model\ndel docs_ds\ndel experiment_args\ndel data_dir",
"_____no_output_____"
]
],
[
[
"## ACL",
"_____no_output_____"
]
],
[
[
"data_dir = Path('./output/acl_docrel')\n\nexperiment_args = ExperimentArguments(\n nlp_dataset='./datasets/acl_docrel/acl_docrel.py',\n nlp_cache_dir='./data/nlp_cache',\n doc_id_col='s2_id',\n doc_a_col='from_s2_id',\n doc_b_col='to_s2_id',\n cv_fold=1,\n)\n\ndocs_ds = load_dataset(experiment_args.nlp_dataset,\n name='docs',\n cache_dir=experiment_args.nlp_cache_dir,\n split=nlp.Split('docs'))",
"Downloading and preparing dataset acl_docrel/docs (download: Unknown size, generated: Unknown size, total: Unknown size) to ./data/nlp_cache/acl_docrel/docs/0.1.0...\n"
],
[
"# Extract tokens from each document and create token file.\ntokens_count = 0\nwith open(data_dir / 'tokens.txt', 'w') as f:\n for idx, doc in docs_ds.data.to_pandas().iterrows():\n text = acl.utils.get_text_from_doc(doc) \n for token in gensim.utils.simple_preprocess(text, min_len=2, max_len=15):\n f.write(token + ' ')\n tokens_count += 1\n f.write('\\n')\n \n# Total tokens: 2,194,010\nprint(f'Total tokens: {tokens_count:,}')",
"Total tokens: 2,194,010\n"
],
[
"import fasttext\n\nmodel = fasttext.train_unsupervised(str(data_dir / 'tokens.txt'), \n model='skipgram', \n lr=0.05, # learning rate [0.05]\n dim=300, # size of word vectors [100]\n ws=5, # size of the context window [5]\n epoch=5, # number of epochs [5]\n thread=4, # number of threads [number of cpus]\n )",
"_____no_output_____"
],
[
"model.save_model(str(data_dir / 'acl.fasttext.bin'))",
"_____no_output_____"
],
[
"from gensim.models.wrappers import FastText\n\nft_model = FastText.load_fasttext_format(str(data_dir / 'acl.fasttext.bin'))\nft_model.wv.save_word2vec_format(data_dir / 'acl.fasttext.w2v.txt')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cb7c93aa6006fe1136d0aa04fcc513c0d46b69cb
| 33,227 |
ipynb
|
Jupyter Notebook
|
workbook_C.ipynb
|
ARU-Bioinformatics/ibdsA-ex-B
|
82739e68e59299804cddfcd74b5eb92f270784d9
|
[
"MIT"
] | null | null | null |
workbook_C.ipynb
|
ARU-Bioinformatics/ibdsA-ex-B
|
82739e68e59299804cddfcd74b5eb92f270784d9
|
[
"MIT"
] | null | null | null |
workbook_C.ipynb
|
ARU-Bioinformatics/ibdsA-ex-B
|
82739e68e59299804cddfcd74b5eb92f270784d9
|
[
"MIT"
] | null | null | null | 32.735961 | 317 | 0.563939 |
[
[
[
"# workbook C: lists and strings\n\nThis activity builds on the Python you have become familiar with in\n\n* *Chapter 2 Python Lists* \n* *Chapter 3 Functions and packages*\n\nfrom the\n[DataCamp online course *Intro to Python for Data Science*](https://www.datacamp.com/courses/intro-to-python-for-data-science). Here we will look at lists and explore how strings and lists are related.",
"_____no_output_____"
],
[
"> ### Reminder: saving your work\n>\n> As you work through the work book it is important to regularly save your work. Notice that as you have made changes the Jupyter window top line will warn you there are `(unsaved changes)` in small text. To save your work in this notebook by either select menu item `File` `Save` or by hit the save button:\n> \n> \n>\n> \n> ### Reminder: getting help \n> Please see the page:\n> [Help with programming](https://canvas.anglia.ac.uk/courses/12178/pages/help-with-programming)\n> on ARU Canvas.",
"_____no_output_____"
],
[
"## Python Lists: defining lists\nWhy do we need lists? Lists are useful for keeping a collection of things in order. \n\nSo suppose we wanted to store information about the number \nof chromosomes for a few selected species:\n\n| Organism | Scientific name | Chromosome number |\n| -------- | :--------------: | :---------------: |\n| fruit fly | Drosophila melanogaster | 8 |\n| rice | Oryza sativa | 24 |\n| mouse | Mus musculus | 40 |\n| wheat | Triticum aestivum | 42 |\n| human | Homo sapiens | 46 |\n| potato | Solanum tuberosum | 48 |\n| great white shark | Carcharodon carcharias | 82 |\n| carp | Carassius carassius | 100 |\n> *information from https://en.wikipedia.org/wiki/List_of_organisms_by_chromosome_count*",
"_____no_output_____"
],
[
"We can store the list of organisms in a Python list:",
"_____no_output_____"
]
],
[
[
"organisms = ['fly', 'rice', 'mouse', 'wheat', 'human', 'potato', 'shark', 'carp']\n# Instruction: add Python command to print organisms list\n### your line here! ",
"_____no_output_____"
]
],
[
[
"Notice the use of square brackets `[]` in both the list definition and when the list is the printed.",
"_____no_output_____"
],
[
"**Now its your turn.** Create a list `chromosomes` that contains information from the table above about the number of chromosomes for each species.",
"_____no_output_____"
]
],
[
[
"# Instruction: define a Python list 'chromosomes' with \n# the number of chromosomes from table above (as integers)\n### your line here! \n\n# Instruction: now print your chromosomes list\n### your line here! ",
"_____no_output_____"
]
],
[
[
"Now run the following following Python that checks the chromosomes list is as it is expected (do not worry about understanding it - for now).",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to check your chromosomes list\n\n# python code to check chromosomes list as described above\n# do not worry about understanding it yet - it just shows what can be done\nif 'chromosomes' not in locals():\n print('Error: chromosomes variable has not been defined! Try again!')\nelif not isinstance(chromosomes, list):\n print('Error: chromosomes is not a list! Try again!')\nelif len(chromosomes) != 8:\n print('Error: chromosomes list does not have 8 elements! Try again!')\nelif sum(chromosomes) != 390:\n print('Error: chromosomes list does not have expected sum! Try again!')\nelse:\n print('Well done chomosomes list checks out!')",
"_____no_output_____"
]
],
[
[
"### Appending items to a list",
"_____no_output_____"
],
[
"You can append extra items to a list. \nSo to define a list of scientific names we could start with an empty list and append the names one by one:",
"_____no_output_____"
]
],
[
[
"scientific = [] # empty list\nscientific.append('Drosophila melanogaster')\nscientific.append('Oryza sativa')\nscientific.append('Mus musculus')\nscientific.append('Triticum aestivum')\nscientific = scientific + ['Homo sapiens', \n 'Solanum tuberosum', \n 'Carcharodon carcharias',\n 'Carassius carassius']\n# Instruction: add Python command to print scientific\n### your line here! ",
"_____no_output_____"
]
],
[
[
"Notice that the last four scientific names have been added by concatenating (joining) two lists together - the result is a new list.\n\nThe concatentation command above could be more simplified by using the `+=` operator: \n```\nscientific += ['Homo sapiens', 'Solanum tuberosum', \n 'Carcharodon carcharias', 'Carassius carassius']\n```",
"_____no_output_____"
],
[
"**Now it is your turn.** From https://en.wikipedia.org/wiki/List_of_organisms_by_chromosome_count The `Red king crab` (`Paralithodes camtschaticus`) has `208` chromosomes. Lets add this information to the lists.",
"_____no_output_____"
]
],
[
[
"# Instruction: append 'king crab' to the list organisms\n### your line here! \n\n# following lines check that 'king crab' is somewhere in the list.\nif not 'king crab' in organisms:\n print('Error: you have not added \"king crab\" to organisms! Try again!')\nelse:\n print('Well done organisms now has a king crab in it:\\n', organisms)",
"_____no_output_____"
]
],
[
[
"Lets add the king crab's number of chromosomes to list `chromosomes`. This time using concatenation rather than `.append()`",
"_____no_output_____"
]
],
[
[
"# Instruction append 208 to the list chromosomes using concatenation\n### your line here! \n\nprint(chromosomes)",
"_____no_output_____"
]
],
[
[
"> *Hint: remember that you can only concentate two lists together so:*\n> ```\n> primes = [2, 3, 5]\n>primes += [7]\n> ```\n> *works fine whereas trying concentenate a list and an integer \n> will result in an error. So:*\n> ```\n> primes = [2, 3, 5]\n> primes += 7\n> ```\n> **will not work**",
"_____no_output_____"
],
[
"Now lets you should add the red kings crab scientific name `Paralithodes camtschaticus` to the `scientific` list. ",
"_____no_output_____"
]
],
[
[
"# Instruction append 'Paralithodes camtschaticus' to the list scientific\n### your line here! \nprint(scientific)",
"_____no_output_____"
]
],
[
[
"### Finding number of items in a list using the `len()` function\n\nReminder in exercise we saw that we use the `len()` function to find the number of letters in a string.\n\nThis function will also return the number of items in a list.\n\nTry running the next cell\n",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to see how len() works with lists.\nprimes = [2, 3, 5]\nprint(len(primes))",
"_____no_output_____"
]
],
[
[
"**Now its your turn**",
"_____no_output_____"
]
],
[
[
"# Instruction: print out the number of items in the a_zero, empty and three_nones lists\na_zero = ['a', 0]\nempty = []\nthree_nones = [None, None, None]\n### your line here! ",
"_____no_output_____"
]
],
[
[
"Notice that a list can be empty `[]`, this is a list with no items in it. Lists can also have `None` in them!",
"_____no_output_____"
],
[
"Now print out the number of items in each of the `organisms`, `scientific` and `chromosomes` lists that have be defined above (they should be in the kernel memory). ",
"_____no_output_____"
],
[
"### Getting an item from a list by using `list_name[index]`\n\n> *If this is unfamiliar, go back and look at the \n> [DataCamp course](https://www.datacamp.com/courses/intro-to-python-for-data-science) \n> particularly Chapter 2, \"Subsetting lists\" video.*\n\nIn the DataCamp course, you have seen that you get a specific item in a list by using `list_name[index]`. So to get the first item of a list `a_list` you can specify `a_list[0]`, the second item of the list by `a_list[1]`:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstation getting a \n# specific item of a list by its index\nfruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']\nprint('first item of list fruits is fruits[0]=' + fruits[0])\nprint('second item of list fruits is fruits[1]=' + fruits[1])\nprint('third item of list fruits is fruits[2]=' + fruits[2])",
"_____no_output_____"
]
],
[
[
"furthermore, you have seen you can get the last item of a list by using an index of `-1`:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstation getting a \n# specific item of a list by its index\nprint('last item of list fruits is fruits[-1]=' + fruits[-1])\nprint('penultimate item of a list is -2, fruits[-2]=' + fruits[-2])",
"_____no_output_____"
]
],
[
[
"**Now its your turn** write python to print out the first, 2nd and last item of the `organisms` list",
"_____no_output_____"
]
],
[
[
"# Instruction: print out the first, 2nd and last item of the `organisms` list\n### your line here!\n### your line here!\n### your line here!",
"_____no_output_____"
]
],
[
[
"### Getting a character from a string by using string_name[index]\nWe have already seen that strings and lists have some features in common as the `len()` function can be used to find the number of characters in a string or the number of items in a list. You will not be surprised to know that you can get individual characters from a string using the index just like for lists.",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstation getting a \n# specific charact of a string by its index\nmy_string = 'A stitch in time, saves 9'\nprint('my string=' + my_string)\nprint('1st character is my_string[0]=' + my_string[0])\nprint('3rd character is my_string[1]=' + my_string[2])\nprint('5th character is my_string[1]=' + my_string[4])\nprint('last character is my_string[-1]=' + my_string[-1])",
"_____no_output_____"
]
],
[
[
"**Now its your turn** write Python:",
"_____no_output_____"
]
],
[
[
"seq_a = 'ATGGGGCATGCATGC'\n# Instruction: print out the first character of seq_a\n### your line here! \n\n# Instruction: print out the 2nd character of seq_a\n### your line here! \n\n# Instruction: print out the 7th character of seq_a\n### your line here! \n\n# Instruction: print out the last character of seq_a\n### your line here! \n\n# Instruction: print out the penultimate (one before last) character of seq_a\n### your line here! ",
"_____no_output_____"
]
],
[
[
" write Python to print out the first and last character of the first item of the fruits list.\n\n> *Hint the first items of fruits is* `fruits[0]`",
"_____no_output_____"
]
],
[
[
"# Instruction: print out the first item of the fruits list defined above\n### your line here! \n# now print out the first character of the first fruit\n### your line here! \n# now print out the last character of the first fruit\n### your line here! ",
"_____no_output_____"
]
],
[
[
"### Slicing lists by using list_name[start:end]\n\n> *If this is unfamiliar, go back and look at the \n> [DataCamp course](https://www.datacamp.com/courses/intro-to-python-for-data-science) \n> particularly Chapter 2, \"Subsetting lists\" video.*\n\nIn the DataCamp course, you have seen that as well as getting specific characters from a list one can **slice** of parts of lists:\n```\nlist_name[ start : end ]\n inclusive : exclusive\n```\n* Remember Python indexes start at zero.\n* Remember the `end` index is exclusive - so the slice will not include that element, ending on the one before\n* If you leave out `start` and/or `end` the slice will be from the start of the list and/or to the end of the list.\nSo lets try this out in practice",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstate list slicing\nfruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\n# index 0 1 2 3 4 5 6\n# Slice the first two fruits \nprint('first two fruits - fruits[0:2]=', fruits[0:2])\n# the previous slice started at the beginning so can leave out the zero\nprint('first two fruits - leaving out initial zero, fruits[:2]=', fruits[:2])\n# create a new list with the first three fruits\nfirst_3_fruits = fruits[:3]\nprint('new list first_3_fruits=', first_3_fruits)\n# the second to the 5th fruit:\nprint('the second to the 5th fruit - fruits[1:5]=', fruits[1:5])\n# all the fruits but the first one:\nprint('all the fruits but the first one - fruits[1:]=', fruits[1:])\n# all the fruits but the last one:\nprint('all the fruits but the last one - fruits[1:]=', fruits[:-1])",
"_____no_output_____"
],
[
"veggies = ['aubergine ', 'broccoli', 'cabbage', 'daikon', 'endive', 'fennel', 'gherkin']\n# Instruction: print out the first four veggies\n### your line here!\n# Instruction: print out the 5th to the last veggies\n### your line here!\n# Instruction: print out all the veggies except the first \n### your line here!\n# Instruction: print out all the veggies except the last\n### your line here!",
"_____no_output_____"
],
[
"# Instruction: create a new list called 'select_v' with all the veggies except the first and last\n### your line here!\n# Instruction: print out the new check your select_v list\n### your line here!",
"_____no_output_____"
],
[
"# Instruction: run this cell to check your select_v list\n# python code to check check your select_v list\n# do not worry about understanding it yet - it just shows what can be done\nif 'select_v' not in locals():\n print('Error: check your select_v list has not been defined! Try again!')\nelif not isinstance(select_v, list):\n print('Error: check your select_v list is not a list! Try again!')\nelif len(select_v) != 5 or select_v[-1] != 'fennel':\n print('Error: your select_v list is not correct!')\nelse:\n print('Well done your select_v list checks out!')",
"_____no_output_____"
]
],
[
[
"In the next section we will answer the question: what is the **type** of a slice from a list?",
"_____no_output_____"
]
],
[
[
"num_list = [0, 1, 2]\nprint('type of num_list is', type(num_list))\n# Instruction: print out the slice containing the first two element of num_list\n### your line here!\n# what type is the slice in the previous line?\n### In the next line replace **** with your predictions\nprint('I predict the type of the slice from a list to be ******') \n# now write Python using type() to check your prediction.\n### your line here!",
"_____no_output_____"
]
],
[
[
"### Slicing strings by using strings[start:end]\n\nGuess what? You can slice strings in exactly the same way as lists. You have a go",
"_____no_output_____"
]
],
[
[
"b_seq = 10*'A' + 10*'G' + 10*'T'\n# Instruction: what are the first 5 characters of b_seq\n### your line here!\n# Instruction: what are the last 11 characters of b_seq\n### your line here!\n# Instruction: what are the 10th to 19th characters of b_seq\n### your line here!\n# Instruction: what is the last character of b_seq\n### your line here!",
"_____no_output_____"
]
],
[
[
"### Advanced slicing with increment list_name[start:end:increment]\nBy default a slice will include all elements between the indices `start` and the `end-1`.\nIf you specify an increment of two then you can select, every second element:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstate list increment\nfruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\n# index 0 1 2 3 4 5 6\nodd_fruits = fruits[::2]\nprint(odd_fruits)",
"_____no_output_____"
],
[
"veggies = ['aubergine ', 'broccoli', 'cabbage', 'daikon', 'endive', 'fennel', 'gherkin']\n# Instruction: create list odd_veggies that has the 1st, 3rd, 5th veggies.\n### your line here!\n# Instruction: create list even_veggies that has the 2nd, 4th, 6th veggies\n### your line here!\n# Instruction: print the two lists\n### your line here!\n### your line here!",
"_____no_output_____"
]
],
[
[
"### Reversing a list (or string) using an increment of minus -1\ntry this out:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstrate reversing a list \nfruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\nreverse_fruits = fruits[::-1]\nprint(reverse_fruits)",
"_____no_output_____"
]
],
[
[
"exactly the same syntax can be use to reverse a string.",
"_____no_output_____"
]
],
[
[
"seq_c = 'AATGCC'\n# Instruction: create a string seq_c_backwards that is the reverse of seq_c\n### your line here!\n# Instruction: print out seq_c_backwards\n### your line here!",
"_____no_output_____"
]
],
[
[
"### Replacing list elements by `list_name[index] = new_value`\n> \n> *Advanced material: If you are confused or time is short go on to [homework B](./ex_B_homework.ipynb)*\n\nAs you have seen in the Data Camp Coures, it is easy to replace a list element: ",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstrate replacing list elements\nfruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\nfruits[1] = 'blueberry'\nfruits[-1] = 'grapefruit'\nprint(fruits)",
"_____no_output_____"
]
],
[
[
"**Now your turn:** Our table of organism and Chromosomes:\n\n| Organism | Scientific name | Chromosome number |\n| -------- | :--------------: | :---------------: |\n| fruit **fli** | Drosophila melanogaster | 8 |\n| rice | Oryza sativa | **20** |\n| mouse | Mus musculus | 30 |\n| wheat | Triticum aestivum | 42 |\n| human | **Hom** sapiens | 46 |\n| potato | Solanum tuberosum | 48 |\n| **grape** white shark | Carcharodon carcharias | 82 |\n| carp | Carassius carassius | **101** |\n> *information from https://en.wikipedia.org/wiki/List_of_organisms_by_chromosome_count*\n\nnow has a number of mistakes shown in **bold**:\n* **fli** should be *fly*\n* **grape white shark** should be *great white shark*\n* **hom sapiens** should *Homo sapiens*\n* **20** the number of chromosomes for rice should be *24*\n* **101** the number of chromosomes for carp should be *100*",
"_____no_output_____"
]
],
[
[
"organisms = ['fruit fli', 'rice', 'mouse', 'wheat', 'human', 'potato', 'grape white shark', 'carp']\nchromosomes = [8, 20, 30, 42, 46, 48, 82, 101]\nscientific = ['Drosophila melanogaster',\n 'Oryza sativa',\n 'Mus musculus',\n 'Triticum aestivum',\n 'Hom sapiens',\n 'Solanum tuberosum',\n 'Carcharodon carcharias',\n 'Carassius carassius']\n# Instruction: correct the three lists by replacing the erroneous entries\n### your lines here!\n\n# Instruction: print the three lists after correction to check your work\n### your lines here!",
"_____no_output_____"
],
[
"# Using Python you will soon learn it is possible to print out the three lists as a table with rows\n# Instruction: run this cell to check your corrections \nfor row in zip(organisms, chromosomes, scientific):\n print(row)",
"_____no_output_____"
]
],
[
[
"### Deleting list elements by `del(list_name[index])`\n> \n> *Advanced material: If you are confused or time is short go on to [homework B](./ex_B_homework.ipynb)*\n\nAs you have seen in the Data Camp Coures, it is easy to delete a list element using the `del()`: ",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstrate deleting list elements\nfruits = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']\n# delete the first fruits item\ndel(fruits[0])\n# delete the last fruits item\ndel(fruits[-1])\nprint('after deleting first and last:', fruits)",
"_____no_output_____"
]
],
[
[
"### You **cannot** use `del()` on strings\n> \n> *Advanced material: If you are confused or time is short go on to [homework B](./ex_B_homework.ipynb)*\n\nAlthough lists and strings are similar note that you cannot reassign specific string characters \nin the same way as you can lists:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstrate that you cannot reassign specific string items\n# N.B. running this cell will cause a failure!\nmy_list = ['a', 'b']\nmy_list[0] = 'c' # works my_list now ['c', 'b']\nmy_string = 'ab'\nmy_string[0] = 'c' # Fails with TypeError: 'str' object does not support item assignment",
"_____no_output_____"
]
],
[
[
"Similarly, you cannot use del() on string characters:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstrate that you cannot del specific string items\n# N.B. running this cell will cause a failure!\nmy_list = ['a', 'b']\ndel(my_list[0]) # works my_list now ['b']\nmy_string = 'ab'\ndel(my_string[0]) # Fails with TypeError: 'str' object doesn't support item deletion",
"_____no_output_____"
]
],
[
[
"the reason is that in Python strings are *immutable* - once defined they cannot be altered. \n\nIf you want to perform this kind of manipulation on a string you can convert to a list, manipulate it and convert it back:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to demonstrate converting \n# a string to a list, manipulation and back conversion\nmy_str = 'happily'\nmy_list = list(my_str)\nmy_list[0] ='H'\ndel(my_list[-3:-1]) # remove the 'il'\nmy_str = ''.join(my_list) # replace my_str with the manipulated one\nprint(my_str)",
"_____no_output_____"
]
],
[
[
"### Lists of lists\n> \n> *Advanced material: If you are confused or time is short go on to* **homework_C.ipynb**\n\nIn the Data camp course you saw how it makes sense to group data by using lists that contain lists in them:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to see simplified DataCamp List of lists example:\n\n# house information as list of lists\nhouse = [[\"hallway\", 32],\n [\"kitchen\", 75.],\n [\"living room\", 33.]]\nprint(type(house))\nprint(house)",
"_____no_output_____"
]
],
[
[
"Lets return to our the table:\n\n| Organism | Scientific name | Chromosome number |\n| -------- | :--------------: | :---------------: |\n| fruit fly | Drosophila melanogaster | 8 |\n| rice | Oryza sativa | 20 |\n| mouse | Mus musculus | 40 |\n| wheat | Triticum aestivum | 42 |\n| human | Homo sapiens | 46 |\n\nabove we have stored the information in three separate lists. But this approach means that information could easily become out of sync. We could store the information in a single list:\n```\ntable_single = ['fruit fly', 'Drosophila melanogaster', 8, 'rice', 'Oryza sativa', 24, ] \n```\nbut this means that accessing/modifying the data is pretty cumbersome\n* the organism is stored in indices 0, 3, 6, ...\n* the Chromosome number in indices 2, 5, 8\n\nInstead storing as in a list of lists makes sense:",
"_____no_output_____"
]
],
[
[
"# Instruction: run this cell to see start of table as a list of lists\ntable_lol = [['fruit fly', 'Drosophila melanogaster', 8],\n ['rice', 'Oryza sativa', 22],\n ['mouse', 'Mus musculus', 40]]\nprint('full table', table_lol)\nprint('first row of table: ', table_lol[0])\nprint('first organism: ', table_lol[0][0])\nprint('first Chromosome number : ', table_lol[0][-1])",
"_____no_output_____"
],
[
"# Instruction: use append or concatention to complete \n# table_lol with the data for wheat and human\nprint('completed table', table_lol)",
"_____no_output_____"
]
],
[
[
"You decide that you want to remove the `'fruit fly'` data from the table and notice there has been a mistake in the number of chromosome for rice that should be 24 rather than 20. Finally print the table to check your work.",
"_____no_output_____"
]
],
[
[
"# Instruction: make corrections to table_lol\n### your lines here!",
"_____no_output_____"
]
],
[
[
"> \n> *Advanced Python Hint: there are other, possibly better choices to store the table information:*\n> * *Could have a list of named tuples or*\n> * *An ordered dictionary of tuples*",
"_____no_output_____"
],
[
"## Homework C\nNow go on and use strings and the string functions and methods introduced here to complete the **homework_C.ipynb** book",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb7c9de1ee23726a295de554f53bbdb67e09d0f7
| 10,559 |
ipynb
|
Jupyter Notebook
|
_build/jupyter_execute/Week2/rng.ipynb
|
ChristopherDavisUCI/UCI-Math-10-W22
|
19efa7f9ff56d8aa1f6cc2af2873f85a771a4496
|
[
"BSD-3-Clause"
] | null | null | null |
_build/jupyter_execute/Week2/rng.ipynb
|
ChristopherDavisUCI/UCI-Math-10-W22
|
19efa7f9ff56d8aa1f6cc2af2873f85a771a4496
|
[
"BSD-3-Clause"
] | null | null | null |
_build/jupyter_execute/Week2/rng.ipynb
|
ChristopherDavisUCI/UCI-Math-10-W22
|
19efa7f9ff56d8aa1f6cc2af2873f85a771a4496
|
[
"BSD-3-Clause"
] | null | null | null | 28.007958 | 250 | 0.455441 |
[
[
[
"# Random numbers in NumPy",
"_____no_output_____"
],
[
"## Random integers\n\nHere is the recommended way to make random integers in NumPy. We first instantiate a \"random number generator\" that we call `rng`.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nrng = np.random.default_rng()",
"_____no_output_____"
],
[
"help(rng.integers)",
"Help on built-in function integers:\n\nintegers(...) method of numpy.random._generator.Generator instance\n integers(low, high=None, size=None, dtype=np.int64, endpoint=False)\n \n Return random integers from `low` (inclusive) to `high` (exclusive), or\n if endpoint=True, `low` (inclusive) to `high` (inclusive). Replaces\n `RandomState.randint` (with endpoint=False) and\n `RandomState.random_integers` (with endpoint=True)\n \n Return random integers from the \"discrete uniform\" distribution of\n the specified dtype. If `high` is None (the default), then results are\n from 0 to `low`.\n \n Parameters\n ----------\n low : int or array-like of ints\n Lowest (signed) integers to be drawn from the distribution (unless\n ``high=None``, in which case this parameter is 0 and this value is\n used for `high`).\n high : int or array-like of ints, optional\n If provided, one above the largest (signed) integer to be drawn\n from the distribution (see above for behavior if ``high=None``).\n If array-like, must contain integer values\n size : int or tuple of ints, optional\n Output shape. If the given shape is, e.g., ``(m, n, k)``, then\n ``m * n * k`` samples are drawn. Default is None, in which case a\n single value is returned.\n dtype : dtype, optional\n Desired dtype of the result. Byteorder must be native.\n The default value is np.int64.\n endpoint : bool, optional\n If true, sample from the interval [low, high] instead of the\n default [low, high)\n Defaults to False\n \n Returns\n -------\n out : int or ndarray of ints\n `size`-shaped array of random integers from the appropriate\n distribution, or a single such random int if `size` not provided.\n \n Notes\n -----\n When using broadcasting with uint64 dtypes, the maximum value (2**64)\n cannot be represented as a standard integer type. The high array (or\n low if high is None) must have object dtype, e.g., array([2**64]).\n \n Examples\n --------\n >>> rng = np.random.default_rng()\n >>> rng.integers(2, size=10)\n array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random\n >>> rng.integers(1, size=10)\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n \n Generate a 2 x 4 array of ints between 0 and 4, inclusive:\n \n >>> rng.integers(5, size=(2, 4))\n array([[4, 0, 2, 1],\n [3, 2, 2, 0]]) # random\n \n Generate a 1 x 3 array with 3 different upper bounds\n \n >>> rng.integers(1, [3, 5, 10])\n array([2, 2, 9]) # random\n \n Generate a 1 by 3 array with 3 different lower bounds\n \n >>> rng.integers([1, 5, 7], 10)\n array([9, 8, 7]) # random\n \n Generate a 2 by 4 array using broadcasting with dtype of uint8\n \n >>> rng.integers([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)\n array([[ 8, 6, 9, 7],\n [ 1, 16, 9, 12]], dtype=uint8) # random\n \n References\n ----------\n .. [1] Daniel Lemire., \"Fast Random Integer Generation in an Interval\",\n ACM Transactions on Modeling and Computer Simulation 29 (1), 2019,\n http://arxiv.org/abs/1805.10941.\n\n"
]
],
[
[
"Making a 10x2 NumPy array of random integers between 1 (inclusive) and 5 (exclusive).",
"_____no_output_____"
]
],
[
[
"rng.integers(1,5,size=(10,2))",
"_____no_output_____"
]
],
[
[
"Here are two ways to include 5.",
"_____no_output_____"
]
],
[
[
"rng.integers(1,6,size=(10,2))",
"_____no_output_____"
],
[
"rng.integers(1,5,size=(10,2),endpoint=True)",
"_____no_output_____"
]
],
[
[
"## Random real numbers\n\nIf making random real numbers, the range is always between 0 and 1; there is no way to specify the upper and lower bounds as inputs to the function. So to increase the range of outputs, you multiply, and to shift the range of outputs, you add.",
"_____no_output_____"
]
],
[
[
"rng.random(size=(10,2))",
"_____no_output_____"
]
],
[
[
"Random real numbers between 0 and 30:",
"_____no_output_____"
]
],
[
[
"30*rng.random(size=(10,2))",
"_____no_output_____"
]
],
[
[
"Random real numbers between 5 and 35:",
"_____no_output_____"
]
],
[
[
"5 + 30*rng.random(size=(10,2))",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7c9f0afc26d7f8312eec90eddcfb61dd3372e2
| 4,380 |
ipynb
|
Jupyter Notebook
|
Introduction to Python/Decorators.ipynb
|
Xelepam/Python_Scripts
|
72779c5b1fa4188b7aaf8def39d5d1902002010b
|
[
"MIT"
] | null | null | null |
Introduction to Python/Decorators.ipynb
|
Xelepam/Python_Scripts
|
72779c5b1fa4188b7aaf8def39d5d1902002010b
|
[
"MIT"
] | null | null | null |
Introduction to Python/Decorators.ipynb
|
Xelepam/Python_Scripts
|
72779c5b1fa4188b7aaf8def39d5d1902002010b
|
[
"MIT"
] | null | null | null | 17.590361 | 250 | 0.454795 |
[
[
[
"def func():\n return 1",
"_____no_output_____"
],
[
"func()",
"_____no_output_____"
],
[
"s = 'This is a global variable'\n\ndef func():\n return locals()",
"_____no_output_____"
],
[
"func()",
"_____no_output_____"
],
[
"print (globals()['s'])",
"This is a global variable\n"
],
[
"def hello(name='Omar'):\n return 'Hello ' + name",
"_____no_output_____"
],
[
"hello()",
"_____no_output_____"
],
[
"greet = hello",
"_____no_output_____"
],
[
"greet",
"_____no_output_____"
],
[
"greet()",
"_____no_output_____"
],
[
"del hello",
"_____no_output_____"
],
[
"hello()",
"_____no_output_____"
],
[
"greet()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7ca294bd8094a128df3ac7a439aa9ef77b1980
| 8,030 |
ipynb
|
Jupyter Notebook
|
_build/jupyter_execute/ch02/ch2_3.ipynb
|
liuzhengqi1996/math452
|
635b6ce53cb792e316abf4f47396f2e4f0686815
|
[
"MIT"
] | null | null | null |
_build/jupyter_execute/ch02/ch2_3.ipynb
|
liuzhengqi1996/math452
|
635b6ce53cb792e316abf4f47396f2e4f0686815
|
[
"MIT"
] | null | null | null |
_build/jupyter_execute/ch02/ch2_3.ipynb
|
liuzhengqi1996/math452
|
635b6ce53cb792e316abf4f47396f2e4f0686815
|
[
"MIT"
] | null | null | null | 42.263158 | 815 | 0.57721 |
[
[
[
"# 2.3 KL divergence and cross-entropy",
"_____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_1x5pta90&flashvars[streamerType]=auto&flashvars[localizationCode]=en&flashvars[leadWithHTML5]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true&flashvars[hotspots.plugin]=1&flashvars[Kaltura.addCrossoriginToIframe]=true&&wid=1_l1sjg1vv\" ,width='800', height='500')\n",
"_____no_output_____"
]
],
[
[
"Cross-entropy minimization is frequently used in optimization and\nrare-event probability estimation. When comparing a distribution against\na fixed reference distribution, cross-entropy and KL divergence are\nidentical up to an additive constant. See more details in\n[@murphy2012machine; @kullback1951information; @kullback1997information]\nand the reference therein.\n\nThe KL(Kullback--Leibler) divergence defines a special distance between\ntwo discrete probability distributions \n$\np=\\left( \\begin{array}{ccc}\np_1\\\\\n\\vdots \\\\\np_k\n\\end{array} \\right),\\quad q=\\left( \\begin{array}{ccc}\nq_1\\\\\n\\vdots \\\\\nq_k\n\\end{array} \\right\n)\n$\nwith $\n0\\le p_i, q_i\\le1$\nand\n$\\sum_{i=1}^{k}p_i=\\sum_{i=1}^{k}q_i=1$ by $\nD_{\\rm KL}(q,p)= \\sum_{i=1}^k q_i\\log \\frac{q_i}{p_i}.$\n\n```{admonition} Lemma\n$D_{\\rm KL}(q,p)$ works like a \"distance\\\" without the symmetry:\n\n1. $D_{\\rm KL}(q,p)\\ge0$;\n\n2. $D_{\\rm KL}(q,p)=0$ if and only if $p=q$;\n```\n\n```{admonition} Proof\n*Proof.* We first note that the elementary inequality\n$\\log x \\le x - 1, \\quad\\mathrm{for\\ any\\ }x\\ge0,$ and the equality\nholds if and only if $x=1$.\n$-D_{\\rm KL}(q,p) = - \\sum_{i=1}^c q_i\\log \\frac{q_i}{p_i} = \\sum_{i=1}^k q_i\\log \\frac{p_i}{q_i} \\le \\sum_{i=1}^k q_i( \\frac{p_i}{q_i} - 1) = 0.$\nAnd the equality holds if and only if\n$\\frac{p_i}{q_i} = 1 \\quad \\forall i = 1:k.$ \n```\n\nDefine cross-entropy for distribution $p$ and $q$ by\n$\nH(q,p) = - \\sum_{i=1}^k q_i \\log p_i,$ and the entropy for distribution\n$q$ by $\nH(q) = - \\sum_{i=1}^k q_i \\log q_i.$ Note that\n$D_{\\rm KL}(q,p)= \\sum_{i=1}^k q_i\\log \\frac{q_i}{p_i} = \\sum_{i=1}^k q_i \\log q_i - \\sum_{i=1}^k q_i \\log p_i$\nThus, \n\n$$\n H(q,p) = H(q) + D_{\\rm KL}(q,p).\n$$ (rel1)\n\nIt follows from the [relation](rel1) that \n\n$$\n \\mathop{\\arg\\min}_p D_{\\rm KL}(q,p)=\\mathop{\\arg\\min}_p H(q,p).\n$$ (rel2)\n\nThe concept of cross-entropy can be used to define a loss function in\nmachine learning and optimization. Let us assume $y_i$ is the true label\nfor $x_i$, for example $y_i = e_{k_i}$ if $x_i \\in A_{k_i}$. Consider\nthe predicted distribution \n$p(x;\\theta) = \\frac{1}{\\sum\\limits_{i=1}^k e^{w_i x+b_i}}$.\n$\\begin{pmatrix}\ne^{w_1 x+b_1}\\\\\ne^{w_2 x+b_2}\\\\\n\\vdots\\\\\ne^{w_k x+b_k}\n\\end{pmatrix}\n= \\begin{pmatrix}\np_1(x; \\theta) \\\\\np_2(x; \\theta) \\\\\n\\vdots \\\\\np_k(x; \\theta)\n\\end{pmatrix}$\nfor any data $x \\in A$. By[.](rel2), the minimization of KL divergence is\nequivalent to the minimization of the cross-entropy, namely\n$\\mathop{\\arg\\min}_{\\theta} \\sum_{i=1}^N D_{\\rm KL}(y_i, p(x_i;\\theta)) = \\mathop{\\arg\\min}_{\\theta} \\sum_{i=1}^N H(y_i, p(x_i; \\theta)).$\nRecall that we have all data\n$D = \\{(x_1,y_1),(x_2,y_2),\\cdots, (x_N, y_N)\\}$. Then, it is natural to\nconsider the loss function as following:\n$\\sum_{j=1}^N H(y_i, p(x_i; \\theta)),$ which measures the\ndistance between the real label and predicted one for all data. In the\nmeantime, we can check that \n$\\begin{aligned}\n\\sum_{j=1}^N H(y_j, p(x_j; \\theta))&=-\\sum_{j=1}^N y_j \\cdot \\log p(x_j; \\theta )\\\\\n&=-\\sum_{j=1}^N \\log p_{i_j}(x_i; \\theta) \\quad (\\text{because}~y_j = e_{i_j}~\\text{for}~x_j \\in A_{i_j})\\\\\n&=-\\sum_{i=1}^k \\sum_{x\\in A_i} \\log p_{i}(x; \\theta) \\\\\n&=-\\log \\prod_{i=1}^k \\prod_{x\\in A_i} p_{i}(x; \\theta)\\\\\n& = L(\\theta)\n\\end{aligned}$ with $L(\\theta)$ \ndefined in as\n$L( \\theta) = - \\sum_{i=1}^k \\sum_{x\\in A_i} \\log p_{i}(x; \\theta).$\n\nThat is to say, the logistic regression loss function defined by\nlikelihood in []() is exact the loss function defined by measuring\nthe distance between real label and predicted one via cross-entropy. We\ncan note $\\label{key}\n\\min_{ \\theta} L_\\lambda( \\theta) \\Leftrightarrow \\min_{ \\theta} \\sum_{j=1}^N H(y_i, p(x_i; \\theta)) + \\lambda R(\\| \\theta\\|) \n\\Leftrightarrow \\min_{ \\theta} \\sum_{j=1}^N D_{\\rm KL}(y_i, p(x_i; \\theta)) + \\lambda R(\\| \\theta\\|).$\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7cb07cdb4130b542fdd3d532b2ba065ca65c8d
| 9,694 |
ipynb
|
Jupyter Notebook
|
4 - Sequences, Time Series and Prediction/Week 3/Course 4 Week 3.ipynb
|
chen-xin-94/DeepLearning.AI-TensorFlow-Developer-Course
|
7d84b2ae362fa57a8c1541ca3007414ea9f8023b
|
[
"Apache-2.0"
] | 79 |
2020-11-05T07:50:41.000Z
|
2022-03-31T04:49:58.000Z
|
Coursera/DeepLearning.AI TensorFlow Developer Professional Certificate/4 - Sequences, Time Series and Prediction/Week 3/Course 4 Week 3.ipynb
|
MaheshBabu11/Python
|
f708cd5f9c561b64a73c63d228c8039ae35e91df
|
[
"MIT"
] | null | null | null |
Coursera/DeepLearning.AI TensorFlow Developer Professional Certificate/4 - Sequences, Time Series and Prediction/Week 3/Course 4 Week 3.ipynb
|
MaheshBabu11/Python
|
f708cd5f9c561b64a73c63d228c8039ae35e91df
|
[
"MIT"
] | 72 |
2020-12-16T03:42:34.000Z
|
2022-03-31T08:24:05.000Z
| 32.861017 | 116 | 0.468537 |
[
[
[
"!pip install tf-nightly-2.0-preview\n",
"_____no_output_____"
],
[
"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nprint(tf.__version__)",
"_____no_output_____"
],
[
"def plot_series(time, series, format=\"-\", start=0, end=None):\n plt.plot(time[start:end], series[start:end], format)\n plt.xlabel(\"Time\")\n plt.ylabel(\"Value\")\n plt.grid(False)\n\ndef trend(time, slope=0):\n return slope * time\n\ndef seasonal_pattern(season_time):\n \"\"\"Just an arbitrary pattern, you can change it if you wish\"\"\"\n return np.where(season_time < 0.1,\n np.cos(season_time * 6 * np.pi),\n 2 / np.exp(9 * season_time))\n\ndef seasonality(time, period, amplitude=1, phase=0):\n \"\"\"Repeats the same pattern at each period\"\"\"\n season_time = ((time + phase) % period) / period\n return amplitude * seasonal_pattern(season_time)\n\ndef noise(time, noise_level=1, seed=None):\n rnd = np.random.RandomState(seed)\n return rnd.randn(len(time)) * noise_level\n\ntime = np.arange(10 * 365 + 1, dtype=\"float32\")\nbaseline = 10\nseries = trend(time, 0.1) \nbaseline = 10\namplitude = 40\nslope = 0.005\nnoise_level = 3\n\n# Create the series\nseries = baseline + trend(time, slope) + seasonality(time, period=365, amplitude=amplitude)\n# Update with noise\nseries += noise(time, noise_level, seed=51)\n\nsplit_time = 3000\ntime_train = time[:split_time]\nx_train = series[:split_time]\ntime_valid = time[split_time:]\nx_valid = series[split_time:]\n\nwindow_size = 20\nbatch_size = 32\nshuffle_buffer_size = 1000\n\nplot_series(time, series)",
"_____no_output_____"
],
[
"def windowed_dataset(series, window_size, batch_size, shuffle_buffer):\n dataset = tf.data.Dataset.from_tensor_slices(series)\n dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)\n dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))\n dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1]))\n dataset = dataset.batch(batch_size).prefetch(1)\n return dataset",
"_____no_output_____"
],
[
"tf.keras.backend.clear_session()\ntf.random.set_seed(51)\nnp.random.seed(51)\n\ntf.keras.backend.clear_session()\ndataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n input_shape=[None]),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(1),\n tf.keras.layers.Lambda(lambda x: x * 10.0)\n])\n\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(\n lambda epoch: 1e-8 * 10**(epoch / 20))\noptimizer = tf.keras.optimizers.SGD(lr=1e-8, momentum=0.9)\nmodel.compile(loss=tf.keras.losses.Huber(),\n optimizer=optimizer,\n metrics=[\"mae\"])\nhistory = model.fit(dataset, epochs=100, callbacks=[lr_schedule])",
"_____no_output_____"
],
[
"plt.semilogx(history.history[\"lr\"], history.history[\"loss\"])\nplt.axis([1e-8, 1e-4, 0, 30])",
"_____no_output_____"
],
[
"tf.keras.backend.clear_session()\ntf.random.set_seed(51)\nnp.random.seed(51)\n\ntf.keras.backend.clear_session()\ndataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),\n input_shape=[None]),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Dense(1),\n tf.keras.layers.Lambda(lambda x: x * 100.0)\n])\n\n\nmodel.compile(loss=\"mse\", optimizer=tf.keras.optimizers.SGD(lr=1e-5, momentum=0.9),metrics=[\"mae\"])\nhistory = model.fit(dataset,epochs=500,verbose=1)",
"_____no_output_____"
],
[
"forecast = []\nresults = []\nfor time in range(len(series) - window_size):\n forecast.append(model.predict(series[time:time + window_size][np.newaxis]))\n\nforecast = forecast[split_time-window_size:]\nresults = np.array(forecast)[:, 0, 0]\n\n\nplt.figure(figsize=(10, 6))\n\nplot_series(time_valid, x_valid)\nplot_series(time_valid, results)",
"_____no_output_____"
],
[
"tf.keras.metrics.mean_absolute_error(x_valid, results).numpy()",
"_____no_output_____"
],
[
"import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\n#-----------------------------------------------------------\n# Retrieve a list of list results on training and test data\n# sets for each training epoch\n#-----------------------------------------------------------\nmae=history.history['mae']\nloss=history.history['loss']\n\nepochs=range(len(loss)) # Get number of epochs\n\n#------------------------------------------------\n# Plot MAE and Loss\n#------------------------------------------------\nplt.plot(epochs, mae, 'r')\nplt.plot(epochs, loss, 'b')\nplt.title('MAE and Loss')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend([\"MAE\", \"Loss\"])\n\nplt.figure()\n\nepochs_zoom = epochs[200:]\nmae_zoom = mae[200:]\nloss_zoom = loss[200:]\n\n#------------------------------------------------\n# Plot Zoomed MAE and Loss\n#------------------------------------------------\nplt.plot(epochs_zoom, mae_zoom, 'r')\nplt.plot(epochs_zoom, loss_zoom, 'b')\nplt.title('MAE and Loss')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend([\"MAE\", \"Loss\"])\n\nplt.figure()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7cb95bb6a8693cce90af3fabc3bf9ebae883a0
| 23,861 |
ipynb
|
Jupyter Notebook
|
bronze/B72_Rotation_Automata_Solutions.ipynb
|
zeynepCankara/Introduction-Quantum-Programming
|
6852a9bb7ba6a58086b2d9eb6a713b21fea20de5
|
[
"MIT"
] | 3 |
2019-06-04T18:50:39.000Z
|
2022-01-17T00:50:13.000Z
|
bronze/B72_Rotation_Automata_Solutions.ipynb
|
zeynepCankara/Introduction-Quantum-Programming
|
6852a9bb7ba6a58086b2d9eb6a713b21fea20de5
|
[
"MIT"
] | null | null | null |
bronze/B72_Rotation_Automata_Solutions.ipynb
|
zeynepCankara/Introduction-Quantum-Programming
|
6852a9bb7ba6a58086b2d9eb6a713b21fea20de5
|
[
"MIT"
] | 2 |
2020-07-22T00:25:48.000Z
|
2022-01-17T00:50:14.000Z
| 36.596626 | 309 | 0.502158 |
[
[
[
"<table>\n <tr><td align=\"right\" style=\"background-color:#ffffff;\">\n <img src=\"../images/logo.jpg\" width=\"20%\" align=\"right\">\n </td></tr>\n <tr><td align=\"right\" style=\"color:#777777;background-color:#ffffff;font-size:12px;\">\n Abuzer Yakaryilmaz | April 30, 2019 (updated) \n </td></tr>\n <tr><td align=\"right\" style=\"color:#bbbbbb;background-color:#ffffff;font-size:11px;font-style:italic;\">\n This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros.\n </td></tr>\n</table>\n$ \\newcommand{\\bra}[1]{\\langle #1|} $\n$ \\newcommand{\\ket}[1]{|#1\\rangle} $\n$ \\newcommand{\\braket}[2]{\\langle #1|#2\\rangle} $\n$ \\newcommand{\\dot}[2]{ #1 \\cdot #2} $\n$ \\newcommand{\\biginner}[2]{\\left\\langle #1,#2\\right\\rangle} $\n$ \\newcommand{\\mymatrix}[2]{\\left( \\begin{array}{#1} #2\\end{array} \\right)} $\n$ \\newcommand{\\myvector}[1]{\\mymatrix{c}{#1}} $\n$ \\newcommand{\\myrvector}[1]{\\mymatrix{r}{#1}} $\n$ \\newcommand{\\mypar}[1]{\\left( #1 \\right)} $\n$ \\newcommand{\\mybigpar}[1]{ \\Big( #1 \\Big)} $\n$ \\newcommand{\\sqrttwo}{\\frac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\dsqrttwo}{\\dfrac{1}{\\sqrt{2}}} $\n$ \\newcommand{\\onehalf}{\\frac{1}{2}} $\n$ \\newcommand{\\donehalf}{\\dfrac{1}{2}} $\n$ \\newcommand{\\hadamard}{ \\mymatrix{rr}{ \\sqrttwo & \\sqrttwo \\\\ \\sqrttwo & -\\sqrttwo }} $\n$ \\newcommand{\\vzero}{\\myvector{1\\\\0}} $\n$ \\newcommand{\\vone}{\\myvector{0\\\\1}} $\n$ \\newcommand{\\vhadamardzero}{\\myvector{ \\sqrttwo \\\\ \\sqrttwo } } $\n$ \\newcommand{\\vhadamardone}{ \\myrvector{ \\sqrttwo \\\\ -\\sqrttwo } } $\n$ \\newcommand{\\myarray}[2]{ \\begin{array}{#1}#2\\end{array}} $\n$ \\newcommand{\\X}{ \\mymatrix{cc}{0 & 1 \\\\ 1 & 0} } $\n$ \\newcommand{\\Z}{ \\mymatrix{rr}{1 & 0 \\\\ 0 & -1} } $\n$ \\newcommand{\\Htwo}{ \\mymatrix{rrrr}{ \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} & \\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} \\\\ \\frac{1}{2} & -\\frac{1}{2} & -\\frac{1}{2} & \\frac{1}{2} } } $\n$ \\newcommand{\\CNOT}{ \\mymatrix{cccc}{1 & 0 & 0 & 0 \\\\ 0 & 1 & 0 & 0 \\\\ 0 & 0 & 0 & 1 \\\\ 0 & 0 & 1 & 0} } $\n$ \\newcommand{\\norm}[1]{ \\left\\lVert #1 \\right\\rVert } $",
"_____no_output_____"
],
[
"<h2> <font color=\"blue\"> Solutions for </font>Rotation Automata</h2>",
"_____no_output_____"
],
[
"<a id=\"task1\"></a>\n<h3> Task 1 </h3>\n\nDo the same task given above by using different angles.\n\nTest at least three different angles. \n\nPlease modify the code above.",
"_____no_output_____"
],
[
"<h3>Solution</h3>",
"_____no_output_____"
],
[
"Any odd multiple of $ \\frac{\\pi}{16} $ works: $ i \\frac{\\pi}{16} $, where $ i \\in \\{1,3,5,7,\\ldots\\} $",
"_____no_output_____"
],
[
"<a id=\"task2\"></a>\n<h3> Task 2 </h3>\n\nLet $ \\mathsf{p} = 11 $.\n\nDetermine an angle of rotation such that when the length of stream is a multiple of $ \\sf p $, then we observe only state $ 0 $, and we can also observe state $ 1 $, otherwise.\n\nTest your rotation by using a quantum circuit. Execute the circuit for all streams of lengths from 1 to 11.",
"_____no_output_____"
],
[
"<h3>Solution</h3>",
"_____no_output_____"
],
[
"We can pick any angle $ k\\frac{2\\pi}{11} $ for $ k \\in \\{1,\\ldots,10\\} $.",
"_____no_output_____"
]
],
[
[
"from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\nfrom math import pi\nfrom random import randrange\n\n# the angle of rotation\nr = randrange(1,11)\nprint(\"the picked angle is\",r,\"times of 2pi/11\")\nprint() \ntheta = r*2*pi/11\n\n# we read streams of length from 1 to 11\nfor i in range(1,12):\n # quantum circuit with one qubit and one bit\n qreg = QuantumRegister(1) \n creg = ClassicalRegister(1) \n mycircuit = QuantumCircuit(qreg,creg)\n # the stream of length i\n for j in range(i):\n mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol\n # we measure after reading the whole stream\n mycircuit.measure(qreg[0],creg[0])\n # execute the circuit 1000 times\n job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000)\n counts = job.result().get_counts(mycircuit)\n print(\"stream of lenght\",i,\"->\",counts)",
"_____no_output_____"
]
],
[
[
"<a id=\"task3\"></a>\n<h3> Task 3 </h3>\n\nList down 10 possible different angles for Task 2, where each angle should be between 0 and $2\\pi$.",
"_____no_output_____"
],
[
"<h3>Solution</h3>",
"_____no_output_____"
],
[
"Any angle $ k\\frac{2\\pi}{11} $ for $ k \\in \\{1,\\ldots,10\\} $.",
"_____no_output_____"
],
[
"<a id=\"task4\"></a>\n<h3> Task 4 </h3>\n\nFor each stream of length from 1 to 10, experimentially determine the best angle of rotation by using your circuit.",
"_____no_output_____"
],
[
"<h3>Solution</h3>",
"_____no_output_____"
]
],
[
[
"from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\nfrom math import pi\nfrom random import randrange\n\n# for each stream of length from 1 to 10\nfor i in range(1,11):\n # we try each angle of the form k*2*pi/11 for k=1,...,10\n # we try to find the best k for which we observe 1 the most\n number_of_one_state = 0\n best_k = 1\n all_outcomes_for_i = \"length \"+str(i)+\"-> \"\n for k in range(1,11):\n theta = k*2*pi/11\n # quantum circuit with one qubit and one bit\n qreg = QuantumRegister(1) \n creg = ClassicalRegister(1) \n mycircuit = QuantumCircuit(qreg,creg)\n # the stream of length i\n for j in range(i):\n mycircuit.ry(2*theta,qreg[0]) # apply one rotation for each symbol\n # we measure after reading the whole stream\n mycircuit.measure(qreg[0],creg[0])\n # execute the circuit 10000 times\n job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=10000)\n counts = job.result().get_counts(mycircuit)\n all_outcomes_for_i = all_outcomes_for_i + str(k)+ \":\" + str(counts['1']) + \" \"\n if int(counts['1']) > number_of_one_state:\n number_of_one_state = counts['1']\n best_k = k\n print(all_outcomes_for_i)\n print(\"for length\",i,\", the best k is\",best_k)\n print()",
"length 1-> 1:2948 2:8226 3:9785 4:5776 5:808 6:808 7:5652 8:9797 9:8300 10:2946 \nfor length 1 , the best k is 8\n\nlength 2-> 1:8276 2:5681 3:820 4:9784 5:2886 6:2887 7:9787 8:746 9:5688 10:8250 \nfor length 2 , the best k is 7\n\nlength 3-> 1:9784 2:858 3:8244 4:2830 5:5716 6:5656 7:2906 8:8297 9:820 10:9777 \nfor length 3 , the best k is 1\n\nlength 4-> 1:5646 2:9788 3:2970 4:787 5:8245 6:8280 7:840 8:3002 9:9825 10:5711 \nfor length 4 , the best k is 9\n\nlength 5-> 1:788 2:2985 3:5671 4:8208 5:9782 6:9797 7:8263 8:5638 9:2980 10:824 \nfor length 5 , the best k is 6\n\nlength 6-> 1:798 2:2939 3:5724 4:8301 5:9812 6:9787 7:8227 8:5710 9:2894 10:801 \nfor length 6 , the best k is 5\n\nlength 7-> 1:5655 2:9803 3:2918 4:776 5:8274 6:8248 7:768 8:2895 9:9780 10:5679 \nfor length 7 , the best k is 2\n\nlength 8-> 1:9802 2:771 3:8345 4:2909 5:5735 6:5743 7:2949 8:8317 9:814 10:9808 \nfor length 8 , the best k is 10\n\nlength 9-> 1:8240 2:5776 3:768 4:9796 5:2932 6:2929 7:9795 8:790 9:5678 10:8306 \nfor length 9 , the best k is 4\n\nlength 10-> 1:2941 2:8223 3:9780 4:5697 5:746 6:802 7:5667 8:9825 9:8276 10:2908 \nfor length 10 , the best k is 8\n\n"
]
],
[
[
"<a id=\"task5\"></a>\n<h3> Task 5 </h3>\n\nLet $ \\mathsf{p} = 31 $.\n\nCreate a circuit with three quantum states and three classical states.\n\nRotate the qubits with angles $ 3\\frac{2\\pi}{31} $, $ 7\\frac{2\\pi}{31} $, and $ 11\\frac{2\\pi}{31} $, respectively.\n\nExecute your circuit for all streams of lengths from 1 to 30. Check whether the number of state $ \\ket{000} $ is less than half or not.\n\n<i>Note that whether a key is in dictionary or not can be checked as follows:</i>\n\n if '000' in counts.keys():\n c = counts['000']\n else:\n c = 0",
"_____no_output_____"
],
[
"<h3>Solution</h3>",
"_____no_output_____"
]
],
[
[
"from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\nfrom math import pi\nfrom random import randrange\n\n# the angles of rotations\ntheta1 = 3*2*pi/31\ntheta2 = 7*2*pi/31\ntheta3 = 11*2*pi/31\n\n# we read streams of length from 1 to 30\nfor i in range(1,31):\n # quantum circuit with three qubits and three bits\n qreg = QuantumRegister(3) \n creg = ClassicalRegister(3) \n mycircuit = QuantumCircuit(qreg,creg)\n # the stream of length i\n for j in range(i):\n # apply rotations for each symbol\n mycircuit.ry(2*theta1,qreg[0]) \n mycircuit.ry(2*theta2,qreg[1]) \n mycircuit.ry(2*theta3,qreg[2]) \n # we measure after reading the whole stream\n mycircuit.measure(qreg,creg)\n # execute the circuit N times\n N = 1000\n job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)\n counts = job.result().get_counts(mycircuit)\n print(counts)\n if '000' in counts.keys():\n c = counts['000']\n else:\n c = 0\n print('000 is observed',c,'times out of',N)\n percentange = round(c/N*100,1)\n print(\"the ratio of 000 is \",percentange,\"%\")\n print()",
"{'001': 4, '101': 7, '110': 399, '100': 8, '011': 109, '010': 250, '111': 218, '000': 5}\n000 is observed 5 times out of 1000\nthe ratio of 000 is 0.5 %\n\n{'001': 51, '101': 749, '110': 9, '100': 92, '011': 3, '010': 1, '111': 90, '000': 5}\n000 is observed 5 times out of 1000\nthe ratio of 000 is 0.5 %\n\n{'001': 166, '010': 38, '111': 129, '101': 25, '110': 6, '000': 8, '011': 628}\n000 is observed 8 times out of 1000\nthe ratio of 000 is 0.8 %\n\n{'001': 218, '101': 70, '110': 50, '100': 81, '011': 116, '010': 133, '111': 38, '000': 294}\n000 is observed 294 times out of 1000\nthe ratio of 000 is 29.4 %\n\n{'010': 10, '111': 9, '000': 9, '101': 5, '110': 513, '100': 454}\n000 is observed 9 times out of 1000\nthe ratio of 000 is 0.9 %\n\n{'001': 43, '101': 49, '110': 260, '100': 123, '011': 62, '010': 231, '111': 76, '000': 156}\n000 is observed 156 times out of 1000\nthe ratio of 000 is 15.6 %\n\n{'001': 639, '010': 47, '111': 1, '000': 143, '101': 10, '100': 2, '011': 158}\n000 is observed 143 times out of 1000\nthe ratio of 000 is 14.3 %\n\n{'001': 37, '010': 3, '111': 608, '101': 86, '110': 18, '000': 2, '011': 246}\n000 is observed 2 times out of 1000\nthe ratio of 000 is 0.2 %\n\n{'001': 56, '111': 28, '000': 59, '101': 433, '110': 20, '100': 402, '011': 2}\n000 is observed 59 times out of 1000\nthe ratio of 000 is 5.9 %\n\n{'010': 884, '111': 3, '110': 76, '000': 4, '011': 33}\n000 is observed 4 times out of 1000\nthe ratio of 000 is 0.4 %\n\n{'001': 111, '010': 8, '000': 547, '101': 54, '110': 6, '100': 274}\n000 is observed 547 times out of 1000\nthe ratio of 000 is 54.7 %\n\n{'001': 1, '010': 1, '111': 669, '101': 45, '110': 270, '100': 13, '011': 1}\n000 is observed 0 times out of 1000\nthe ratio of 000 is 0.0 %\n\n{'001': 519, '111': 62, '000': 1, '101': 324, '100': 1, '011': 93}\n000 is observed 1 times out of 1000\nthe ratio of 000 is 0.1 %\n\n{'001': 162, '101': 8, '110': 12, '100': 5, '011': 452, '010': 263, '111': 16, '000': 82}\n000 is observed 82 times out of 1000\nthe ratio of 000 is 8.2 %\n\n{'001': 9, '101': 36, '110': 320, '100': 433, '011': 10, '010': 76, '111': 28, '000': 88}\n000 is observed 88 times out of 1000\nthe ratio of 000 is 8.8 %\n\n{'001': 7, '101': 42, '110': 295, '100': 433, '011': 11, '010': 68, '111': 29, '000': 115}\n000 is observed 115 times out of 1000\nthe ratio of 000 is 11.5 %\n\n{'001': 190, '101': 7, '110': 9, '100': 4, '011': 427, '010': 254, '111': 13, '000': 96}\n000 is observed 96 times out of 1000\nthe ratio of 000 is 9.6 %\n\n{'001': 481, '111': 55, '000': 3, '101': 368, '100': 1, '011': 92}\n000 is observed 3 times out of 1000\nthe ratio of 000 is 0.3 %\n\n{'111': 678, '000': 1, '101': 47, '110': 249, '100': 23, '011': 2}\n000 is observed 1 times out of 1000\nthe ratio of 000 is 0.1 %\n\n{'001': 85, '010': 7, '000': 557, '101': 63, '110': 2, '100': 284, '011': 2}\n000 is observed 557 times out of 1000\nthe ratio of 000 is 55.7 %\n\n{'010': 878, '111': 3, '110': 74, '000': 2, '011': 43}\n000 is observed 2 times out of 1000\nthe ratio of 000 is 0.2 %\n\n{'001': 57, '111': 25, '000': 50, '101': 426, '110': 20, '100': 420, '011': 2}\n000 is observed 50 times out of 1000\nthe ratio of 000 is 5.0 %\n\n{'001': 42, '101': 89, '110': 18, '100': 1, '011': 225, '010': 8, '111': 616, '000': 1}\n000 is observed 1 times out of 1000\nthe ratio of 000 is 0.1 %\n\n{'001': 588, '010': 41, '111': 1, '000': 156, '101': 5, '100': 1, '011': 208}\n000 is observed 156 times out of 1000\nthe ratio of 000 is 15.6 %\n\n{'001': 35, '101': 46, '110': 261, '100': 149, '011': 57, '010': 219, '111': 80, '000': 153}\n000 is observed 153 times out of 1000\nthe ratio of 000 is 15.3 %\n\n{'010': 13, '111': 7, '000': 4, '101': 1, '110': 518, '100': 457}\n000 is observed 4 times out of 1000\nthe ratio of 000 is 0.4 %\n\n{'001': 199, '101': 78, '110': 50, '100': 90, '011': 102, '010': 144, '111': 34, '000': 303}\n000 is observed 303 times out of 1000\nthe ratio of 000 is 30.3 %\n\n{'001': 163, '101': 33, '110': 15, '100': 1, '011': 619, '010': 43, '111': 114, '000': 12}\n000 is observed 12 times out of 1000\nthe ratio of 000 is 1.2 %\n\n{'001': 49, '111': 76, '000': 6, '101': 746, '110': 16, '100': 103, '011': 4}\n000 is observed 6 times out of 1000\nthe ratio of 000 is 0.6 %\n\n{'001': 4, '101': 4, '110': 416, '100': 5, '011': 100, '010': 268, '111': 201, '000': 2}\n000 is observed 2 times out of 1000\nthe ratio of 000 is 0.2 %\n\n"
]
],
[
[
"<a id=\"task6\"></a>\n<h3> Task 6 </h3>\n\nLet $ \\mathsf{p} = 31 $.\n\nCreate a circuit with three quantum states and three classical states.\n\nRotate the qubits with random angles of the form $ k\\frac{2\\pi}{31}, $ where $ k \n\\in \\{1,\\ldots,30\\}.$\n\nExecute your circuit for all streams of lengths from 1 to 30.\n\nCalculate the maximum percentage of observing the state $ \\ket{000} $.\n\nRepeat this task for a few times.\n\n<i>Note that whether a key is in dictionary or not can be checked as follows:</i>\n\n if '000' in counts.keys():\n c = counts['000']\n else:\n c = 0",
"_____no_output_____"
],
[
"<h3>Solution</h3>",
"_____no_output_____"
]
],
[
[
"from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\nfrom math import pi\nfrom random import randrange\n\n# randomly picked angles of rotations \nk1 = randrange(1,31)\ntheta1 = k1*2*pi/31\nk2 = randrange(1,31)\ntheta2 = k2*2*pi/31\nk3 = randrange(1,31)\ntheta3 = k3*2*pi/31\nprint(\"k1 =\",k1,\"k2 =\",k2,\"k3 =\",k3)\nprint()\n\nmax_percentange = 0\n# we read streams of length from 1 to 30\nfor i in range(1,31):\n # quantum circuit with three qubits and three bits\n qreg = QuantumRegister(3) \n creg = ClassicalRegister(3) \n mycircuit = QuantumCircuit(qreg,creg)\n # the stream of length i\n for j in range(i):\n # apply rotations for each symbol\n mycircuit.ry(2*theta1,qreg[0]) \n mycircuit.ry(2*theta2,qreg[1]) \n mycircuit.ry(2*theta3,qreg[2]) \n # we measure after reading the whole stream\n mycircuit.measure(qreg,creg)\n # execute the circuit N times\n N = 1000\n job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)\n counts = job.result().get_counts(mycircuit)\n # print(counts)\n if '000' in counts.keys():\n c = counts['000']\n else:\n c = 0\n # print('000 is observed',c,'times out of',N)\n percentange = round(c/N*100,1)\n if max_percentange < percentange: max_percentange = percentange\n # print(\"the ration of 000 is \",percentange,\"%\")\n # print()\nprint(\"max percentage is\",max_percentange)",
"_____no_output_____"
]
],
[
[
"<a id=\"task7\"></a>\n<h3> Task 7 </h3>\n\nRepeat Task 6 by using four and five qubits.",
"_____no_output_____"
],
[
"<h3>Solution</h3>",
"_____no_output_____"
]
],
[
[
"from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer\nfrom math import pi\nfrom random import randrange\n\nnumber_of_qubits = 4\n#number_of_qubits = 5\n# randomly picked angles of rotations \ntheta = []\nfor i in range(number_of_qubits):\n k = randrange(1,31)\n print(\"k\",str(i),\"=\",k)\n theta += [k*2*pi/31]\n# print(theta)\n\n# we count the number of zeros\nzeros = ''\nfor i in range(number_of_qubits):\n zeros = zeros + '0'\nprint(\"zeros = \",zeros)\nprint()\n\nmax_percentange = 0\n# we read streams of length from 1 to 30\nfor i in range(1,31):\n # quantum circuit with qubits and bits\n qreg = QuantumRegister(number_of_qubits) \n creg = ClassicalRegister(number_of_qubits) \n mycircuit = QuantumCircuit(qreg,creg)\n # the stream of length i\n for j in range(i):\n # apply rotations for each symbol\n for k in range(number_of_qubits):\n mycircuit.ry(2*theta[k],qreg[k]) \n # we measure after reading the whole stream\n mycircuit.measure(qreg,creg)\n # execute the circuit N times\n N = 1000\n job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=N)\n counts = job.result().get_counts(mycircuit)\n # print(counts)\n if zeros in counts.keys():\n c = counts[zeros]\n else:\n c = 0\n # print('000 is observed',c,'times out of',N)\n percentange = round(c/N*100,1)\n if max_percentange < percentange: max_percentange = percentange\n # print(\"the ration of 000 is \",percentange,\"%\")\n # print()\nprint(\"max percentage is\",max_percentange)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
cb7ccb4b9c70cfa36cce6c1f53a0d8d58261f2d1
| 368,502 |
ipynb
|
Jupyter Notebook
|
UK_Charities_Classification.ipynb
|
PranavBansal04/UK_Boards_Data
|
73283e1f335e4f291c18400f94d92a67e93d830f
|
[
"MIT"
] | null | null | null |
UK_Charities_Classification.ipynb
|
PranavBansal04/UK_Boards_Data
|
73283e1f335e4f291c18400f94d92a67e93d830f
|
[
"MIT"
] | null | null | null |
UK_Charities_Classification.ipynb
|
PranavBansal04/UK_Boards_Data
|
73283e1f335e4f291c18400f94d92a67e93d830f
|
[
"MIT"
] | null | null | null | 51.90169 | 8,542 | 0.388473 |
[
[
[
"# Classification of UK Charities\nIn this notebook, data from several sources has been used to classify UK charities",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive/')",
"Drive already mounted at /content/drive/; to attempt to forcibly remount, call drive.mount(\"/content/drive/\", force_remount=True).\n"
],
[
"import json\nimport pandas as pd\nimport networkx as nx\nfrom numpy.core.numeric import NaN\nwith open('drive/My Drive/UK_Data/json/publicextract.charity_trustee.json', encoding=\"utf-8-sig\") as f:\n data = json.load(f)\nprint(len(data))\nprint(json.dumps(data[0],indent=4))",
"942096\n{\n \"date_of_extract\": \"2022-01-11T00:00:00\",\n \"organisation_number\": 521013,\n \"registered_charity_number\": 521013,\n \"linked_charity_number\": 0,\n \"trustee_id\": 23760,\n \"trustee_name\": \"AUGHTON PARISH COUNCIL\",\n \"trustee_is_chair\": false,\n \"individual_or_organisation\": \"O\",\n \"trustee_date_of_appointment\": null\n}\n"
]
],
[
[
"- In the charity_trustee table we have all combinations of trustees and charities.\n- Website https://register-of-charities.charitycommission.gov.uk/sector-data/sector-overview\n",
"_____no_output_____"
]
],
[
[
"members = {}\norgs = {}\n\nfor trustee in data:\n tid = trustee['trustee_id']\n oid = trustee['organisation_number']\n if(tid not in members):\n members[tid] = [trustee]\n else:\n members[tid].append(trustee)\n if(oid not in orgs):\n orgs[oid] = [trustee]\n else:\n orgs[oid].append(trustee)\n\nprint(\"Total Trustees : \",len(members))\nprint(\"Total Organizations: \",len(orgs))",
"Total Trustees : 851555\nTotal Organizations: 170190\n"
],
[
"with open('drive/My Drive/UK_Data/json/publicextract.charity.json', encoding=\"utf-8-sig\") as f:\n charity_data = json.load(f)\n\nprint(len(charity_data))\nprint(json.dumps(charity_data[3],indent=4))",
"376413\n{\n \"date_of_extract\": \"2022-01-11T00:00:00\",\n \"organisation_number\": 4,\n \"registered_charity_number\": 200028,\n \"linked_charity_number\": 2,\n \"charity_name\": \"TOWN LANDS CHARITY FOR THE CHURCH\",\n \"charity_type\": null,\n \"charity_registration_status\": \"Removed\",\n \"date_of_registration\": \"1961-10-19T00:00:00\",\n \"date_of_removal\": \"1997-09-17T00:00:00\",\n \"charity_reporting_status\": null,\n \"latest_acc_fin_period_start_date\": null,\n \"latest_acc_fin_period_end_date\": null,\n \"latest_income\": null,\n \"latest_expenditure\": null,\n \"charity_contact_address1\": null,\n \"charity_contact_address2\": null,\n \"charity_contact_address3\": null,\n \"charity_contact_address4\": null,\n \"charity_contact_address5\": null,\n \"charity_contact_postcode\": null,\n \"charity_contact_phone\": null,\n \"charity_contact_email\": null,\n \"charity_contact_web\": null,\n \"charity_company_registration_number\": null,\n \"charity_insolvent\": false,\n \"charity_in_administration\": false,\n \"charity_previously_excepted\": null,\n \"charity_is_cdf_or_cif\": null,\n \"charity_is_cio\": null,\n \"cio_is_dissolved\": null,\n \"date_cio_dissolution_notice\": null,\n \"charity_activities\": null,\n \"charity_gift_aid\": null,\n \"charity_has_land\": null\n}\n"
],
[
"total_registered_main = 0\ntotal_registered_linked = 0\ntotal_removed = 0\nnc = 0\nfor i in charity_data:\n if(i['charity_registration_status']!=\"Removed\"):\n if(i['linked_charity_number']!=0):\n total_registered_linked+=1\n else:\n total_registered_main+=1\n if(i['charity_activities']==None):\n nc+=1\n else:\n total_removed+=1\n\nprint(\"Total Registered Main : \",total_registered_main)\nprint(\"Total Registered Linked: \",total_registered_linked)\nprint(\"Total Removed : \",total_removed)\nprint(nc)",
"Total Registered Main : 170570\nTotal Registered Linked: 15166\nTotal Removed : 190677\n6029\n"
],
[
"for i in charity_data:\n if(i['registered_charity_number']==200027):\n print(i)\n# print(charity_data[0])\n",
"{'date_of_extract': '2022-01-11T00:00:00', 'organisation_number': 1, 'registered_charity_number': 200027, 'linked_charity_number': 1, 'charity_name': 'POTTERNE MISSION ROOM AND TRUST', 'charity_type': None, 'charity_registration_status': 'Removed', 'date_of_registration': '1962-05-17T00:00:00', 'date_of_removal': '2014-04-16T00:00:00', 'charity_reporting_status': None, 'latest_acc_fin_period_start_date': None, 'latest_acc_fin_period_end_date': None, 'latest_income': None, 'latest_expenditure': None, 'charity_contact_address1': None, 'charity_contact_address2': None, 'charity_contact_address3': None, 'charity_contact_address4': None, 'charity_contact_address5': None, 'charity_contact_postcode': None, 'charity_contact_phone': None, 'charity_contact_email': None, 'charity_contact_web': None, 'charity_company_registration_number': None, 'charity_insolvent': False, 'charity_in_administration': False, 'charity_previously_excepted': None, 'charity_is_cdf_or_cif': None, 'charity_is_cio': None, 'cio_is_dissolved': None, 'date_cio_dissolution_notice': None, 'charity_activities': None, 'charity_gift_aid': None, 'charity_has_land': None}\n{'date_of_extract': '2022-01-11T00:00:00', 'organisation_number': 2, 'registered_charity_number': 200027, 'linked_charity_number': 2, 'charity_name': 'HITCHAM FREE CHURCH', 'charity_type': None, 'charity_registration_status': 'Registered', 'date_of_registration': '1962-05-17T00:00:00', 'date_of_removal': None, 'charity_reporting_status': None, 'latest_acc_fin_period_start_date': None, 'latest_acc_fin_period_end_date': None, 'latest_income': None, 'latest_expenditure': None, 'charity_contact_address1': None, 'charity_contact_address2': None, 'charity_contact_address3': None, 'charity_contact_address4': None, 'charity_contact_address5': None, 'charity_contact_postcode': None, 'charity_contact_phone': None, 'charity_contact_email': None, 'charity_contact_web': None, 'charity_company_registration_number': None, 'charity_insolvent': False, 'charity_in_administration': False, 'charity_previously_excepted': None, 'charity_is_cdf_or_cif': None, 'charity_is_cio': None, 'cio_is_dissolved': None, 'date_cio_dissolution_notice': None, 'charity_activities': None, 'charity_gift_aid': None, 'charity_has_land': None}\n{'date_of_extract': '2022-01-11T00:00:00', 'organisation_number': 200027, 'registered_charity_number': 200027, 'linked_charity_number': 0, 'charity_name': 'RURAL MINISTRIES', 'charity_type': 'Charitable company', 'charity_registration_status': 'Registered', 'date_of_registration': '1962-05-17T00:00:00', 'date_of_removal': None, 'charity_reporting_status': 'Submission Received', 'latest_acc_fin_period_start_date': '2020-04-01T00:00:00', 'latest_acc_fin_period_end_date': '2021-03-31T00:00:00', 'latest_income': 93073.0, 'latest_expenditure': 264019.0, 'charity_contact_address1': 'Rural Ministries', 'charity_contact_address2': 'PO Box 293', 'charity_contact_address3': 'ROYSTON', 'charity_contact_address4': None, 'charity_contact_address5': None, 'charity_contact_postcode': 'SG8 1FS', 'charity_contact_phone': '01763 878539', 'charity_contact_email': '[email protected]', 'charity_contact_web': 'www.ruralministries.org.uk', 'charity_company_registration_number': '00688281', 'charity_insolvent': False, 'charity_in_administration': False, 'charity_previously_excepted': False, 'charity_is_cdf_or_cif': None, 'charity_is_cio': False, 'cio_is_dissolved': False, 'date_cio_dissolution_notice': None, 'charity_activities': 'To support rural churches in their growth and development and assist in the planting of new rural churches.', 'charity_gift_aid': True, 'charity_has_land': True}\n"
]
],
[
[
"* For charity classification we have charity_activities field in the charity table which has a description(one line summary) of how the charity spends its money, might be used for classification. This field is not None only for the parent organisations, i.e. orgs with linked charity no. = 0. \n* charity_governing_document table has a charitable_objects field which is a paragraph desscription. Might be used for charity classification.\n* there seems to be a discrepency, in the charity table - charity no. 200027 points to POTTERNE MISSION ROOM AND TRUST but while searched online on the website 200027 points to RURAL MINISTRIES => RESOLVED - the latter seems to be the main organisation and the former is a linked charity which was removed\n\n* there are many cases where a single charity is classified into various types i.e. it has various \"what\" descriptions in the charity classification table. same goes for other fields - \"WHO\" and \"HOW\". Therefore, the provided classification will create ambiguity if directly used.",
"_____no_output_____"
],
[
"# Charities with income > 10 Million",
"_____no_output_____"
]
],
[
[
"#Lets try figuring out charities with income over 10 Million Pounds\ncharity10m = []\ncount10m = 0\nfor charity in charity_data:\n if(charity['charity_registration_status']!=\"Removed\" and \n charity['latest_income']!= None and \n charity['latest_income'] >= 10000000):\n count10m+=1\n charity10m.append(charity)\nprint(count10m)",
"1329\n"
],
[
"#Sort charity10m in descending order of income\nn = len(charity10m)\nfor i in range(n-1):\n for j in range(0, n-i-1):\n if charity10m[j]['latest_income'] < charity10m[j + 1]['latest_income'] :\n charity10m[j], charity10m[j + 1] = charity10m[j + 1], charity10m[j]\n\n# charity10m[:10]\nfor i in charity10m[0:10]:\n print(i['charity_name'],\"|\",i['registered_charity_number'],\"|\",i['organisation_number'])",
"THE ARTS COUNCIL OF ENGLAND | 1036733 | 1036733\nLLOYD'S REGISTER FOUNDATION | 1145988 | 5025687\nTHE BRITISH COUNCIL | 209131 | 209131\nINTERNATIONAL FINANCE FACILITY FOR IMMUNISATION COMPANY | 1115413 | 4016873\nTHE CHARITIES AID FOUNDATION | 268369 | 268369\nSAVE THE CHILDREN INTERNATIONAL | 1076822 | 3961959\nNUFFIELD HEALTH | 205533 | 205533\nCANCER RESEARCH UK | 1089464 | 3987102\nCARDIFF UNIVERSITY | 1136855 | 5010420\nUNITED CHURCH SCHOOLS FOUNDATION LTD | 313999 | 313999\n"
],
[
"print(json.dumps(charity10m[0],indent=3))",
"{\n \"date_of_extract\": \"2022-01-11T00:00:00\",\n \"organisation_number\": 1036733,\n \"registered_charity_number\": 1036733,\n \"linked_charity_number\": 0,\n \"charity_name\": \"THE ARTS COUNCIL OF ENGLAND\",\n \"charity_type\": \"Other\",\n \"charity_registration_status\": \"Registered\",\n \"date_of_registration\": \"1994-04-19T00:00:00\",\n \"date_of_removal\": null,\n \"charity_reporting_status\": \"Submission Received\",\n \"latest_acc_fin_period_start_date\": \"2020-04-01T00:00:00\",\n \"latest_acc_fin_period_end_date\": \"2021-03-31T00:00:00\",\n \"latest_income\": 1488506017.0,\n \"latest_expenditure\": 1419616010.0,\n \"charity_contact_address1\": \"21 Bloomsbury Street\",\n \"charity_contact_address2\": \"London\",\n \"charity_contact_address3\": null,\n \"charity_contact_address4\": null,\n \"charity_contact_address5\": null,\n \"charity_contact_postcode\": \"WC1B 3HF\",\n \"charity_contact_phone\": \"08453006200\",\n \"charity_contact_email\": \"[email protected]\",\n \"charity_contact_web\": \"www.artscouncil.org.uk\",\n \"charity_company_registration_number\": null,\n \"charity_insolvent\": false,\n \"charity_in_administration\": false,\n \"charity_previously_excepted\": false,\n \"charity_is_cdf_or_cif\": null,\n \"charity_is_cio\": false,\n \"cio_is_dissolved\": false,\n \"date_cio_dissolution_notice\": null,\n \"charity_activities\": \"Arts Council England works to get great art to everyone by championing, developing and investing in artistic experiences that enrich people's lives. As the national development agency for the arts we support a range of artistic activities, acting as an independent body at arm's length from government. 'Achieving great art for everyone' is our 10-year strategic framework for the arts.\",\n \"charity_gift_aid\": false,\n \"charity_has_land\": true\n}\n"
],
[
"# create a dict for accessing charity information through organisation number\ncharity = {}\nfor ch in charity_data:\n charity[ch['organisation_number']] = ch\n# charity",
"_____no_output_____"
],
[
"with open('drive/My Drive/UK_Data/json/publicextract.charity_governing_document.json', encoding=\"utf-8-sig\") as f:\n charity_governing_document = json.load(f)\n\nprint(len(charity_governing_document))",
"376413\n"
],
[
"# create a dict for accessing governing document info using organisation number\ncharity_governing_document_data = {}\nfor i in charity_governing_document:\n charity_governing_document_data[i['organisation_number']] = i",
"_____no_output_____"
],
[
"# check if all charities have data in the charitable object column\ncount = 0\nc2=0\nempty_objects = []\nfor i in charity_governing_document:\n if(i['charitable_objects'] == None):\n empty_objects.append(i)\n # print(i)\n if(i['linked_charity_number']!=0):\n c2+=1\n else:\n count+=1\n\nprint(count)\nprint(c2)",
"13\n27\n"
]
],
[
[
"There are 27 Parent orgs and 13 linked charities in charity_governing_document table which have empty chartiable objects column.",
"_____no_output_____"
]
],
[
[
"# check how many charities with empty charitable objects are still registered\nregistered = 0\nremoved = 0\nfor i in empty_objects:\n if(charity[i['organisation_number']]['charity_registration_status'] == \"Removed\"):\n removed+=1\n else:\n registered+=1\n # print(i)\n\nprint(\"Registered = \",registered)\nprint(\"Removed = \",removed)",
"Registered = 24\nRemoved = 16\n"
]
],
[
[
"Out of 40 (13+27) charities that have empty charitable objects, 24 are still registered and only 16 are removed. However we can still simply ignore these charities since they only contribute to an extremely small fraction of all charities in the dataset.",
"_____no_output_____"
]
],
[
[
"charity_classification = pd.read_csv(\"drive/My Drive/UK_Data/text/publicextract.charity_classification.txt\",sep=\"\\t\")\n# refer to the data definition file on the website to understand detailed description of each table and the columns\nprint(len(charity_classification))\n%load_ext google.colab.data_table\ncharity_classification.head(10)",
"1602240\n"
],
[
"from collections import Counter\nCounter(charity_classification['classification_description'])",
"_____no_output_____"
],
[
"# we are only concerned with the descriptions corresponding to 'What' classification type\nfiltered = charity_classification[charity_classification['classification_type'] == 'What']\nprint(filtered.shape)\nfiltered.head(10)",
"(599055, 7)\n"
],
[
"Counter(filtered['classification_description'])",
"_____no_output_____"
],
[
"# count the number of classifications for each organisation\nclassification_count = Counter(filtered['organisation_number'])\npc=0\nfor i in classification_count.items():\n print(i)\n pc+=1\n if pc==10:\n break",
"(200001, 4)\n(200002, 2)\n(200009, 3)\n(200012, 3)\n(200014, 1)\n(200017, 1)\n(200023, 3)\n(200024, 2)\n(200027, 1)\n(200032, 2)\n"
],
[
"# we only want to work with charities that are still registered\nar = []\nfor i in charity_data:\n if(i['charity_registration_status']!=\"Removed\"):\n ar.append(i['organisation_number'])\n \nlen(set(ar))",
"_____no_output_____"
],
[
"# check the number of charities from registered charities that have a classification provided in the classification table\nfinal = set(ar).intersection(set(classification_count.keys()))\nlen(final)",
"_____no_output_____"
],
[
"# counting the number of charities having n classifications\ncount_num_type = {}\nfor i in classification_count:\n if(i in final):\n idx = classification_count[i]\n if(idx in count_num_type):\n count_num_type[idx]+=1\n else:\n count_num_type[idx] = 1\n \nprint(sum(count_num_type.values()))\ncount_num_type",
"170390\n"
]
],
[
[
"- a lot of charities (71916) have just 1 classification\n- around 100,000 charities are classified into more than 1 category",
"_____no_output_____"
]
],
[
[
"# lets work with charities that have a unique classification - classified only into a single category\nunique_category = []\nfor i in classification_count:\n if(classification_count[i]==1 and (i in final) ):\n unique_category.append(i)\n\nunique_category[:10]",
"_____no_output_____"
],
[
"# filtering data for charities with unique category\nfiltered_single = filtered[filtered['organisation_number'].isin(unique_category) ]\nfiltered_single.shape",
"_____no_output_____"
],
[
"# view classification of charities, it will not include overlapping results since each charity is only assigned a single category\nCounter(filtered_single['classification_description'])",
"_____no_output_____"
]
],
[
[
"# Non Profit Classifier\n- Mapping UK charities to US charity classification\n- https://github.com/ma-ji/npo_classifier\n- based on NTEE classification - https://en.wikipedia.org/wiki/National_Taxonomy_of_Exempt_Entities#:~:text=The%20National%20Taxonomy%20of%20Exempt%20Entities%20%28NTEE%29%20is,case%20when%20the%20organization%20is%20recognized%20as%20tax-exempt\n- NTEE code structure - https://nccs.urban.org/project/national-taxonomy-exempt-entities-ntee-codes#overview\n",
"_____no_output_____"
]
],
[
[
"!pip install transformers",
"Collecting transformers\n Downloading transformers-4.18.0-py3-none-any.whl (4.0 MB)\n\u001b[K |████████████████████████████████| 4.0 MB 5.3 MB/s \n\u001b[?25hCollecting huggingface-hub<1.0,>=0.1.0\n Downloading huggingface_hub-0.5.1-py3-none-any.whl (77 kB)\n\u001b[K |████████████████████████████████| 77 kB 6.0 MB/s \n\u001b[?25hCollecting pyyaml>=5.1\n Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)\n\u001b[K |████████████████████████████████| 596 kB 45.8 MB/s \n\u001b[?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers) (2.23.0)\nRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.7/dist-packages (from transformers) (4.64.0)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (2019.12.20)\nRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.7/dist-packages (from transformers) (1.21.6)\nCollecting tokenizers!=0.11.3,<0.13,>=0.11.1\n Downloading tokenizers-0.12.1-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (6.6 MB)\n\u001b[K |████████████████████████████████| 6.6 MB 35.1 MB/s \n\u001b[?25hCollecting sacremoses\n Downloading sacremoses-0.0.53.tar.gz (880 kB)\n\u001b[K |████████████████████████████████| 880 kB 61.9 MB/s \n\u001b[?25hRequirement already satisfied: filelock in /usr/local/lib/python3.7/dist-packages (from transformers) (3.6.0)\nRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from transformers) (4.11.3)\nRequirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.7/dist-packages (from transformers) (21.3)\nRequirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.7/dist-packages (from huggingface-hub<1.0,>=0.1.0->transformers) (4.2.0)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging>=20.0->transformers) (3.0.8)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->transformers) (3.8.0)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2021.10.8)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->transformers) (2.10)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.15.0)\nRequirement already satisfied: click in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (7.1.2)\nRequirement already satisfied: joblib in /usr/local/lib/python3.7/dist-packages (from sacremoses->transformers) (1.1.0)\nBuilding wheels for collected packages: sacremoses\n Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for sacremoses: filename=sacremoses-0.0.53-py3-none-any.whl size=895260 sha256=cb1aa29dc59527737c9753def00aa4e450a972f8e12b7ccacaafd2e66171985c\n Stored in directory: /root/.cache/pip/wheels/87/39/dd/a83eeef36d0bf98e7a4d1933a4ad2d660295a40613079bafc9\nSuccessfully built sacremoses\nInstalling collected packages: pyyaml, tokenizers, sacremoses, huggingface-hub, transformers\n Attempting uninstall: pyyaml\n Found existing installation: PyYAML 3.13\n Uninstalling PyYAML-3.13:\n Successfully uninstalled PyYAML-3.13\nSuccessfully installed huggingface-hub-0.5.1 pyyaml-6.0 sacremoses-0.0.53 tokenizers-0.12.1 transformers-4.18.0\n"
],
[
"import requests\nexec(requests.get('https://raw.githubusercontent.com/ma-ji/npo_classifier/master/API/npoclass.py').text)",
"_____no_output_____"
],
[
"!pip3 install pickle5\nimport pickle5 as pickle",
"Collecting pickle5\n Downloading pickle5-0.0.12-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (256 kB)\n\u001b[?25l\r\u001b[K |█▎ | 10 kB 15.7 MB/s eta 0:00:01\r\u001b[K |██▋ | 20 kB 5.2 MB/s eta 0:00:01\r\u001b[K |███▉ | 30 kB 4.4 MB/s eta 0:00:01\r\u001b[K |█████▏ | 40 kB 4.3 MB/s eta 0:00:01\r\u001b[K |██████▍ | 51 kB 3.6 MB/s eta 0:00:01\r\u001b[K |███████▊ | 61 kB 4.3 MB/s eta 0:00:01\r\u001b[K |█████████ | 71 kB 4.4 MB/s eta 0:00:01\r\u001b[K |██████████▎ | 81 kB 5.0 MB/s eta 0:00:01\r\u001b[K |███████████▌ | 92 kB 4.9 MB/s eta 0:00:01\r\u001b[K |████████████▉ | 102 kB 4.8 MB/s eta 0:00:01\r\u001b[K |██████████████ | 112 kB 4.8 MB/s eta 0:00:01\r\u001b[K |███████████████▍ | 122 kB 4.8 MB/s eta 0:00:01\r\u001b[K |████████████████▋ | 133 kB 4.8 MB/s eta 0:00:01\r\u001b[K |██████████████████ | 143 kB 4.8 MB/s eta 0:00:01\r\u001b[K |███████████████████▏ | 153 kB 4.8 MB/s eta 0:00:01\r\u001b[K |████████████████████▌ | 163 kB 4.8 MB/s eta 0:00:01\r\u001b[K |█████████████████████▊ | 174 kB 4.8 MB/s eta 0:00:01\r\u001b[K |███████████████████████ | 184 kB 4.8 MB/s eta 0:00:01\r\u001b[K |████████████████████████▎ | 194 kB 4.8 MB/s eta 0:00:01\r\u001b[K |█████████████████████████▋ | 204 kB 4.8 MB/s eta 0:00:01\r\u001b[K |██████████████████████████▉ | 215 kB 4.8 MB/s eta 0:00:01\r\u001b[K |████████████████████████████▏ | 225 kB 4.8 MB/s eta 0:00:01\r\u001b[K |█████████████████████████████▍ | 235 kB 4.8 MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▊ | 245 kB 4.8 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 256 kB 4.8 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 256 kB 4.8 MB/s \n\u001b[?25hInstalling collected packages: pickle5\nSuccessfully installed pickle5-0.0.12\n"
]
],
[
[
"- refer to the documentation on github website to learn more about using the ML classifier API\n- API => npoclass(inputs, gpu_core=True, model_path=None, ntee_type='bc', n_jobs=4, backend='multiprocessing', batch_size_dl=64, verbose=1)",
"_____no_output_____"
]
],
[
[
"# testing out the classifier\n# make sure you have uploaded the model data to your drive so that it can be accessed by the API\nout = npoclass(\"helping poor individuals\",\n True,\n \"drive/My Drive/UK_Data/npoclass_model_bc/\",\n 'bc')\nprint(out)",
"No GPU acceleration available or gpu_core=False, using CPU.\nEncoding inputs ...\nPredicting categories ...\n"
]
],
[
[
"It takes more time than expected to classify a single charity by the API, so it might take a huge amount of time if we want to classify all 170k charities this way.",
"_____no_output_____"
]
],
[
[
"category_map = {\"I\": \"Arts, Culture, and Humanities\",\n \"II\": \"Education\",\n \"III\": \"Environment and Animals\",\n \"IV\": \"Health\",\n \"V\": \"Human Services\",\n \"VI\": \"International, Foreign Affairs\",\n \"VII\": \"Public, Societal Benefit\",\n \"VIII\": \"Religion Related\",\n \"IX\": \"Mutual/Membership Benefit\",\n \"X\": \"Unknown, Unclassified\"}",
"_____no_output_____"
],
[
"# create a new dataframe to store the classification results from the ML classifier\n# more useful columns can be added to this dataframe if required\nclassification_us_data = pd.DataFrame({'organisation_number': pd.Series(dtype='int'),\n 'registered_charity_number': pd.Series(dtype='int'),\n 'charity_name':pd.Series(dtype='str'),\n 'classification_code_us': pd.Series(dtype='str'),\n 'classification_description_us':pd.Series(dtype='str'),\n 'confidence':pd.Series(dtype='float')})",
"_____no_output_____"
],
[
"# we will be using this 'final' list which contains the organisaiton numbers of all registered charities\n# we will be using the description from the charity activities column to be given as input to the classifier\nparent_list = list(final)\ncc = 0\ncompression_opts = dict(method='zip',\n archive_name='classification_us_data.csv')\n\n# a list of charity descriptions can be given as input to the API, which will save time in the overall classification due to API response time\n# we basically want to iterate over all the charities in the parent_list and sent theit activity decriptions as inputs to the API\n# in the code chunk below classification has been done in groups of 20 to save time and to ensure that no data is lost due to network issue\n# if for some reason the notebook disconnects or the code produces some error then the results fetched till that point will all be save in the output file\n# in case if the connection is lost and for loop is broken then it is best to first download the output file from the notebook environment\n# and then read in the dataframe from the output file and then start the loop again from the point where it was broken\n# make sure to modify the start and end range and the step size of the for loop according the the requirement\n\nCHUNK_SIZE = 20 # define the chunk size - no. of charities to be processed together\n\nfor i in range (630,650,CHUNK_SIZE):\n # separating out 20 ids\n chunk_list = parent_list[i:i+CHUNK_SIZE]\n print(chunk_list)\n # input list will contains descriptions for the corresponding 20 organisations\n input_list = []\n for j in chunk_list:\n if(charity[j]['charity_activities']!=None):\n input_list.append(charity[j]['charity_activities'])\n # get the prediction from the API\n pred = npoclass(input_list,\n True,\n \"drive/My Drive/UK_Data/npoclass_model_bc/\",\n 'bc',\n batch_size_dl=128)\n # if the charity activities column is empty for a charity then simply add its classification as unknown/unclassified\n for jj in range(len(chunk_list)):\n if(charity[chunk_list[jj]]['charity_activities']==None):\n pred.insert(jj,{\"recommended\":\"X\"})\n \n # insert the data for all charities in the chunk list to the main dataframe\n for k in range (len(pred)):\n org_num = chunk_list[k]\n element = pred[k]\n classification_us_data = classification_us_data.append({'organisation_number': int(org_num), \n 'registered_charity_number': int(charity[org_num]['registered_charity_number']),\n 'charity_name':charity[org_num]['charity_name'],\n 'classification_code_us':element['recommended'],\n 'classification_description_us':category_map[element['recommended']],\n 'confidence':0 if element['recommended']=='X' else round(element['probabilities'][element['recommended']],2)},\n ignore_index=True)\n \n # save the dataframe at every step so that no progress is lost, note that the code will simply keep overwriting the output file\n classification_us_data.to_csv('classification_us_data.zip', index=False,\n compression=compression_opts)\n\n\n",
"[524965, 1049252, 524967, 1049253, 1049257, 1049254, 524971, 1049259, 524973, 1049261, 524975, 1049265, 524978, 524979, 524980, 1049266, 5002040, 524984, 524985, 524986]\nNo GPU acceleration available or gpu_core=False, using CPU.\nEncoding inputs ...\n"
],
[
"classification_us_data[:10]",
"_____no_output_____"
],
[
"# predict the classification using charitable object instead of charity activities\n# this can be integrated in the block above as well\nclassification_us_data1 = classification_us_data\nactivities = []\ncobjects = []\ncodes = []\ndescp = []\nconfd = []\nct = 0\nfor i in classification_us_data1[\"organisation_number\"]:\n print(ct)\n obj = charity_governing_document_data[i][\"charitable_objects\"]\n cobjects.append(obj)\n activities.append(charity[i][\"charity_activities\"])\n if(obj==None):\n codes.append(\"X\")\n descp.append(\"Unknown, Unclassified\")\n confd.append(0)\n else:\n pred = npoclass(obj,\n True,\n \"drive/My Drive/UK_Data/npoclass_model_bc/\",\n 'bc',\n batch_size_dl=128)[0]\n codes.append(pred['recommended'])\n descp.append(category_map[pred['recommended']])\n confd.append(round(pred['probabilities'][pred['recommended']],2))\n ct+=1\n\n",
"0\nNo GPU acceleration available or gpu_core=False, using CPU.\nEncoding inputs ...\nPredicting categories ...\n"
],
[
"# rename a few columns so that the data from previous data frame inclusing classification using charity activities can be incorporated\nclassification_us_data1 = classification_us_data1.rename(columns={\"classification_code_us\":'classification_code1',\n \"classification_description_us\":'classification_description1',\n \"confidence\":\"confidence1\"})\nclassification_us_data1['charity_activities'] = activities\nclassification_us_data1['charitable_objects'] = cobjects\nclassification_us_data1['classification_code2'] = codes\nclassification_us_data1['classification_description2'] = descp\nclassification_us_data1['confidence2'] = confd\nclassification_us_data1.head()",
"_____no_output_____"
],
[
"# save the data frame to csv\nclassification_us_data1.to_csv('classification_us_data_WHOLE.zip', \n index=False,\n compression=compression_opts)",
"_____no_output_____"
],
[
"# count how many times different category predicitons were given for charity activity and charitable object based classification\ndc=0 # difference count\nfor index, row in classification_us_data1.iterrows():\n if(row['classification_code1'] !=row['classification_code2']):\n dc+=1\nprint(dc)\n",
"7\n"
]
],
[
[
"This might not be an appropriate classification for us since it is not really producing same output based on charity activity and charitable object. Moreover, it does take some time to get the classification from the API so it might take a lot of time to classify all the charities. This is something that can be explored more in future but for now the focus is being shifted to a new classification found below.",
"_____no_output_____"
],
[
"### Classification by charityclassification.org.uk - UKCAT - Rules Based Classification\n- src - https://charityclassification.org.uk\n- refer to the information provided on classification on the mentioned website\n- Classification data is already provided, simply download the CSV file from the website and upload it to drive for accessibility.",
"_____no_output_____"
]
],
[
[
"classification = pd.read_csv('drive/My Drive/UK_Data/Classification/charities_active-ukcat.csv')\nclassification.head()",
"_____no_output_____"
],
[
"# splitting the first columns into Island, Country and org number\n\n# the first part of an org identifier represents the Island\n\n# second part represents the country :\n# CHC - charities in England and Wales\n# NIC - charities in northern ireland\n# SC - charities in Scotland\n\n# third part is the unique org no.\n\nclassification[['Island', 'Country', 'organisation_number']] = classification['org_id'].str.split('-', expand=True)\nclassification.head()",
"_____no_output_____"
],
[
"classification.drop(\"org_id\", axis=1, inplace=True)\nnew_cols = ['Island','Country','organisation_number','ukcat_code']\nclassification=classification.reindex(columns=new_cols)\nprint(classification.shape)\nprint(classification.head())\n",
"(780301, 4)\n Island Country organisation_number ukcat_code\n0 GB CHC 1000000 ED\n1 GB CHC 1000000 ED102\n2 GB CHC 1000001 AR\n3 GB CHC 1000001 AR104\n4 GB CHC 1000001 AR201\n"
],
[
"Counter(classification['Island'])\n# all orgs are inside Great Britain",
"_____no_output_____"
],
[
"Counter(classification['Country'])\n# CHC - England and Wales\n# NIC - Northern Ireland\n# SC - Scotland",
"_____no_output_____"
],
[
"# focus on charities in England and Wales\nclassification_england = classification[classification['Country']==\"CHC\"]\nclassification_england.shape",
"_____no_output_____"
],
[
"classification_england = classification_england.rename(columns={'ukcat_code':'Code'})\nclassification_england.head()",
"_____no_output_____"
],
[
"# charity classification website also provides detailed description for all the classification codes\ncodes = pd.read_csv('drive/My Drive/UK_Data/Classification/ukcat-codes.csv')\ncodes.head()",
"_____no_output_____"
],
[
"# merge the previous data frame with code description dataframe\nclassification_england = classification_england.merge(codes,on=\"Code\",how=\"left\")\nclassification_england.head()",
"_____no_output_____"
],
[
"# dropping the columns that won't be required\nclassification_england.drop(['Regular expression','Exclude regular expression'], axis=1, inplace=True)\nclassification_england.head()\n",
"_____no_output_____"
],
[
"Counter(classification_england['Category'])",
"_____no_output_____"
],
[
"# add some more data to the classification dataframe such as no. of trustees, \n# latest income, expenditure and registration status\nn_trustees = []\nlatest_income = []\nlatest_expenditure = []\nregistration_status = []\nctr = 0\nfor i,row in classification_england.iterrows():\n if(ctr%20000==0):\n print(ctr,end=\" \")\n id = int(row['organisation_number'])\n try:\n n_trustees.append(len(orgs[id]))\n except:\n n_trustees.append(None)\n try:\n latest_income.append(charity[id]['latest_income'])\n latest_expenditure.append(charity[id]['latest_expenditure'])\n registration_status.append(charity[id]['charity_registration_status'])\n except:\n latest_income.append(0)\n latest_expenditure.append(0)\n registration_status.append(\"Unknown\")\n ctr+=1",
"0 20000 40000 60000 80000 100000 120000 140000 160000 180000 200000 220000 240000 260000 280000 300000 320000 340000 360000 380000 400000 420000 440000 460000 480000 500000 520000 540000 560000 580000 600000 620000 "
],
[
"# update the dataframe\nclassification_england['num_trustees'] = n_trustees\nclassification_england['latest_income'] = latest_income\nclassification_england['latest_expenditure'] = latest_expenditure\nclassification_england['registration_status'] = registration_status\nclassification_england.head()",
"_____no_output_____"
],
[
"Counter(classification_england['registration_status'])",
"_____no_output_____"
],
[
"#filtering out charities with \"Removed\" or \"Unknown\" registration status from the dataframe\nclassification_england_filtered = classification_england[classification_england['registration_status'] == 'Registered']\nprint(classification_england_filtered.shape)",
"(242395, 14)\n"
],
[
"#adding a column with each entry 1 so that the nubmber of charities in each category can be counted at the time of aggregation using groupby\nrws = classification_england_filtered.shape[0]\nnums = [1 for i in range(rws)]\nclassification_england_filtered['total_organisations'] = nums\nclassification_england_filtered.head()",
"_____no_output_____"
],
[
"# aggregate all the data into tags\ngroupedbyTag = classification_england_filtered.groupby('tag').agg({'total_organisations':'sum',\n 'num_trustees':'sum',\n 'latest_income':'sum',\n 'latest_expenditure':'sum'})\n\ngroupedbyTag.head()",
"_____no_output_____"
],
[
"# aggregate all data into categories\ngroupedbyCategory = classification_england_filtered.groupby('Category').agg({'total_organisations':'sum',\n 'num_trustees':'sum',\n 'latest_income':'sum',\n 'latest_expenditure':'sum'})\n\ngroupedbyCategory.head()",
"_____no_output_____"
],
[
"# save the dataframes as CSVs\ncompression_opts1 = dict(method='zip',archive_name='gropuedbyTag.csv')\ncompression_opts2 = dict(method='zip',archive_name='gropuedbyCategory.csv')\ngroupedbyTag.to_csv('groupedbyTag.zip', index=True, compression=compression_opts1)\ngroupedbyCategory.to_csv('groupedbyCategory.zip', index=True, compression=compression_opts2)",
"_____no_output_____"
],
[
"compression_opts = dict(method='zip',\n archive_name='classification_england_filtered.csv')\nclassification_england_filtered.to_csv('classification_england_filtered.zip', index=False, compression=compression_opts)",
"_____no_output_____"
],
[
"compression_opts = dict(method='zip',\n archive_name='classification_england_whole.csv')\nclassification_england.to_csv('classification_england_whole.zip', index=False, compression=compression_opts)",
"_____no_output_____"
],
[
"#REMOVING CATEGORY DUPLICATES FOR AN ORGANISATION\n# there are rows in the main dataframe where the org no. and category is same but the the tags or sub categories are different\n# we need to account for them while groupong by categories as it will produce false results if not taken into account\nclassification_england_filtered_category = classification_england_filtered.drop_duplicates(subset =[\"organisation_number\",\"Category\"],\n keep = \"first\", inplace = False)\nprint(classification_england_filtered_category.shape)\nclassification_england_filtered_category.head()",
"(173125, 15)\n"
],
[
"classification_england_filtered_category.to_csv('classification_england_filtered_RemovedCategoryDuplicates.zip', index=False, compression=compression_opts)",
"_____no_output_____"
],
[
"#Grouping by category again after removing the duplicates\ngroupedbyCategory_filtered = classification_england_filtered_category.groupby('Category').agg({'total_organisations':'sum',\n 'num_trustees':'sum',\n 'latest_income':'sum',\n 'latest_expenditure':'sum'})\n\ngroupedbyCategory_filtered.head()",
"_____no_output_____"
],
[
"compression_opts111 = dict(method='zip',archive_name='gropuedbyCategory_filtered.csv')\ngroupedbyCategory_filtered.to_csv('groupedbyCategory_filtered.zip', index=True, compression=compression_opts111)",
"_____no_output_____"
],
[
"#Arranged in decreasing number of total organisations\ngroupedbyCategory_filtered.sort_values(by=['total_organisations'],ascending=False)\n",
"_____no_output_____"
]
],
[
[
"We have 24 different categories with highest number of organisations in the 'Beneficiary Group' category followed by Education, Associations, Charity and VCS support etc.",
"_____no_output_____"
],
[
"### Classification by charityclassification.org.uk - ICNPTSO - ML Classifier\n\nThis is something that can be explored in future if required",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
],
[
[
"### Creating Clean Dataset in Graph Object Form",
"_____no_output_____"
]
],
[
[
"import networkx as nx",
"_____no_output_____"
],
[
"classification_england_filtered_category.reset_index(drop=True,inplace=True)\nprint(classification_england_filtered_category.shape)\nclassification_england_filtered_category.head(5)",
"(173125, 15)\n"
],
[
"#categorywise classification, no category duplicates\n# `classification_england_filtered_category` includes the individual organisation data classified into unique categories\n# we are not concerned with tags or sub categories right now\n# it is still possible that a single organiastion is classified into multiple categories and we want to all of those in the final classification\nfinal_classification = {}\nfor i,row in classification_england_filtered_category.iterrows():\n nn = row['organisation_number']\n if(nn not in final_classification.keys()):\n final_classification[nn] = [row['Category']]\n else:\n final_classification[nn].append(row['Category']) # store all the categories inside an array\n\n# the classification categories for an organisation will be accessible by the org number\n",
"_____no_output_____"
],
[
"fc=0\nfor i in final_classification.items():\n print(i)\n fc+=1\n if fc==10:\n break",
"('1000000', ['Education'])\n('1000001', ['Arts'])\n('1000002', ['Beneficiary group', 'Social welfare'])\n('1000003', ['Arts', 'Charitable activities', 'Education', 'Heritage', 'Social welfare'])\n('1000005', ['Facilities', 'Religion'])\n('1000007', ['Associations', 'Charitable activities', 'Education'])\n('1000008', ['Associations'])\n('1000009', ['Charity and VCS support'])\n('1000013', ['Beneficiary group', 'Charity and VCS support', 'Health'])\n('1000019', ['Associations', 'Facilities', 'Leisure'])\n"
],
[
"# fetch all metadata of a particular charity if its registration status is - 'registered'\n# they keys in the below dictionary are registered charity numbers and not the organisation number\nfinal_charity = {}\nfor i in charity.keys():\n if(charity[i]['charity_registration_status']==\"Registered\"):\n # id = charity[i]['registered_charity_number']\n final_charity[i] = charity[i]\nprint(len(final_charity.keys()))\nprint(json.dumps(list(final_charity.items())[0],indent=3))",
"185736\n[\n 2,\n {\n \"date_of_extract\": \"2022-01-11T00:00:00\",\n \"organisation_number\": 2,\n \"registered_charity_number\": 200027,\n \"linked_charity_number\": 2,\n \"charity_name\": \"HITCHAM FREE CHURCH\",\n \"charity_type\": null,\n \"charity_registration_status\": \"Registered\",\n \"date_of_registration\": \"1962-05-17T00:00:00\",\n \"date_of_removal\": null,\n \"charity_reporting_status\": null,\n \"latest_acc_fin_period_start_date\": null,\n \"latest_acc_fin_period_end_date\": null,\n \"latest_income\": null,\n \"latest_expenditure\": null,\n \"charity_contact_address1\": null,\n \"charity_contact_address2\": null,\n \"charity_contact_address3\": null,\n \"charity_contact_address4\": null,\n \"charity_contact_address5\": null,\n \"charity_contact_postcode\": null,\n \"charity_contact_phone\": null,\n \"charity_contact_email\": null,\n \"charity_contact_web\": null,\n \"charity_company_registration_number\": null,\n \"charity_insolvent\": false,\n \"charity_in_administration\": false,\n \"charity_previously_excepted\": null,\n \"charity_is_cdf_or_cif\": null,\n \"charity_is_cio\": null,\n \"cio_is_dissolved\": null,\n \"date_cio_dissolution_notice\": null,\n \"charity_activities\": null,\n \"charity_gift_aid\": null,\n \"charity_has_land\": null\n }\n]\n"
],
[
"# check if classification of all the charities is available in the dataset from charityclassification.org\nne = []\nfor i in final_charity.keys():\n try:\n temp = final_classification[str(i)]\n except:\n ne.append(i)\n\nprint(len(final_charity.keys()))\nprint(len(ne))",
"185736\n117681\n"
]
],
[
[
"- 117681 organisation seem to have no classification data from charityclassification.org\n- 185736 - 117681 = 68055 charities have classifications\n- need to figure it out, why are the classifications missing? ",
"_____no_output_____"
]
],
[
[
"# we need no. of trustees and trustee list for every organisation\n# trustees are added in a list for corresponsing charity\norgs_trustees = {}\nfor i in orgs:\n for j in orgs[i]:\n if(i not in orgs_trustees.keys()):\n orgs_trustees[i] = [(j['trustee_id'],j['trustee_name'])]\n else:\n orgs_trustees[i].append((j['trustee_id'],j['trustee_name']))\n\nlist(orgs_trustees.items())[0]",
"_____no_output_____"
],
[
"# we need number of orgs and org list for every trustee\n# orgs are added into a list for every trustee\ntrustee_orgs = {}\nfor i in members:\n for j in members[i]:\n id = j['organisation_number']\n if i not in trustee_orgs.keys():\n trustee_orgs[i] = [(id,charity[id]['charity_name'])]\n else:\n trustee_orgs[i].append((id,charity[id]['charity_name']))\n\nlist(trustee_orgs.items())[0]",
"_____no_output_____"
],
[
"trusteeList = members.keys()\norgList = orgs.keys()\nprint(len(trusteeList),len(set(trusteeList)))\nprint(len(orgList),len(set(orgList)))",
"851555 851555\n170190 170190\n"
],
[
"common = set(trusteeList).intersection(set(orgList))\nprint(len(common))",
"1073\n"
]
],
[
[
"This might create conflict since we are adding nodes to the network by their ids and if trustees and orgs share some common ids then it will create conflicts and data will be lost.",
"_____no_output_____"
]
],
[
[
"#createing clean graph object dataset\nG = nx.MultiGraph()\ncount = 0 \nfor i in orgs:\n count+=1\n G.add_node(i)\n # copy metadata\n attribute_dict = final_charity[i].copy()\n try:\n attribute_dict['Classification'] = final_classification[str(i)]\n except:\n # add an empty list if no classification is found\n attribute_dict['Classification'] = []\n \n # add no. of trustees\n attribute_dict['num_trustee'] = len(orgs[i])\n attribute_dict['type'] = 0 #denoting the node type as organisation\n\n # add trustee list as attribute to the org node\n attribute_dict['trustees'] = orgs_trustees[i]\n\n # node id is the org number\n # setting attributes for org i\n attrs = {i:attribute_dict}\n nx.set_node_attributes(G, attrs)\n\n # add trustee data\n for j in orgs_trustees[i]:\n #if its a common id\n if(j[0] in common):\n # add T at the end of the id so that it can be added as a separate node\n node_id = str(j[0])+'T'\n else:\n node_id = j[0]\n # add node to the network\n G.add_node(node_id)\n nattrs = {node_id:{\"Name\":j[1],\"type\":1,\"organisations\":trustee_orgs[j[0]]}} #1 denotes node type as trustee\n nx.set_node_attributes(G, nattrs)\n if(count%10000==0):\n print(count,end=\" \")",
"10000 20000 30000 40000 50000 60000 70000 80000 90000 100000 110000 120000 130000 140000 150000 160000 170000 "
],
[
"G.number_of_nodes()",
"_____no_output_____"
],
[
"#Adding edges\nfor p in members.keys():\n # modify the node id if its a common id\n if p in common:\n node_id = str(p)+'T'\n else:\n node_id = p\n if(node_id in G.nodes(0)):\n boards = []\n for j in members[p]:\n if(j['organisation_number'] in G.nodes()):\n boards.append(j['organisation_number'])\n res = [ (node_id,sub) for sub in boards ]\n G.add_edges_from(res)",
"_____no_output_____"
],
[
"G.nodes[23760]",
"_____no_output_____"
],
[
"G.nodes[3123875]",
"_____no_output_____"
],
[
"import pickle\n# export the graph data to a pickle file\nwith open(\"dataset.pickle\", 'wb') as f:\n pickle.dump(G, f)\n",
"_____no_output_____"
],
[
"import pickle\n# this is how data can be loaded from the saved pickle file for future use\n# note that the data will be loaded as a networkx multigraph since that was the format it was initially exported in\ndata = pickle.load(open(\"dataset.pickle\", \"rb\"))",
"_____no_output_____"
],
[
"type(data)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7ccbd2466450da03d9c41a328c3b7b08417342
| 466,522 |
ipynb
|
Jupyter Notebook
|
01.pre_processamento.ipynb
|
JohnnyUFT/KDD
|
2b99a5cd4e7e614a356502a9f19c367aae8e1bc3
|
[
"MIT"
] | 2 |
2021-10-29T21:59:26.000Z
|
2022-03-08T19:24:07.000Z
|
01.pre_processamento.ipynb
|
JohnnyUFT/KDD
|
2b99a5cd4e7e614a356502a9f19c367aae8e1bc3
|
[
"MIT"
] | null | null | null |
01.pre_processamento.ipynb
|
JohnnyUFT/KDD
|
2b99a5cd4e7e614a356502a9f19c367aae8e1bc3
|
[
"MIT"
] | null | null | null | 126.531598 | 27,504 | 0.827819 |
[
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\n%matplotlib inline",
"_____no_output_____"
],
[
"isolados = pd.read_csv('data/01 - geral_normalizada.csv')\nisolados.sample(5)",
"_____no_output_____"
],
[
"df = pd.read_csv('data/02 - reacoes_normalizada.csv', names=['Ano','CCR','Composto','Resultado'], header=None, index_col=0)\ndf.sample(5)",
"_____no_output_____"
],
[
"# junta os termos em um unico identificador do isolado:\ndf[\"Isolado\"] = \"UFT.\"+df['Ano'].astype(str)+\"(L)\"+df['CCR'].astype(str)\n\n# remove as colunas que não serao mais uteis:\ndel df['Ano']\ndel df['CCR']",
"_____no_output_____"
],
[
"# define nova coluna de indice:\ndf.set_index(['Isolado'], inplace=True)",
"_____no_output_____"
],
[
"# compostos = []\n# for i in range(1,81):\n# compostos.append(i)\n\n# compostos\ndf.sample(5)",
"_____no_output_____"
],
[
"# converte coluna de resultados em linhas:\ndf = df.pivot(columns='Composto')",
"_____no_output_____"
],
[
"# salva estado atual do dataframe em arquivo CSV:\ndf.to_csv('03 - reacoes_formatadas.csv')",
"_____no_output_____"
],
[
"df.sample(5)",
"_____no_output_____"
]
],
[
[
"### Análise Exploratória de Dados:\n1. Informações Gerais\n2. Tratamento de valores Nulos\n3. ",
"_____no_output_____"
],
[
"Questions to answer:\n* How many features do you have?\n* How many observations do you have?\n* What is the data type of each feature?",
"_____no_output_____"
]
],
[
[
"# dimensoes - linhas e colunas\ndf.shape\n\n# informações diversas:\n# df.info()",
"_____no_output_____"
],
[
"# descricao dos dados sob analise:\ndf.describe(include='object')",
"_____no_output_____"
],
[
"# mostra valores faltantes dentro de uma amostra dos dados:\nsns.heatmap(df.isnull())\nplt.show()",
"_____no_output_____"
],
[
"# plota cada característica categorica:\nfor column in df.select_dtypes(include='object'):\n if df[column].nunique() < 10:\n sns.countplot(y=column, data=df)\n plt.show()",
"_____no_output_____"
]
],
[
[
"Are there so many missing values for a variable that you should drop that variable from your dataset?",
"_____no_output_____"
]
],
[
[
"# remocao das colunas com maioria dos valores nulos:\n#df.isnull().sum()\ndf[df.columns[df.isnull().any()]].isnull().sum() * 100 / df.shape[0]",
"_____no_output_____"
],
[
"# mostra colunas com qtd de valores nulos maior que 50% dos possiveis registros: \ntotal = df.isnull().sum().sort_values(ascending=False)\npercent = (df.isnull().sum()/df.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Missing Percent'])\nmissing_data['Missing Percent'] = missing_data['Missing Percent'].apply(lambda x: x * 100)\nmissing_data.loc[missing_data['Missing Percent'] > 50]",
"_____no_output_____"
],
[
"df.sample(5)",
"_____no_output_____"
],
[
"# o dataframe é o mesmo, só eliminei manualmente o identificador \"Resultado\" e ajeitei o header do arquivo:\ndata = pd.read_csv('data/03.1 - reacoes_formatadas.csv', index_col=0)\ndata.sample(5)",
"_____no_output_____"
],
[
"from pandas_profiling import ProfileReport",
"_____no_output_____"
],
[
"relatorio_inicial = ProfileReport(data, title=\"Reações - Relatorio Inicial\", correlations={\"cramers\": {\"calculate\": False}})",
"_____no_output_____"
],
[
"relatorio_inicial.to_widgets()",
"_____no_output_____"
],
[
"relatorio_inicial.to_file(\"01 - relatorio-inicial_reacoes.html\")\n",
"_____no_output_____"
]
],
[
[
"Deleta (arbitrariamente) colunas com menos de 50% de preenchimento dos dados:\nAs colunas com mais de 50% de valores nulos são, respectivamente:\n1, 39, 40, 45, 46, 48, 64, 67, 68, 69, 78 e 79;\n\nLogo, ...",
"_____no_output_____"
]
],
[
[
"# TODO: automatizar/melhorar isso aqui:\ncolunas_excluir = [ '1', '39', '40', '45', '46', '48', '64', '67', '68', '69', '78', '79' ]\n# for coluna in colunas_excluir:\n\ndata.drop(columns=colunas_excluir, axis=0, inplace=True)\n",
"_____no_output_____"
],
[
"# dimensao atual, sem os 12 compostos removidos por pela alta taxa de valores em branco:\ndata.shape\n",
"_____no_output_____"
]
],
[
[
"Verificar colunas com baixa cardinalidade (com cardinalidade igual a 1). Colunas cujos valores não possuem variação não contribuem para algoritmo de agrupamento; \n",
"_____no_output_____"
]
],
[
[
"# apenas um coluna apresenta cardinalidade == 1. Coluna correspondente ao composto 48. \n#Já removido na operação anterior por apresentar 92% dos dados faltantes.\n",
"_____no_output_____"
],
[
"# salva estado atual da tabela:\n# salva estado atual do dataframe em arquivo CSV:\ndata.to_csv('03.1 - reacoes_col_removidas.csv')\n",
"_____no_output_____"
],
[
"# ainda temos valores nulos, vamos vê-los:\n\n# mostra colunas com qtd de valores nulos maior que 40% dos possiveis registros: \ntotal = data.isnull().sum().sort_values(ascending=False)\npercent = (data.isnull().sum()/data.isnull().count()).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Missing Percent'])\nmissing_data['Missing Percent'] = missing_data['Missing Percent'].apply(lambda x: x * 100)\nmissing_data.loc[missing_data['Missing Percent'] > 40]",
"_____no_output_____"
]
],
[
[
"### 4 - Como tratar essa grande qtd de valores faltantes???\n1. Ignorar, tratar values faltantes com o vector de zeros do **Dummie Enconding**;\n2. Remover todos e tratar registros como linhas de uma matriz 'banguela';\n3. Converter esses valores para uma representação qualquer: fill in the missing values --converter e depois remover;\n4. Usar interpolação (**Impute**): decidir, de maneira inteligente o que deverá substituir o espaço em branco --geralmente ecolhe o valor com maior frequência;",
"_____no_output_____"
]
],
[
[
"# 4.1. Ignorar valores nulos e tratar tudo com o One Hot Encoding:\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\n",
"_____no_output_____"
],
[
"data.columns",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"# colunas para transformar: todas, exceto a coluna de índice (coluna zero)\n# data[:-1]\n\ndata_encoded = pd.get_dummies(data, prefix=data.columns, prefix_sep=' ', dummy_na=False)\n\n# a diferenca esta no drop_firt=True\n# este parametro permite que o dataframe fique mais enxuto gerando k-1 registros no One-Hot-Encoding:\n# o uso do drop_first permite que o encoding utilizado seja o verdadeiro dunny encoding (sem el o metodo faz o one hot encoding)\n# data_encoded2 = pd.get_dummies(data, prefix=data.columns, prefix_sep=' ', dummy_na=False, drop_first=True)\n",
"_____no_output_____"
],
[
"data_encoded.head(7)",
"_____no_output_____"
],
[
"data_encoded.shape # não é um metodo .shape() e sim uma propriedade .shape",
"_____no_output_____"
],
[
"# salva estado atual do dataframe em arquivo CSV:\ndata_encoded.to_csv('04.1 - reacoes_one-hot_encoded.csv')\n",
"_____no_output_____"
],
[
"# gera o dataframe resultante do verdadeiro dummy_encoding:\n\ndata_encoded2 = pd.get_dummies(data, prefix=data.columns, prefix_sep=' ', dummy_na=False, drop_first=True)\n\n# salva estado atual do dataframe em arquivo CSV:\ndata_encoded2.to_csv('04.2 - reacoes_dummy_encoded.csv')\n",
"_____no_output_____"
],
[
"data_encoded2.head()",
"_____no_output_____"
],
[
"# 4.2 - TODO: construção da Matriz 'Banguela':\ndata.sample(6)",
"_____no_output_____"
],
[
"# 4.3 - TODO:\n\n",
"_____no_output_____"
],
[
"# 4.4 - TODO:\n\n",
"_____no_output_____"
],
[
"# geração do relatório do Pandas Profiling, novamente:\nrelatorio_final = ProfileReport(data_encoded2, title=\"Reações - Relatorio Final\", correlations={\"cramers\": {\"calculate\": False}})\n\nrelatorio_final.to_widgets()\n",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7cd3284819166c90aef83698bc909b7bc9c4eb
| 59,341 |
ipynb
|
Jupyter Notebook
|
notebooks/mini-data-lake.ipynb
|
DonPeregrina/mini-data-lake
|
2c0429918f7adc55b0410e7c88c9ba84cee54036
|
[
"Apache-2.0"
] | null | null | null |
notebooks/mini-data-lake.ipynb
|
DonPeregrina/mini-data-lake
|
2c0429918f7adc55b0410e7c88c9ba84cee54036
|
[
"Apache-2.0"
] | null | null | null |
notebooks/mini-data-lake.ipynb
|
DonPeregrina/mini-data-lake
|
2c0429918f7adc55b0410e7c88c9ba84cee54036
|
[
"Apache-2.0"
] | null | null | null | 57.445305 | 248 | 0.495795 |
[
[
[
"from pyspark import SparkConf, SparkContext\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import *\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.window import Window\nNoneType = type(None)\nimport os\nimport socket\nimport hashlib\nimport string\n\nimport time\nfrom osgeo import ogr\nimport geopandas as gpd\nfrom pyspark.sql import SparkSession\nfrom sedona.register import SedonaRegistrator\nfrom sedona.utils import SedonaKryoRegistrator, KryoSerializer",
"_____no_output_____"
],
[
"def createMd5(text):\n return hashlib.md5(text.encode('utf-8')).hexdigest()\nmd5Udf= udf(lambda z: createMd5(z),StringType())\n\ndef clean_lower(text):\n sentence = text.translate(str.maketrans('', '', '!\"#$%&\\'()*+,./:;<=>?@[\\\\]^`{|}~-_”“«»‘')).lower()\n return \" \".join(sentence.split())\ncleanLowerUdf= udf(lambda z: clean_lower(z),StringType())\n\ndef get_site_from_url(text):\n return text.split(\"/\")[2]\ngetUrl= udf(lambda z: get_site_from_url(z),StringType()) \n",
"_____no_output_____"
],
[
"minio_ip = socket.gethostbyname('minio')\nspark = SparkSession. \\\n builder. \\\n appName(\"Python Spark S3\"). \\\n config(\"spark.serializer\", KryoSerializer.getName). \\\n config(\"spark.executor.memory\", \"80g\"). \\\n config(\"spark.driver.memory\", \"80g\"). \\\n config('spark.dirver.maxResultSize', '5g'). \\\n config(\"spark.kryo.registrator\", SedonaKryoRegistrator.getName). \\\n config('spark.hadoop.fs.s3a.endpoint', 'http://'+minio_ip+':9000'). \\\n config(\"spark.hadoop.fs.s3a.access.key\", \"minio-access-key\"). \\\n config(\"spark.hadoop.fs.s3a.secret.key\", \"minio-secret-key\"). \\\n config('spark.hadoop.fs.s3a.impl', 'org.apache.hadoop.fs.s3a.S3AFileSystem'). \\\n config('spark.jars.packages',\n 'org.apache.sedona:sedona-python-adapter-3.0_2.12:1.0.0-incubating,org.datasyslab:geotools-wrapper:geotools-24.0'). \\\n getOrCreate()\nSedonaRegistrator.registerAll(spark)",
"_____no_output_____"
],
[
"\nst= StructType([\n StructField(\"abstract\", StringType()),\n StructField(\"authors\", StringType()),\n StructField(\"image\", StringType()),\n StructField(\"metadata\", StringType()),\n StructField(\"publish_date\", TimestampType()),\n StructField(\"text\", StringType()),\n StructField(\"title\", StringType()),\n StructField(\"url\", StringType()),\n])",
"_____no_output_____"
],
[
"df_news_covid_mexico = spark \\\n .read.schema(st).option(\"timestampFormat\", \"dd-MM-yyyy\") \\\n .json(\"s3a://news/Samuel_Garcia/*.json\")",
"_____no_output_____"
],
[
"df_news_covid_mexico.count()",
"_____no_output_____"
],
[
"df_news_covid_mexico.printSchema()",
"root\n |-- abstract: string (nullable = true)\n |-- authors: string (nullable = true)\n |-- image: string (nullable = true)\n |-- metadata: string (nullable = true)\n |-- publish_date: timestamp (nullable = true)\n |-- text: string (nullable = true)\n |-- title: string (nullable = true)\n |-- url: string (nullable = true)\n\n"
],
[
"df_news_covid_mexico.show(10)",
"+--------+-------+-----+--------+------------+----+-----+---+\n|abstract|authors|image|metadata|publish_date|text|title|url|\n+--------+-------+-----+--------+------------+----+-----+---+\n+--------+-------+-----+--------+------------+----+-----+---+\n\n"
],
[
"df_news_covid_mexico_date_text = df_news_covid_mexico.select(md5Udf(\"url\").alias(\"article_id\"),\"title\",\"url\",\"publish_date\",cleanLowerUdf(\"text\").alias(\"clean_text\"),getUrl(\"url\").alias(\"site\")).filter(\"length(text) >= 2\")",
"_____no_output_____"
],
[
"df_news_covid_mexico_date_text.show(15)",
"+--------------------+--------------------+--------------------+-------------------+--------------------+--------------------+\n| article_id| title| url| publish_date| clean_text| site|\n+--------------------+--------------------+--------------------+-------------------+--------------------+--------------------+\n|562d622a58c373745...|México se acerca ...|https://www.excel...|2021-03-21 00:00:00|al hacer click en...|www.excelsior.com.mx|\n|b77cd49c6e490dc06...|Mapa del coronavi...|https://www.infob...|2021-03-21 00:00:00|gráfica jovani pé...| www.infobae.com|\n|70d59b3cac0a6cc24...|Las claves e incó...|https://www.anima...|2021-03-21 00:00:00|en los últimos dí...|www.animalpolitic...|\n|e7d826dfb328b0d24...|“Abre mi escuela”...|https://www.infob...|2021-03-21 00:00:00|las instalaciones...| www.infobae.com|\n|d453f2247fda4ef5d...|Covid-19 afecta f...|https://www.eluni...|2021-03-21 00:00:00|la arquidiócesis ...|www.eluniversal.c...|\n|324ff9866349b35c7...|Estado de México ...|https://www.infob...|2021-03-21 00:00:00|narrativa domingo...| www.infobae.com|\n|4174cc0d5d1a1b893...|70% de familias d...|https://www.eluni...|2021-03-21 00:00:00|al 15 de marzo pa...|www.eluniversal.c...|\n|9718ae87edc04fff2...|Vacuna Covid-19 e...|https://www.marca...|2021-03-21 00:00:00|la pandemia por c...| www.marca.com|\n|29a518094e7b46133...|El fármaco Napabe...|https://www.jorna...|2021-03-21 00:00:00|la comisión feder...| www.jornada.com.mx|\n|e24f8c7b91fa302ca...|Ciudad de México ...|https://www.infob...|2021-03-21 00:00:00|narrativa domingo...| www.infobae.com|\n|2ae8936590ffd0526...|Coronavirus.- La ...|https://www.infob...|2021-03-21 00:00:00|madrid 21 europa ...| www.infobae.com|\n|da439be51b588fd3e...|Jalisco: caos y l...|https://www.jorna...|2021-03-21 00:00:00|guadalajara jal a...| www.jornada.com.mx|\n|41a61bb15e84d262c...|Todo lo que debes...|https://www.milen...|2021-03-21 00:00:00|gustavo pacheco a...| www.milenio.com|\n|03c27b6e6ffeb0400...|Aseguran laborato...|https://noticiero...|2021-03-21 00:00:00|elementos ministe...|noticieros.televi...|\n|61f85cb23d9827940...|'We got bored and...|https://www.usato...|2021-03-21 00:00:00|cancun getty imag...| www.usatoday.com|\n+--------------------+--------------------+--------------------+-------------------+--------------------+--------------------+\nonly showing top 15 rows\n\n"
],
[
"df_news_covid_mexico_date_text.count()",
"_____no_output_____"
],
[
"df_news_covid_mexico_date_text.select(\"title\").show(15,False)",
"+---------------------------------------------------------------------------------------------------------------------------+\n|title |\n+---------------------------------------------------------------------------------------------------------------------------+\n|México se acerca a los 198 mil decesos por covid |\n|Mapa del coronavirus en México 21 de marzo: Querétaro ya es el tercer estado con más contagios activos detrás CDMX y Edomex|\n|Las claves e incógnitas del nuevo plan para frenar la ... |\n|“Abre mi escuela”: exigieron regresar a clases presenciales en 10 estados a un año del cierre por COVID-19 |\n|Covid-19 afecta festejos en iglesia | El Universal |\n|Estado de México no registra nuevas muertes por coronavirus en el último día |\n|70% de familias de muertos por Covid-19 siguen sin apoyo | El Universal |\n|Vacuna Covid-19 en México este 21 de marzo: Vacunas aplicadas, casos de coronavirus y muertes |\n|El fármaco Napabeltan no tiene autorización de uso seguro ... |\n|Ciudad de México acumula 594.301 contagios y 29.701 fallecimientos desde el inicio de la pandemia |\n|Coronavirus.- La pandemia roza los 123 millones de contagios mundiales tras dejar casi 500.000 nuevos casos |\n|Jalisco: caos y larga espera en el primer día de vacunación |\n|Todo lo que debes saber de la vacuna contra covid-19 de AstraZeneca |\n|Aseguran laboratorios en Cancún que aplicaron pruebas COVID a jóvenes argentinos |\n|'We got bored and wanted to go on a trip': Tales from a pandemic spring break in Cancun, Mexico |\n+---------------------------------------------------------------------------------------------------------------------------+\nonly showing top 15 rows\n\n"
],
[
"url = \"jdbc:postgresql://postgres/shared\"\nmode=\"overwrite\"\nproperties = {\n \"user\": \"shared\",\n \"password\": os.environ['SHARED_PASSWORD']\n}",
"_____no_output_____"
],
[
"df_news_covid_mexico_date_text.write.jdbc(url=url, table=\"tb_news_covid_mexico_date_text\", mode=mode, properties=properties)",
"_____no_output_____"
],
[
"df_news_covid_mexico_palabras = df_news_covid_mexico_date_text.select(\"article_id\",\"publish_date\",explode(split(df_news_covid_mexico_date_text.clean_text, \"\\s\")).alias(\"palabra\")).where(length('palabra') > 1)",
"_____no_output_____"
],
[
"df_news_covid_mexico_palabras.show(30)",
"+--------------------+-------------------+-----------+\n| article_id| publish_date| palabra|\n+--------------------+-------------------+-----------+\n|562d622a58c373745...|2021-03-21 00:00:00| al|\n|562d622a58c373745...|2021-03-21 00:00:00| hacer|\n|562d622a58c373745...|2021-03-21 00:00:00| click|\n|562d622a58c373745...|2021-03-21 00:00:00| en|\n|562d622a58c373745...|2021-03-21 00:00:00| enviar|\n|562d622a58c373745...|2021-03-21 00:00:00| quedaras|\n|562d622a58c373745...|2021-03-21 00:00:00| regitrad|\n|562d622a58c373745...|2021-03-21 00:00:00| nuestro|\n|562d622a58c373745...|2021-03-21 00:00:00| boletín|\n|562d622a58c373745...|2021-03-21 00:00:00| el|\n|562d622a58c373745...|2021-03-21 00:00:00| cual|\n|562d622a58c373745...|2021-03-21 00:00:00| podrás|\n|562d622a58c373745...|2021-03-21 00:00:00| cancelar|\n|562d622a58c373745...|2021-03-21 00:00:00| en|\n|562d622a58c373745...|2021-03-21 00:00:00| cualquier|\n|562d622a58c373745...|2021-03-21 00:00:00| momentono|\n|562d622a58c373745...|2021-03-21 00:00:00| olvides|\n|562d622a58c373745...|2021-03-21 00:00:00| revisar|\n|562d622a58c373745...|2021-03-21 00:00:00| tu|\n|562d622a58c373745...|2021-03-21 00:00:00| carpeta|\n|562d622a58c373745...|2021-03-21 00:00:00| de|\n|562d622a58c373745...|2021-03-21 00:00:00| spam|\n|562d622a58c373745...|2021-03-21 00:00:00| ciudad|\n|562d622a58c373745...|2021-03-21 00:00:00| de|\n|562d622a58c373745...|2021-03-21 00:00:00| méxico|\n|562d622a58c373745...|2021-03-21 00:00:00| la|\n|562d622a58c373745...|2021-03-21 00:00:00| ssa|\n|562d622a58c373745...|2021-03-21 00:00:00| reportó|\n|562d622a58c373745...|2021-03-21 00:00:00| 608|\n|562d622a58c373745...|2021-03-21 00:00:00|defunciones|\n+--------------------+-------------------+-----------+\nonly showing top 30 rows\n\n"
],
[
"#https://sigdelta.com/blog/word-count-in-spark-with-a-pinch-of-tf-idf/\ndf_news_covid_mexico_palabras.groupBy('article_id', 'palabra','publish_date')\\\n .count()\\\n .orderBy('count', ascending=False)\\\n .show(25)",
"+--------------------+-------+-------------------+-----+\n| article_id|palabra| publish_date|count|\n+--------------------+-------+-------------------+-----+\n|61f85cb23d9827940...| the|2021-03-21 00:00:00| 129|\n|9f123746139b1f0ea...| de|2021-03-21 00:00:00| 92|\n|6aa6971a33b988654...| de|2021-03-21 00:00:00| 82|\n|61f85cb23d9827940...| in|2021-03-21 00:00:00| 77|\n|61f85cb23d9827940...| and|2021-03-21 00:00:00| 74|\n|72236c94ac71feaf4...| de|2021-03-22 00:00:00| 74|\n|8327c6e59ed7f3df3...| de|2021-03-21 00:00:00| 74|\n|57c9f33b7ef72ab61...| de|2021-03-27 00:00:00| 69|\n|d5b1ce551006f587b...| de|2021-03-21 00:00:00| 69|\n|a082606587ab3227a...| de|2021-03-21 00:00:00| 66|\n|065df75dc352b9913...| de|2021-03-21 00:00:00| 65|\n|70d59b3cac0a6cc24...| de|2021-03-21 00:00:00| 64|\n|68e032f866fec4d26...| de|2021-03-26 00:00:00| 64|\n|61f85cb23d9827940...| to|2021-03-21 00:00:00| 63|\n|320a8502c488ae08c...| de|2021-03-24 00:00:00| 63|\n|05e3adcba9f7c2b9f...| de|2021-03-26 00:00:00| 63|\n|bc1da01183b8164fb...| de|2021-03-21 00:00:00| 62|\n|a0ce891e10d4bac57...| de|2021-03-21 00:00:00| 61|\n|ed2a11140e8d50cd8...| the|2021-03-21 00:00:00| 60|\n|4c2b8d97bb1ceae8a...| de|2021-03-21 00:00:00| 59|\n|9f123746139b1f0ea...| en|2021-03-21 00:00:00| 59|\n|66419733e7e4a67e0...| de|2021-03-21 00:00:00| 58|\n|6aa6971a33b988654...| que|2021-03-21 00:00:00| 58|\n|85017fa18c961dd9c...| de|2021-03-21 00:00:00| 56|\n|61f85cb23d9827940...| of|2021-03-21 00:00:00| 56|\n+--------------------+-------+-------------------+-----+\nonly showing top 25 rows\n\n"
],
[
"#https://sigdelta.com/blog/word-count-in-spark-with-a-pinch-of-tf-idf-continued/\nw = Window.partitionBy(df_news_covid_mexico_palabras['article_id'])\n\narticle_tf = df_news_covid_mexico_palabras.groupBy('article_id', 'palabra', 'publish_date')\\\n .agg(count('*').alias('n_w'),sum(count('*')).over(w).alias('n_d'),(count('*')/sum(count('*')).over(w)).alias('tf'))\\\n .orderBy('n_w', ascending=False)\\\n .cache()\n\narticle_tf.show(truncate=15)",
"+---------------+-------+---------------+---+----+---------------+\n| article_id|palabra| publish_date|n_w| n_d| tf|\n+---------------+-------+---------------+---+----+---------------+\n|61f85cb23d98...| the|2021-03-21 0...|129|2788|0.0462697274...|\n|9f123746139b...| de|2021-03-21 0...| 92|1093|0.0841720036...|\n|6aa6971a33b9...| de|2021-03-21 0...| 82|1204|0.0681063122...|\n|61f85cb23d98...| in|2021-03-21 0...| 77|2788|0.0276183644...|\n|8327c6e59ed7...| de|2021-03-21 0...| 74| 707|0.1046676096...|\n|61f85cb23d98...| and|2021-03-21 0...| 74|2788|0.0265423242...|\n|72236c94ac71...| de|2021-03-22 0...| 74| 711|0.1040787623...|\n|57c9f33b7ef7...| de|2021-03-27 0...| 69| 765|0.0901960784...|\n|d5b1ce551006...| de|2021-03-21 0...| 69| 884|0.0780542986...|\n|a082606587ab...| de|2021-03-21 0...| 66| 846|0.0780141843...|\n|065df75dc352...| de|2021-03-21 0...| 65| 716|0.0907821229...|\n|68e032f866fe...| de|2021-03-26 0...| 64| 719|0.0890125173...|\n|70d59b3cac0a...| de|2021-03-21 0...| 64| 958|0.0668058455...|\n|61f85cb23d98...| to|2021-03-21 0...| 63|2788|0.0225968436...|\n|05e3adcba9f7...| de|2021-03-26 0...| 63| 761|0.0827858081...|\n|320a8502c488...| de|2021-03-24 0...| 63| 787|0.0800508259...|\n|bc1da01183b8...| de|2021-03-21 0...| 62| 780|0.0794871794...|\n|a0ce891e10d4...| de|2021-03-21 0...| 61| 497|0.1227364185...|\n|ed2a11140e8d...| the|2021-03-21 0...| 60| 937|0.0640341515...|\n|4c2b8d97bb1c...| de|2021-03-21 0...| 59| 876|0.0673515981...|\n+---------------+-------+---------------+---+----+---------------+\nonly showing top 20 rows\n\n"
],
[
"w = Window.partitionBy('palabra')\n\nc_d = df_news_covid_mexico_palabras.select('article_id').distinct().count()\n\narticle_idf = df_news_covid_mexico_palabras.groupBy('palabra', 'article_id','publish_date').agg(\n lit(c_d).alias('c_d'),\n count('*').over(w).alias('i_d'),\n log(lit(c_d)/count('*').over(w)).alias('idf')\n )\\\n .orderBy('idf', ascending=False)\\\n .cache()",
"_____no_output_____"
],
[
"article_idf.show(150, truncate=15)",
"+---------------+---------------+---------------+---+---+---------------+\n| palabra| article_id| publish_date|c_d|i_d| idf|\n+---------------+---------------+---------------+---+---+---------------+\n| 296|99aab48771a6...|2021-03-21 0...| 85| 1|4.4426512564...|\n| 49003|8327c6e59ed7...|2021-03-21 0...| 85| 1|4.4426512564...|\n| 596354|b77cd49c6e49...|2021-03-21 0...| 85| 1|4.4426512564...|\n| advertido|713f2e2880e2...|2021-03-22 0...| 85| 1|4.4426512564...|\n| bamx|99aab48771a6...|2021-03-21 0...| 85| 1|4.4426512564...|\n| coincidiendo|4c2b8d97bb1c...|2021-03-21 0...| 85| 1|4.4426512564...|\n| consumen|9f123746139b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| didi|7a3031279dfe...|2021-03-21 0...| 85| 1|4.4426512564...|\n| eligen|6aa6971a33b9...|2021-03-21 0...| 85| 1|4.4426512564...|\n| etiquetado|29a518094e7b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| few|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| inventando|66419733e7e4...|2021-03-21 0...| 85| 1|4.4426512564...|\n| pools|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| repetir|320a8502c488...|2021-03-24 0...| 85| 1|4.4426512564...|\n| requirement|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| sepmx|202e89bfbaa3...|2021-03-21 0...| 85| 1|4.4426512564...|\n| suministro|713f2e2880e2...|2021-03-22 0...| 85| 1|4.4426512564...|\n| verte|abd44d708948...|2021-03-21 0...| 85| 1|4.4426512564...|\n| volando|6aa6971a33b9...|2021-03-21 0...| 85| 1|4.4426512564...|\n| waters|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| 5523|8eedb3c3b3b6...|2021-03-21 0...| 85| 1|4.4426512564...|\n| beverages|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| col|62b5d0088902...|2021-03-21 0...| 85| 1|4.4426512564...|\n| confesados|065df75dc352...|2021-03-21 0...| 85| 1|4.4426512564...|\n| eliminar|41a61bb15e84...|2021-03-21 0...| 85| 1|4.4426512564...|\n| filled|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| highest|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| juniojulio|a0ce891e10d4...|2021-03-21 0...| 85| 1|4.4426512564...|\n| malt|9f123746139b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| marley|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| nights|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| oddly|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| often|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| olas|d5b1ce551006...|2021-03-21 0...| 85| 1|4.4426512564...|\n| partially|ed2a11140e8d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| portaron|202e89bfbaa3...|2021-03-21 0...| 85| 1|4.4426512564...|\n| preguntaba|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| scorn|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| semblanza|d26a8e852ac2...|2021-03-21 0...| 85| 1|4.4426512564...|\n| semipresencial|7f3dab2ab309...|2021-03-21 0...| 85| 1|4.4426512564...|\n| stations|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| vacunará|62b5d0088902...|2021-03-21 0...| 85| 1|4.4426512564...|\n| vigentes|d5b1ce551006...|2021-03-21 0...| 85| 1|4.4426512564...|\n| vocal|abd44d708948...|2021-03-21 0...| 85| 1|4.4426512564...|\n| acuden|4c2b8d97bb1c...|2021-03-21 0...| 85| 1|4.4426512564...|\n| arguing|ed2a11140e8d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| australia|713f2e2880e2...|2021-03-22 0...| 85| 1|4.4426512564...|\n| aval|29a518094e7b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| cuestionado|6aa6971a33b9...|2021-03-21 0...| 85| 1|4.4426512564...|\n| der|62b5d0088902...|2021-03-21 0...| 85| 1|4.4426512564...|\n| entregaron|05e3adcba9f7...|2021-03-26 0...| 85| 1|4.4426512564...|\n| infografía|b77cd49c6e49...|2021-03-21 0...| 85| 1|4.4426512564...|\n| inmunológica|41a61bb15e84...|2021-03-21 0...| 85| 1|4.4426512564...|\n| innovación|8327c6e59ed7...|2021-03-21 0...| 85| 1|4.4426512564...|\n| internos|065df75dc352...|2021-03-21 0...| 85| 1|4.4426512564...|\n| jardines|85017fa18c96...|2021-03-21 0...| 85| 1|4.4426512564...|\n| marat|4c2b8d97bb1c...|2021-03-21 0...| 85| 1|4.4426512564...|\n| mora|03c27b6e6ffe...|2021-03-21 0...| 85| 1|4.4426512564...|\n| parentesco|4174cc0d5d1a...|2021-03-21 0...| 85| 1|4.4426512564...|\n| propiedad|a082606587ab...|2021-03-21 0...| 85| 1|4.4426512564...|\n| reflexionar|7f3dab2ab309...|2021-03-21 0...| 85| 1|4.4426512564...|\n| reportes|68e032f866fe...|2021-03-26 0...| 85| 1|4.4426512564...|\n| rezagados|85017fa18c96...|2021-03-21 0...| 85| 1|4.4426512564...|\n| soporte|abacfa41a5fc...|2021-03-21 0...| 85| 1|4.4426512564...|\n| trampa|5cb5333b683d...|2021-03-21 0...| 85| 1|4.4426512564...|\n|ultracongela...|05e3adcba9f7...|2021-03-26 0...| 85| 1|4.4426512564...|\n| 124|8327c6e59ed7...|2021-03-21 0...| 85| 1|4.4426512564...|\n| acabar|70d59b3cac0a...|2021-03-21 0...| 85| 1|4.4426512564...|\n| admitting|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| basa|68e032f866fe...|2021-03-26 0...| 85| 1|4.4426512564...|\n| certidumbre|66419733e7e4...|2021-03-21 0...| 85| 1|4.4426512564...|\n| colleges|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| colocaron|202e89bfbaa3...|2021-03-21 0...| 85| 1|4.4426512564...|\n| compras|065df75dc352...|2021-03-21 0...| 85| 1|4.4426512564...|\n| contraparte|b77cd49c6e49...|2021-03-21 0...| 85| 1|4.4426512564...|\n| creada|66419733e7e4...|2021-03-21 0...| 85| 1|4.4426512564...|\n| descontento|7f3dab2ab309...|2021-03-21 0...| 85| 1|4.4426512564...|\n| dishes|6ae38bfe419d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| exacta|2aa027a3cd50...|2021-03-19 0...| 85| 1|4.4426512564...|\n| fallecen|57c9f33b7ef7...|2021-03-27 0...| 85| 1|4.4426512564...|\n| incorporar|62b5d0088902...|2021-03-21 0...| 85| 1|4.4426512564...|\n| modificado|72236c94ac71...|2021-03-22 0...| 85| 1|4.4426512564...|\n| papa|bc1da01183b8...|2021-03-21 0...| 85| 1|4.4426512564...|\n| paulina|0f466bacde44...|2021-03-21 0...| 85| 1|4.4426512564...|\n| presente|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| procedimientos|b21e020e64a2...|2021-03-21 0...| 85| 1|4.4426512564...|\n| quedaba|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| quejaron|bf790cc1d07e...|2021-03-21 0...| 85| 1|4.4426512564...|\n| repetitiva|d5b1ce551006...|2021-03-21 0...| 85| 1|4.4426512564...|\n| shut|ed2a11140e8d...|2021-03-21 0...| 85| 1|4.4426512564...|\n|socioemocion...|202e89bfbaa3...|2021-03-21 0...| 85| 1|4.4426512564...|\n| solicitantes|70d59b3cac0a...|2021-03-21 0...| 85| 1|4.4426512564...|\n| surf|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| typically|ed2a11140e8d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| verdadera|66419733e7e4...|2021-03-21 0...| 85| 1|4.4426512564...|\n| éste|5cb5333b683d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| 475|60b86f26f919...|2021-03-21 0...| 85| 1|4.4426512564...|\n| 613|b77cd49c6e49...|2021-03-21 0...| 85| 1|4.4426512564...|\n| actores|d283aaae8850...|2021-03-21 0...| 85| 1|4.4426512564...|\n| baño|7a3031279dfe...|2021-03-21 0...| 85| 1|4.4426512564...|\n| brotes|8eedb3c3b3b6...|2021-03-21 0...| 85| 1|4.4426512564...|\n| debate|270dcfd1740b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| difuntos|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| estacionado|d5b1ce551006...|2021-03-21 0...| 85| 1|4.4426512564...|\n| fluctuación|abacfa41a5fc...|2021-03-21 0...| 85| 1|4.4426512564...|\n| gloggles|62b5d0088902...|2021-03-21 0...| 85| 1|4.4426512564...|\n| mason|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| octopus|6ae38bfe419d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| odio|abd44d708948...|2021-03-21 0...| 85| 1|4.4426512564...|\n| oscuros|bf790cc1d07e...|2021-03-21 0...| 85| 1|4.4426512564...|\n| platicar|66419733e7e4...|2021-03-21 0...| 85| 1|4.4426512564...|\n| port|ed2a11140e8d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| puntual|bf790cc1d07e...|2021-03-21 0...| 85| 1|4.4426512564...|\n| reiteró|c040637b801b...|2021-03-23 0...| 85| 1|4.4426512564...|\n| rubicela|bf790cc1d07e...|2021-03-21 0...| 85| 1|4.4426512564...|\n| sospechosa|9d7b435a84fd...|2021-03-21 0...| 85| 1|4.4426512564...|\n| traffic|ed2a11140e8d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| wall|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| 169|6b4610a37ce5...|2021-03-25 0...| 85| 1|4.4426512564...|\n| adquirir|9f123746139b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| among|ed2a11140e8d...|2021-03-21 0...| 85| 1|4.4426512564...|\n| antiguos|9f123746139b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| apuntar|b77cd49c6e49...|2021-03-21 0...| 85| 1|4.4426512564...|\n| carrera|68e032f866fe...|2021-03-26 0...| 85| 1|4.4426512564...|\n| conocidos|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| contribuciones|7f3dab2ab309...|2021-03-21 0...| 85| 1|4.4426512564...|\n| day|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| decisiones|70d59b3cac0a...|2021-03-21 0...| 85| 1|4.4426512564...|\n| detección|31805d98e113...|2021-03-26 0...| 85| 1|4.4426512564...|\n| económicos|0f466bacde44...|2021-03-21 0...| 85| 1|4.4426512564...|\n| habrían|e9a418947cd6...|2021-03-19 0...| 85| 1|4.4426512564...|\n| harmony|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| moda|9f123746139b...|2021-03-21 0...| 85| 1|4.4426512564...|\n| módicos|6aa6971a33b9...|2021-03-21 0...| 85| 1|4.4426512564...|\n| nova|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| presentamos|72236c94ac71...|2021-03-22 0...| 85| 1|4.4426512564...|\n| primavera|4c2b8d97bb1c...|2021-03-21 0...| 85| 1|4.4426512564...|\n| relata|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| respuestas|320a8502c488...|2021-03-24 0...| 85| 1|4.4426512564...|\n| rowdy|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| rueda|1742b505699e...|2021-03-24 0...| 85| 1|4.4426512564...|\n| santos|6aa6971a33b9...|2021-03-21 0...| 85| 1|4.4426512564...|\n| session|61f85cb23d98...|2021-03-21 0...| 85| 1|4.4426512564...|\n| vacunamos|06b7885989a5...|2021-03-21 0...| 85| 1|4.4426512564...|\n| venía|18dd46f597aa...|2021-03-21 0...| 85| 1|4.4426512564...|\n| 462|6b4610a37ce5...|2021-03-25 0...| 85| 1|4.4426512564...|\n| 470|b90768906066...|2021-03-26 0...| 85| 1|4.4426512564...|\n| acumulaba|1742b505699e...|2021-03-24 0...| 85| 1|4.4426512564...|\n| aguardando|70d59b3cac0a...|2021-03-21 0...| 85| 1|4.4426512564...|\n| alrededores|6aa6971a33b9...|2021-03-21 0...| 85| 1|4.4426512564...|\n+---------------+---------------+---------------+---+---+---------------+\nonly showing top 150 rows\n\n"
],
[
"article_tfidf = article_tf.join(article_idf, ['article_id', 'palabra', 'publish_date'])\\\n .withColumn('tf_idf', col('tf') * col('idf'))\\\n .cache()",
"_____no_output_____"
],
[
"article_tfidf.orderBy('tf_idf', ascending=False).show(150,truncate=12)",
"+------------+------------+------------+---+----+------------+---+---+------------+------------+\n| article_id| palabra|publish_date|n_w| n_d| tf|c_d|i_d| idf| tf_idf|\n+------------+------------+------------+---+----+------------+---+---+------------+------------+\n|ed2a11140...| the|2021-03-2...| 60| 937|0.0640341...| 85| 5|2.8332133...|0.1814224...|\n|6ae38bfe4...| the|2021-03-2...| 47| 788|0.0596446...| 85| 5|2.8332133...|0.1689860...|\n|61f85cb23...| the|2021-03-2...|129|2788|0.0462697...| 85| 5|2.8332133...|0.1310920...|\n|5a9f0fdac...| milenio|2021-03-2...| 2| 43|0.0465116...| 85| 7|2.4967411...|0.1161274...|\n|ed2a11140...| to|2021-03-2...| 32| 937|0.0341515...| 85| 3|3.3440389...|0.1142041...|\n|ed2a11140...| of|2021-03-2...| 31| 937|0.0330843...| 85| 3|3.3440389...|0.1106352...|\n|5a9f0fdac...| 114|2021-03-2...| 1| 43|0.0232558...| 85| 1|4.4426512...|0.1033174...|\n|5a9f0fdac...| 159|2021-03-2...| 1| 43|0.0232558...| 85| 1|4.4426512...|0.1033174...|\n|5a9f0fdac...| 910|2021-03-2...| 1| 43|0.0232558...| 85| 1|4.4426512...|0.1033174...|\n|6ae38bfe4...| and|2021-03-2...| 24| 788|0.0304568...| 85| 3|3.3440389...|0.1018489...|\n|ea1b8d4f2...| montreal|2021-03-2...| 6| 276|0.0217391...| 85| 1|4.4426512...|0.0965793...|\n|ed2a11140...| border|2021-03-2...| 23| 937|0.0245464...| 85| 2|3.7495040...|0.0920369...|\n|6ae38bfe4...| to|2021-03-2...| 21| 788|0.0266497...| 85| 3|3.3440389...|0.0891177...|\n|61f85cb23...| and|2021-03-2...| 74|2788|0.0265423...| 85| 3|3.3440389...|0.0887585...|\n|5a9f0fdac...| 187|2021-03-2...| 1| 43|0.0232558...| 85| 2|3.7495040...|0.0871977...|\n|ed2a11140...| and|2021-03-2...| 24| 937|0.0256136...| 85| 3|3.3440389...|0.0856530...|\n|61f85cb23...| in|2021-03-2...| 77|2788|0.0276183...| 85| 4|3.0563568...|0.0844115...|\n|577a0e78e...| aterrizó|2021-03-2...| 3| 165|0.0181818...| 85| 1|4.4426512...|0.0807754...|\n|ea1b8d4f2...| david|2021-03-2...| 5| 276|0.0181159...| 85| 1|4.4426512...|0.0804828...|\n|ed2a11140...| in|2021-03-2...| 24| 937|0.0256136...| 85| 4|3.0563568...|0.0782844...|\n|5a9f0fdac...| detectados|2021-03-2...| 1| 43|0.0232558...| 85| 3|3.3440389...|0.0777683...|\n|03c27b6e6...| cancún|2021-03-2...| 9| 334|0.0269461...| 85| 5|2.8332133...|0.0763440...|\n|61f85cb23...| to|2021-03-2...| 63|2788|0.0225968...| 85| 3|3.3440389...|0.0755647...|\n|abd44d708...| dua|2021-03-2...| 10| 597|0.0167504...| 85| 1|4.4426512...|0.0744162...|\n|6ae38bfe4...| in|2021-03-2...| 19| 788|0.0241116...| 85| 4|3.0563568...|0.0736938...|\n|06b788598...| quieren|2021-03-2...| 6| 365|0.0164383...| 85| 1|4.4426512...|0.0730298...|\n|61f85cb23...| of|2021-03-2...| 56|2788|0.0200860...| 85| 3|3.3440389...|0.0671686...|\n|abd44d708...| lipa|2021-03-2...| 9| 597|0.0150753...| 85| 1|4.4426512...|0.0669746...|\n|d453f2247...|celebraci...|2021-03-2...| 3| 150| 0.02| 85| 3|3.3440389...|0.0668807...|\n|ea1b8d4f2...| padre|2021-03-2...| 6| 276|0.0217391...| 85| 4|3.0563568...|0.0664425...|\n|a0ce891e1...| ciento|2021-03-2...| 16| 497|0.0321931...| 85| 12|1.9577446...|0.0630259...|\n|2aa027a3c...| 870000|2021-03-1...| 3| 212|0.0141509...| 85| 1|4.4426512...|0.0628677...|\n|5a9f0fdac...| sigue|2021-03-2...| 1| 43|0.0232558...| 85| 6|2.6508917...|0.0616486...|\n|5a9f0fdac...| acumula|2021-03-2...| 1| 43|0.0232558...| 85| 6|2.6508917...|0.0616486...|\n|713f2e288...| demócratas|2021-03-2...| 4| 290|0.0137931...| 85| 1|4.4426512...|0.0612779...|\n|29a518094...| medicamento|2021-03-2...| 3| 218|0.0137614...| 85| 1|4.4426512...|0.0611374...|\n|9f1237461...| whisky|2021-03-2...| 15|1093|0.0137236...| 85| 1|4.4426512...|0.0609695...|\n|18dd46f59...| campanas|2021-03-2...| 13| 949|0.0136986...| 85| 1|4.4426512...|0.0608582...|\n|d453f2247...| piedad|2021-03-2...| 2| 150|0.0133333...| 85| 1|4.4426512...|0.0592353...|\n|d453f2247...| fieles|2021-03-2...| 2| 150|0.0133333...| 85| 1|4.4426512...|0.0592353...|\n|7f3dab2ab...| superior|2021-03-2...| 5| 380|0.0131578...| 85| 1|4.4426512...|0.0584559...|\n|99aab4877...| bamx|2021-03-2...| 5| 384|0.0130208...| 85| 1|4.4426512...|0.0578470...|\n|202e89bfb...| escuelas|2021-03-2...| 6| 390|0.0153846...| 85| 2|3.7495040...|0.0576846...|\n|6d514ef70...| naciones|2021-03-2...| 2| 155|0.0129032...| 85| 1|4.4426512...|0.0573245...|\n|5a9f0fdac...| digital|2021-03-2...| 1| 43|0.0232558...| 85| 8|2.3632097...|0.0549583...|\n|5a9f0fdac...| león|2021-03-2...| 1| 43|0.0232558...| 85| 8|2.3632097...|0.0549583...|\n|61f85cb23...| cancun|2021-03-2...| 40|2788|0.0143472...| 85| 2|3.7495040...|0.0537948...|\n|8eedb3c3b...| hospitales|2021-03-2...| 2| 106|0.0188679...| 85| 5|2.8332133...|0.0534568...|\n|7a3031279...| uber|2021-03-2...| 6| 507|0.0118343...| 85| 1|4.4426512...|0.0525757...|\n|7a3031279...|repartidores|2021-03-2...| 6| 507|0.0118343...| 85| 1|4.4426512...|0.0525757...|\n|5a9f0fdac...| ayer|2021-03-2...| 1| 43|0.0232558...| 85| 9|2.2454266...|0.0522192...|\n|5a9f0fdac...| noticias|2021-03-2...| 1| 43|0.0232558...| 85| 9|2.2454266...|0.0522192...|\n|5a9f0fdac...| reportó|2021-03-2...| 1| 43|0.0232558...| 85| 9|2.2454266...|0.0522192...|\n|577a0e78e...|pfizerbio...|2021-03-2...| 3| 165|0.0181818...| 85| 5|2.8332133...|0.0515129...|\n|202e89bfb...| padres|2021-03-2...| 6| 390|0.0153846...| 85| 3|3.3440389...|0.0514467...|\n|6ae38bfe4...| at|2021-03-2...| 12| 788|0.0152284...| 85| 3|3.3440389...|0.0509244...|\n|6ae38bfe4...| of|2021-03-2...| 12| 788|0.0152284...| 85| 3|3.3440389...|0.0509244...|\n|06b788598...| vacunar|2021-03-2...| 7| 365|0.0191780...| 85| 6|2.6508917...|0.0508390...|\n|8eedb3c3b...| comunidad|2021-03-2...| 2| 106|0.0188679...| 85| 6|2.6508917...|0.0500168...|\n|8eedb3c3b...| siete|2021-03-2...| 2| 106|0.0188679...| 85| 6|2.6508917...|0.0500168...|\n|9f1237461...| botellas|2021-03-2...| 12|1093|0.0109789...| 85| 1|4.4426512...|0.0487756...|\n|9f1237461...| macallan|2021-03-2...| 12|1093|0.0109789...| 85| 1|4.4426512...|0.0487756...|\n|06b788598...| privilegios|2021-03-2...| 4| 365|0.0109589...| 85| 1|4.4426512...|0.0486865...|\n|06b788598...| conservar|2021-03-2...| 4| 365|0.0109589...| 85| 1|4.4426512...|0.0486865...|\n|29a518094...| cofepris|2021-03-2...| 4| 218|0.0183486...| 85| 6|2.6508917...|0.0486402...|\n|ea1b8d4f2...| melgarejo|2021-03-2...| 3| 276|0.0108695...| 85| 1|4.4426512...|0.0482896...|\n|b17ec6dd3...| vuelos|2021-03-2...| 2| 140|0.0142857...| 85| 3|3.3440389...|0.0477719...|\n|b17ec6dd3...|provenientes|2021-03-2...| 2| 140|0.0142857...| 85| 3|3.3440389...|0.0477719...|\n|5a9f0fdac...| 22|2021-03-2...| 1| 43|0.0232558...| 85| 11|2.0447559...|0.0475524...|\n|5a9f0fdac...| mundo|2021-03-2...| 1| 43|0.0232558...| 85| 11|2.0447559...|0.0475524...|\n|ed2a11140...| from|2021-03-2...| 13| 937|0.0138740...| 85| 3|3.3440389...|0.0463954...|\n|99aab4877...| corteva|2021-03-2...| 4| 384|0.0104166...| 85| 1|4.4426512...|0.0462776...|\n|99aab4877...| comunidades|2021-03-2...| 4| 384|0.0104166...| 85| 1|4.4426512...|0.0462776...|\n|713f2e288...| suministro|2021-03-2...| 3| 290|0.0103448...| 85| 1|4.4426512...|0.0459584...|\n|593c6c23d...| internación|2021-03-1...| 2| 195|0.0102564...| 85| 1|4.4426512...|0.0455656...|\n|5cb5333b6...| acta|2021-03-2...| 7| 577|0.0121317...| 85| 2|3.7495040...|0.0454879...|\n|577a0e78e...| avión|2021-03-2...| 2| 165|0.0121212...| 85| 2|3.7495040...|0.0454485...|\n|577a0e78e...| aicm|2021-03-2...| 2| 165|0.0121212...| 85| 2|3.7495040...|0.0454485...|\n|577a0e78e...| 625|2021-03-2...| 2| 165|0.0121212...| 85| 2|3.7495040...|0.0454485...|\n|abd44d708...| cantante|2021-03-2...| 6| 597|0.0100502...| 85| 1|4.4426512...|0.0446497...|\n|8eedb3c3b...| cifra|2021-03-2...| 2| 106|0.0188679...| 85| 8|2.3632097...|0.0445888...|\n|d453f2247...| tendrán|2021-03-2...| 2| 150|0.0133333...| 85| 3|3.3440389...|0.0445871...|\n|d283aaae8...| ortizgris|2021-03-2...| 3| 299|0.0100334...| 85| 1|4.4426512...|0.0445750...|\n|039459da2...|conversación|2021-03-1...| 2| 200| 0.01| 85| 1|4.4426512...|0.0444265...|\n|8327c6e59...| euros|2021-03-2...| 7| 707|0.0099009...| 85| 1|4.4426512...|0.0439866...|\n|b17ec6dd3...| brasil|2021-03-2...| 3| 140|0.0214285...| 85| 11|2.0447559...|0.0438161...|\n|7a3031279...| eats|2021-03-2...| 5| 507|0.0098619...| 85| 1|4.4426512...|0.0438131...|\n|593c6c23d...| frontera|2021-03-1...| 3| 195|0.0153846...| 85| 5|2.8332133...|0.0435878...|\n|ed2a11140...| said|2021-03-2...| 12| 937|0.0128068...| 85| 3|3.3440389...|0.0428265...|\n|6ae38bfe4...| on|2021-03-2...| 10| 788|0.0126903...| 85| 3|3.3440389...|0.0424370...|\n|03c27b6e6...| argentinos|2021-03-2...| 5| 334|0.0149700...| 85| 5|2.8332133...|0.0424133...|\n|29a518094...| comisión|2021-03-2...| 3| 218|0.0137614...| 85| 4|3.0563568...|0.0420599...|\n|5a9f0fdac...| defunciones|2021-03-2...| 1| 43|0.0232558...| 85| 14|1.8035939...|0.0419440...|\n|8eedb3c3b...| consejería|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|2aa027a3c...| cederá|2021-03-1...| 2| 212|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| vinculados|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| 1590|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| quince|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| ofrecidos|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| brotes|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| ascienden|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| castilla|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| 5523|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| 215281|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| 142|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|8eedb3c3b...| 27681|2021-03-2...| 1| 106|0.0094339...| 85| 1|4.4426512...|0.0419118...|\n|474e010bc...| mil|2021-03-2...| 9| 189|0.0476190...| 85| 36|0.8591323...|0.0409110...|\n|2aa027a3c...| astrazeneca|2021-03-1...| 5| 212|0.0235849...| 85| 15|1.7346010...|0.0409104...|\n|29a518094...| napabeltan|2021-03-2...| 2| 218|0.0091743...| 85| 1|4.4426512...|0.0407582...|\n|ea1b8d4f2...| joven|2021-03-2...| 3| 276|0.0108695...| 85| 2|3.7495040...|0.0407554...|\n|62b5d0088...|nezahualc...|2021-03-2...| 5| 461|0.0108459...| 85| 2|3.7495040...|0.0406670...|\n|a0ce891e1...| agosto|2021-03-2...| 6| 497|0.0120724...| 85| 3|3.3440389...|0.0403706...|\n|5a9f0fdac...| últimas|2021-03-2...| 1| 43|0.0232558...| 85| 15|1.7346010...|0.0403395...|\n|5a9f0fdac...| mil|2021-03-2...| 2| 43|0.0465116...| 85| 36|0.8591323...|0.0399596...|\n|562d622a5...| mil|2021-03-2...| 14| 301|0.0465116...| 85| 36|0.8591323...|0.0399596...|\n|03c27b6e6...| cv|2021-03-2...| 3| 334|0.0089820...| 85| 1|4.4426512...|0.0399040...|\n|03c27b6e6...| sa|2021-03-2...| 3| 334|0.0089820...| 85| 1|4.4426512...|0.0399040...|\n|72236c94a...| cansino|2021-03-2...| 12| 711|0.0168776...| 85| 8|2.3632097...|0.0398853...|\n|ed2a11140...| that|2021-03-2...| 11| 937|0.0117395...| 85| 3|3.3440389...|0.0392576...|\n|5a9f0fdac...| actualmente|2021-03-2...| 1| 43|0.0232558...| 85| 16|1.6700625...|0.0388386...|\n|bc1da0118...| precios|2021-03-2...| 9| 780|0.0115384...| 85| 3|3.3440389...|0.0385850...|\n|62b5d0088...| vehicular|2021-03-2...| 4| 461|0.0086767...| 85| 1|4.4426512...|0.0385479...|\n|593c6c23d...| inm|2021-03-1...| 2| 195|0.0102564...| 85| 2|3.7495040...|0.0384564...|\n|61f85cb23...| at|2021-03-2...| 32|2788|0.0114777...| 85| 3|3.3440389...|0.0383820...|\n|6ae38bfe4...| for|2021-03-2...| 9| 788|0.0114213...| 85| 3|3.3440389...|0.0381933...|\n|6ae38bfe4...| are|2021-03-2...| 9| 788|0.0114213...| 85| 3|3.3440389...|0.0381933...|\n|c040637b8...| casa|2021-03-2...| 8| 449|0.0178173...| 85| 10|2.1400661...|0.0381303...|\n|6b4610a37...| diarios|2021-03-2...| 4| 352|0.0113636...| 85| 3|3.3440389...|0.0380004...|\n|b17ec6dd3...| chile|2021-03-2...| 2| 140|0.0142857...| 85| 6|2.6508917...|0.0378698...|\n|8327c6e59...| aramco|2021-03-2...| 6| 707|0.0084865...| 85| 1|4.4426512...|0.0377028...|\n|039459da2...| próxima|2021-03-1...| 2| 200| 0.01| 85| 2|3.7495040...|0.0374950...|\n|562d622a5...| 250|2021-03-2...| 3| 301|0.0099667...| 85| 2|3.7495040...|0.0373704...|\n|562d622a5...| ayer|2021-03-2...| 5| 301|0.0166112...| 85| 9|2.2454266...|0.0372994...|\n|9718ae87e...| ocupadas|2021-03-2...| 2| 202|0.0099009...| 85| 2|3.7495040...|0.0371238...|\n|8eedb3c3b...| ellas|2021-03-2...| 2| 106|0.0188679...| 85| 12|1.9577446...|0.0369385...|\n|a0ce891e1...| edad|2021-03-2...| 6| 497|0.0120724...| 85| 4|3.0563568...|0.0368976...|\n|e7d826dfb...| clases|2021-03-2...| 7| 583|0.0120068...| 85| 4|3.0563568...|0.0366972...|\n|6b4610a37...| mil|2021-03-2...| 15| 352|0.0426136...| 85| 36|0.8591323...|0.0366107...|\n|6d514ef70...| argentinos|2021-03-2...| 2| 155|0.0129032...| 85| 5|2.8332133...|0.0365575...|\n|06b788598...|conservad...|2021-03-2...| 3| 365|0.0082191...| 85| 1|4.4426512...|0.0365149...|\n|20e7a2da5...| alomía|2021-03-2...| 2| 137|0.0145985...| 85| 7|2.4967411...|0.0364487...|\n|ea1b8d4f2...| canadá|2021-03-2...| 4| 276|0.0144927...| 85| 7|2.4967411...|0.0361846...|\n|a0ce891e1...| dge|2021-03-2...| 4| 497|0.0080482...| 85| 1|4.4426512...|0.0357557...|\n|4c2b8d97b...| equinoccio|2021-03-2...| 7| 876|0.0079908...| 85| 1|4.4426512...|0.0355006...|\n|8eedb3c3b...| 245|2021-03-2...| 1| 106|0.0094339...| 85| 2|3.7495040...|0.0353726...|\n|8eedb3c3b...| sanidad|2021-03-2...| 1| 106|0.0094339...| 85| 2|3.7495040...|0.0353726...|\n|8eedb3c3b...| altas|2021-03-2...| 1| 106|0.0094339...| 85| 2|3.7495040...|0.0353726...|\n|8eedb3c3b...|estadísticas|2021-03-2...| 1| 106|0.0094339...| 85| 2|3.7495040...|0.0353726...|\n|8eedb3c3b...| publicadas|2021-03-2...| 1| 106|0.0094339...| 85| 2|3.7495040...|0.0353726...|\n|8eedb3c3b...| eleva|2021-03-2...| 1| 106|0.0094339...| 85| 2|3.7495040...|0.0353726...|\n+------------+------------+------------+---+----+------------+---+---+------------+------------+\nonly showing top 150 rows\n\n"
],
[
"w = Window.partitionBy('article_id').orderBy(col('tf_idf').desc())\n\narticle_tfidf_top_15=article_tfidf.withColumn('rank', rank().over(w))\\\n .where('rank <= 15')\\\n .drop('rank')\\\n .orderBy('article_id', 'tf_idf','n_w')\\\n .select('article_id','publish_date','palabra','n_w','tf_idf')",
"_____no_output_____"
],
[
"article_tfidf_top_15.show(truncate=12, n=30)",
"+------------+------------+------------+---+------------+\n| article_id|publish_date| palabra|n_w| tf_idf|\n+------------+------------+------------+---+------------+\n|039459da2...|2021-03-1...| señalo| 1|0.0222132...|\n|039459da2...|2021-03-1...|funcionarios| 1|0.0222132...|\n|039459da2...|2021-03-1...| agradezco| 1|0.0222132...|\n|039459da2...|2021-03-1...| impulsar| 1|0.0222132...|\n|039459da2...|2021-03-1...| ayudarnos| 1|0.0222132...|\n|039459da2...|2021-03-1...| homólogo| 1|0.0222132...|\n|039459da2...|2021-03-1...| telefónica| 1|0.0222132...|\n|039459da2...|2021-03-1...| abordado| 1|0.0222132...|\n|039459da2...|2021-03-1...| pedí| 1|0.0222132...|\n|039459da2...|2021-03-1...| enviarnos| 1|0.0222132...|\n|039459da2...|2021-03-1...| logrará| 1|0.0222132...|\n|039459da2...|2021-03-1...| calculo| 1|0.0222132...|\n|039459da2...|2021-03-1...| tema| 2|0.0224542...|\n|039459da2...|2021-03-1...| biden| 2|0.0236320...|\n|039459da2...|2021-03-1...| vacunas| 6|0.0257739...|\n|039459da2...|2021-03-1...| expresó| 2|0.0305635...|\n|039459da2...|2021-03-1...| 700| 2|0.0305635...|\n|039459da2...|2021-03-1...| llegarán| 2|0.0334403...|\n|039459da2...|2021-03-1...| próxima| 2|0.0374950...|\n|039459da2...|2021-03-1...|conversación| 2|0.0444265...|\n|03c27b6e6...|2021-03-2...| pruebas| 3|0.0224258...|\n|03c27b6e6...|2021-03-2...|investiga...| 3|0.0224258...|\n|03c27b6e6...|2021-03-2...| detectar| 2|0.0224521...|\n|03c27b6e6...|2021-03-2...| solicitó| 2|0.0224521...|\n|03c27b6e6...|2021-03-2...| marbus| 2|0.0266027...|\n|03c27b6e6...|2021-03-2...| fernando| 2|0.0266027...|\n|03c27b6e6...|2021-03-2...|ministeri...| 2|0.0266027...|\n|03c27b6e6...|2021-03-2...| mora| 2|0.0266027...|\n|03c27b6e6...|2021-03-2...| empresa| 4|0.0268913...|\n|03c27b6e6...|2021-03-2...| quintana| 4|0.0283019...|\n+------------+------------+------------+---+------------+\nonly showing top 30 rows\n\n"
],
[
"article_tfidf_top_15_site = article_tfidf_top_15.join(df_news_covid_mexico_date_text, ['article_id','publish_date']).select('article_id','publish_date','site','palabra','n_w','tf_idf')",
"_____no_output_____"
],
[
"article_tfidf_top_15_site.show(15)",
"+--------------------+-------------------+---------------+----------------+---+--------------------+\n| article_id| publish_date| site| palabra|n_w| tf_idf|\n+--------------------+-------------------+---------------+----------------+---+--------------------+\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com|correspondientes| 2| 0.02551621226311474|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| 5811| 1|0.025242336684604072|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| acumulando| 1|0.025242336684604072|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| 66041| 1|0.025242336684604072|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| 2193639| 2|0.024318933676093987|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| contagios| 5| 0.0236287881774458|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| fallecidas| 2|0.023235863451044843|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| positivo| 2|0.022247097803435412|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| 21| 3| 0.02155563794560859|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| afectados| 2| 0.0213375215798725|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| contagio| 2| 0.0213375215798725|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| primer| 3|0.020859808493558788|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| coahuila| 1| 0.01900022140808072|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| actualmente| 2|0.018977983343756083|\n|e386a6062c63e081c...|2021-03-21 00:00:00|www.infobae.com| total| 3|0.017193137250088128|\n+--------------------+-------------------+---------------+----------------+---+--------------------+\nonly showing top 15 rows\n\n"
],
[
"article_tfidf_top_15_site.write.jdbc(url=url, table=\"tb_news_covid_mexico_palabras_top_tfidf\", mode=mode, properties=properties)",
"_____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"
]
] |
cb7cd48ceada74091147e98b11980254432a9438
| 310,780 |
ipynb
|
Jupyter Notebook
|
BLAST tutorials/notebooks/GSD/GSD Rpb1_orthologs_in_1011_genomes.ipynb
|
NCBI-Hackathons/ncbi-cloud-tutorials
|
172f3d50e5a84dbcb72f9139acc34cbe020a69e0
|
[
"MIT"
] | 11 |
2019-08-14T14:48:23.000Z
|
2022-02-11T17:24:12.000Z
|
BLAST tutorials/notebooks/GSD/GSD Rpb1_orthologs_in_1011_genomes.ipynb
|
NCBI-Hackathons/ncbi-cloud-tutorials
|
172f3d50e5a84dbcb72f9139acc34cbe020a69e0
|
[
"MIT"
] | 1 |
2022-02-26T02:26:06.000Z
|
2022-03-02T21:52:04.000Z
|
BLAST tutorials/notebooks/GSD/GSD Rpb1_orthologs_in_1011_genomes.ipynb
|
NCBI-Hackathons/ncbi-cloud-tutorials
|
172f3d50e5a84dbcb72f9139acc34cbe020a69e0
|
[
"MIT"
] | 6 |
2019-07-29T21:41:49.000Z
|
2021-05-07T18:52:12.000Z
| 80.554692 | 87,292 | 0.711442 |
[
[
[
"# GSD: Rpb1 orthologs in 1011 genomes collection\n\nThis collects Rpb1 gene and protein sequences from a collection of natural isolates of sequenced yeast genomes from [Peter et al 2017](https://www.ncbi.nlm.nih.gov/pubmed/29643504), and then estimates the count of the heptad repeats. It builds directly on the notebook [here](GSD%20Rpb1_orthologs_in_PB_genomes.ipynb), which descends from [Searching for coding sequences in genomes using BLAST and Python](../Searching%20for%20coding%20sequences%20in%20genomes%20using%20BLAST%20and%20Python.ipynb). It also builds on the notebooks shown [here](https://nbviewer.jupyter.org/github/fomightez/cl_sq_demo-binder/blob/master/notebooks/GSD/GSD%20Add_Supplemental_data_info_to_nt_count%20data%20for%201011_cerevisiae_collection.ipynb) and [here](https://github.com/fomightez/patmatch-binder). \n\nReference for sequence data: \n[Genome evolution across 1,011 Saccharomyces cerevisiae isolates. Peter J, De Chiara M, Friedrich A, Yue JX, Pflieger D, Bergström A, Sigwalt A, Barre B, Freel K, Llored A, Cruaud C, Labadie K, Aury JM, Istace B, Lebrigand K, Barbry P, Engelen S, Lemainque A, Wincker P, Liti G, Schacherer J. Nature. 2018 Apr;556(7701):339-344. doi: 10.1038/s41586-018-0030-5. Epub 2018 Apr 11. PMID: 29643504](https://www.ncbi.nlm.nih.gov/pubmed/29643504)\n\n \n -----",
"_____no_output_____"
],
[
"## Overview\n",
"_____no_output_____"
],
[
"## Preparation\n\nGet scripts and sequence data necessary.\n\n**DO NOT 'RUN ALL'. AN INTERACTION IS NECESSARY AT CELL FIVE. AFTER THAT INTERACTION, THE REST BELOW IT CAN BE RUN.**\n\n(Caveat: right now this is written for genes with no introns. Only a few hundred have in yeast and that is the organism in this example. Intron presence would only become important when trying to translate in late stages of this workflow.)",
"_____no_output_____"
]
],
[
[
"gene_name = \"RPB1\"\nsize_expected = 5202\nget_seq_from_link = False\nlink_to_FASTA_of_gene = \"https://gist.githubusercontent.com/fomightez/f46b0624f1d8e3abb6ff908fc447e63b/raw/625eaba76bb54e16032f90c8812350441b753a0c/uz_S288C_YOR270C_VPH1_coding.fsa\"\n#**Possible future enhancement would be to add getting the FASTA of the gene from Yeastmine with just systematic id**",
"_____no_output_____"
]
],
[
[
"Get the `blast_to_df` script by running this commands.",
"_____no_output_____"
]
],
[
[
"import os\nfile_needed = \"blast_to_df.py\"\nif not os.path.isfile(file_needed):\n !curl -O https://raw.githubusercontent.com/fomightez/sequencework/master/blast-utilities/blast_to_df.py\nimport pandas as pd",
"_____no_output_____"
]
],
[
[
"**Now to get the entire collection or a subset of the 1011 genomes, the next cell will need to be edited.** I'll probably leave it with a small set for typical running purposes. However, to make it run fast, try the 'super-tiny' set with just two.",
"_____no_output_____"
]
],
[
[
"# Method to get ALL the genomes. TAKES A WHILE!!! \n# (ca. 1 hour and 15 minutes to download alone? + Extracting is a while.)\n# Easiest way to minotor extracting step is to open terminal, cd to \n# `GENOMES_ASSEMBLED`, & use `ls | wc -l` to count files extracted.\n#!curl -O http://1002genomes.u-strasbg.fr/files/1011Assemblies.tar.gz\n#!tar xzf 1011Assemblies.tar.gz\n#!rm 1011Assemblies.tar.gz\n\n# Small development set\n!curl -OL https://www.dropbox.com/s/f42tiygq9tr1545/medium_setGENOMES_ASSEMBLED.tar.gz\n!tar xzf medium_setGENOMES_ASSEMBLED.tar.gz\n\n# Tiny development set\n#!curl -OL https://www.dropbox.com/s/txufq2jflkgip82/tiny_setGENOMES_ASSEMBLED.tar.gz\n#!tar xzf tiny_setGENOMES_ASSEMBLED.tar.gz\n#!mv tiny_setGENOMES_ASSEMBLED GENOMES_ASSEMBLED\n\n#define directory with genomes\ngenomes_dirn = \"GENOMES_ASSEMBLED\"",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\n 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0\n100 1034 0 1034 0 0 819 0 --:--:-- 0:00:01 --:--:-- 0\n100 183M 100 183M 0 0 23.6M 0 0:00:07 0:00:07 --:--:-- 52.4M\n"
]
],
[
[
"Before process the list of all of them, fix one that has an file name mismatch with what the description lines have. \nSpecifically, the assembly file name is `CDH.re.fa`, but the FASTA-entries inside begin `CDH-3`. \nSimple file name mismatch. So next cell will change that file name to match. ",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nfile_with_issues = \"CDH.re.fa\"\nif os.path.isfile(\"GENOMES_ASSEMBLED/\"+file_with_issues):\n sys.stderr.write(\"\\nFile with name non-matching entries ('{}') observed and\"\n \" fixed.\".format(file_with_issues))\n !mv GENOMES_ASSEMBLED/CDH.re.fa GENOMES_ASSEMBLED/CDH_3.re.fa\n #pause and then check if file with original name is there still because\n # it means this was attempted too soon and need to start over.\n import time\n time.sleep(12) #12 seconds \n if os.path.isfile(\"GENOMES_ASSEMBLED/\"+file_with_issues):\n sys.stderr.write(\"\\n***PROBLEM. TRIED THIS CELL BEFORE FINISHED UPLOADING.\\n\"\n \"DELETE FILES ASSOCIATED AND START ALL OVER AGAIN WITH UPLOAD STEP***.\")\nelse:\n sys.stderr.write(\"\\nFile '{}' not seen and so nothing done\"\n \". Seems wrong.\".format(file_with_issues))\n sys.exit(1)",
"\nFile with name non-matching entries ('CDH.re.fa') observed and fixed."
],
[
"# Get SGD gene sequence in FASTA format to search for best matches in the genomes\nimport sys\ngene_filen = gene_name + \".fsa\"\nif get_seq_from_link:\n !curl -o {gene_filen} {link_to_FASTA_of_gene}\nelse:\n !touch {gene_filen}\n sys.stderr.write(\"\\nEDIT THE FILE '{}' TO CONTAIN \"\n \"YOUR GENE OF INTEREST (FASTA-FORMATTED)\"\n \".\".format(gene_filen))\n sys.exit(0)",
"\nEDIT THE FILE 'RPB1.fsa' TO CONTAIN YOUR GENE OF INTEREST (FASTA-FORMATTED)."
]
],
[
[
"**I PUT CONTENTS OF FILE `S288C_YDL140C_RPO21_coding.fsa` downloaded from [here](https://www.yeastgenome.org/locus/S000002299/sequence) as 'RPB1.fsa'.**\n\nNow you are prepared to run BLAST to search each PacBio-sequenced genomes for the best match to a gene from the Saccharomyces cerevisiae strain S288C reference sequence.",
"_____no_output_____"
],
[
"## Use BLAST to search the genomes for matches to the gene in the reference genome at SGD\n\nSGD is the [Saccharomyces cerevisiae Genome Database site](http:yeastgenome.org) and the reference genome is from S288C.\n\nThis is going to go through each genome and make a database so it is searchable and then search for matches to the gene. The information on the best match will be collected. One use for that information will be collecting the corresponding sequences later.\n\nImport the script that allows sending BLAST output to Python dataframes so that we can use it here.",
"_____no_output_____"
]
],
[
[
"from blast_to_df import blast_to_df",
"_____no_output_____"
],
[
"# Make a list of all `genome.fa` files, excluding `genome.fa.nhr` and `genome.fa.nin` and `genome.fansq`\n# The excluding was only necessary because I had run some queries preliminarily in development. Normally, it would just be the `.re.fa` at the outset.\nfn_to_check = \"re.fa\" \ngenomes = []\nimport os\nimport fnmatch\nfor file in os.listdir(genomes_dirn):\n if fnmatch.fnmatch(file, '*'+fn_to_check):\n if not file.endswith(\".nhr\") and not file.endswith(\".nin\") and not file.endswith(\".nsq\") :\n # plus skip hidden files\n if not file.startswith(\"._\"):\n genomes.append(file)\nlen(genomes)",
"_____no_output_____"
]
],
[
[
"Using the trick of putting `%%capture` on first line from [here](https://stackoverflow.com/a/23692951/8508004) to suppress the output from BLAST for many sequences from filling up cell. \n(You can monitor the making of files ending in `.nhr` for all the FASTA files in `GENOMES_ASSEMBLED` to monitor progress'.)",
"_____no_output_____"
]
],
[
[
"%%time\n%%capture\nSGD_gene = gene_filen\ndfs = []\nfor genome in genomes:\n !makeblastdb -in {genomes_dirn}/{genome} -dbtype nucl\n result = !blastn -query {SGD_gene} -db {genomes_dirn}/{genome} -outfmt \"6 qseqid sseqid stitle pident qcovs length mismatch gapopen qstart qend sstart send qframe sframe frames evalue bitscore qseq sseq\" -task blastn\n from blast_to_df import blast_to_df\n blast_df = blast_to_df(result.n)\n dfs.append(blast_df.head(1))",
"CPU times: user 1.74 s, sys: 1.22 s, total: 2.97 s\nWall time: 1min 21s\n"
],
[
"# merge the dataframes in the list `dfs` into one dataframe\ndf = pd.concat(dfs)",
"_____no_output_____"
],
[
"#Save the df\nfilen_prefix = gene_name + \"_orthologBLASTdf\"\ndf.to_pickle(filen_prefix+\".pkl\")\ndf.to_csv(filen_prefix+'.tsv', sep='\\t',index = False) ",
"_____no_output_____"
],
[
"#df",
"_____no_output_____"
]
],
[
[
"Computationally check if any genomes missing from the BLAST results list?",
"_____no_output_____"
]
],
[
[
"subjids = df.sseqid.tolist()\n#print (subjids)\n#print (subjids[0:10])\nsubjids = [x.split(\"-\")[0] for x in subjids]\n#print (subjids)\n#print (subjids[0:10])\nlen_genome_fn_end = len(fn_to_check) + 1 # plus one to accound for the period that will be \n# between `fn_to_check` and strain_id`, such as `SK1.genome.fa`\ngenome_ids = [x[:-len_genome_fn_end] for x in genomes]\n#print (genome_ids[0:10])\n\na = set(genome_ids)\n#print (a)\nprint (\"initial:\",len(a))\nr = set(subjids)\nprint(\"results:\",len(r))\nprint (\"missing:\",len(a-r))\nif len(a-r):\n print(\"\\n\")\n print(\"ids missing:\",a-r)\n#a - r",
"initial: 48\nresults: 48\nmissing: 0\n"
]
],
[
[
"Sanity check: Report on how expected size compares to max size seen?",
"_____no_output_____"
]
],
[
[
"size_seen = df.length.max(0)\nprint (\"Expected size of gene:\", size_expected)\nprint (\"Most frequent size of matches:\", df.length.mode()[0])\nprint (\"Maximum size of matches:\", df.length.max(0))",
"Expected size of gene: 5202\nMost frequent size of matches: 5202\nMaximum size of matches: 5306\n"
]
],
[
[
"## Collect the identified, raw sequences\n\nGet the expected size centered on the best match, plus a little flanking each because they might not exactly cover the entire open reading frame. (Although, the example here all look to be full size.)",
"_____no_output_____"
]
],
[
[
"# Get the script for extracting based on position (and install dependency pyfaidx)\nimport os\nfile_needed = \"extract_subsequence_from_FASTA.py\"\nif not os.path.isfile(file_needed):\n !curl -O https://raw.githubusercontent.com/fomightez/sequencework/master/Extract_from_FASTA/extract_subsequence_from_FASTA.py\n!pip install pyfaidx",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 16964 100 16964 0 0 74078 0 --:--:-- --:--:-- --:--:-- 74078\nRequirement already satisfied: pyfaidx in /srv/conda/lib/python3.7/site-packages (0.5.5.2)\nRequirement already satisfied: setuptools>=0.7 in /srv/conda/lib/python3.7/site-packages (from pyfaidx) (40.8.0)\nRequirement already satisfied: six in /srv/conda/lib/python3.7/site-packages (from pyfaidx) (1.12.0)\n"
]
],
[
[
"For the next cell, I am going to use the trick of putting `%%capture` on first line from [here](https://stackoverflow.com/a/23692951/8508004) to suppress the output from the entire set making a long list of output.\nFor ease just monitor the progress in a launched terminal with the following code run in the directory where this notebook will be because the generated files only moved into the `raw` directory as last step of cell:\n\n ls seq_extracted* | wc -l\n \n(**NOTE: WHEN RUNNING WITH THE FULL SET, THIS CELL BELOW WILL REPORT AROUND A DOZEN `FileNotFoundError:`/Exceptions. HOWEVER, THEY DON'T CAUSE THE NOTEBOOK ITSELF TO CEASE TO RUN. SO DISREGARD THEM FOR THE TIME BEING.** )",
"_____no_output_____"
]
],
[
[
"%%capture\nsize_expected = size_expected # use value from above, or alter at this point.\n#size_expected = df.length.max(0) #bp length of SGD coding sequence; should be equivalent and that way not hardcoded?\nextra_add_to_start = 51 #to allow for 'fuzziness' at starting end\nextra_add_to_end = 51 #to allow for 'fuzziness' at far end\ngenome_fn_end = \"re.fa\" \n\n\ndef midpoint(items):\n '''\n takes a iterable of items and returns the midpoint (integer) of the first \n and second values\n '''\n return int((int(items[0])+int(items[1]))/2)\n\n#midpoint((1,100))\n\ndef determine_pos_to_get(match_start,match_end):\n '''\n Take the start and end of the matched region.\n \n Calculate midpoint between those and then \n center expected size on that to determine\n preliminary start and preliminary end to get.\n Add the extra basepairs to get at each end\n to allow for fuzziness/differences of actual\n gene ends for orthologs. \n Return the final start and end positions to get.\n \n '''\n center_of_match = midpoint((match_start,match_end))\n half_size_expected = int(size_expected/2.0)\n if size_expected % 2 != 0:\n half_size_expected += 1\n start_pos = center_of_match - half_size_expected\n end_pos = center_of_match + half_size_expected\n start_pos -= extra_add_to_start\n end_pos += extra_add_to_end \n \n # Because of getting some flanking sequences to account for 'fuzziness', it \n # is possible the start and end can exceed possible. 'End' is not a problem \n # because the `extract_subsequence_from_FASTA.py` script will get as much as\n # it from the indicated sequence if a larger than possible number is \n # provided. However,'start' can become negative and because the region to \n # extract is provided as a string the dash can become a problem. Dealing \n # with it here by making sequence positive only.\n # Additionally, because I rely on center of match to position where to get,\n # part being cut-off due to absence on sequence fragment will shift center\n # of match away from what is actually center of gene and to counter-balance\n # add twice the amount to the other end. (Actually, I feel I should adjust\n # the start end likewise if the sequence happens to be shorter than portion\n # I would like to capture but I don't know length of involved hit yet and\n # that would need to be added to allow that to happen!<--TO DO)\n if start_pos < 0:\n raw_amount_missing_at_start = abs(start_pos)# for counterbalancing; needs\n # to be collected before `start_pos` adjusted\n start_pos = 1\n end_pos += 2 * raw_amount_missing_at_start\n \n return start_pos, end_pos\n\n\n\n# go through the dataframe using information on each to come up with sequence file, \n# specific indentifier within sequence file, and the start and end to extract\n# store these valaues as a list in a dictionary with the strain identifier as the key.\nextracted_info = {}\nstart,end = 0,0\nfor row in df.itertuples():\n #print (row.length)\n start_to_get, end_to_get = determine_pos_to_get(row.sstart, row.send)\n posns_to_get = \"{}-{}\".format(start_to_get, end_to_get)\n record_id = row.sseqid\n strain_id = row.sseqid.split(\"-\")[0]\n seq_fn = strain_id + \".\" + genome_fn_end\n extracted_info[strain_id] = [seq_fn, record_id, posns_to_get]\n# Use the dictionary to get the sequences\nfor id_ in extracted_info:\n #%run extract_subsequence_from_FASTA.py {*extracted_info[id_]} #unpacking doesn't seem to work here in `%run`\n %run extract_subsequence_from_FASTA.py {genomes_dirn}/{extracted_info[id_][0]} {extracted_info[id_][1]} {extracted_info[id_][2]}\n\n#package up the retrieved sequences\narchive_file_name = gene_name+\"_raw_ortholog_seqs.tar.gz\"\n# make list of extracted files using fnmatch\nfn_part_to_match = \"seq_extracted\"\ncollected_seq_files_list = []\nimport os\nimport sys\nimport fnmatch\nfor file in os.listdir('.'):\n if fnmatch.fnmatch(file, fn_part_to_match+'*'):\n #print (file)\n collected_seq_files_list.append(file)\n!tar czf {archive_file_name} {\" \".join(collected_seq_files_list)} # use the list for archiving command\nsys.stderr.write(\"\\n\\nCollected RAW sequences gathered and saved as \"\n \"`{}`.\".format(archive_file_name))\n# move the collected raw sequences to a folder in preparation for\n# extracting encoding sequence from original source below\n!mkdir raw\n!mv seq_extracted*.fa raw",
"_____no_output_____"
]
],
[
[
"That archive should contain the \"raw\" sequence for each gene, even if the ends are a little different for each. At minimum the entire gene sequence needs to be there at this point; extra at each end is preferable at this point.\n\nYou should inspect them as soon as possible and adjust the extra sequence to add higher or lower depending on whether the ortholog genes vary more or less, respectively. The reason they don't need to be perfect yet though is because next we are going to extract the longest open reading frame, which presumably demarcates the entire gene. Then we can return to use that information to clean up the collected sequences to just be the coding sequence.",
"_____no_output_____"
],
[
"## Collect protein translations of the genes and then clean up \"raw\" sequences to just be coding\n\nWe'll assume the longest translatable frame in the collected \"raw\" sequences encodes the protein sequence for the gene orthologs of interest. Well base these steps on the [section '20.1.13 Identifying open reading frames'](http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc299) in the present version of the [Biopython Tutorial and Cookbook](http://biopython.org/DIST/docs/tutorial/Tutorial.html) (Last Update – 18 December 2018 (Biopython 1.73).",
"_____no_output_____"
],
[
"(First run the next cell to get a script needed for dealing with the strand during the translation and gathering of thge encoding sequence.)",
"_____no_output_____"
]
],
[
[
"import os\nfile_needed = \"convert_fasta_to_reverse_complement.py\"\nif not os.path.isfile(file_needed):\n !curl -O https://raw.githubusercontent.com/fomightez/sequencework/master/ConvertSeq/convert_fasta_to_reverse_complement.py",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 8851 100 8851 0 0 28644 0 --:--:-- --:--:-- --:--:-- 28644\n"
]
],
[
[
"Now to perform the work described in the header to this section...\n\nFor the next cell, I am going to use the trick of putting `%%capture` on first line from [here](https://stackoverflow.com/a/23692951/8508004) to suppress the output from the entire set making a long list of output.\nFor ease just monitor the progress in a launched terminal with the following code run in the directory where this notebook will be:\n\n ls *_ortholog_gene.fa | wc -l",
"_____no_output_____"
]
],
[
[
"%%capture\n# find the featured open reading frame and collect presumed protein sequences\n# Collect the corresponding encoding sequence from the original source\ndef len_ORF(items):\n # orf is fourth item in the tuples\n return len(items[3])\ndef find_orfs_with_trans(seq, trans_table, min_protein_length):\n '''\n adapted from the present section '20.1.13 Identifying open reading frames'\n http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc299 in the \n present version of the [Biopython Tutorial and Cookbook at \n http://biopython.org/DIST/docs/tutorial/Tutorial.html \n (Last Update – 18 December 2018 (Biopython 1.73)\n Same as there except altered to sort on the length of the\n open reading frame.\n '''\n answer = []\n seq_len = len(seq)\n for strand, nuc in [(+1, seq), (-1, seq.reverse_complement())]:\n for frame in range(3):\n trans = str(nuc[frame:].translate(trans_table))\n trans_len = len(trans)\n aa_start = 0\n aa_end = 0\n while aa_start < trans_len:\n aa_end = trans.find(\"*\", aa_start)\n if aa_end == -1:\n aa_end = trans_len\n if aa_end-aa_start >= min_protein_length:\n if strand == 1:\n start = frame+aa_start*3\n end = min(seq_len,frame+aa_end*3+3)\n else:\n start = seq_len-frame-aa_end*3-3\n end = seq_len-frame-aa_start*3\n answer.append((start, end, strand,\n trans[aa_start:aa_end]))\n aa_start = aa_end+1\n answer.sort(key=len_ORF, reverse = True)\n return answer\n\ndef generate_rcoutput_file_name(file_name,suffix_for_saving = \"_rc\"):\n '''\n from https://github.com/fomightez/sequencework/blob/master/ConvertSeq/convert_fasta_to_reverse_complement.py\n Takes a file name as an argument and returns string for the name of the\n output file. The generated name is based on the original file\n name.\n Specific example\n =================\n Calling function with\n (\"sequence.fa\", \"_rc\")\n returns\n \"sequence_rc.fa\"\n '''\n main_part_of_name, file_extension = os.path.splitext(\n file_name) #from \n #http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python\n if '.' in file_name: #I don't know if this is needed with the os.path.splitext method but I had it before so left it\n return main_part_of_name + suffix_for_saving + file_extension\n else:\n return file_name + suffix_for_saving + \".fa\"\n \ndef add_strand_to_description_line(file,strand=\"-1\"):\n '''\n Takes a file and edits description line to add \n strand info at end.\n \n Saves the fixed file\n '''\n import sys\n output_file_name = \"temp.txt\"\n # prepare output file for saving so it will be open and ready\n with open(output_file_name, 'w') as output_file:\n\n # read in the input file\n with open(file, 'r') as input_handler:\n # prepare to give feeback later or allow skipping to certain start\n lines_processed = 0\n\n for line in input_handler:\n lines_processed += 1\n if line.startswith(\">\"):\n new_line = line.strip() + \"; {} strand\\n\".format(strand)\n else:\n new_line = line\n \n # Send text to output\n output_file.write(new_line)\n\n \n # replace the original file with edited\n !mv temp.txt {file}\n # Feedback\n sys.stderr.write(\"\\nIn {}, strand noted.\".format(file))\n\ntable = 1 #sets translation table to standard nuclear, see \n# https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi\nmin_pro_len = 80 #cookbook had the standard `100`. Feel free to adjust.\nprot_seqs_info = {} #collect as dictionary with strain_id as key. Values to\n# be list with source id as first item and protein length as second and \n# strand in source seq as third item, and start and end in source sequence as fourth and fifth,\n# and file name of protein and gene as sixth and seventh.\n# Example key and value pair: 'YPS138':['<source id>','<protein length>',-1,52,2626,'<gene file name>','<protein file name>']\ngene_seqs_fn_list = []\nprot_seqs_fn_list = []\nfrom Bio import SeqIO\nfor raw_seq_filen in collected_seq_files_list:\n #strain_id = raw_seq_filen[:-len_genome_fn_end] #if was dealing with source seq\n strain_id = raw_seq_filen.split(\"-\")[0].split(\"seq_extracted\")[1]\n record = SeqIO.read(\"raw/\"+raw_seq_filen,\"fasta\")\n raw_seq_source_fn = strain_id + \".\" + genome_fn_end\n raw_seq_source_id = record.description.split(\":\")[0]\n orf_list = find_orfs_with_trans(record.seq, table, min_pro_len)\n orf_start, orf_end, strand, prot_seq = orf_list[0] #longest ORF seq for protein coding\n \n location_raw_seq = record.description.rsplit(\":\",1)[1] #get to use in calculating\n # the start and end position in original genome sequence.\n raw_loc_parts = location_raw_seq.split(\"-\")\n start_from_raw_seq = int(raw_loc_parts[0])\n end_from_raw_seq = int(raw_loc_parts[1])\n length_extracted = len(record) #also to use in calculating relative original\n \n #Fix negative value. (Somehow Biopython can report negative value when hitting\n # end of sequence without encountering stop codon and negatives messes up \n # indexing later it seems.)\n if orf_start < 0:\n orf_start = 0\n \n # Trim back to the first Methionine, assumed to be the initiating MET.\n # (THIS MIGHT BE A SOURCE OF EXTRA 'LEADING' RESIDUES IN SOME CASES & ARGUES \n # FOR LIMITING THE AMOUNT OF FLANKING SEQUENCE ADDED TO ALLOW FOR FUZINESS.)\n try:\n amt_resi_to_trim = prot_seq.index(\"M\")\n except ValueError:\n sys.stderr.write(\"**ERROR**When searching for initiating methionine,\\n\"\n \"no Methionine found in the traslated protein sequence.**ERROR**\")\n sys.exit(1)\n prot_seq = prot_seq[amt_resi_to_trim:]\n len_seq_trimmed = amt_resi_to_trim * 3\n \n # Calculate the adjusted start and end values for the untrimmed ORF\n adj_start = start_from_raw_seq + orf_start\n adj_end = end_from_raw_seq - (length_extracted - orf_end)\n \n # Adjust for trimming for appropriate strand.\n if strand == 1:\n adj_start += len_seq_trimmed\n #adj_end += 3 # turns out stop codon is part of numbering biopython returns\n elif strand == -1:\n adj_end -= len_seq_trimmed\n #adj_start -= 3 # turns out stop codon is part of numbering biopython returns\n else:\n sys.stderr.write(\"**ERROR**No strand match option detected!**ERROR**\")\n sys.exit(1)\n \n # Collect the sequence for the actual gene encoding region from\n # the original sequence. This way the original numbers will\n # be put in the file.\n start_n_end_str = \"{}-{}\".format(adj_start,adj_end)\n %run extract_subsequence_from_FASTA.py {genomes_dirn}/{raw_seq_source_fn} {raw_seq_source_id} {start_n_end_str}\n \n # rename the extracted subsequence a more distinguishing name and notify\n g_output_file_name = strain_id +\"_\" + gene_name + \"_ortholog_gene.fa\"\n !mv {raw_seq_filen} {g_output_file_name} # because the sequence saved happens to \n # be same as raw sequence file saved previously, that name can be used to\n # rename new file.\n gene_seqs_fn_list.append(g_output_file_name)\n sys.stderr.write(\"\\n\\nRenamed gene file to \"\n \"`{}`.\".format(g_output_file_name))\n \n # Convert extracted sequence to reverse complement if translation was on negative strand.\n if strand == -1:\n %run convert_fasta_to_reverse_complement.py {g_output_file_name}\n # replace original sequence file with the produced file\n produced_fn = generate_rcoutput_file_name(g_output_file_name)\n !mv {produced_fn} {g_output_file_name}\n # add (after saved) onto the end of the description line for that `-1 strand` \n # No way to do this in my current version of convert sequence. So editing descr line.\n add_strand_to_description_line(g_output_file_name)\n\n \n #When settled on actual protein encoding sequence, fill out\n # description to use for saving the protein sequence.\n prot_descr = (record.description.rsplit(\":\",1)[0]+ \" \"+ gene_name \n + \"_ortholog\"+ \"| \" +str(len(prot_seq)) + \" aas | from \" \n + raw_seq_source_id + \" \"\n + str(adj_start) + \"-\"+str(adj_end))\n if strand == -1:\n prot_descr += \"; {} strand\".format(strand)\n \n # save the protein sequence as FASTA\n chunk_size = 70 #<---amino acids per line to have in FASTA\n prot_seq_chunks = [prot_seq[i:i+chunk_size] for i in range(\n 0, len(prot_seq),chunk_size)]\n prot_seq_fa = \">\" + prot_descr + \"\\n\"+ \"\\n\".join(prot_seq_chunks)\n p_output_file_name = strain_id +\"_\" + gene_name + \"_protein_ortholog.fa\"\n with open(p_output_file_name, 'w') as output:\n output.write(prot_seq_fa)\n prot_seqs_fn_list.append(p_output_file_name)\n sys.stderr.write(\"\\n\\nProtein sequence saved as \"\n \"`{}`.\".format(p_output_file_name))\n \n \n # at end store information in `prot_seqs_info` for later making a dataframe \n # and then text table for saving summary\n #'YPS138':['<source id>',<protein length>,-1,52,2626,'<gene file name>','<protein file name>']\n prot_seqs_info[strain_id] = [raw_seq_source_id,len(prot_seq),strand,adj_start,adj_end,\n g_output_file_name,p_output_file_name]\n \n sys.stderr.write(\"\\n******END OF A SET OF PROTEIN ORTHOLOG \"\n \"AND ENCODING GENE********\")",
"_____no_output_____"
],
[
"# use `prot_seqs_info` for saving a summary text table (first convert to dataframe?)\ntable_fn_prefix = gene_name + \"_orthologs_table\"\ntable_fn = table_fn_prefix + \".tsv\"\npkl_table_fn = table_fn_prefix + \".pkl\"\nimport pandas as pd\ninfo_df = pd.DataFrame.from_dict(prot_seqs_info, orient='index',\n columns=['descr_id', 'length', 'strand', 'start','end','gene_file','prot_file']) # based on\n# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html and\n# note from Python 3.6 that `pd.DataFrame.from_items` is deprecated; \n#\"Please use DataFrame.from_dict\"\ninfo_df.to_pickle(pkl_table_fn)\ninfo_df.to_csv(table_fn, sep='\\t') # keep index is default\nsys.stderr.write(\"Text file of associated details saved as '{}'.\".format(table_fn))",
"Text file of associated details saved as 'RPB1_orthologs_table.tsv'."
],
[
"# pack up archive of gene and protein sequences plus the table\nseqs_list = gene_seqs_fn_list + prot_seqs_fn_list + [table_fn,pkl_table_fn]\narchive_file_name = gene_name+\"_ortholog_seqs.tar.gz\"\n!tar czf {archive_file_name} {\" \".join(seqs_list)} # use the list for archiving command\nsys.stderr.write(\"\\nCollected gene and protein sequences\"\n \" (plus table of details) gathered and saved as \"\n \"`{}`.\".format(archive_file_name))",
"\nCollected gene and protein sequences (plus table of details) gathered and saved as `RPB1_ortholog_seqs.tar.gz`."
]
],
[
[
"Save the tarballed archive to your local machine.",
"_____no_output_____"
],
[
"-----",
"_____no_output_____"
],
[
"## Estimate the count of the heptad repeats\n\nMake a table of the estimate of heptad repeats for each orthlogous protein sequence.",
"_____no_output_____"
]
],
[
[
"# get the 'patmatch results to dataframe' script\n!curl -O https://raw.githubusercontent.com/fomightez/sequencework/master/patmatch-utilities/patmatch_results_to_df.py",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 18722 100 18722 0 0 75491 0 --:--:-- --:--:-- --:--:-- 75491\n"
]
],
[
[
"Using the trick of putting `%%capture` on first line from [here](https://stackoverflow.com/a/23692951/8508004) to suppress the output from `patmatch_results_to_df` function from filling up cell.",
"_____no_output_____"
]
],
[
[
"%%time\n%%capture\n# Go through each protein sequence file and look for matches to heptad pattern\n\n# LATER POSSIBLE IMPROVEMENT. Translate pasted gene sequence and add SGD REF S228C as first in list `prot_seqs_fn_list`. Because \n# although this set of orthologs includes essentially S228C, other lists won't and best to have reference for comparing.\n\n\nheptad_pattern = \"[YF]SP[TG]SP[STAGN]\" # will catch repeats#2 through #26 of S288C according to Corden, 2013 PMID: 24040939\n\nfrom patmatch_results_to_df import patmatch_results_to_df\nsum_dfs = []\nraw_dfs = []\nfor prot_seq_fn in prot_seqs_fn_list:\n !perl ../../patmatch_1.2/unjustify_fasta.pl {prot_seq_fn}\n output = !perl ../../patmatch_1.2/patmatch.pl -p {heptad_pattern} {prot_seq_fn}.prepared\n os.remove(os.path.join(prot_seq_fn+\".prepared\")) #delete file made for PatMatch\n raw_pm_df = patmatch_results_to_df(output.n, pattern=heptad_pattern, name=\"CTD_heptad\")\n raw_pm_df.sort_values('hit_number', ascending=False, inplace=True)\n sum_dfs.append(raw_pm_df.groupby('FASTA_id').head(1))\n raw_dfs.append(raw_pm_df)\nsum_pm_df = pd.concat(sum_dfs, ignore_index=True)\nsum_pm_df.sort_values('hit_number', ascending=False, inplace=True)\nsum_pm_df = sum_pm_df[['FASTA_id','hit_number']]\n#make protein length into dictionary with ids as keys to map to FASTA_ids in \n# order to add protein length as a column in summary table\nlength_info_by_id= dict(zip(info_df.descr_id,info_df.length))\nsum_pm_df['prot_length'] = sum_pm_df['FASTA_id'].map(length_info_by_id)\nsum_pm_df = sum_pm_df.reset_index(drop=True)\nraw_pm_df = pd.concat(raw_dfs, ignore_index=True)",
"CPU times: user 1.54 s, sys: 917 ms, total: 2.45 s\nWall time: 55.9 s\n"
]
],
[
[
"Because of use of `%%capture` to suppress output, need a separate cell to see results summary. (Only showing parts here because will add more useful information below.)",
"_____no_output_____"
]
],
[
[
"sum_pm_df.head() # don't show all yet since lots and want to make this dataframe more useful below",
"_____no_output_____"
],
[
"sum_pm_df.tail() # don't show all yet since lots and want to make this dataframe more useful below",
"_____no_output_____"
]
],
[
[
"I assume that '+ 2' should be added to the hit_number for each based on S288C according to [Corden, 2013](https://www.ncbi.nlm.nih.gov/pubmed/24040939) (or `+1` like [Hsin and Manley, 2012](https://www.ncbi.nlm.nih.gov/pubmed/23028141)); however, that is something that could be explored further.",
"_____no_output_____"
],
[
"WHAT ONES MISSING NOW?",
"_____no_output_____"
],
[
"Computationally check if any genomes missing from the list of orthologs?",
"_____no_output_____"
]
],
[
[
"subjids = df.sseqid.tolist()\n#print (subjids)\n#print (subjids[0:10])\nsubjids = [x.split(\"-\")[0] for x in subjids]\n#print (subjids)\n#print (subjids[0:10])\nlen_genome_fn_end = len(fn_to_check) + 1 # plus one to accound for the period that will be \n# between `fn_to_check` and strain_id`, such as `SK1.genome.fa`\ngenome_ids = [x[:-len_genome_fn_end] for x in genomes]\n#print (genome_ids[0:10])\n\n\northolg_ids = sum_pm_df.FASTA_id.tolist()\northolg_ids = [x.split(\"-\")[0] for x in ortholg_ids]\n\na = set(genome_ids)\n#print (a)\nprint (\"initial:\",len(a))\nr = set(subjids)\nprint(\"BLAST results:\",len(r))\nprint (\"missing from BLAST:\",len(a-r))\nif len(a-r):\n #print(\"\\n\")\n print(\"ids missing in BLAST results:\",a-r)\n#a - r\n\nprint (\"\\n\\n=====POST-BLAST=======\\n\\n\")\no = set(ortholg_ids)\nprint(\"orthologs extracted:\",len(o))\nprint (\"missing post-BLAST:\",len(r-o))\nif len(r-o):\n print(\"\\n\")\n print(\"ids lost post-BLAST:\",r-o)\n#r - o\nprint (\"\\n\\n\\n=====SUMMARY=======\\n\\n\")\nif len(a-r) and len(r-o):\n print(\"\\nAll missing in end:\",(a-r) | (r-o))",
"initial: 48\nBLAST results: 48\nmissing from BLAST: 0\n\n\n=====POST-BLAST=======\n\n\northologs extracted: 48\nmissing post-BLAST: 0\n\n\n\n=====SUMMARY=======\n\n\n"
]
],
[
[
"## Make the Summarizing Dataframe more informative\n\nAdd information on whether a stretch of 'N's is present. Making the data suspect and fit to be filtered out. Distinguish between cases where it is in what corresponds to the last third of the protein vs. elsewhere, if possible. Plus whether stop codon is present at end of encoding sequence because such cases also probably should be filtered out.\n\nAdd information from the supplemental data table so possible patterns can be assessed more easily.",
"_____no_output_____"
],
[
"#### Add information about N stretches and stop codon",
"_____no_output_____"
]
],
[
[
"# Collect following information for each gene sequence: \n# N stretch of at least two or more present in first 2/3 of gene sequence\n# N stretch of at least two or more present in last 1/3 of gene sequence\n# stop codon encoded at end of sequence?\n\nimport re\nmin_number_Ns_in_row_to_collect = 2\npattern_obj = re.compile(\"N{{{},}}\".format(min_number_Ns_in_row_to_collect), re.I) # adpated from\n# code worked out in `collapse_large_unknown_blocks_in_DNA_sequence.py`, which relied heavily on\n# https://stackoverflow.com/a/250306/8508004\ndef longest_stretch2ormore_found(string, pattern_obj):\n '''\n Check if a string has stretches of Ns of length two or more.\n If it does, return the length of longest stretch.\n If it doesn't return zero.\n Based on https://stackoverflow.com/a/1155805/8508004 and\n GSD Assessing_ambiguous_nts_in_nuclear_PB_genomes.ipynb\n '''\n longest_match = ''\n for m in pattern_obj.finditer(string):\n if len(m.group()) > len(longest_match):\n longest_match = m.group()\n if longest_match == '':\n return 0\n else:\n return len(longest_match)\n\ndef chunk(xs, n):\n '''Split the list, xs, into n chunks;\n from http://wordaligned.org/articles/slicing-a-list-evenly-with-python'''\n L = len(xs)\n assert 0 < n <= L\n s, r = divmod(L, n)\n chunks = [xs[p:p+s] for p in range(0, L, s)]\n chunks[n-1:] = [xs[-r-s:]]\n return chunks\n \nn_stretch_last_third_by_id = {}\nn_stretch_first_two_thirds_by_id = {}\nstop_codons = ['TAA','TAG','TGA']\nstop_codon_presence_by_id = {}\nfor fn in gene_seqs_fn_list:\n # read in sequence without using pyfaidx because small and not worth making indexing files\n lines = []\n with open(fn, 'r') as seqfile:\n for line in seqfile:\n lines.append(line.strip())\n descr_line = lines[0]\n seq = ''.join(lines[1:])\n gene_seq_id = descr_line.split(\":\")[0].split(\">\")[1]#first line parsed for all in front of \":\" and without caret\n \n # determine first two-thirds and last third\n chunks = chunk(seq,3)\n assert len(chunks) == 3, (\"The sequence must be split in three parts'.\")\n first_two_thirds = chunks[0] + chunks[1]\n last_third = chunks[-1]\n # Examine each part\n n_stretch_last_third_by_id[gene_seq_id] = longest_stretch2ormore_found(last_third,pattern_obj)\n n_stretch_first_two_thirds_by_id[gene_seq_id] = longest_stretch2ormore_found(first_two_thirds,pattern_obj)\n #print(gene_seq_id)\n #print (seq[-3:] in stop_codons)\n #stop_codon_presence_by_id[gene_seq_id] = seq[-3:] in stop_codons\n stop_codon_presence_by_id[gene_seq_id] = \"+\" if seq[-3:] in stop_codons else \"-\"\n\n# Add collected information to sum_pm_df\nsum_pm_df['NstretchLAST_THIRD'] = sum_pm_df['FASTA_id'].map(n_stretch_last_third_by_id)\nsum_pm_df['NstretchELSEWHERE'] = sum_pm_df['FASTA_id'].map(n_stretch_first_two_thirds_by_id)\nsum_pm_df['stop_codon'] = sum_pm_df['FASTA_id'].map(stop_codon_presence_by_id)\n# Safe to ignore any warnings about copy. I think because I swapped columns in and out\n# of sum_pm_df earlier perhaps.",
"_____no_output_____"
]
],
[
[
"#### Add details on strains from the published supplemental information\n\nThis section is based on [this notebook entitled 'GSD: Add Supplemental data info to nt count data for 1011 cerevisiae collection'](https://github.com/fomightez/cl_sq_demo-binder/blob/master/notebooks/GSD/GSD%20Add_Supplemental_data_info_to_nt_count%20data%20for%201011_cerevisiae_collection.ipynb).",
"_____no_output_____"
]
],
[
[
"!curl -OL https://static-content.springer.com/esm/art%3A10.1038%2Fs41586-018-0030-5/MediaObjects/41586_2018_30_MOESM3_ESM.xls\n!pip install xlrd",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 1934k 100 1934k 0 0 2046k 0 --:--:-- --:--:-- --:--:-- 2044k\nCollecting xlrd\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/b0/16/63576a1a001752e34bf8ea62e367997530dc553b689356b9879339cf45a4/xlrd-1.2.0-py2.py3-none-any.whl (103kB)\n\u001b[K 100% |████████████████████████████████| 112kB 2.5MB/s \n\u001b[?25hInstalling collected packages: xlrd\nSuccessfully installed xlrd-1.2.0\n"
],
[
"import pandas as pd\n#sum_pm_TEST_df = sum_pm_df.copy()\nsupp_df = pd.read_excel('41586_2018_30_MOESM3_ESM.xls', sheet_name=0, header=3, skipfooter=31) \nsupp_df['Standardized name'] = supp_df['Standardized name'].str.replace('SACE_','')\nsuppl_info_dict = supp_df.set_index('Standardized name').to_dict('index')\n\n#Make new column with simplified strain_id tags to use for relating to supplemental table\ndef add_id_tags(fasta_fn):\n return fasta_fn[:3]\nsum_pm_df[\"id_tag\"] = sum_pm_df['FASTA_id'].apply(add_id_tags)\n\nploidy_dict_by_id = {x:suppl_info_dict[x]['Ploidy'] for x in suppl_info_dict}\naneuploidies_dict_by_id = {x:suppl_info_dict[x]['Aneuploidies'] for x in suppl_info_dict}\neco_origin_dict_by_id = {x:suppl_info_dict[x]['Ecological origins'] for x in suppl_info_dict}\nclade_dict_by_id = {x:suppl_info_dict[x]['Clades'] for x in suppl_info_dict}\nsum_pm_df['Ploidy'] = sum_pm_df.id_tag.map(ploidy_dict_by_id) #Pandas docs has `Index.map` (uppercase `I`) but only lowercase works.\nsum_pm_df['Aneuploidies'] = sum_pm_df.id_tag.map(aneuploidies_dict_by_id)\nsum_pm_df['Ecological origin'] = sum_pm_df.id_tag.map(eco_origin_dict_by_id)\nsum_pm_df['Clade'] = sum_pm_df.id_tag.map(clade_dict_by_id)\n\n# remove the `id_tag` column add for relating details from supplemental to summary df\nsum_pm_df = sum_pm_df.drop('id_tag',1)",
"_____no_output_____"
],
[
"# use following two lines when sure want to see all and COMMENT OUT BOTTOM LINE\n#with pd.option_context('display.max_rows', None, 'display.max_columns', None):\n# display(sum_pm_df)\nsum_pm_df",
"_____no_output_____"
]
],
[
[
"I assume that '+ 2' should be added to the hit_number for each based on S288C according to [Corden, 2013](https://www.ncbi.nlm.nih.gov/pubmed/24040939) (or `+1` like [Hsin and Manley, 2012](https://www.ncbi.nlm.nih.gov/pubmed/23028141)); however, that is something that could be explored further.",
"_____no_output_____"
],
[
"## Filter collected set to those that are 'complete'\n\nFor plotting and summarizing with a good set of information, best to remove any where the identified ortholog gene has stretches of 'N's or lacks a stop codon.\n\n(Keep unfiltered dataframe around though.)",
"_____no_output_____"
]
],
[
[
"sum_pm_UNFILTEREDdf = sum_pm_df.copy()\n#subset to those where there noth columns for Nstretch assessment are zero\nsum_pm_df = sum_pm_df[(sum_pm_df[['NstretchLAST_THIRD','NstretchELSEWHERE']] == 0).all(axis=1)] # based on https://codereview.stackexchange.com/a/185390\n#remove any where there isn't a stop codon\nsum_pm_df = sum_pm_df.drop(sum_pm_df[sum_pm_df.stop_codon != '+'].index)",
"_____no_output_____"
]
],
[
[
"Computationally summarize result of filtering in comparison to previous steps:",
"_____no_output_____"
]
],
[
[
"subjids = df.sseqid.tolist()\n#print (subjids)\n#print (subjids[0:10])\nsubjids = [x.split(\"-\")[0] for x in subjids]\n#print (subjids)\n#print (subjids[0:10])\nlen_genome_fn_end = len(fn_to_check) + 1 # plus one to accound for the period that will be \n# between `fn_to_check` and strain_id`, such as `SK1.genome.fa`\ngenome_ids = [x[:-len_genome_fn_end] for x in genomes]\n#print (genome_ids[0:10])\n\n\northolg_ids = sum_pm_UNFILTEREDdf.FASTA_id.tolist()\northolg_ids = [x.split(\"-\")[0] for x in ortholg_ids]\n\nfiltered_ids = sum_pm_df.FASTA_id.tolist()\nfiltered_ids =[x.split(\"-\")[0] for x in filtered_ids]\n\na = set(genome_ids)\n#print (a)\nprint (\"initial:\",len(a))\nr = set(subjids)\nprint(\"BLAST results:\",len(r))\nprint (\"missing from BLAST:\",len(a-r))\nif len(a-r):\n #print(\"\\n\")\n print(\"ids missing in BLAST results:\",a-r)\n#a - r\n\nprint (\"\\n\\n=====POST-BLAST=======\\n\\n\")\no = set(ortholg_ids)\nprint(\"orthologs extracted:\",len(o))\nprint (\"missing post-BLAST:\",len(r-o))\nif len(r-o):\n print(\"\\n\")\n print(\"ids lost post-BLAST:\",r-o)\n#r - o\nprint (\"\\n\\n\\n=====PRE-FILTERING=======\\n\\n\")\nprint(\"\\nNumber before filtering:\",len(sum_pm_UNFILTEREDdf))\nif len(a-r) and len(r-o):\n print(\"\\nAll missing in unfiltered:\",(a-r) | (r-o))\nprint (\"\\n\\n\\n=====POST-FILTERING SUMMARY=======\\n\\n\")\nf = set(filtered_ids)\nprint(\"\\nNumber left in filtered set:\",len(sum_pm_df))\nprint (\"Number removed by filtering:\",len(o-f))\nif len(a-r) and len(r-o) and len(o-f):\n print(\"\\nAll missing in filtered:\",(a-r) | (r-o) | (o-f))",
"initial: 48\nBLAST results: 48\nmissing from BLAST: 0\n\n\n=====POST-BLAST=======\n\n\northologs extracted: 48\nmissing post-BLAST: 0\n\n\n\n=====PRE-FILTERING=======\n\n\n\nNumber before filtering: 48\n\n\n\n=====POST-FILTERING SUMMARY=======\n\n\n\nNumber left in filtered set: 42\nNumber removed by filtering: 6\n"
],
[
"# use following two lines when sure want to see all and COMMENT OUT BOTTOM LINE\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None):\n display(sum_pm_df)\n#sum_pm_df",
"_____no_output_____"
]
],
[
[
"I assume that '+ 2' should be added to the hit_number for each based on S288C according to [Corden, 2013](https://www.ncbi.nlm.nih.gov/pubmed/24040939) (or `+1` like [Hsin and Manley, 2012](https://www.ncbi.nlm.nih.gov/pubmed/23028141)); however, that is something that could be explored further.",
"_____no_output_____"
],
[
"#### Archive the 'Filtered' set of sequences\n\nAbove I saved all the gene and deduced protein sequences of the orthologs in a single archive. It might be useful to just have an archive of the 'filtered' set.",
"_____no_output_____"
]
],
[
[
"# pack up archive of gene and protein sequences for the 'filtered' set. \n# Include the summary table too.\n# This is different than the other sets I made because this 'filtering' was\n# done using the dataframe and so I don't have the file associations. The file names\n# though can be generated using the unfiltered file names for the genes and proteins\n# and sorting which ones don't remain in the filtered set using 3-letter tags at \n# the beginning of the entries in `FASTA_id` column to relate them.\n\n# Use the `FASTA_id` column of sum_pm_df to make a list of tags that remain in filtered set\ntags_remaining_in_filtered = [x[:3] for x in sum_pm_df.FASTA_id.tolist()]\n# Go through the gene and protein sequence list and collect those where the first\n# three letters match the tag\ngene_seqs_FILTfn_list = [x for x in gene_seqs_fn_list if x[:3] in tags_remaining_in_filtered]\nprot_seqs_FILTfn_list = [x for x in prot_seqs_fn_list if x[:3] in tags_remaining_in_filtered]\n\n# Save the files in those two lists along with the sum_pm_df (as tabular data and pickled form)\npatmatchsum_fn_prefix = gene_name + \"_orthologs_patmatch_results_summary\"\npatmatchsum_fn = patmatchsum_fn_prefix + \".tsv\"\npklsum_patmatch_fn = patmatchsum_fn_prefix + \".pkl\"\nimport pandas as pd\nsum_pm_df.to_pickle(pklsum_patmatch_fn)\nsum_pm_df.to_csv(patmatchsum_fn, sep='\\t') # keep index is default\nFILTEREDseqs_n_df_list = gene_seqs_FILTfn_list + prot_seqs_FILTfn_list + [patmatchsum_fn,pklsum_patmatch_fn]\narchive_file_name = gene_name+\"_ortholog_seqsFILTERED.tar.gz\"\n!tar czf {archive_file_name} {\" \".join(FILTEREDseqs_n_df_list)} # use the list for archiving command\nsys.stderr.write(\"\\nCollected gene and protein sequences\"\n \" (plus table of details) for 'FILTERED' set gathered and saved as \"\n \"`{}`.\".format(archive_file_name))",
"\nCollected gene and protein sequences (plus table of details) for 'FILTERED' set gathered and saved as `RPB1_ortholog_seqsFILTERED.tar.gz`."
]
],
[
[
"Download the 'filtered' sequences to your local machine.",
"_____no_output_____"
],
[
"## Summarizing with filtered set\n\nPlot distribution.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline \nimport math\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\n#Want an image file of the figure saved?\nsaveplot = True\nsaveplot_fn_prefix = 'heptad_repeat_distribution'\n\n#sns.distplot(sum_pm_df[\"hit_number\"], kde=False, bins = max(sum_pm_df[\"hit_number\"]));\np= sns.countplot(sum_pm_df[\"hit_number\"],\n order = list(range(sum_pm_df.hit_number.min(),sum_pm_df.hit_number.max()+1)), \n color=\"C0\", alpha= 0.93)\n #palette=\"Blues\"); # `order` to get those categories with zero \n # counts to show up from https://stackoverflow.com/a/45359713/8508004\np.set_xlabel(\"heptad repeats\")\n\n#add percent above bars, based on code in middle of https://stackoverflow.com/a/33259038/8508004\nncount = len(sum_pm_df)\nfor pat in p.patches:\n x=pat.get_bbox().get_points()[:,0]\n y=pat.get_bbox().get_points()[1,1]\n # note that this check on the next line was necessary to add when I went back to cases where there's\n # no counts for certain categories and so `y` was coming up `nan` for for thos and causing error\n # about needing positive value for the y value; `math.isnan(y)` based on https://stackoverflow.com/a/944733/8508004\n if not math.isnan(y):\n p.annotate('{:.1f}%'.format(100.*y/(ncount)), (x.mean(), y), ha='center', va='bottom', size = 9, color='#333333')\n\n\nif saveplot:\n fig = p.get_figure() #based on https://stackoverflow.com/a/39482402/8508004\n fig.savefig(saveplot_fn_prefix + '.png', bbox_inches='tight')\n fig.savefig(saveplot_fn_prefix + '.svg');",
"_____no_output_____"
]
],
[
[
"However, with the entire 1011 collection, those at the bottom can not really be seen. The next plot shows this by limiting y-axis to 103.\nIt should be possible to make a broken y-axis plot for this eventually but not right now as there is no automagic way. So for now will need to composite the two plots together outside.\n\n\n(Note that adding percents annotations makes height of this plot look odd in the notebook cell for now.)",
"_____no_output_____"
]
],
[
[
"%matplotlib inline \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\n#Want an image file of the figure saved?\nsaveplot = True\nsaveplot_fn_prefix = 'heptad_repeat_distributionLIMIT103'\n\n#sns.distplot(sum_pm_df[\"hit_number\"], kde=False, bins = max(sum_pm_df[\"hit_number\"]));\np= sns.countplot(sum_pm_df[\"hit_number\"],\n order = list(range(sum_pm_df.hit_number.min(),sum_pm_df.hit_number.max()+1)), \n color=\"C0\", alpha= 0.93)\n #palette=\"Blues\"); # `order` to get those categories with zero \n # counts to show up from https://stackoverflow.com/a/45359713/8508004\np.set_xlabel(\"heptad repeats\")\nplt.ylim(0, 103)\n\n#add percent above bars, based on code in middle of https://stackoverflow.com/a/33259038/8508004\nncount = len(sum_pm_df)\nfor pat in p.patches:\n x=pat.get_bbox().get_points()[:,0]\n y=pat.get_bbox().get_points()[1,1]\n # note that this check on the next line was necessary to add when I went back to cases where there's\n # no counts for certain categories and so `y` was coming up `nan` for those and causing error\n # about needing positive value for the y value; `math.isnan(y)` based on https://stackoverflow.com/a/944733/8508004\n if not math.isnan(y):\n p.annotate('{:.1f}%'.format(100.*y/(ncount)), (x.mean(), y), ha='center', va='bottom', size = 9, color='#333333')\n\nif saveplot:\n fig = p.get_figure() #based on https://stackoverflow.com/a/39482402/8508004\n fig.savefig(saveplot_fn_prefix + '.png')\n fig.savefig(saveplot_fn_prefix + '.svg');",
"_____no_output_____"
]
],
[
[
"I assume that '+ 2' should be added to the hit_number for each based on S288C according to [Corden, 2013](https://www.ncbi.nlm.nih.gov/pubmed/24040939) (or `+1` like [Hsin and Manley, 2012](https://www.ncbi.nlm.nih.gov/pubmed/23028141)); however, that is something that could be explored further.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline \n# above line works for JupyterLab which I was developing in. Try `%matplotlib notebook` for when in classic.\n\n# Visualization\n# This is loosely based on my past use of seaborn when making `plot_sites_position_across_chromosome.py` and related scripts.\n# For example, see `GC-clusters relative mito chromosome and feature` where I ran \n# `%run plot_sites_position_across_chromosome.py GC_df_for_merging.pkl -o strand_ofGCacross_mito_chrom`\n\n# add the strain info for listing that without chr info & add species information for coloring on that\nchromosome_id_prefix = \"-\"\ndef FASTA_id_to_strain(FAid):\n '''\n use FASTA_id column value to convert to strain_id \n and then return the strain_id\n '''\n return FAid.split(chromosome_id_prefix)[0]\nsum_pm_df_for_plot = sum_pm_df.copy()\nsum_pm_df_for_plot['strain'] = sum_pm_df['FASTA_id'].apply(FASTA_id_to_strain)\n# sum_pm_df['species'] = sum_pm_df['FASTA_id'].apply(strain_to_species) # since need species for label plot strips\n# it is easier to add species column first and then use map instead of doing both at same with one `apply`\n# of a function or both separately, both with `apply` of two different function.\n# sum_pm_df['species'] = sum_pm_df['strain'].apply(strain_to_species)\nsum_pm_df_for_plot['species'] = 'cerevisiae'\n\n#Want an image file of the figure saved?\nsaveplot = True\nsaveplot_fn_prefix = 'heptad_repeats_by_strain'\n\nimport matplotlib.pyplot as plt\nif len(sum_pm_df) > 60:\n plt.figure(figsize=(8,232))\nelse:\n plt.figure(figsize=(8,12))\nimport seaborn as sns\nsns.set()\n# Simple look - Comment out everything below to the next two lines to see it again.\np = sns.stripplot(x=\"hit_number\", y=\"strain\", data=sum_pm_df_for_plot, marker=\"h\", size=7.5, alpha=.98, palette=\"tab20b\")\np = sns.stripplot(x=\"hit_number\", y=\"strain\", data=sum_pm_df_for_plot, marker=\"D\", size=9.5, alpha=.98, hue=\"Clade\")\n# NOTE CANNOT JUST USE ONE WITH `hue` by 'Clase' because several don't Clades assigned in the supplemental data\n# and so those left off. This overlays the two and doesn't cause artifacts when size of first maker smaller.\np.set_xlabel(\"heptad repeats\")\n#p.set_xticklabels([\" \",\"23\",\" \",\"24\", \" \", \"25\"]) # This was much easier than all the stuff I tried for `Adjusted` look below\n# and the only complaint I have with the results is that what I assume are the `minor` tick lines show up; still ended up\n# needing this when added `xticks = p.xaxis.get_major_ticks()` in order to not show decimals for ones I kept\n#p.set(xticks=[]) # this works to remove the ticks entirely; however, I want to keep major ticks\n'''\nxticks = p.xaxis.get_major_ticks() #based on https://stackoverflow.com/q/50820043/8508004\nfor i in range(len(xticks)):\n #print (i) # WAS FOR DEBUGGING\n keep_ticks = [1,3,5] #harcoding essentially again, but at least it works\n if i not in keep_ticks:\n xticks[i].set_visible(False)\n'''\n'''\n# Highly Adjusted look - Comment out default look parts above. Ended up going with simple above because still couldn't get\n# those with highest number of repeats with combination I could come up with.\nsum_pm_df_for_plot[\"repeats\"] = sum_pm_df_for_plot[\"hit_number\"].astype(str) # when not here (use `x=\"hit_number\"` in plot) or \n# tried `.astype('category')` get plotting of the 0.5 values too\nsum_pm_df_for_plot.sort_values('hit_number', ascending=True, inplace=True) #resorting again was necessary when\n# added `sum_pm_df[\"hit_number\"].astype(str)` to get 'lower' to 'higher' as left to right for x-axis; otherwise\n# it was putting the first rows on the left, which happened to be the 'higher' repeat values\n#p = sns.catplot(x=\"repeats\", y=\"strain\", hue=\"species\", data=sum_pm_df, marker=\"D\", size=10, alpha=.98) #marker size ignored in catplot?\np = sns.stripplot(x=\"repeats\", y=\"strain\", hue=\"species\", data=sum_pm_df, marker=\"D\", size=10, alpha=.98)\n#p = sns.stripplot(x=\"repeats\", y=\"strain\", hue=\"species\", order = list(species_dict.keys()), data=sum_pm_df_for_plot, marker=\"D\", \n# size=10, alpha=.98) # not fond of essentially harcoding to strain order but makes more logical sense to have\n # strains with most repeats at the top of the y-axis; adding `order` makes `sort` order be ignored\np.set_xlabel(\"heptad repeats\")\nsum_pm_df_for_plot.sort_values('hit_number', ascending=False, inplace=True) #revert to descending sort for storing df;\n'''\nif saveplot:\n fig = p.get_figure() #based on https://stackoverflow.com/a/39482402/8508004\n fig.savefig(saveplot_fn_prefix + '.png', bbox_inches='tight')\n fig.savefig(saveplot_fn_prefix + '.svg');",
"_____no_output_____"
]
],
[
[
"(Hexagons are used for those without an assigned clade in [the supplemental data Table 1](https://www.nature.com/articles/s41586-018-0030-5) in the plot above.)\n\nI assume that '+ 2' should be added to the hit_number for each based on S288C according to [Corden, 2013](https://www.ncbi.nlm.nih.gov/pubmed/24040939) (or `+1` like [Hsin and Manley, 2012](https://www.ncbi.nlm.nih.gov/pubmed/23028141)); however, that is something that could be explored further.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline \n# above line works for JupyterLab which I was developing in. Try `%matplotlib notebook` for when in classic.\n\n# Visualization\n# This is loosely based on my past use of seaborn when making `plot_sites_position_across_chromosome.py` and related scripts.\n# For example, see `GC-clusters relative mito chromosome and feature` where I ran \n# `%run plot_sites_position_across_chromosome.py GC_df_for_merging.pkl -o strand_ofGCacross_mito_chrom`\n\n# add the strain info for listing that without chr info & add species information for coloring on that\nchromosome_id_prefix = \"-\"\ndef FASTA_id_to_strain(FAid):\n '''\n use FASTA_id column value to convert to strain_id \n and then return the strain_id\n '''\n return FAid.split(chromosome_id_prefix)[0]\nsum_pm_df_for_plot = sum_pm_df.copy()\nsum_pm_df_for_plot['strain'] = sum_pm_df['FASTA_id'].apply(FASTA_id_to_strain)\n# sum_pm_df['species'] = sum_pm_df['FASTA_id'].apply(strain_to_species) # since need species for label plot strips\n# it is easier to add species column first and then use map instead of doing both at same with one `apply`\n# of a function or both separately, both with `apply` of two different function.\n# sum_pm_df['species'] = sum_pm_df['strain'].apply(strain_to_species)\nsum_pm_df_for_plot['species'] = 'cerevisiae'\n\n#Want an image file of the figure saved?\nsaveplot = True\nsaveplot_fn_prefix = 'heptad_repeats_by_proteinlen'\n\nimport matplotlib.pyplot as plt\nif len(sum_pm_df) > 60:\n plt.figure(figsize=(8,232))\nelse:\n plt.figure(figsize=(8,12))\nimport seaborn as sns\nsns.set()\n# Simple look - Comment out everything below to the next two lines to see it again.\n#p = sns.stripplot(x=\"hit_number\", y=\"strain\", data=sum_pm_df_for_plot, marker=\"h\", size=7.5, alpha=.98, palette=\"tab20b\")\np = sns.stripplot(x=\"hit_number\", y=\"strain\", data=sum_pm_df_for_plot, marker=\"D\", size=9.5, alpha=.98, hue=\"prot_length\")\n# NOTE CANNOT JUST USE ONE WITH `hue` by 'Clase' because several don't Clades assigned in the supplemental data\n# and so those left off. This overlays the two and doesn't cause artifacts when size of first maker smaller.\np.set_xlabel(\"heptad repeats\")\n#p.set_xticklabels([\" \",\"23\",\" \",\"24\", \" \", \"25\"]) # This was much easier than all the stuff I tried for `Adjusted` look below\n# and the only complaint I have with the results is that what I assume are the `minor` tick lines show up; still ended up\n# needing this when added `xticks = p.xaxis.get_major_ticks()` in order to not show decimals for ones I kept\n#p.set(xticks=[]) # this works to remove the ticks entirely; however, I want to keep major ticks\n'''\nxticks = p.xaxis.get_major_ticks() #based on https://stackoverflow.com/q/50820043/8508004\nfor i in range(len(xticks)):\n #print (i) # WAS FOR DEBUGGING\n keep_ticks = [1,3,5] #harcoding essentially again, but at least it works\n if i not in keep_ticks:\n xticks[i].set_visible(False)\n'''\n'''\n# Highly Adjusted look - Comment out default look parts above. Ended up going with simple above because still couldn't get\n# those with highest number of repeats with combination I could come up with.\nsum_pm_df_for_plot[\"repeats\"] = sum_pm_df_for_plot[\"hit_number\"].astype(str) # when not here (use `x=\"hit_number\"` in plot) or \n# tried `.astype('category')` get plotting of the 0.5 values too\nsum_pm_df_for_plot.sort_values('hit_number', ascending=True, inplace=True) #resorting again was necessary when\n# added `sum_pm_df[\"hit_number\"].astype(str)` to get 'lower' to 'higher' as left to right for x-axis; otherwise\n# it was putting the first rows on the left, which happened to be the 'higher' repeat values\n#p = sns.catplot(x=\"repeats\", y=\"strain\", hue=\"species\", data=sum_pm_df, marker=\"D\", size=10, alpha=.98) #marker size ignored in catplot?\np = sns.stripplot(x=\"repeats\", y=\"strain\", hue=\"species\", data=sum_pm_df, marker=\"D\", size=10, alpha=.98)\n#p = sns.stripplot(x=\"repeats\", y=\"strain\", hue=\"species\", order = list(species_dict.keys()), data=sum_pm_df_for_plot, marker=\"D\", \n# size=10, alpha=.98) # not fond of essentially harcoding to strain order but makes more logical sense to have\n # strains with most repeats at the top of the y-axis; adding `order` makes `sort` order be ignored\np.set_xlabel(\"heptad repeats\")\nsum_pm_df_for_plot.sort_values('hit_number', ascending=False, inplace=True) #revert to descending sort for storing df;\n'''\nif saveplot:\n fig = p.get_figure() #based on https://stackoverflow.com/a/39482402/8508004\n fig.savefig(saveplot_fn_prefix + '.png', bbox_inches='tight')\n fig.savefig(saveplot_fn_prefix + '.svg');",
"_____no_output_____"
]
],
[
[
"I assume that '+ 2' should be added to the hit_number for each based on S288C according to [Corden, 2013](https://www.ncbi.nlm.nih.gov/pubmed/24040939) (or `+1` like [Hsin and Manley, 2012](https://www.ncbi.nlm.nih.gov/pubmed/23028141)); however, that is something that could be explored further.",
"_____no_output_____"
],
[
"\n\n## Make raw and summary data available for use elsewhere\n\nAll the raw data is there for each strain in `raw_pm_df`. For example, the next cell shows how to view the data associated with the summary table for isolate ADK_8:",
"_____no_output_____"
]
],
[
[
"ADK_8_raw = raw_pm_df[raw_pm_df['FASTA_id'] == 'ADK_8-20587'].sort_values('hit_number', ascending=True).reset_index(drop=True)\nADK_8_raw ",
"_____no_output_____"
]
],
[
[
"The summary and raw data will be packaged up into one file in the cell below. One of the forms will be a tabular text data ('.tsv') files that can be opened in any spreadsheet software.",
"_____no_output_____"
]
],
[
[
"# save summary and raw results for use elsewhere (or use `.pkl` files for reloading the pickled dataframe into Python/pandas)\npatmatch_fn_prefix = gene_name + \"_orthologs_patmatch_results\"\npatmatchsum_fn_prefix = gene_name + \"_orthologs_patmatch_results_summary\"\npatmatchsumFILTERED_fn_prefix = gene_name + \"_orthologs_patmatch_results_summaryFILTERED\"\npatmatch_fn = patmatch_fn_prefix + \".tsv\"\npkl_patmatch_fn = patmatch_fn_prefix + \".pkl\"\npatmatchsumUNF_fn = patmatchsumFILTERED_fn_prefix + \".tsv\"\npklsum_patmatchUNF_fn = patmatchsumFILTERED_fn_prefix + \".pkl\"\npatmatchsum_fn = patmatchsum_fn_prefix + \".tsv\"\npklsum_patmatch_fn = patmatchsum_fn_prefix + \".pkl\"\n\n\nimport pandas as pd\nsum_pm_df.to_pickle(pklsum_patmatch_fn)\nsum_pm_df.to_csv(patmatchsum_fn, sep='\\t') # keep index is default\nsys.stderr.write(\"Text file of summary details after filtering saved as '{}'.\".format(patmatchsum_fn))\nsum_pm_UNFILTEREDdf.to_pickle(pklsum_patmatchUNF_fn)\nsum_pm_UNFILTEREDdf.to_csv(patmatchsumUNF_fn, sep='\\t') # keep index is default\nsys.stderr.write(\"\\nText file of summary details before filtering saved as '{}'.\".format(patmatchsumUNF_fn))\nraw_pm_df.to_pickle(pkl_patmatch_fn)\nraw_pm_df.to_csv(patmatch_fn, sep='\\t') # keep index is default\nsys.stderr.write(\"\\nText file of raw details saved as '{}'.\".format(patmatchsum_fn))\n# pack up archive dataframes\npm_dfs_list = [patmatch_fn,pkl_patmatch_fn,patmatchsumUNF_fn,pklsum_patmatchUNF_fn, patmatchsum_fn,pklsum_patmatch_fn]\narchive_file_name = patmatch_fn_prefix+\".tar.gz\"\n!tar czf {archive_file_name} {\" \".join(pm_dfs_list)} # use the list for archiving command\nsys.stderr.write(\"\\nCollected pattern matching\"\n \" results gathered and saved as \"\n \"`{}`.\".format(archive_file_name))",
"Text file of summary details after filtering saved as 'RPB1_orthologs_patmatch_results_summary.tsv'.\nText file of summary details before filtering saved as 'RPB1_orthologs_patmatch_results_summaryFILTERED.tsv'.\nText file of raw details saved as 'RPB1_orthologs_patmatch_results_summary.tsv'.\nCollected pattern matching results gathered and saved as `RPB1_orthologs_patmatch_results.tar.gz`."
]
],
[
[
"Download the tarballed archive of the files to your computer.\n\nFor now that archive doesn't include the figures generated from the plots because with a lot of strains they can get large. Download those if you want them. (Look for `saveplot_fn_prefix` settings in the code to help identify file names.)",
"_____no_output_____"
],
[
"----",
"_____no_output_____"
]
],
[
[
"import time\n\ndef executeSomething():\n #code here\n print ('.')\n time.sleep(480) #60 seconds times 8 minutes\n\nwhile True:\n executeSomething()",
".\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
cb7cfaaf8085139112ed53bc95f3a127576c70a1
| 1,980 |
ipynb
|
Jupyter Notebook
|
notebooks/beginner/exercises/numbers_exercise.ipynb
|
4TINI/learn-python3
|
72e6625782d9e526c590389a6c92f04223b93c3c
|
[
"MIT"
] | null | null | null |
notebooks/beginner/exercises/numbers_exercise.ipynb
|
4TINI/learn-python3
|
72e6625782d9e526c590389a6c92f04223b93c3c
|
[
"MIT"
] | null | null | null |
notebooks/beginner/exercises/numbers_exercise.ipynb
|
4TINI/learn-python3
|
72e6625782d9e526c590389a6c92f04223b93c3c
|
[
"MIT"
] | null | null | null | 18.504673 | 77 | 0.484848 |
[
[
[
"# 1. Creating formulas\nWrite the following mathematical formula in Python:\n\n\\begin{align}\n result = 6a^3 - \\frac{8b^2 }{4c} + 11\n\\end{align}\n",
"_____no_output_____"
]
],
[
[
"a = 2\nb = 3\nc = 2",
"_____no_output_____"
],
[
"# Your formula here:\nresult = 6*a**3 - (8*b**2)/(4*c) + 11",
"_____no_output_____"
],
[
"\nassert result == 50",
"_____no_output_____"
]
],
[
[
"# 2. Floating point pitfalls\nShow that `0.1 + 0.2 == 0.3`",
"_____no_output_____"
]
],
[
[
"# Your solution here\nfrom decimal import Decimal\n\nDecimal('0.1') + Decimal('0.2') == Decimal('0.3')\n# This won't work:\n# assert 0.1 + 0.2 == 0.3",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7d0c6b28c0098d2878131226261344060a7e59
| 93,275 |
ipynb
|
Jupyter Notebook
|
Dawn/practice_code/Loan-Model-1-Dawn-Copy1.ipynb
|
dsalisbury1141/Predicting-Loan-Eligibility-Project
|
2e753dd1de3b02a86dafc66437dfa3f02ceedba8
|
[
"MIT"
] | 1 |
2021-03-11T04:18:36.000Z
|
2021-03-11T04:18:36.000Z
|
Dawn/practice_code/Loan-Model-1-Dawn-Copy1.ipynb
|
dsalisbury1141/Predicting-Loan-Eligibility-Machine-Learning
|
2e753dd1de3b02a86dafc66437dfa3f02ceedba8
|
[
"MIT"
] | null | null | null |
Dawn/practice_code/Loan-Model-1-Dawn-Copy1.ipynb
|
dsalisbury1141/Predicting-Loan-Eligibility-Machine-Learning
|
2e753dd1de3b02a86dafc66437dfa3f02ceedba8
|
[
"MIT"
] | null | null | null | 58.663522 | 11,696 | 0.621088 |
[
[
[
"#pip install seaborn",
"_____no_output_____"
]
],
[
[
"# Import Libraries",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"# Read the CSV and Perform Basic Data Cleaning",
"_____no_output_____"
]
],
[
[
"# Raw dataset drop NA\ndf = pd.read_csv(\"../resources/train_predict.csv\")\n# Drop the null columns where all values are null\ndf1 = df.dropna(axis='columns', how='all')\ndf1.head()",
"_____no_output_____"
],
[
"#Reviewing the % of null values\n100*df1.isnull().sum()/df.shape[0]",
"_____no_output_____"
],
[
"# Drop the null rows data cleaning, making all column headers lowercase\nloan_df = df.dropna()\nloan_df.columns=df.columns.str.lower()\nloan_df.head()",
"_____no_output_____"
],
[
"#Update column names\nloan_df.columns=['loan_id', 'gender', 'married', 'dependents', 'education','self_employed'\n , 'income', 'co_income'\n , 'loan_amount', 'loan_term', 'credit_history', 'property_area', 'loan_status']",
"_____no_output_____"
],
[
"#Test data_df after drop NAN\nloan_df.dtypes",
"_____no_output_____"
],
[
"loan_df.shape",
"_____no_output_____"
],
[
"#Reviewing data\nloan_df['dependents'].unique()",
"_____no_output_____"
],
[
"#Reviewing data\nloan_df['self_employed'].unique()",
"_____no_output_____"
],
[
"#Reviewing data\nloan_df['loan_term'].unique()",
"_____no_output_____"
],
[
"#Reviewing data\nloan_df['credit_history'].unique()",
"_____no_output_____"
],
[
"loan_df.describe()",
"_____no_output_____"
]
],
[
[
"# Select your features (columns)",
"_____no_output_____"
]
],
[
[
"# Set features. This will also be used as your x values. Removed 'loan_id', 'property_area'\nloan_features_df = loan_df[['gender', 'married', 'dependents', 'education','self_employed'\n , 'income', 'co_income'\n , 'loan_amount', 'loan_term', 'credit_history', 'loan_status']]\nloan_features_df.head()",
"_____no_output_____"
],
[
"sns.countplot(y='gender', hue ='loan_status',data =loan_features_df)",
"_____no_output_____"
],
[
"sns.countplot(y='married', hue ='loan_status',data =loan_features_df)",
"_____no_output_____"
],
[
"sns.countplot(y='credit_history', hue ='loan_status',data =loan_features_df)",
"_____no_output_____"
],
[
"sns.countplot(y='loan_term', hue ='loan_status',data =loan_features_df)",
"_____no_output_____"
]
],
[
[
"# Create a Train Test Split\n\nUse `loan_status` for the y values",
"_____no_output_____"
]
],
[
[
"y = loan_features_df[[\"loan_status\"]] \nX = loan_features_df.drop(columns=[\"loan_status\"])\nprint(X.shape, y.shape)",
"(480, 10) (480, 1)\n"
],
[
"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y)",
"_____no_output_____"
],
[
"#code to numberic Hold-> ‘Urban’: 3, ‘Semiurban’: 2,’Rural’: 1,\ncode_numeric = {'Female': 1, 'Male': 2,'Yes': 1, 'No': 2,\n'Graduate': 1, 'Not Graduate': 2, 'Y': 1, 'N': 0, '3+': 3}",
"_____no_output_____"
],
[
"loan_features_df = loan_features_df.applymap(lambda s: code_numeric.get(s) if s in code_numeric else s)",
"_____no_output_____"
],
[
"loan_features_df.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 480 entries, 1 to 613\nData columns (total 11 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 gender 480 non-null int64 \n 1 married 480 non-null int64 \n 2 dependents 480 non-null object \n 3 education 480 non-null int64 \n 4 self_employed 480 non-null int64 \n 5 income 480 non-null int64 \n 6 co_income 480 non-null float64\n 7 loan_amount 480 non-null float64\n 8 loan_term 480 non-null float64\n 9 credit_history 480 non-null float64\n 10 loan_status 480 non-null int64 \ndtypes: float64(4), int64(6), object(1)\nmemory usage: 65.0+ KB\n"
]
],
[
[
"# Pre-processing\n\nScale the data and perform some feature selection",
"_____no_output_____"
]
],
[
[
"# Scale Data\nfrom sklearn.preprocessing import StandardScaler\n\n# Create a StandardScater model and fit it to the training data\nX_scaler = StandardScaler().fit(X_train)\n\n#y_scaler = StandardScaler().fit(y_train)",
"_____no_output_____"
],
[
"# to_categorical(y)\n# StandardScaler().fit(X)",
"_____no_output_____"
],
[
"# Preprocessing\n#from sklearn.preprocessing import LabelEncoder\nfrom tensorflow.keras.utils import to_categorical\n\n# label_encoder = LabelEncoder()\n# label_encoder.fit(y_train)\n# encoded_y_train = label_encoder.transform(y_train)\n# encoded_y_test = label_encoder.transform(y_test)\ny_train_categorical = to_categorical(y_train)\ny_test_categorical = to_categorical(y_test)\n",
"_____no_output_____"
]
],
[
[
"# Train the Model\n",
"_____no_output_____"
]
],
[
[
"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\n\nmodel = Sequential()\nmodel.add(Dense(units=500, activation='relu', input_dim=10))\n# model.add(Dense(units=100, activation='relu'))\nmodel.add(Dense(units=2, activation='softmax'))",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense_2 (Dense) (None, 500) 5500 \n_________________________________________________________________\ndense_3 (Dense) (None, 2) 1002 \n=================================================================\nTotal params: 6,502\nTrainable params: 6,502\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"model.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])",
"_____no_output_____"
],
[
"# Fit the model to the training data\nmodel.fit(\n X_scaled,\n y_train_categorical,\n epochs=100,\n shuffle=True,\n verbose=2\n)",
"_____no_output_____"
],
[
"from sklearn.svm import SVC \nmodel = SVC(kernel='linear')\nmodel.fit(X_train_scaled, y_train.values.ravel())\n\nprint(f\"Training Data Score: {model.score(X_train_scaled, y_train)}\")\nprint(f\"Testing Data Score: {model.score(X_test_scaled, y_test)}\")",
"Training Data Score: 0.7972222222222223\nTesting Data Score: 0.8416666666666667\n"
],
[
"from sklearn.metrics import classification_report\npredictions = model.predict(X_test)\nprint(classification_report(y_test, predictions))",
" precision recall f1-score support\n\n 0 0.31 0.95 0.47 37\n 1 0.71 0.06 0.11 83\n\n accuracy 0.33 120\n macro avg 0.51 0.50 0.29 120\nweighted avg 0.59 0.33 0.22 120\n\n"
]
],
[
[
"# Hyperparameter Tuning\n\nUse `GridSearchCV` to tune the model's parameters",
"_____no_output_____"
]
],
[
[
"# Create the GridSearchCV model\nfrom sklearn.model_selection import GridSearchCV\nparam_grid = {'C': [1, 2, 10, 50],\n 'gamma': [0.0001, 0.0005, 0.001, 0.005]}\ngrid = GridSearchCV(model, param_grid, verbose=3)",
"_____no_output_____"
],
[
"# Train the model with GridSearch\ngrid.fit(X_train, y_train.values.ravel())",
"Fitting 5 folds for each of 16 candidates, totalling 80 fits\n[CV] C=1, gamma=0.0001 ...............................................\n"
],
[
"#print params, scores\nprint(grid.best_params_)\nprint(grid.best_score_)",
"_____no_output_____"
]
],
[
[
"# Save the Model",
"_____no_output_____"
]
],
[
[
"import joblib",
"_____no_output_____"
],
[
"# save your model by updating \"your_name\" with your name\n# and \"your_model\" with your model variable\n# be sure to turn this in to BCS\n# if joblib fails to import, try running the command to install in terminal/git-bash\nfilename = 'finalized_Plant_model1.sav'\njoblib.dump(model, filename)\n \n",
"_____no_output_____"
],
[
"#To be done later\n# load the model from disk\nloaded_model = joblib.load(filename)\nresult = loaded_model.score(X_test, y_test_categorical)\nprint(result)",
"_____no_output_____"
]
]
] |
[
"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",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cb7d11edcfe312a37724b6cd251bed27ba812d7b
| 14,883 |
ipynb
|
Jupyter Notebook
|
Model backlog/Inference/7-tweet-inference-distilbert-lower-v2.ipynb
|
dimitreOliveira/Tweet-Sentiment-Extraction
|
0a775abe9a92c4bc2db957519c523be7655df8d8
|
[
"MIT"
] | 11 |
2020-06-17T07:30:20.000Z
|
2022-03-25T16:56:01.000Z
|
Model backlog/Inference/7-tweet-inference-distilbert-lower-v2.ipynb
|
dimitreOliveira/Tweet-Sentiment-Extraction
|
0a775abe9a92c4bc2db957519c523be7655df8d8
|
[
"MIT"
] | null | null | null |
Model backlog/Inference/7-tweet-inference-distilbert-lower-v2.ipynb
|
dimitreOliveira/Tweet-Sentiment-Extraction
|
0a775abe9a92c4bc2db957519c523be7655df8d8
|
[
"MIT"
] | null | null | null | 29.885542 | 135 | 0.477122 |
[
[
[
"## Dependencies",
"_____no_output_____"
]
],
[
[
"import glob\nimport numpy as np\nimport pandas as pd\nfrom transformers import TFDistilBertModel\nfrom tokenizers import BertWordPieceTokenizer\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Input, Dropout, GlobalAveragePooling1D, Concatenate",
"_____no_output_____"
],
[
"# Auxiliary functions\n# Transformer inputs\ndef preprocess_test(text, context, tokenizer, max_seq_len):\n context_encoded = tokenizer.encode(context)\n context_encoded = context_encoded.ids[1:-1]\n \n encoded = tokenizer.encode(text)\n encoded.pad(max_seq_len)\n encoded.truncate(max_seq_len)\n input_ids = encoded.ids\n attention_mask = encoded.attention_mask\n token_type_ids = ([0] * 3) + ([1] * (max_seq_len - 3))\n \n input_ids = [101] + context_encoded + [102] + input_ids\n # update input ids and attentions masks size\n input_ids = input_ids[:-3]\n attention_mask = [1] * 3 + attention_mask[:-3]\n \n x = [np.asarray(input_ids, dtype=np.int32), \n np.asarray(attention_mask, dtype=np.int32), \n np.asarray(token_type_ids, dtype=np.int32)]\n \n return x\n\ndef get_data_test(df, tokenizer, MAX_LEN):\n x_input_ids = []\n x_attention_masks = []\n x_token_type_ids = []\n for row in df.itertuples(): \n x = preprocess_test(getattr(row, \"text\"), getattr(row, \"sentiment\"), tokenizer, MAX_LEN)\n x_input_ids.append(x[0])\n x_attention_masks.append(x[1])\n x_token_type_ids.append(x[2])\n\n x_data = [np.asarray(x_input_ids), np.asarray(x_attention_masks), np.asarray(x_token_type_ids)]\n return x_data\n\ndef decode(pred_start, pred_end, text, tokenizer):\n offset = tokenizer.encode(text).offsets\n \n if pred_end >= len(offset):\n pred_end = len(offset)-1\n \n decoded_text = \"\"\n for i in range(pred_start, pred_end+1):\n decoded_text += text[offset[i][0]:offset[i][1]]\n if (i+1) < len(offset) and offset[i][1] < offset[i+1][0]:\n decoded_text += \" \"\n return decoded_text",
"_____no_output_____"
]
],
[
[
"# Load data",
"_____no_output_____"
]
],
[
[
"test = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/test.csv')\n\nprint('Test samples: %s' % len(test))\ndisplay(test.head())",
"Test samples: 3535\n"
]
],
[
[
"# Model parameters",
"_____no_output_____"
]
],
[
[
"MAX_LEN = 128\n\nbase_path = '/kaggle/input/qa-transformers/distilbert/'\nbase_model_path = base_path + 'distilbert-base-uncased-distilled-squad-tf_model.h5'\nconfig_path = base_path + 'distilbert-base-uncased-distilled-squad-config.json'\n\ninput_base_path = '/kaggle/input/7-tweet-train-distilbert-lower-lower-v2/'\ntokenizer_path = input_base_path + 'vocab.txt'\nmodel_path_list = glob.glob(input_base_path + '*.h5')\nmodel_path_list.sort()\nprint('Models to predict:')\nprint(*model_path_list, sep = \"\\n\")",
"Models to predict:\n/kaggle/input/7-tweet-train-distilbert-lower-lower-v2/model.h5\n"
]
],
[
[
"# Tokenizer",
"_____no_output_____"
]
],
[
[
"tokenizer = BertWordPieceTokenizer(tokenizer_path , lowercase=True)",
"_____no_output_____"
]
],
[
[
"# Pre process",
"_____no_output_____"
]
],
[
[
"test['text'].fillna('', inplace=True)\ntest[\"text\"] = test[\"text\"].apply(lambda x: x.lower())\n\nx_test = get_data_test(test, tokenizer, MAX_LEN)",
"_____no_output_____"
]
],
[
[
"# Model",
"_____no_output_____"
]
],
[
[
"def model_fn():\n input_ids = Input(shape=(MAX_LEN,), dtype=tf.int32, name='input_ids')\n attention_mask = Input(shape=(MAX_LEN,), dtype=tf.int32, name='attention_mask')\n token_type_ids = Input(shape=(MAX_LEN,), dtype=tf.int32, name='token_type_ids')\n \n base_model = TFDistilBertModel.from_pretrained(base_model_path, config=config_path, name=\"base_model\")\n sequence_output = base_model({'input_ids': input_ids, 'attention_mask': attention_mask, 'token_type_ids': token_type_ids})\n last_state = sequence_output[0]\n \n x = GlobalAveragePooling1D()(last_state)\n \n y_start = Dense(MAX_LEN, activation='sigmoid', name='y_start')(x)\n y_end = Dense(MAX_LEN, activation='sigmoid', name='y_end')(x)\n \n model = Model(inputs=[input_ids, attention_mask, token_type_ids], outputs=[y_start, y_end])\n \n return model",
"_____no_output_____"
]
],
[
[
"# Make predictions",
"_____no_output_____"
]
],
[
[
"NUM_TEST_IMAGES = len(test)\ntest_start_preds = np.zeros((NUM_TEST_IMAGES, MAX_LEN))\ntest_end_preds = np.zeros((NUM_TEST_IMAGES, MAX_LEN))\n\nfor model_path in model_path_list:\n print(model_path)\n model = model_fn()\n model.load_weights(model_path)\n \n test_preds = model.predict(x_test) \n test_start_preds += test_preds[0] / len(model_path_list)\n test_end_preds += test_preds[1] / len(model_path_list)",
"/kaggle/input/7-tweet-train-distilbert-lower-lower-v2/model.h5\n"
]
],
[
[
"# Post process",
"_____no_output_____"
]
],
[
[
"test['start'] = test_start_preds.argmax(axis=-1)\ntest['end'] = test_end_preds.argmax(axis=-1)\ntest['selected_text'] = test.apply(lambda x: decode(x['start'], x['end'], x['text'], tokenizer), axis=1)",
"_____no_output_____"
]
],
[
[
"# Test set predictions",
"_____no_output_____"
]
],
[
[
"submission = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/sample_submission.csv')\nsubmission['selected_text'] = test[\"selected_text\"]\nsubmission.to_csv('submission.csv', index=False)\nsubmission.head(10)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7d27c1bc017c7b4ea86297082f781a76325001
| 113,583 |
ipynb
|
Jupyter Notebook
|
lib/ActivationAnalysisMnist_Graphs.ipynb
|
joaquimlyrio/feat-visualization
|
47ead5044d1239dba1133b7ea812b2ed7f2564dc
|
[
"MIT"
] | null | null | null |
lib/ActivationAnalysisMnist_Graphs.ipynb
|
joaquimlyrio/feat-visualization
|
47ead5044d1239dba1133b7ea812b2ed7f2564dc
|
[
"MIT"
] | null | null | null |
lib/ActivationAnalysisMnist_Graphs.ipynb
|
joaquimlyrio/feat-visualization
|
47ead5044d1239dba1133b7ea812b2ed7f2564dc
|
[
"MIT"
] | null | null | null | 207.268248 | 17,614 | 0.894949 |
[
[
[
"MNIST\nAproximate error rate BEFORE training is 90.7 %\nAproximate error rate during iteration 0 is 80.8 %\nAproximate error rate during iteration 100 is 6.6 %\nAproximate error rate during iteration 200 is 4.6 %\nAproximate error rate during iteration 300 is 3.4 %\nAproximate error rate during iteration 400 is 3.4 %\nAproximate error rate during iteration 500 is 2.6 %\nAproximate error rate during iteration 600 is 3.7 %\nAproximate error rate during iteration 700 is 2.6 %\nAproximate error rate during iteration 800 is 2.2 %\nAproximate error rate during iteration 900 is 3.3 %\n\nTotal training time: 90.77 seconds\n\nFinal aproximate training error is 2.4 %\n\nFinal test error is 2.79 %",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport random\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"#\n# read original images\n#\neval_data_mnist = np.load(\"tmp/MNIST/eval_data_mnist.npy\")\neval_data_mnist.shape",
"_____no_output_____"
],
[
"#\n# get filter numbers for each of the layers\n#\nfiltersLayer1 = np.load(\"tmp/MNIST/RandomFiltersIndexMnist_Layer1_Features.npy\")\nfiltersLayer2 = np.load(\"tmp/MNIST/RandomFiltersIndexMnist_Layer2_Features.npy\")\nfiltersLayer2",
"_____no_output_____"
],
[
"#\n# read activations\n#\n\n# layer 1\nActivations1 = np.load(\"tmp/MNIST/ActivationsMnist_Layer1_Features.npy\")\n\n# layer 2\nActivations2 = np.load(\"tmp/MNIST/ActivationsMnist_Layer2_Features.npy\")\n\nprint(Activations1.shape)\nprint(Activations2.shape)",
"(3, 3, 14, 14, 1)\n(3, 3, 7, 7, 1)\n"
],
[
"#\n# read deconvolved activations\n#\n\n# layer 1\nDeconvActivations1 = np.load(\"tmp/MNIST/ActivationsMnist_Layer1.npy\")\n\n# layer 2\nDeconvActivations2 = np.load(\"tmp/MNIST/ActivationsMnist_Layer2.npy\")\n\nprint(DeconvActivations1.shape)\nprint(DeconvActivations2.shape)",
"(3, 3, 28, 28, 1)\n(3, 3, 28, 28, 1)\n"
],
[
"#\n# get index of images that maximally activates each the specific nodes of each layer\n#\nmaxIndexesLayer1 = np.load(\"tmp/MNIST/BestImagesMnist_Layer1.npy\")\nmaxIndexesLayer2 = np.load(\"tmp/MNIST/BestImagesMnist_Layer2.npy\")\nprint(maxIndexesLayer1)\nprint(maxIndexesLayer2)",
"[[ 64. 18. 51.]\n [ 11. 33. 66.]\n [ 64. 51. 18.]]\n[[ 52. 69. 64.]\n [ 69. 52. 51.]\n [ 68. 51. 52.]]\n"
]
],
[
[
"# Best Nodes Layer 1",
"_____no_output_____"
],
[
"## Node 16",
"_____no_output_____"
]
],
[
[
"# index\niNode = 0\nindexNode1 = filtersLayer1[0]\n\n# images\nplt.subplot(331)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 0] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(332)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 1] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(333)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 2] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(334)\nplt.imshow( Activations1[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(335)\nplt.imshow( Activations1[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(336)\nplt.imshow( Activations1[iNode,2,:,:,0], cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(337)\nplt.imshow( DeconvActivations1[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(338)\nplt.imshow( DeconvActivations1[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(339)\nplt.imshow( DeconvActivations1[iNode,2,:,:,0], cmap = \"gray\" )\n\nplt.savefig('../img/node{}_layer1_mnist'.format(indexNode1))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Node 22",
"_____no_output_____"
]
],
[
[
"# index\niNode = 1\nindexNode1 = filtersLayer1[1]\n\n# images\nplt.subplot(331)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 0] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(332)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 1] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(333)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 2] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(334)\nplt.imshow( Activations1[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(335)\nplt.imshow( Activations1[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(336)\nplt.imshow( Activations1[iNode,2,:,:,0], cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(337)\nplt.imshow( DeconvActivations1[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(338)\nplt.imshow( DeconvActivations1[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(339)\nplt.imshow( DeconvActivations1[iNode,2,:,:,0], cmap = \"gray\" )\n\nplt.savefig('../img/node{}_layer1_mnist'.format(indexNode1))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Node 1",
"_____no_output_____"
]
],
[
[
"# index\niNode = 2\nindexNode1 = filtersLayer1[2]\n\n# images\nplt.subplot(331)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 0] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(332)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 1] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(333)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer1[iNode, 2] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(334)\nplt.imshow( Activations1[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(335)\nplt.imshow( Activations1[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(336)\nplt.imshow( Activations1[iNode,2,:,:,0], cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(337)\nplt.imshow( DeconvActivations1[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(338)\nplt.imshow( DeconvActivations1[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(339)\nplt.imshow( DeconvActivations1[iNode,2,:,:,0], cmap = \"gray\" )\n\nplt.savefig('../img/node{}_layer1_mnist'.format(indexNode1))\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Best Nodes Layer 2",
"_____no_output_____"
],
[
"## Node 32",
"_____no_output_____"
]
],
[
[
"# index\niNode = 0\nindexNode1 = filtersLayer2[0]\n\n# images\nplt.subplot(331)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 0] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(332)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 1] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(333)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 2] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(334)\nplt.imshow( Activations2[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(335)\nplt.imshow( Activations2[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(336)\nplt.imshow( Activations2[iNode,2,:,:,0], cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(337)\nplt.imshow( DeconvActivations2[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(338)\nplt.imshow( DeconvActivations2[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(339)\nplt.imshow( DeconvActivations2[iNode,2,:,:,0], cmap = \"gray\" )\n\nplt.savefig('../img/node{}_layer2_mnist'.format(indexNode1))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Node 45",
"_____no_output_____"
]
],
[
[
"# index\niNode = 1\nindexNode1 = filtersLayer2[1]\n\n# images\nplt.subplot(331)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 0] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(332)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 1] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(333)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 2] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(334)\nplt.imshow( Activations2[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(335)\nplt.imshow( Activations2[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(336)\nplt.imshow( Activations2[iNode,2,:,:,0], cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(337)\nplt.imshow( DeconvActivations2[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(338)\nplt.imshow( DeconvActivations2[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(339)\nplt.imshow( DeconvActivations2[iNode,2,:,:,0], cmap = \"gray\" )\n\nplt.savefig('../img/node{}_layer2_mnist'.format(indexNode1))\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Node 3",
"_____no_output_____"
]
],
[
[
"# index\niNode = 2\nindexNode1 = filtersLayer2[2]\n\n# images\nplt.subplot(331)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 0] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(332)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 1] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\nplt.subplot(333)\nplt.imshow( eval_data_mnist[int( maxIndexesLayer2[iNode, 2] ),:].reshape(28,28) , interpolation=\"nearest\", cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(334)\nplt.imshow( Activations2[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(335)\nplt.imshow( Activations2[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(336)\nplt.imshow( Activations2[iNode,2,:,:,0], cmap = \"gray\" )\n\n# feature map visualization\nplt.subplot(337)\nplt.imshow( DeconvActivations2[iNode,0,:,:,0], cmap = \"gray\" )\nplt.subplot(338)\nplt.imshow( DeconvActivations2[iNode,1,:,:,0], cmap = \"gray\" )\nplt.subplot(339)\nplt.imshow( DeconvActivations2[iNode,2,:,:,0], cmap = \"gray\" )\n\nplt.savefig('../img/node{}_layer2_mnist'.format(indexNode1))\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7d32286d50f2687bfa2dab5e1edc4c0e544ffd
| 172,132 |
ipynb
|
Jupyter Notebook
|
analysis/submitted/.ipynb_checkpoints/milestone3feedback-checkpoint.ipynb
|
data301-2020-winter1/course-project-solo_303
|
34533843e91c3e2974c9e0979687678727bdd7fd
|
[
"MIT"
] | null | null | null |
analysis/submitted/.ipynb_checkpoints/milestone3feedback-checkpoint.ipynb
|
data301-2020-winter1/course-project-solo_303
|
34533843e91c3e2974c9e0979687678727bdd7fd
|
[
"MIT"
] | 1 |
2020-12-03T23:05:06.000Z
|
2020-12-03T23:05:06.000Z
|
analysis/submitted/.ipynb_checkpoints/milestone3feedback-checkpoint.ipynb
|
data301-2020-winter1/course-project-solo_303
|
34533843e91c3e2974c9e0979687678727bdd7fd
|
[
"MIT"
] | null | null | null | 329.754789 | 55,712 | 0.925987 |
[
[
[
"# Art(ists)(work)\n(Milestone 3 - Task 1: Address project feedback)\n## Introduction\n\n### Information About the Data\nThe data I am working on is from the Musuem of Modern Art (MoMA) and it consists of two datasets: Artists and Artworks.\n\nArtists' columns are Artist ID, Name, Nationality, Gender, Birth Year, and Death Year. These features are self explanatory.\n\nThe Artworks dataset is more complex than Artists in terms of features due to the uniqueness of each artwork. Artworks' columns are Artwork ID, Title, Artist ID, Name, Date, Medium, Dimensions, Acquisition Date, Credit, Catalogue, Classification, Object Number, Diameter (cm), Circumference (cm), Height (cm), Length (cm), Width (cm), Depth (cm), Weight (kg), and Duration (s). I will be focusing on the Classification because the physical attributes and dates are extremely variable in format. To clarify, Title is the title of the artwork, and Name is the name of the artist who created the work. The physical attributes are Diamater, Circumference, Height, Length, Width, Depth, Weight, and Duration. In particular, duration is for performance art or videos and such.\n\n### Research Questions\n<!-- (Explain the importance of those questions) -->\n\n#### What is the Gender Gap between Female and Male Artists within the Artists dataset? Does this ratio differ in American Artists?\n\nThis question is important because it addresses the gender disparity in artists that have their work shown in museums. The most commonly known famed artists are men. When we get asked to name an artists, we name men: \"Da Vinci, Michelangelo, Andy Warhol, Van Gogh, Rembrandt, Monet, Picasso, Pollock, Dalí. This question seeks not to discredit all great male artists, but pokes at how we can only see and remember men for their work.\n\n\n\nFig 1. \"Do Women STILL Have to be Naked to Get Into the Met. Museum?\", Guerilla Girls \n\nThe subquestion seeks to define a difference in the gender ratio in American artists instead of the whole dataset. I speculate that there would be a higher, albeit still low, female to male ratio because an American Museum would want to display more American female artists.\n\n#### What are the top five Nationalities in the Artists Dataset?\n\n\nThis dataset is from the Museum of Modern Art in America, but what other countries are the artists from? I want to discover what the top five nationalities in artists tells us about the museum itself. In short, the importance of this question lies in the importance of artist nationality.\n\n#### What is the average death of Artists within MoMA?\n\nMany great artists do not seem to live very long, perhaps due to [mental](https://en.wikipedia.org/wiki/Creativity_and_mental_health) or physical illnesses. I do not mean to link creativity to mental illness, but I would like to point out that art is a form of self-expression. Smoking and drinking were very also prevalent in the mid century. I speculate that the average death of artists in the Artists dataset was lower than it is [now](https://en.wikipedia.org/wiki/List_of_countries_by_life_expectancy).\n\n#### What are the 5 most popular Classifications?\n\nI want to find out which category of Classification holds the greatest quantity because it could show how some Classifications are more \"modern\" than others. Maybe the most quantified methods will also tell us how artists prefer one method over another.",
"_____no_output_____"
],
[
"## Analysis\n<!-- (why exactly you chose those visualization methods) -->",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\nimport seaborn as sns\n\n# functions\ndef load_and_process(path):\n #(Load data and deal with missing data)\n df = (\n pd.read_csv(path)\n .dropna() )\n return df\n\ndef clean_date(row): # some dates are ranges. this function choses the start date\n if(len(row.Date)>4):\n x = row.Date.split('-')\n row.Date = x[0]\n\n return row.Date \ndef clean_df_artworks(artworks):\n df_cleaned = artworks.copy()\n df_cleaned['Date'] = df_cleaned.apply(lambda row: clean_date(row), axis=1)\n return df_cleaned",
"_____no_output_____"
],
[
"path_artists = \"../../data/raw/artists.csv\"\npath_artworks = \"../../data/raw/artworks.csv\"\n\ndf_artists = load_and_process(path_artists) # all these artists are dead\ndf_artworks = pd.read_csv(path_artworks)\ndf_artworks = clean_df_artworks(df_artworks[df_artworks['Date'].notna()])\n\n# cleaning\ndf_artists= df_artists[df_artists.Gender != 'male'] #got rid of one mismarked row\ndf_artists = df_artists[df_artists.Nationality != 'Nationality unknown'] # some artists have an unknown nationality, got rid of that",
"_____no_output_____"
]
],
[
[
"### Gender\n",
"_____no_output_____"
]
],
[
[
"gender = sns.countplot(y='Gender',data=df_artists).set_title('Gender Ratio')\nmale_female_ratio = (df_artists[df_artists.Gender == 'Male'].count()/df_artists[df_artists.Gender == 'Female'].count())",
"_____no_output_____"
]
],
[
[
"Fig 1. We can see that for every female artist in MoMA, there are 7.82 males.\n\nI choose a count plot to visualize the gap between the number of female and male artists because it is simple and easy to understand. Blue represents male and orange represents female.",
"_____no_output_____"
],
[
"#### American Gender Ratio\nLet's see the American male and female chart:",
"_____no_output_____"
]
],
[
[
"df_am_gender = df_artists[df_artists['Nationality']=='American']\ngender_am = sns.countplot(y='Gender',data=df_am_gender).set_title('American Gender Ratio')\nam_male_female_ratio = (df_am_gender[df_am_gender.Gender == 'Male'].count()/df_am_gender[df_am_gender.Gender == 'Female'].count())\nam_male_female_ratio",
"_____no_output_____"
]
],
[
[
"Fig 2. The American male to female ratio is 5.75.",
"_____no_output_____"
],
[
"### Nationality \nI want to see which which Nationality is the most represented in the MoMA artists",
"_____no_output_____"
]
],
[
[
"nationality=sns.countplot(y='Nationality',data=df_artists,order = df_artists['Nationality'].value_counts().index).set_title('Sorted Number of Nationalities')\nfig = plt.gcf()\nfig.set_size_inches(8, 12)",
"_____no_output_____"
]
],
[
[
"Fig 3.Top 5 Nationalities (by count): American, French, German, British, Italian\n\nI used a count plot and ordered the nationalities that hold the most artists. It is easy to see that America is in the lead here, not that it is a competition.\n\n### Age \nI am going to see if there is anything in Birth Year and Death Year (EDA)",
"_____no_output_____"
]
],
[
[
"hexbin=sns.jointplot(x='Birth Year',y='Death Year',data=df_artists,kind=\"hex\")",
"_____no_output_____"
]
],
[
[
"Fig 4. EDA. This HexBin plot shows more information than the Fig4 scatter plot. there is a high concentration of artists born in the late 1800's - early 1900's and dying in the late 1990's and early 2000's. I can see that the definition of \"Modern\" works are created by artists born around the late 1800's. So \"Modern\" most popularily means post-1900's.\n\nI used a joint plot with hexagonal bins to show the pattern between Death Year and Birth Year. The darkest bins show the highest concentration of artists born and dying in a 2 particular years. This plot is also very useful because the bar plots on the side show wear the highest concentration is independent of the other variable.",
"_____no_output_____"
]
],
[
[
"df_artists['age']=(df_artists['Death Year']-df_artists['Birth Year'])\nage_line = sns.displot(df_artists['age'])\nage_line.fig.suptitle(\"Age of Death\")\ndf_artists['age'].mean()\n# got rid of boxplot",
"_____no_output_____"
]
],
[
[
"Fig 5. Artists in this dataset died at the average age of 72.8.\n\nI got rid of the box plot and although this bar plot does not show the average age of death, it does show how the quantities in each bin can more or less make up the average.",
"_____no_output_____"
],
[
"### Artwork",
"_____no_output_____"
],
[
"What are the 5 most popular Classifications?",
"_____no_output_____"
]
],
[
[
"plot_class= (\n sns.countplot(\n y='Classification',\n data=df_artworks,\n order = df_artworks['Classification']\n .value_counts()\n .index)\n .set_title('Popular Classsifications')\n)\nfig= plt.gcf()\nfig.set_size_inches(8, 12)",
"_____no_output_____"
]
],
[
[
"Fig 6. Top 5 Classifications: Print, Photograph, Illustrated Book, Drawing, and Design. \n\nI count and sort the amounts of each Classification's artworks. The warmer colours on the plot indicate higher quantities of a Classification in Artworks.",
"_____no_output_____"
],
[
"## Conclusion\nI think these visualizations answered all my questions. If I had more experience in data cleaning I would ask more interesting questions.\n \n#### What is the Gender Gap between Female and Male Artists within the Artists dataset? Does this ratio differ in American Artists?\nFor every female artist in this dataset, there are 7.82 males. For artists with American Nationality, there are 5.75 males to each female. It makes sense that the ratio is better in terms of gender equality, because an American Mueseum would want to represent more American artists, and therefore more American _female_ artists.\n\n#### What are the top five Nationalities in the Artists Dataset?\nThe top five Nationalities in this dataset are American, French, German, British and Italian. This clearly shows how Eurocentric MoMA is. \n\n#### What is the average death of Artists within MoMA?\n\nThe average age of death of artists in this dataset is 72.8. It is definitely as lower it is [now](https://en.wikipedia.org/wiki/List_of_countries_by_life_expectancy). \n\n#### What are the 5 most popular Classifications?\nThe top 5 Classifications of Artworks are Print, Photograph, Illustrated Book, Drawing, and Design. I think that there are much more prints and photographs than any other Classification because they are on paper, and are therefore more accessible and perhaps easier to store and digitize. This may be way a museum has more prints and photographs in the Artworks dataset. Artists may prefer to experiment on paper due to its acessibility and flexibility.\n",
"_____no_output_____"
],
[
"#### References\n\n[Guerilla Girls Image](https://www.guerrillagirls.com/naked-through-the-ages)\n\n[Creativity and mental health](https://en.wikipedia.org/wiki/Creativity_and_mental_health)\n\n[Life expectancy](https://en.wikipedia.org/wiki/List_of_countries_by_life_expectancy)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cb7d385d775da23b9c53b376107162cec80b7a96
| 7,098 |
ipynb
|
Jupyter Notebook
|
notebooks/Staeckel-Delta-grid.ipynb
|
adrn/thrift-shop
|
8dcd8d7e242ded1263edb4b1fb7c05f04c05b47c
|
[
"MIT"
] | null | null | null |
notebooks/Staeckel-Delta-grid.ipynb
|
adrn/thrift-shop
|
8dcd8d7e242ded1263edb4b1fb7c05f04c05b47c
|
[
"MIT"
] | 11 |
2020-09-29T19:18:19.000Z
|
2020-11-21T21:26:09.000Z
|
notebooks/Staeckel-Delta-grid.ipynb
|
adrn/thrift-shop
|
8dcd8d7e242ded1263edb4b1fb7c05f04c05b47c
|
[
"MIT"
] | 1 |
2021-09-07T22:36:06.000Z
|
2021-09-07T22:36:06.000Z
| 25.44086 | 92 | 0.520851 |
[
[
[
"import astropy.coordinates as coord\nimport astropy.table as at\nimport astropy.units as u\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\nfrom scipy.spatial import cKDTree\nfrom scipy.stats import binned_statistic\nfrom scipy.interpolate import interp1d\n\n# gala\nimport gala.coordinates as gc\nimport gala.dynamics as gd\nimport gala.integrate as gi\nimport gala.potential as gp\nfrom gala.units import galactic\n\nfrom totoro.config import galcen_frame\nfrom totoro.data import load_apogee_sample\nfrom totoro.potentials import potentials, galpy_potentials",
"_____no_output_____"
],
[
"t, c = load_apogee_sample('../data/apogee-parent-sample.fits')\nt = t[np.argsort(t['APOGEE_ID'])]",
"_____no_output_____"
],
[
"galcen = c.transform_to(galcen_frame)\nw0s = gd.PhaseSpacePosition(galcen.data)",
"_____no_output_____"
],
[
"from galpy.actionAngle import estimateDeltaStaeckel, actionAngleStaeckel\nfrom totoro.config import rsun as ro, vcirc as vo\nfrom totoro.galpy_helpers import gala_to_galpy_orbit",
"_____no_output_____"
]
],
[
[
"### Compute Staeckel delta on a grid:",
"_____no_output_____"
]
],
[
[
"Rz_grids = (np.arange(8-2.5, 8+2.5 + 1e-3, 0.05),\n np.arange(-2.5, 2.5 + 1e-3, 0.05))\nRz_grid = np.stack(list(map(np.ravel, np.meshgrid(*Rz_grids)))).T",
"_____no_output_____"
],
[
"for pot_name in ['0.4', '1.0', '1.6']:\n pot = galpy_potentials[pot_name]\n\n delta_staeckels = []\n for i in range(Rz_grid.shape[0]):\n R = (Rz_grid[i, 0] * u.kpc).to_value(ro)\n z = (Rz_grid[i, 1] * u.kpc).to_value(ro)\n delta_staeckels.append(estimateDeltaStaeckel(\n pot, R, z))\n\n plt.figure()\n plt.title(pot_name)\n plt.scatter(Rz_grid[:, 0], Rz_grid[:, 1], \n c=delta_staeckels,\n vmin=2, vmax=6, s=8, marker='s')",
"_____no_output_____"
],
[
"from scipy.interpolate import NearestNDInterpolator",
"_____no_output_____"
],
[
"pot = galpy_potentials['1.0']\n\ndelta_staeckels = []\nfor i in range(Rz_grid.shape[0]):\n R = (Rz_grid[i, 0] * u.kpc).to_value(ro)\n z = (Rz_grid[i, 1] * u.kpc).to_value(ro)\n delta_staeckels.append(estimateDeltaStaeckel(\n pot, R, z))\n \ndelta_interp = NearestNDInterpolator(Rz_grid, \n delta_staeckels)",
"_____no_output_____"
],
[
"# def fast_actions():\n\ndeltas = delta_interp(w0s.cylindrical.rho.to_value(u.kpc),\n w0s.z.to_value(u.kpc))\n\no = gala_to_galpy_orbit(w0s)\naAS = actionAngleStaeckel(pot=pot, delta=deltas)\nactions = np.squeeze(aAS(o)).T * ro * vo",
"_____no_output_____"
]
],
[
[
"### Compare to Sanders & Binney actions",
"_____no_output_____"
]
],
[
[
"sb_aaf = at.Table.read('../cache_new_zsun/aaf-1.0.fits')\nsb_aaf = sb_aaf[np.isin(sb_aaf['APOGEE_ID'], t['APOGEE_ID'])]\n\nassert len(sb_aaf) == len(t)\nsb_aaf = sb_aaf[np.argsort(sb_aaf['APOGEE_ID'])] \nassert np.all(t['APOGEE_ID'] == sb_aaf['APOGEE_ID'])",
"_____no_output_____"
],
[
"sb_actions = sb_aaf['actions']",
"_____no_output_____"
],
[
"actions.shape, sb_actions.shape",
"_____no_output_____"
],
[
"from scipy.stats import binned_statistic\nfrom astropy.stats import median_absolute_deviation",
"_____no_output_____"
],
[
"k = 0\nfor k in [0, 2]:\n sb_J = sb_actions[:, k]\n J = actions[:, k]\n mask = np.isfinite(sb_J) & np.isfinite(J)\n sb_J = sb_J[mask]\n J = J[mask]\n stat = binned_statistic(np.log10(sb_J), \n (J - sb_J) / sb_J,\n statistic=lambda x: 1.5 * median_absolute_deviation(x),\n bins=np.arange(-1, 3, 0.1))\n bincen = 0.5 * (10 ** stat.bin_edges[:-1] + 10 ** stat.bin_edges[1:])\n \n fig = plt.figure()\n plt.plot(sb_J, (J - sb_J) / sb_J,\n alpha=0.1, ls='none', ms=2, mew=0)\n\n plt.plot(bincen, stat.statistic)\n\n plt.xscale('log')\n plt.xlim(0.1, 2000)\n plt.ylim(-1, 1)\n \n fig.set_facecolor('w')",
"_____no_output_____"
]
],
[
[
"---",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cb7d3b1272d29c7f8dcf5b74e63f95a0c5f9e1cf
| 6,854 |
ipynb
|
Jupyter Notebook
|
Twitter-Sentiment-Analysis (Nigerian_2019_Elections).ipynb
|
Behordeun/twitter-sentiment-analysis
|
dec1fec1a3f75b0eede893a46c2c7422867196de
|
[
"Apache-2.0"
] | 1 |
2021-10-30T23:59:51.000Z
|
2021-10-30T23:59:51.000Z
|
Twitter-Sentiment-Analysis (Nigerian_2019_Elections).ipynb
|
Behordeun/twitter-sentiment-analysis
|
dec1fec1a3f75b0eede893a46c2c7422867196de
|
[
"Apache-2.0"
] | null | null | null |
Twitter-Sentiment-Analysis (Nigerian_2019_Elections).ipynb
|
Behordeun/twitter-sentiment-analysis
|
dec1fec1a3f75b0eede893a46c2c7422867196de
|
[
"Apache-2.0"
] | null | null | null | 26.565891 | 157 | 0.572075 |
[
[
[
"## Importing necessary library",
"_____no_output_____"
]
],
[
[
"import snscrape.modules.twitter as sntwitter\nimport pandas as pd\nimport itertools\nimport plotly.graph_objects as go\nfrom datetime import datetime",
"_____no_output_____"
]
],
[
[
"## Creating a data frame called \"df\" for storing the data to be scraped. Here, \"2019 Elections\" was the search keyword\"",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame(itertools.islice(sntwitter.TwitterSearchScraper(\n '\"2019 elections\"').get_items(), 5000000))",
"_____no_output_____"
]
],
[
[
"## Reading the column names from the dataframe to check the attributes",
"_____no_output_____"
]
],
[
[
"df.columns",
"_____no_output_____"
]
],
[
[
"## Calculate the time for scraping the 5000000 tweets\n\nHere our search parameters are modified to search for tweets around Abuja within __2017-01-01 to 2021-10-23__ using the keyword __2019 elections__. \n\n__NB:__ we set the result to be returned to __5000000__ so we can get as much as possible results (tweets).",
"_____no_output_____"
]
],
[
[
"# Set start time\nstart_time = datetime.now()\n#Creating dataframe called 'data' and storing the tweets\ndata = pd.DataFrame(itertools.islice(sntwitter.TwitterSearchScraper(\n '\"2019 elections near:Abuja since:2017-01-01 until:2021-10-23\"').get_items(), 5000000))\n# Set end time\nend_time = datetime.now()\n#Printing the time duration for scraping these tweets\nprint('Duration: {}'.format(end_time - start_time))",
"_____no_output_____"
],
[
"#keeping only date, id, content, user, and url and stored into dataframe called 'df'\ndf = data[['date', 'id', 'content', 'username', 'url']]",
"_____no_output_____"
],
[
"# If you don't have transformers library installed before, kindly install it using the command:\n# !pip install transformers.\n\n# PS: Remember to remove the leading # in front of \"pip install transformers\"",
"_____no_output_____"
],
[
"#Importing the pipeline from Transformers.\nfrom transformers import pipeline\nsentiment_classifier = pipeline('sentiment-analysis')",
"_____no_output_____"
],
[
"#Taking only 1000000 (20%) records and creating new dataframe called df1\ndf1 = df.head(1000000)\n# Passing the tweets into the sentiment pipeline and extracting the sentiment score and label\ndf1 = (df1.assign(sentiment = lambda x: x['content'].apply(lambda s: sentiment_classifier(s)))\n.assign(\nlabel = lambda x: x['sentiment'].apply(lambda s: (s[0]['label'])),\nscore = lambda x: x['sentiment'].apply(lambda s: (s[0]['score']))))\ndf1.head()",
"_____no_output_____"
],
[
"#checking the 1000th tweet, to check the sentiment label whether it is \"positive\" or “negative”\ndf1['content'][1000]",
"_____no_output_____"
],
[
"# Visualizing the sentiments\nfig = go.Figure()\nfig.add_trace(go.Bar(x = df1[\"score\"],\ny = df1[\"label\"],\norientation = \"h\")) #set orientation to horizontal because we want to flip the x and y-axis\nfig.update_layout(plot_bgcolor = \"white\")\nfig.show()",
"_____no_output_____"
],
[
"# Taking the entire 5000000 (100%) records and creating new dataframe called df1\ndf2 = df\n# Passing the tweets into the sentiment pipeline and extracting the sentiment score and label\ndf2 = (df2.assign(sentiment = lambda x: x['content'].apply(lambda s: sentiment_classifier(s)))\n.assign(\nlabel = lambda x: x['sentiment'].apply(lambda s: (s[0]['label'])),\nscore = lambda x: x['sentiment'].apply(lambda s: (s[0]['score']))))\ndf2.head()",
"_____no_output_____"
],
[
"#Visualizing the sentiments\nfig1 = go.Figure()\nfig1.add_trace(go.Bar(x = df2[\"Sentiment score\"],\ny = df2[\"Sentiment label\"],\norientation = \"h\")) #set orientation to horizontal because we want to flip the x and y-axis\nfig1.update_layout(plot_bgcolor = \"white\")\nfig1.show()",
"_____no_output_____"
],
[
"df2.to_csv('Abj-Elect-Tweets-Sentiment.csv', index=True)",
"_____no_output_____"
],
[
"df1.to_csv('Abj-Elect-Tweets-Sentiment1.csv', index=True)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7d40d514959de3c5b9a6ed5c842aad61289245
| 11,824 |
ipynb
|
Jupyter Notebook
|
ch06/HalvingGridSearchCV.ipynb
|
songyw0517/python-machine-learning-book-3rd-edition
|
70a32005f86c602242e134626701194e1fc4f9a4
|
[
"MIT"
] | 40 |
2020-09-08T04:28:40.000Z
|
2022-03-29T06:57:59.000Z
|
ch06/HalvingGridSearchCV.ipynb
|
songyw0517/python-machine-learning-book-3rd-edition
|
70a32005f86c602242e134626701194e1fc4f9a4
|
[
"MIT"
] | null | null | null |
ch06/HalvingGridSearchCV.ipynb
|
songyw0517/python-machine-learning-book-3rd-edition
|
70a32005f86c602242e134626701194e1fc4f9a4
|
[
"MIT"
] | 41 |
2020-10-26T21:33:19.000Z
|
2022-03-30T04:18:26.000Z
| 31.280423 | 398 | 0.571465 |
[
[
[
"# 머신 러닝 교과서 3판",
"_____no_output_____"
],
[
"# HalvingGridSearchCV",
"_____no_output_____"
],
[
"### 경고: 이 노트북은 사이킷런 0.24 이상에서 실행할 수 있습니다.",
"_____no_output_____"
]
],
[
[
"# 코랩에서 실행할 경우 최신 버전의 사이킷런을 설치합니다.\n!pip install --upgrade scikit-learn",
"Requirement already satisfied: scikit-learn in /home/haesun/python-machine-learning-book-3rd-edition/.env/lib/python3.7/site-packages (1.0)\nRequirement already satisfied: scipy>=1.1.0 in /home/haesun/python-machine-learning-book-3rd-edition/.env/lib/python3.7/site-packages (from scikit-learn) (1.7.1)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /home/haesun/python-machine-learning-book-3rd-edition/.env/lib/python3.7/site-packages (from scikit-learn) (3.0.0)\nRequirement already satisfied: numpy>=1.14.6 in /home/haesun/python-machine-learning-book-3rd-edition/.env/lib/python3.7/site-packages (from scikit-learn) (1.21.3)\nRequirement already satisfied: joblib>=0.11 in /home/haesun/python-machine-learning-book-3rd-edition/.env/lib/python3.7/site-packages (from scikit-learn) (1.1.0)\n"
],
[
"import pandas as pd\n\ndf = pd.read_csv('https://archive.ics.uci.edu/ml/'\n 'machine-learning-databases'\n '/breast-cancer-wisconsin/wdbc.data', header=None)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import LabelEncoder\n\nX = df.loc[:, 2:].values\ny = df.loc[:, 1].values\nle = LabelEncoder()\ny = le.fit_transform(y)",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = \\\n train_test_split(X, y, \n test_size=0.20,\n stratify=y,\n random_state=1)",
"_____no_output_____"
]
],
[
[
"비교를 위해 `GridSearchCV` 실행 결과를 출력합니다.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import make_pipeline\nimport numpy as np\n\npipe_svc = make_pipeline(StandardScaler(),\n SVC(random_state=1))\n\nparam_range = [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0]\n\nparam_grid = [{'svc__C': param_range, \n 'svc__kernel': ['linear']},\n {'svc__C': param_range, \n 'svc__gamma': param_range, \n 'svc__kernel': ['rbf']}]\n\ngs = GridSearchCV(estimator=pipe_svc, \n param_grid=param_grid,\n cv=10,\n n_jobs=-1)\ngs = gs.fit(X_train, y_train)\nprint(gs.best_score_)\nprint(gs.best_params_)\nprint(np.sum(gs.cv_results_['mean_fit_time']))",
"0.9846859903381642\n{'svc__C': 100.0, 'svc__gamma': 0.001, 'svc__kernel': 'rbf'}\n1.206097149848938\n"
]
],
[
[
"사이킷런 0.24 버전에서 추가된 `HalvingGridsearchCV`는 모든 파라미터 조합에 대해 제한된 자원으로 실행한 다음 가장 좋은 후보를 골라서 더 많은 자원을 투여하는 식으로 반복적으로 탐색을 수행합니다. 이런 방식을 SH(Successive Halving)이라고 부릅니다. `HalvingGridsearchCV`의 `resource` 매개변수는 반복마다 늘려갈 자원을 정의합니다. 기본값은 `'n_samples'`로 샘플 개수입니다. 이 외에도 탐색 대상 모델에서 양의 정수 값을 가진 매개변수를 지정할 수 있습니다. 예를 들면 랜덤 포레스트의 `n_estimators`가 가능합니다.\n\n`factor` 매개변수는 반복마다 선택할 후보의 비율을 지정합니다. 기본값은 3으로 후보 중에서 성능이 높은 1/3만 다음 반복으로 전달합니다. `max_resources` 매개변수는 각 후보가 사용할 최대 자원을 지정합니다. 기본값은 `'auto'`로 `resources='n_samples'`일 때 샘플 개수가 됩니다.\n\n`min_resources`는 첫 번째 반복에서 각 후보가 사용할 최소 자원을 지정합니다. `resources='n_samples'`이고 `min_resources='smallest'`이면 회귀일 때 `cv` $\\times$ 2가 되고 분류일 때는 `cv` $\\times$ 클래스개수 $\\times$ 2가 됩니다. 그외에는 1입니다. `min_resources='exhaust'`이면 앞에서 계산한 값과 `max_resources`를 `factor`\\*\\*`n_required_iterations`으로 나눈 몫 중 큰 값입니다. 기본값은 `'exhaust'`입니다(`n_required_iterations`는 $ \\text{log}_{factor}(전체 후보 갯수) + 1$ 입니다).\n\n마지막으로 `aggressive_elimination` 매개변수를 `True`로 지정하면 마지막 반복에서 `factor`만큼 후보가 남을 수 있도록 자원을 늘리지 않고 초기에 반복을 여러 번 진행합니다. 기본값은 `False`입니다.\n\n`HalvingGridsearchCV` 아직 실험적이기 때문에 `sklearn.experimental` 패키지 아래에 있는 `enable_halving_search_cv`을 임포트해야 사용할 수 있습니다. `verbose=1`로 지정하면 각 반복 과정을 자세히 살펴 볼 수 있습니다.",
"_____no_output_____"
]
],
[
[
"from sklearn.experimental import enable_halving_search_cv\nfrom sklearn.model_selection import HalvingGridSearchCV\n\nhgs = HalvingGridSearchCV(estimator=pipe_svc,\n param_grid=param_grid,\n cv=10,\n n_jobs=-1, verbose=1)\nhgs = hgs.fit(X_train, y_train)\nprint(hgs.best_score_)\nprint(hgs.best_params_)",
"n_iterations: 3\nn_required_iterations: 4\nn_possible_iterations: 3\nmin_resources_: 40\nmax_resources_: 455\naggressive_elimination: False\nfactor: 3\n----------\niter: 0\nn_candidates: 72\nn_resources: 40\nFitting 10 folds for each of 72 candidates, totalling 720 fits\n----------\niter: 1\nn_candidates: 24\nn_resources: 120\nFitting 10 folds for each of 24 candidates, totalling 240 fits\n----------\niter: 2\nn_candidates: 8\nn_resources: 360\nFitting 10 folds for each of 8 candidates, totalling 80 fits\n0.9776190476190477\n{'svc__C': 100.0, 'svc__gamma': 0.001, 'svc__kernel': 'rbf'}\n"
]
],
[
[
"출력 결과를 보면 첫 번째 반복(iter: 0)에서 72개의 후보를 40개의 샘플로 교차 검증을 수행합니다. 여기에서 72/3 = 24개의 후보를 뽑아 두 번째 반복(iter: 1)을 수행합니다. 두 번째 반복에서는 40 * 3 = 120개의 샘플을 사용합니다. 같은 방식으로 세 번째 반복(iter: 2)에서는 8개의 후보가 360개의 샘플로 평가됩니다. 최종 결과는 98.3%로 `GridSearchCV` 보다 조금 낮습니다. 찾은 매개변수 조합도 달라진 것을 볼 수 있습니다.\n\n3번의 반복 동안 `HalvingGridSearchCV`가 수행한 교차 검증 횟수는 모두 104번입니다. 각 교차 검증에 걸린 시간은 `cv_results_` 속성의 `mean_fit_time`에 저장되어 있습니다. 이를 `GridSearchCV`와 비교해 보면 5배 이상 빠른 것을 볼 수 있습니다.",
"_____no_output_____"
]
],
[
[
"print(np.sum(hgs.cv_results_['mean_fit_time']))",
"0.22894012928009033\n"
]
],
[
[
"각 반복 단계에서 사용한 샘플 개수와 후보 개수는 각각 `n_resources_` 속성과 `n_candidates_` 속성에 저장되어 있습니다.",
"_____no_output_____"
]
],
[
[
"print('자원 리스트:', hgs.n_resources_)\nprint('후보 리스트:', hgs.n_candidates_)",
"자원 리스트: [40, 120, 360]\n후보 리스트: [72, 24, 8]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7d47d2ec8fcd64afebd4b209df752259b7bbad
| 133,925 |
ipynb
|
Jupyter Notebook
|
Regression/RadiusNeighborsRegressor_MinMaxScaler_PolynomialFeatures.ipynb
|
devVipin01/Machine-learning-AI-Templates
|
d2afa815b88cd8ddf1d6869e2e93a7d9d49d8b9a
|
[
"Apache-2.0"
] | 2 |
2021-10-03T11:09:59.000Z
|
2021-12-02T08:33:58.000Z
|
Regression/RadiusNeighborsRegressor_MinMaxScaler_PolynomialFeatures.ipynb
|
devVipin01/Machine-learning-AI-Templates
|
d2afa815b88cd8ddf1d6869e2e93a7d9d49d8b9a
|
[
"Apache-2.0"
] | 1 |
2021-10-03T04:54:35.000Z
|
2021-10-03T06:55:50.000Z
|
Regression/RadiusNeighborsRegressor_MinMaxScaler_PolynomialFeatures.ipynb
|
devVipin01/Machine-learning-AI-Templates
|
d2afa815b88cd8ddf1d6869e2e93a7d9d49d8b9a
|
[
"Apache-2.0"
] | 1 |
2021-10-03T07:47:03.000Z
|
2021-10-03T07:47:03.000Z
| 167.40625 | 50,448 | 0.881971 |
[
[
[
"# RadiusNeighborsRegressor with MinMaxScaler & Polynomial Features\n",
"_____no_output_____"
],
[
"**This Code template is for the regression analysis using a RadiusNeighbors Regression and the feature rescaling technique MinMaxScaler along with Polynomial Features as a feature transformation technique in a pipeline** ",
"_____no_output_____"
],
[
"### Required Packages",
"_____no_output_____"
]
],
[
[
"import warnings as wr\nimport numpy as np \nimport pandas as pd \nimport seaborn as sns\nimport matplotlib.pyplot as plt \nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import MinMaxScaler,PolynomialFeatures\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.neighbors import RadiusNeighborsRegressor\nfrom sklearn.metrics import mean_squared_error, r2_score,mean_absolute_error\nwr.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"### Initialization\n\nFilepath of CSV file",
"_____no_output_____"
]
],
[
[
"#filepath\nfile_path= \"\"",
"_____no_output_____"
]
],
[
[
"List of features which are required for model training .",
"_____no_output_____"
]
],
[
[
"#x_values\nfeatures=[]",
"_____no_output_____"
]
],
[
[
"Target feature for prediction.",
"_____no_output_____"
]
],
[
[
"#y_value\ntarget=''",
"_____no_output_____"
]
],
[
[
"### Data Fetching\n\nPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.\n\nWe will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry.",
"_____no_output_____"
]
],
[
[
"df=pd.read_csv(file_path) #reading file\ndf.head()#displaying initial entries",
"_____no_output_____"
],
[
"print('Number of rows are :',df.shape[0], ',and number of columns are :',df.shape[1])",
"Number of rows are : 400 ,and number of columns are : 9\n"
],
[
"df.columns.tolist()\n",
"_____no_output_____"
]
],
[
[
"### Data Preprocessing\n\nSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes.\n",
"_____no_output_____"
]
],
[
[
"def NullClearner(df):\n if(isinstance(df, pd.Series) and (df.dtype in [\"float64\",\"int64\"])):\n df.fillna(df.mean(),inplace=True)\n return df\n elif(isinstance(df, pd.Series)):\n df.fillna(df.mode()[0],inplace=True)\n return df\n else:return df\ndef EncodeX(df):\n return pd.get_dummies(df)",
"_____no_output_____"
]
],
[
[
"#### Correlation Map\n\nIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (15, 10))\ncorr = df.corr()\nmask = np.triu(np.ones_like(corr, dtype = bool))\nsns.heatmap(corr, mask = mask, linewidths = 1, annot = True, fmt = \".2f\")\nplt.show()",
"_____no_output_____"
],
[
"correlation = df[df.columns[1:]].corr()[target][:]\ncorrelation",
"_____no_output_____"
]
],
[
[
"### Feature Selections\n\nIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.\n\nWe will assign all the required input features to X and target/outcome to Y.",
"_____no_output_____"
]
],
[
[
"#spliting data into X(features) and Y(Target)\n\nX=df[features]\nY=df[target] ",
"_____no_output_____"
]
],
[
[
"Calling preprocessing functions on the feature and target set.",
"_____no_output_____"
]
],
[
[
"x=X.columns.to_list()\nfor i in x:\n X[i]=NullClearner(X[i])\nX=EncodeX(X)\nY=NullClearner(Y)\nX.head()",
"_____no_output_____"
]
],
[
[
"### Data Splitting\n\nThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data.",
"_____no_output_____"
]
],
[
[
"#we can choose randomstate and test_size as over requerment\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 1) #performing datasplitting",
"_____no_output_____"
]
],
[
[
"\n### Data Scaling\n**Used MinMaxScaler**\n* Transform features by scaling each feature to a given range.\n\n* This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one.\n\n### Feature Transformation\n**PolynomialFeatures :**\n* Generate polynomial and interaction features.\n\n* Generate a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree.\n\n## Model\n**RadiusNeighborsRegressor** \n\nRadiusNeighborsRegressor implements learning based on the neighbors within a fixed radius of the query point, where is a floating-point value specified by the user.\n\n**Tuning parameters :-**\n* **radius:** Range of parameter space to use by default for radius_neighbors queries.\n\n* **algorithm:** Algorithm used to compute the nearest neighbors:\n\n* **leaf_size:** Leaf size passed to BallTree or KDTree.\n\n* **p:** Power parameter for the Minkowski metric.\n\n* **metric:** the distance metric to use for the tree.\n\n* **outlier_label:** label for outlier samples\n\n* **weights:** weight function used in prediction.",
"_____no_output_____"
]
],
[
[
"#training the RadiusNeighborsRegressor\n\nmodel = make_pipeline(MinMaxScaler(),PolynomialFeatures(),RadiusNeighborsRegressor(radius=1.5))\nmodel.fit(X_train,y_train)",
"_____no_output_____"
]
],
[
[
"#### Model Accuracy\nscore() method return the mean accuracy on the given test data and labels.\n\nIn multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.",
"_____no_output_____"
]
],
[
[
"print(\"Accuracy score {:.2f} %\\n\".format(model.score(X_test,y_test)*100))",
"Accuracy score 71.19 %\n\n"
],
[
"#prediction on testing set\nprediction=model.predict(X_test)",
"_____no_output_____"
]
],
[
[
"### Model evolution\n\n\n**r2_score:** The r2_score function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions.\n\n**MAE:** The mean abosolute error function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model.\n\n**MSE:** The mean squared error function squares the error(penalizes the model for large errors) by our model.",
"_____no_output_____"
]
],
[
[
"print('Mean Absolute Error:', mean_absolute_error(y_test, prediction)) \nprint('Mean Squared Error:', mean_squared_error(y_test, prediction)) \nprint('Root Mean Squared Error:', np.sqrt(mean_squared_error(y_test, prediction)))",
"Mean Absolute Error: 0.05762369892537518\nMean Squared Error: 0.006661892378988193\nRoot Mean Squared Error: 0.08162041643478789\n"
],
[
"print(\"R-squared score : \",r2_score(y_test,prediction))",
"R-squared score : 0.7119485295771226\n"
],
[
"#ploting actual and predicted\nred = plt.scatter(np.arange(0,80,5),prediction[0:80:5],color = \"red\")\ngreen = plt.scatter(np.arange(0,80,5),y_test[0:80:5],color = \"green\")\nplt.title(\"Comparison of Regression Algorithms\")\nplt.xlabel(\"Index of Candidate\")\nplt.ylabel(\"target\")\nplt.legend((red,green),('RadiusNeighborsRegressor', 'REAL'))\nplt.show()\n",
"_____no_output_____"
]
],
[
[
"### Prediction Plot\nFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis. For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(10,6))\nplt.plot(range(20),y_test[0:20], color = \"green\")\nplt.plot(range(20),model.predict(X_test[0:20]), color = \"red\")\nplt.legend([\"Actual\",\"prediction\"]) \nplt.title(\"Predicted vs True Value\")\nplt.xlabel(\"Record number\")\nplt.ylabel(target)\nplt.show()",
"_____no_output_____"
]
],
[
[
"#### Creator: Vipin Kumar , Github: [Profile](https://github.com/devVipin01)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cb7d4e12f59b75064dae0988c8bdb3f13f70fd07
| 1,771 |
ipynb
|
Jupyter Notebook
|
analysis/Tariq/EDA.ipynb
|
suyashrs/suyash.github.io
|
957e613e6cf41952326e6b74b8528aec3489a6df
|
[
"MIT"
] | null | null | null |
analysis/Tariq/EDA.ipynb
|
suyashrs/suyash.github.io
|
957e613e6cf41952326e6b74b8528aec3489a6df
|
[
"MIT"
] | 1 |
2021-03-20T00:39:57.000Z
|
2021-03-31T01:10:02.000Z
|
analysis/Tariq/EDA.ipynb
|
suyashrs/suyash.github.io
|
957e613e6cf41952326e6b74b8528aec3489a6df
|
[
"MIT"
] | 1 |
2021-02-15T18:16:36.000Z
|
2021-02-15T18:16:36.000Z
| 31.625 | 468 | 0.580463 |
[
[
[
"from ......analysis.scripts import project_functions # This is called a relative import",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
cb7d7b204374e7a0a9a89f559ff97c37c80671b4
| 37,166 |
ipynb
|
Jupyter Notebook
|
notebooks/Topic Modeling.ipynb
|
amrendra1002/ML-DL
|
66f0eb843ccfd4bca5fc4e4cd6ee95d1a078f708
|
[
"FTL"
] | 1 |
2021-01-31T08:41:58.000Z
|
2021-01-31T08:41:58.000Z
|
notebooks/Topic Modeling.ipynb
|
amrendra1002/ML-DL
|
66f0eb843ccfd4bca5fc4e4cd6ee95d1a078f708
|
[
"FTL"
] | null | null | null |
notebooks/Topic Modeling.ipynb
|
amrendra1002/ML-DL
|
66f0eb843ccfd4bca5fc4e4cd6ee95d1a078f708
|
[
"FTL"
] | null | null | null | 30.142741 | 1,563 | 0.366894 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport re\nfrom itertools import accumulate",
"_____no_output_____"
],
[
"emails = pd.read_csv(r'C:\\Users\\amrenkumar\\Desktop\\TestData\\full-output1.csv')",
"_____no_output_____"
],
[
"emails.shape",
"_____no_output_____"
],
[
"emails_clean = emails[~emails.interaction_content.isnull()]",
"_____no_output_____"
],
[
"emails_clean = emails_clean.interaction_content",
"_____no_output_____"
],
[
"emails_clean.drop_duplicates(keep='first', inplace=True)",
"_____no_output_____"
],
[
"emails_clean=emails_clean.take(np.random.permutation(len(emails_clean))[:1000])",
"_____no_output_____"
],
[
"emails_content = pd.DataFrame(emails_clean)",
"_____no_output_____"
],
[
"emails_content['index'] = emails_clean.index",
"_____no_output_____"
],
[
"emails_content_clean= emails_content.interaction_content.str.replace(\"[^a-zA-Z ]\", \"\")",
"_____no_output_____"
],
[
"import gensim\nfrom gensim.utils import simple_preprocess\nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom nltk.stem import WordNetLemmatizer, SnowballStemmer\nfrom nltk.stem.porter import *\nimport numpy as np\nnp.random.seed(2018)\nimport nltk\nnltk.download('wordnet')",
"[nltk_data] Downloading package wordnet to\n[nltk_data] C:\\Users\\amrenkumar\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package wordnet is already up-to-date!\n"
],
[
"def lemmatize_stemming(text):\n stemmer = PorterStemmer()\n return stemmer.stem(WordNetLemmatizer().lemmatize(text, pos='v'))\ndef preprocess(text):\n result = []\n for token in gensim.utils.simple_preprocess(text):\n if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3:\n result.append(lemmatize_stemming(token))\n return result",
"_____no_output_____"
],
[
"doc_sample = emails_content[emails_content['index'] == 14].values[0][0]\nprint('original document: ')\nwords = []\nfor word in doc_sample.split(' '):\n words.append(word)\nprint(words)\nprint('\\n\\n tokenized and lemmatized document: ')\nprint(preprocess(doc_sample))",
"_____no_output_____"
],
[
"processed_docs = emails_content['interaction_content'].map(preprocess)\nprocessed_docs[:10]",
"_____no_output_____"
],
[
"dictionary = gensim.corpora.Dictionary(processed_docs)\ncount = 0\nfor k, v in dictionary.iteritems():\n print(k, v)\n count += 1\n if count > 10:\n break",
"0 date\n1 eurask\n2 eurbid\n3 eurmid\n4 gbpask\n5 gbpbid\n6 gbpmid\n7 intra\n8 rat\n9 spot\n10 usdask\n"
],
[
"dictionary.filter_extremes(no_below=15, no_above=0.5, keep_n=100000)",
"_____no_output_____"
],
[
"bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]\nbow_corpus[10]",
"_____no_output_____"
],
[
"from gensim import corpora, models\ntfidf = models.TfidfModel(bow_corpus)\ncorpus_tfidf = tfidf[bow_corpus]\nfrom pprint import pprint\nfor doc in corpus_tfidf:\n pprint(doc)\n break",
"[(0, 0.17938968373469746),\n (1, 0.3007455041990572),\n (2, 0.3007455041990572),\n (3, 0.3007455041990572),\n (4, 0.3007455041990572),\n (5, 0.3007455041990572),\n (6, 0.3007455041990572),\n (7, 0.29632462905370255),\n (8, 0.16541872759330464),\n (9, 0.19651202376357674),\n (10, 0.3007455041990572),\n (11, 0.3007455041990572),\n (12, 0.3007455041990572)]\n"
],
[
"lda_model = gensim.models.LdaMulticore(bow_corpus, num_topics=10, id2word=dictionary, passes=2, workers=2)",
"_____no_output_____"
],
[
"for idx, topic in lda_model.print_topics(-1):\n print('Topic: {} \\nWords: {}'.format(idx, topic))",
"Topic: 0 \nWords: 0.017*\"lynch\" + 0.013*\"merril\" + 0.012*\"bank\" + 0.010*\"sierrdbo\" + 0.009*\"report\" + 0.009*\"employe\" + 0.009*\"rminoo\" + 0.007*\"expens\" + 0.007*\"secur\" + 0.007*\"compani\"\nTopic: 1 \nWords: 0.142*\"quot\" + 0.021*\"bank\" + 0.009*\"trade\" + 0.007*\"merril\" + 0.007*\"payment\" + 0.007*\"true\" + 0.006*\"lynch\" + 0.006*\"bfix\" + 0.005*\"port\" + 0.005*\"rat\"\nTopic: 2 \nWords: 0.014*\"merril\" + 0.013*\"europ\" + 0.012*\"lynch\" + 0.009*\"trade\" + 0.008*\"bank\" + 0.007*\"financi\" + 0.007*\"price\" + 0.006*\"report\" + 0.006*\"unit\" + 0.006*\"bofa\"\nTopic: 3 \nWords: 0.015*\"merril\" + 0.014*\"lynch\" + 0.010*\"secur\" + 0.009*\"bank\" + 0.009*\"march\" + 0.008*\"flow\" + 0.008*\"rate\" + 0.008*\"real\" + 0.007*\"america\" + 0.007*\"money\"\nTopic: 4 \nWords: 0.026*\"merril\" + 0.026*\"lynch\" + 0.015*\"report\" + 0.010*\"research\" + 0.010*\"rat\" + 0.010*\"bofa\" + 0.009*\"global\" + 0.008*\"bank\" + 0.008*\"financi\" + 0.008*\"secur\"\nTopic: 5 \nWords: 0.048*\"bank\" + 0.019*\"icap\" + 0.015*\"date\" + 0.015*\"unit\" + 0.013*\"rat\" + 0.012*\"state\" + 0.011*\"spot\" + 0.011*\"usdask\" + 0.011*\"usdmid\" + 0.011*\"eurmid\"\nTopic: 6 \nWords: 0.018*\"bank\" + 0.012*\"lynch\" + 0.011*\"merril\" + 0.008*\"global\" + 0.007*\"inflat\" + 0.007*\"price\" + 0.007*\"growth\" + 0.006*\"report\" + 0.006*\"trade\" + 0.006*\"secur\"\nTopic: 7 \nWords: 0.021*\"payment\" + 0.016*\"bank\" + 0.013*\"april\" + 0.013*\"price\" + 0.012*\"merril\" + 0.012*\"rate\" + 0.012*\"lynch\" + 0.009*\"chang\" + 0.008*\"januari\" + 0.008*\"hedg\"\nTopic: 8 \nWords: 0.014*\"lynch\" + 0.014*\"merril\" + 0.011*\"price\" + 0.009*\"risk\" + 0.009*\"growth\" + 0.009*\"expect\" + 0.009*\"research\" + 0.008*\"inflat\" + 0.007*\"report\" + 0.007*\"rat\"\nTopic: 9 \nWords: 0.508*\"quot\" + 0.018*\"instal\" + 0.016*\"bank\" + 0.013*\"fxall\" + 0.007*\"ebsd\" + 0.006*\"bana\" + 0.005*\"merril\" + 0.005*\"lynch\" + 0.004*\"nbkr\" + 0.004*\"leiiva\"\n"
],
[
"df_annotated_final_clean",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7d84b4ac9557f85d165cf11754de5cd24dfa31
| 41,313 |
ipynb
|
Jupyter Notebook
|
MedicaidFeeSchedules/WA/readFeeSchedule.ipynb
|
simonvc17/PublicUseData
|
04e9e69823a111937151813d2e08eba19cdad27b
|
[
"MIT"
] | 19 |
2017-08-11T12:55:50.000Z
|
2021-11-19T13:12:23.000Z
|
MedicaidFeeSchedules/WA/readFeeSchedule.ipynb
|
mrobertson-ipg/PublicUseData
|
04e9e69823a111937151813d2e08eba19cdad27b
|
[
"MIT"
] | 6 |
2015-11-11T18:31:15.000Z
|
2016-07-12T22:13:56.000Z
|
MedicaidFeeSchedules/WA/readFeeSchedule.ipynb
|
mrobertson-ipg/PublicUseData
|
04e9e69823a111937151813d2e08eba19cdad27b
|
[
"MIT"
] | 23 |
2016-05-17T05:14:55.000Z
|
2020-06-18T04:52:35.000Z
| 67.837438 | 747 | 0.452255 |
[
[
[
"# Read Washington Medicaid Fee Schedules\n\nThe Washington state Health Care Authority website for fee schedules is [here](http://www.hca.wa.gov/medicaid/rbrvs/Pages/index.aspx).\n\n* Fee schedules come in Excel format\n* Fee schedules are *usually* biannual (January and July)\n* Publicly available fee schedules go back to January 2011\n\nHowever, Washington's Medicaid fee schedules are a pain in the ass.\nThey are publicly available as Microsoft Excel files but...\n\n* File names are not systematic\n* They do not read directly into R nicely (using either the `readxl` or `xlsx` packages)\n* Data lines start at different rows\n\nAll these issues makes codifying difficult.\nAs a workaround, the following steps were taken.\n\n1. Excel files are saved locally\n2. Excel files are converted to CSV\n3. CSV files are version controlled in this repository (since they are not large)\n4. CSV files are read into R\n\nThe first 3 steps were done manually.\nThe SHA for the commit of the CSV files is 5bde7f3e33e0c83bdace0ed0cf04553a41a8efb1 (5/5/2016).\nStep 4 is below.",
"_____no_output_____"
]
],
[
[
"files <- list.files(file.path(getwd(), \"Data\"))\nfiles\nfiles <- paste(\"Data\", files, sep=\"/\")",
"_____no_output_____"
]
],
[
[
"## Physician-Related/Professional Services",
"_____no_output_____"
]
],
[
[
"library(data.table)\nreadFS <- function (f, skip) {\n require(data.table, quietly=TRUE)\n for (i in 11:16) {if (grepl(sprintf(\"%d\\\\.csv\", i), f)) {year <- as.numeric(sprintf(\"20%d\", i))}}\n for (i in 1:12) {\n monname <- format(as.Date(sprintf(\"%d-%d-01\", year, i)), format=\"%B\")\n if (grepl(sprintf(\"_%02d\", i), f) | grepl(tolower(monname), f, ignore.case=TRUE)) {\n mm <- i\n }\n }\n colClasses <- rep(\"character\", 9)\n D <- data.table(read.csv(f, header=FALSE, colClasses=colClasses, skip=skip, na.strings=c(\"\"), strip.white=TRUE))\n old <- names(D)\n keep <- c(\"code_status_indicator\",\n \"code\",\n \"mod\",\n \"nfs_maximum_allowable\",\n \"fs_maximum_allowable\",\n \"pa_required\",\n \"global_days\",\n \"comments\")\n if (length(old) > length(keep)) {new <- c(keep, old[(length(keep) + 1):length(old)])}\n else {new <- keep}\n setnames(D, old, new)\n D <- D[, effective_date := as.Date(sprintf(\"%d-%d-01\", year, mm))]\n D[, c(keep, \"effective_date\"), with=FALSE]\n}",
"_____no_output_____"
],
[
"fs <- rbindlist(list(readFS(file.path(getwd(), \"Data/HCA_PREOH_January_1_2013.csv\"), 9),\n readFS(file.path(getwd(), \"Data/physician_010114.csv\"), 9),\n readFS(file.path(getwd(), \"Data/physician_010115.csv\"), 9),\n readFS(file.path(getwd(), \"Data/physician_010116.csv\"), 10),\n readFS(file.path(getwd(), \"Data/physician_040115.csv\"), 9),\n readFS(file.path(getwd(), \"Data/physician_040116.csv\"), 10),\n readFS(file.path(getwd(), \"Data/physician_070114.csv\"), 9),\n readFS(file.path(getwd(), \"Data/physician_070115.csv\"), 10),\n readFS(file.path(getwd(), \"Data/physician_100115.csv\"), 10),\n readFS(file.path(getwd(), \"Data/preoh_010112.csv\"), 6),\n readFS(file.path(getwd(), \"Data/preoh_01012011.csv\"), 6),\n readFS(file.path(getwd(), \"Data/preoh_070112.csv\"), 9),\n readFS(file.path(getwd(), \"Data/preoh_070113.csv\"), 9),\n readFS(file.path(getwd(), \"Data/preoh_07012011.csv\"), 6)))\nstr(fs)",
"Classes 'data.table' and 'data.frame':\t164912 obs. of 9 variables:\n $ code_status_indicator: chr NA NA NA NA ...\n $ code : chr \"00100\" \"00102\" \"00103\" \"00104\" ...\n $ mod : chr NA NA NA NA ...\n $ nfs_maximum_allowable: chr \"5 Base\" \"6 Base\" \"5 Base\" \"4 Base\" ...\n $ fs_maximum_allowable : chr \"5 Base\" \"6 Base\" \"5 Base\" \"4 Base\" ...\n $ pa_required : chr NA NA NA NA ...\n $ global_days : chr \"000\" \"000\" \"000\" \"000\" ...\n $ comments : chr \"N\" \"N\" \"N\" \"N\" ...\n $ effective_date : Date, format: \"2013-01-01\" \"2013-01-01\" ...\n - attr(*, \".internal.selfref\")=<externalptr> \n"
],
[
"fs[, .N, effective_date][order(effective_date)]",
"_____no_output_____"
],
[
"head(fs)\ntail(fs)",
"_____no_output_____"
]
],
[
[
"Rename object",
"_____no_output_____"
]
],
[
[
"fsPhysician <- fs",
"_____no_output_____"
]
],
[
[
"## Ambulance Transportation",
"_____no_output_____"
]
],
[
[
"library(data.table)\nf <- file.path(getwd(), \"Data/ambulance_transportation_022016.csv\")\nD <- data.table(read.csv(f, header=TRUE, na.strings=c(\"\"), strip.white=TRUE, stringsAsFactors=FALSE))\nold <- names(D)\nnew <- c(\"code_status_indicator\",\n \"code\",\n \"description\",\n \"fs_maximum_allowable\",\n \"limits\")\nsetnames(D, old, new)\nD <- D[, fs_maximum_allowable := as.numeric(gsub(\"[^0-9\\\\.]\", \"\", fs_maximum_allowable))]\nD <- D[, effective_date := as.Date(\"2006-07-01\")]\nstr(D)\nD",
"Classes 'data.table' and 'data.frame':\t14 obs. of 6 variables:\n $ code_status_indicator: logi NA NA NA NA NA NA ...\n $ code : chr \"A0430\" \"A0431\" \"A0435\" \"A0436\" ...\n $ description : chr \"Ambulance service, conventional air services, transport, one way (fixed wing)\" \"Ambulance service, conventional air services, transport, one way (rotary wing)\" \"Fixed wing air mileage, per statute mile\" \"Rotary wing air mileage, per statute mile\" ...\n $ fs_maximum_allowable : num 910.8 804.5 5.5 13.3 115.3 ...\n $ limits : chr \"Per client transported.\" \"Per client transported.\" \"One way, per flight, equally divided by the number of clients transported.\" \"One way, per flight, equally divided by the number of clients transported.\" ...\n $ effective_date : Date, format: \"2006-07-01\" \"2006-07-01\" ...\n - attr(*, \".internal.selfref\")=<externalptr> \n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7d865e18d4a0765ea9560c8dd4f6d63bfd833b
| 982,708 |
ipynb
|
Jupyter Notebook
|
Lesson 6: Convolutional Neural Networks/5_cifar10_cnn_exercise.ipynb
|
makeithappenlois/Udacity-AI
|
c82c7abaf179730740fecae76d388b14cbb3917c
|
[
"MIT"
] | 2 |
2020-01-03T17:36:15.000Z
|
2020-01-13T18:24:14.000Z
|
Lesson 6: Convolutional Neural Networks/5_cifar10_cnn_exercise.ipynb
|
makeithappenlois/Udacity-AI
|
c82c7abaf179730740fecae76d388b14cbb3917c
|
[
"MIT"
] | null | null | null |
Lesson 6: Convolutional Neural Networks/5_cifar10_cnn_exercise.ipynb
|
makeithappenlois/Udacity-AI
|
c82c7abaf179730740fecae76d388b14cbb3917c
|
[
"MIT"
] | 2 |
2020-01-03T16:30:16.000Z
|
2020-01-08T15:03:14.000Z
| 1,196.964677 | 714,050 | 0.939394 |
[
[
[
"# Convolutional Neural Networks\n---\nIn this notebook, we train a **CNN** to classify images from the CIFAR-10 database.\n\nThe images in this database are small color images that fall into one of ten classes; some example images are pictured below.\n\n\n",
"_____no_output_____"
],
[
"### Test for [CUDA](http://pytorch.org/docs/stable/cuda.html)\n\nSince these are larger (32x32x3) images, it may prove useful to speed up your training time by using a GPU. CUDA is a parallel computing platform and CUDA Tensors are the same as typical Tensors, only they utilize GPU's for computation.",
"_____no_output_____"
]
],
[
[
"import torch\nimport numpy as np\n\n# check if CUDA is available\ntrain_on_gpu = torch.cuda.is_available()\n\nif not train_on_gpu:\n print('CUDA is not available. Training on CPU ...')\nelse:\n print('CUDA is available! Training on GPU ...')",
"CUDA is available! Training on GPU ...\n"
]
],
[
[
"---\n## Load the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)\n\nDownloading may take a minute. We load in the training and test data, split the training data into a training and validation set, then create DataLoaders for each of these sets of data.",
"_____no_output_____"
]
],
[
[
"from torchvision import datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\n# number of subprocesses to use for data loading\nnum_workers = 0\n# how many samples per batch to load\nbatch_size = 20\n# percentage of training set to use as validation\nvalid_size = 0.2\n\n# convert data to a normalized torch.FloatTensor\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n\n# choose the training and test datasets\ntrain_data = datasets.CIFAR10('data', train=True,\n download=True, transform=transform)\ntest_data = datasets.CIFAR10('data', train=False,\n download=True, transform=transform)\n\n# obtain training indices that will be used for validation\nnum_train = len(train_data)\nindices = list(range(num_train))\nnp.random.shuffle(indices)\nsplit = int(np.floor(valid_size * num_train))\ntrain_idx, valid_idx = indices[split:], indices[:split]\n\n# define samplers for obtaining training and validation batches\ntrain_sampler = SubsetRandomSampler(train_idx)\nvalid_sampler = SubsetRandomSampler(valid_idx)\n\n# prepare data loaders (combine dataset and sampler)\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,\n sampler=train_sampler, num_workers=num_workers)\nvalid_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, \n sampler=valid_sampler, num_workers=num_workers)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, \n num_workers=num_workers)\n\n# specify the image classes\nclasses = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck']",
"\r0it [00:00, ?it/s]"
]
],
[
[
"### Visualize a Batch of Training Data",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n\n# helper function to un-normalize and display an image\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n plt.imshow(np.transpose(img, (1, 2, 0))) # convert from Tensor image",
"_____no_output_____"
],
[
"# obtain one batch of training images\ndataiter = iter(train_loader)\nimages, labels = dataiter.next()\nimages = images.numpy() # convert images to numpy for display\n\n# plot the images in the batch, along with the corresponding labels\nfig = plt.figure(figsize=(25, 4))\n# display 20 images\nfor idx in np.arange(20):\n ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n imshow(images[idx])\n ax.set_title(classes[labels[idx]])",
"_____no_output_____"
]
],
[
[
"### View an Image in More Detail\n\nHere, we look at the normalized red, green, and blue (RGB) color channels as three separate, grayscale intensity images.",
"_____no_output_____"
]
],
[
[
"rgb_img = np.squeeze(images[3])\nchannels = ['red channel', 'green channel', 'blue channel']\n\nfig = plt.figure(figsize = (36, 36)) \nfor idx in np.arange(rgb_img.shape[0]):\n ax = fig.add_subplot(1, 3, idx + 1)\n img = rgb_img[idx]\n ax.imshow(img, cmap='gray')\n ax.set_title(channels[idx])\n width, height = img.shape\n thresh = img.max()/2.5\n for x in range(width):\n for y in range(height):\n val = round(img[x][y],2) if img[x][y] !=0 else 0\n ax.annotate(str(val), xy=(y,x),\n horizontalalignment='center',\n verticalalignment='center', size=8,\n color='white' if img[x][y]<thresh else 'black')",
"_____no_output_____"
]
],
[
[
"---\n## Define the Network [Architecture](http://pytorch.org/docs/stable/nn.html)\n\nThis time, you'll define a CNN architecture. Instead of an MLP, which used linear, fully-connected layers, you'll use the following:\n* [Convolutional layers](https://pytorch.org/docs/stable/nn.html#conv2d), which can be thought of as stack of filtered images.\n* [Maxpooling layers](https://pytorch.org/docs/stable/nn.html#maxpool2d), which reduce the x-y size of an input, keeping only the most _active_ pixels from the previous layer.\n* The usual Linear + Dropout layers to avoid overfitting and produce a 10-dim output.\n\nA network with 2 convolutional layers is shown in the image below and in the code, and you've been given starter code with one convolutional and one maxpooling layer.\n\n\n\n\n#### TODO: Define a model with multiple convolutional layers, and define the feedforward network behavior.\n\nThe more convolutional layers you include, the more complex patterns in color and shape a model can detect. It's suggested that your final model include 2 or 3 convolutional layers as well as linear layers + dropout in between to avoid overfitting. \n\nIt's good practice to look at existing research and implementations of related models as a starting point for defining your own models. You may find it useful to look at [this PyTorch classification example](https://github.com/pytorch/tutorials/blob/master/beginner_source/blitz/cifar10_tutorial.py) or [this, more complex Keras example](https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py) to help decide on a final structure.\n\n#### Output volume for a convolutional layer\n\nTo compute the output size of a given convolutional layer we can perform the following calculation (taken from [Stanford's cs231n course](http://cs231n.github.io/convolutional-networks/#layers)):\n> We can compute the spatial size of the output volume as a function of the input volume size (W), the kernel/filter size (F), the stride with which they are applied (S), and the amount of zero padding used (P) on the border. The correct formula for calculating how many neurons define the output_W is given by `(W−F+2P)/S+1`. \n\nFor example for a 7x7 input and a 3x3 filter with stride 1 and pad 0 we would get a 5x5 output. With stride 2 we would get a 3x3 output.",
"_____no_output_____"
]
],
[
[
"import torch.nn as nn\nimport torch.nn.functional as F\n\n# define the CNN architecture\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n # convolutional layer (sees 32x32x3 image tensor)\n self.conv1 = nn.Conv2d(3, 16, 3, padding=1)\n # convolutional layer (sees 16x16x16 tensor)\n self.conv2 = nn.Conv2d(16, 32, 3, padding=1)\n self.pool = nn.MaxPool2d(2, 2)\n # convolutional layer (sees 8x8x32 tensor)\n self.conv3 = nn.Conv2d(32, 64, 3, padding=1)\n # max pooling layer\n self.pool = nn.MaxPool2d(2, 2)\n # linear layer (64 * 4 * 4 -> 500)\n self.fc1 = nn.Linear(64 * 4 * 4, 500)\n # linear layer (500 -> 10)\n self.fc2 = nn.Linear(500, 10)\n # dropout layer (p=0.25)\n self.dropout = nn.Dropout(0.25)\n\n def forward(self, x):\n # add sequence of convolutional and max pooling layers\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = self.pool(F.relu(self.conv3(x)))\n # flatten image input\n x = x.view(-1, 64 * 4 * 4)\n # add dropout layer\n x = self.dropout(x)\n # add 1st hidden layer, with relu activation function\n x = F.relu(self.fc1(x))\n # add dropout layer\n x = self.dropout(x)\n # add 2nd hidden layer, with relu activation function\n x = self.fc2(x)\n return x\n\n# create a complete CNN\nmodel = Net()\nprint(model)\n\n# move tensors to GPU if CUDA is available\nif train_on_gpu:\n model.cuda()",
"Net(\n (conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (conv2): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n (conv3): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (fc1): Linear(in_features=1024, out_features=500, bias=True)\n (fc2): Linear(in_features=500, out_features=10, bias=True)\n (dropout): Dropout(p=0.25, inplace=False)\n)\n"
]
],
[
[
"### Specify [Loss Function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [Optimizer](http://pytorch.org/docs/stable/optim.html)\n\nDecide on a loss and optimization function that is best suited for this classification task. The linked code examples from above, may be a good starting point; [this PyTorch classification example](https://github.com/pytorch/tutorials/blob/master/beginner_source/blitz/cifar10_tutorial.py) or [this, more complex Keras example](https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py). Pay close attention to the value for **learning rate** as this value determines how your model converges to a small error.\n\n#### TODO: Define the loss and optimizer and see how these choices change the loss over time.",
"_____no_output_____"
]
],
[
[
"import torch.optim as optim\n\n# specify loss function\ncriterion = torch.nn.CrossEntropyLoss()\n\n# specify optimizer\noptimizer = optim.Adam(model.parameters(), lr=0.005)",
"_____no_output_____"
]
],
[
[
"---\n## Train the Network\n\nRemember to look at how the training and validation loss decreases over time; if the validation loss ever increases it indicates possible overfitting.",
"_____no_output_____"
]
],
[
[
"# number of epochs to train the model\nn_epochs = 15 # you may increase this number to train a final model\n\nvalid_loss_min = np.Inf # track change in validation loss\ntrain_losses, test_losses = [], []\n\nfor epoch in range(1, n_epochs+1):\n\n # keep track of training and validation loss\n train_loss = 0.0\n valid_loss = 0.0\n \n ###################\n # train the model #\n ###################\n model.train()\n for data, target in train_loader:\n # move tensors to GPU if CUDA is available\n if train_on_gpu:\n data, target = data.cuda(), target.cuda()\n # clear the gradients of all optimized variables\n optimizer.zero_grad()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the batch loss\n loss = criterion(output, target)\n # backward pass: compute gradient of the loss with respect to model parameters\n loss.backward()\n # perform a single optimization step (parameter update)\n optimizer.step()\n # update training loss\n train_loss += loss.item()*data.size(0)\n \n ###################### \n # validate the model #\n ######################\n model.eval()\n for data, target in valid_loader:\n # move tensors to GPU if CUDA is available\n if train_on_gpu:\n data, target = data.cuda(), target.cuda()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the batch loss\n loss = criterion(output, target)\n # update average validation loss \n valid_loss += loss.item()*data.size(0)\n \n # calculate average losses\n train_loss = train_loss/len(train_loader.dataset)\n valid_loss = valid_loss/len(valid_loader.dataset)\n\n train_losses.append(train_loss/len(train_loader))\n test_losses.append(test_loss/len(test_loader))\n \n # print training/validation statistics \n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n epoch, train_loss, valid_loss))\n \n # save model if validation loss has decreased\n if valid_loss <= valid_loss_min:\n print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format(\n valid_loss_min,\n valid_loss))\n torch.save(model.state_dict(), 'model_cifar.pt')\n valid_loss_min = valid_loss",
"Epoch: 1 \tTraining Loss: 1.171979 \tValidation Loss: 0.274696\nValidation loss decreased (inf --> 0.274696). Saving model ...\nEpoch: 2 \tTraining Loss: 1.180991 \tValidation Loss: 0.272276\nValidation loss decreased (0.274696 --> 0.272276). Saving model ...\nEpoch: 3 \tTraining Loss: 1.160663 \tValidation Loss: 0.275070\nEpoch: 4 \tTraining Loss: 1.172775 \tValidation Loss: 0.275793\nEpoch: 5 \tTraining Loss: 1.169148 \tValidation Loss: 0.270886\nValidation loss decreased (0.272276 --> 0.270886). Saving model ...\nEpoch: 6 \tTraining Loss: 1.171081 \tValidation Loss: 0.286211\nEpoch: 7 \tTraining Loss: 1.170156 \tValidation Loss: 0.282326\nEpoch: 8 \tTraining Loss: 1.165546 \tValidation Loss: 0.270570\nValidation loss decreased (0.270886 --> 0.270570). Saving model ...\nEpoch: 9 \tTraining Loss: 1.158709 \tValidation Loss: 0.274183\nEpoch: 10 \tTraining Loss: 1.172803 \tValidation Loss: 0.281134\nEpoch: 11 \tTraining Loss: 1.178599 \tValidation Loss: 0.288189\nEpoch: 12 \tTraining Loss: 1.174456 \tValidation Loss: 0.274868\nEpoch: 13 \tTraining Loss: 1.164091 \tValidation Loss: 0.266444\nValidation loss decreased (0.270570 --> 0.266444). Saving model ...\nEpoch: 14 \tTraining Loss: 1.173492 \tValidation Loss: 0.267461\nEpoch: 15 \tTraining Loss: 1.173499 \tValidation Loss: 0.283879\n"
]
],
[
[
"### Load the Model with the Lowest Validation Loss",
"_____no_output_____"
]
],
[
[
"model.load_state_dict(torch.load('model_cifar.pt'))",
"_____no_output_____"
]
],
[
[
"---\n## Test the Trained Network\n\nTest your trained model on previously unseen data! A \"good\" result will be a CNN that gets around 70% (or more, try your best!) accuracy on these test images.",
"_____no_output_____"
]
],
[
[
"# track test loss\ntest_loss = 0.0\nclass_correct = list(0. for i in range(10))\nclass_total = list(0. for i in range(10))\n\nmodel.eval()\n# iterate over test data\nfor data, target in test_loader:\n # move tensors to GPU if CUDA is available\n if train_on_gpu:\n data, target = data.cuda(), target.cuda()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the batch loss\n loss = criterion(output, target)\n # update test loss \n test_loss += loss.item()*data.size(0)\n # convert output probabilities to predicted class\n _, pred = torch.max(output, 1) \n # compare predictions to true label\n correct_tensor = pred.eq(target.data.view_as(pred))\n correct = np.squeeze(correct_tensor.numpy()) if not train_on_gpu else np.squeeze(correct_tensor.cpu().numpy())\n # calculate test accuracy for each object class\n for i in range(batch_size):\n label = target.data[i]\n class_correct[label] += correct[i].item()\n class_total[label] += 1\n\n# average test loss\ntest_loss = test_loss/len(test_loader.dataset)\nprint('Test Loss: {:.6f}\\n'.format(test_loss))\n\nfor i in range(10):\n if class_total[i] > 0:\n print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (\n classes[i], 100 * class_correct[i] / class_total[i],\n np.sum(class_correct[i]), np.sum(class_total[i])))\n else:\n print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i]))\n\nprint('\\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % (\n 100. * np.sum(class_correct) / np.sum(class_total),\n np.sum(class_correct), np.sum(class_total)))",
"Test Loss: 1.349731\n\nTest Accuracy of airplane: 64% (644/1000)\nTest Accuracy of automobile: 65% (657/1000)\nTest Accuracy of bird: 24% (242/1000)\nTest Accuracy of cat: 30% (300/1000)\nTest Accuracy of deer: 37% (379/1000)\nTest Accuracy of dog: 52% (523/1000)\nTest Accuracy of frog: 71% (712/1000)\nTest Accuracy of horse: 60% (608/1000)\nTest Accuracy of ship: 48% (484/1000)\nTest Accuracy of truck: 64% (641/1000)\n\nTest Accuracy (Overall): 51% (5190/10000)\n"
]
],
[
[
"### Question: What are your model's weaknesses and how might they be improved?",
"_____no_output_____"
],
[
"**Answer**: (double-click to edit and add an answer)",
"_____no_output_____"
],
[
"### Visualize Sample Test Results",
"_____no_output_____"
]
],
[
[
"# obtain one batch of test images\ndataiter = iter(test_loader)\nimages, labels = dataiter.next()\nimages.numpy()\n\n# move model inputs to cuda, if GPU available\nif train_on_gpu:\n images = images.cuda()\n\n# get sample outputs\noutput = model(images)\n# convert output probabilities to predicted class\n_, preds_tensor = torch.max(output, 1)\npreds = np.squeeze(preds_tensor.numpy()) if not train_on_gpu else np.squeeze(preds_tensor.cpu().numpy())\n\n# plot the images in the batch, along with predicted and true labels\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(20):\n ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n imshow(images.cpu()[idx])\n ax.set_title(\"{} ({})\".format(classes[preds[idx]], classes[labels[idx]]),\n color=(\"green\" if preds[idx]==labels[idx].item() else \"red\"))",
"_____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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cb7d88b9a23e43b856c737c5c6da3ad58256bd39
| 24,756 |
ipynb
|
Jupyter Notebook
|
ml/google_colab_spark_catboost.ipynb
|
GrishenkovP/Spark
|
c7c84ff485b657484c0a71929f4ee5a725e92172
|
[
"MIT"
] | 1 |
2022-01-20T13:09:26.000Z
|
2022-01-20T13:09:26.000Z
|
ml/google_colab_spark_catboost.ipynb
|
GrishenkovP/Spark
|
c7c84ff485b657484c0a71929f4ee5a725e92172
|
[
"MIT"
] | null | null | null |
ml/google_colab_spark_catboost.ipynb
|
GrishenkovP/Spark
|
c7c84ff485b657484c0a71929f4ee5a725e92172
|
[
"MIT"
] | null | null | null | 33.184987 | 167 | 0.406366 |
[
[
[
"# **CatBoost**",
"_____no_output_____"
],
[
"### За основу взят ноутбук из вебинара \"CatBoost на больших данных\", канал Karpov.Courses, ведущий вебинара Александр Савченко",
"_____no_output_____"
],
[
"Репозиторий с исходником: https://github.com/AlexKbit/pyspark-catboost-example",
"_____no_output_____"
]
],
[
[
"%%capture\n!pip install pyspark==3.0.3",
"_____no_output_____"
],
[
"from pyspark.ml import Pipeline\nfrom pyspark.ml.feature import VectorAssembler, StringIndexer\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import DataFrame\nfrom pyspark.sql.functions import col\nfrom pyspark.sql.types import StructField, StructType",
"_____no_output_____"
],
[
"spark = SparkSession.builder\\\n .master('local[*]')\\\n .appName('CatBoostWithSpark')\\\n .config(\"spark.jars.packages\", \"ai.catboost:catboost-spark_3.0_2.12:1.0.3\")\\\n .config(\"spark.executor.cores\", \"2\")\\\n .config(\"spark.task.cpus\", \"2\")\\\n .config(\"spark.driver.memory\", \"2g\")\\\n .config(\"spark.driver.memoryOverhead\", \"2g\")\\\n .config(\"spark.executor.memory\", \"2g\")\\\n .config(\"spark.executor.memoryOverhead\", \"2g\")\\\n .getOrCreate()",
"_____no_output_____"
],
[
"spark",
"_____no_output_____"
],
[
"import catboost_spark",
"_____no_output_____"
],
[
"schema_dataset = \"col1 String, col2 String, col3 Double, col4 Double, col5 Double, target Integer\"\ndf = spark.read.csv('/content/data.csv',sep=',',header=True,schema = schema_dataset)",
"_____no_output_____"
],
[
"df.printSchema()",
"root\n |-- col1: string (nullable = true)\n |-- col2: string (nullable = true)\n |-- col3: double (nullable = true)\n |-- col4: double (nullable = true)\n |-- col5: double (nullable = true)\n |-- target: integer (nullable = true)\n\n"
],
[
"print(df.describe().show())",
"+-------+----+----+------------------+------------------+-----------------+------------------+\n|summary|col1|col2| col3| col4| col5| target|\n+-------+----+----+------------------+------------------+-----------------+------------------+\n| count| 999| 999| 999| 999| 999| 999|\n| mean|null|null| 6.126728018535534|3091.0939393577505| 315.711484855864|0.4954954954954955|\n| stddev|null|null|0.5898659455919512| 6063.724047846411|248.0598507266117|0.5002301371468432|\n| min| a| a| 4.605170186| 2.718281828| 0.010761534| 0|\n| max| z| z| 6.907755279| 22026.46579| 984.2199136| 1|\n+-------+----+----+------------------+------------------+-----------------+------------------+\n\nNone\n"
],
[
"print(df.show(7))",
"+----+----+-----------+-----------+-----------+------+\n|col1|col2| col3| col4| col5|target|\n+----+----+-----------+-----------+-----------+------+\n| o| r|6.084499413|2980.957987| 1.737842| 0|\n| z| x|6.553933404|8103.083928|2.884142703| 0|\n| w| w|4.779123493|22026.46579|0.035646382| 0|\n| t| w|6.663132696|148.4131591|4.600071127| 0|\n| p| s|6.508769137|7.389056099|1.625782932| 1|\n| u| r|5.860786223|54.59815003|6.712529775| 1|\n| r| a|6.708084084|2980.957987|7.360113804| 0|\n+----+----+-----------+-----------+-----------+------+\nonly showing top 7 rows\n\nNone\n"
],
[
"TARGET_LABEL = 'target'",
"_____no_output_____"
],
[
"evaluator = MulticlassClassificationEvaluator(\n labelCol=TARGET_LABEL, \n predictionCol=\"prediction\", \n metricName='f1')",
"_____no_output_____"
],
[
"train_df, test_df = df.randomSplit([0.75, 0.25])",
"_____no_output_____"
]
],
[
[
"### Train CatBoost with Pool",
"_____no_output_____"
]
],
[
[
"col1_indexer = StringIndexer(inputCol='col1', outputCol=\"col1_index\")\ncol2_indexer = StringIndexer(inputCol='col2', outputCol=\"col2_index\")\nfeatures = [\"col1_index\", \"col2_index\", \"col3\", \"col4\", \"col5\"]\nassembler = VectorAssembler(inputCols=features, outputCol='features')",
"_____no_output_____"
],
[
"def prepare_vector(df: DataFrame)-> DataFrame:\n result_df = col1_indexer.fit(df).transform(df)\n result_df = col2_indexer.fit(result_df).transform(result_df)\n result_df = assembler.transform(result_df)\n return result_df",
"_____no_output_____"
],
[
"train = prepare_vector(train_df)\ntest = prepare_vector(test_df)",
"_____no_output_____"
],
[
"print(train.show(7))",
"+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+\n|col1|col2| col3| col4| col5|target|col1_index|col2_index| features|\n+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+\n| a| a|5.129898715|20.08553692|272.5829356| 1| 8.0| 23.0|[8.0,23.0,5.12989...|\n| a| b|4.804021045|403.4287935| 888.578495| 0| 8.0| 4.0|[8.0,4.0,4.804021...|\n| a| b|5.446737372|54.59815003|537.8494671| 0| 8.0| 4.0|[8.0,4.0,5.446737...|\n| a| b|6.401917197|148.4131591|101.2690374| 0| 8.0| 4.0|[8.0,4.0,6.401917...|\n| a| b|6.883462586|1096.633158|670.3254037| 0| 8.0| 4.0|[8.0,4.0,6.883462...|\n| a| e| 6.03787092|20.08553692|464.8122752| 0| 8.0| 12.0|[8.0,12.0,6.03787...|\n| a| f|5.407171771|20.08553692|390.9714078| 1| 8.0| 2.0|[8.0,2.0,5.407171...|\n+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+\nonly showing top 7 rows\n\nNone\n"
],
[
"train_pool = catboost_spark.Pool(train.select(['features', TARGET_LABEL]))\ntrain_pool.setLabelCol(TARGET_LABEL)\ntrain_pool.setFeaturesCol('features')",
"_____no_output_____"
],
[
"classifier = catboost_spark.CatBoostClassifier(featuresCol='features', labelCol=TARGET_LABEL)\nclassifier.setIterations(50)\nclassifier.setDepth(5)",
"_____no_output_____"
],
[
"model = classifier.fit(train_pool)\npredict = model.transform(test)\nprint(f'Model F1 = {evaluator.evaluate(predict)}')",
"Model F1 = 0.5133384417477316\n"
],
[
"print(predict.show(7))",
"+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+--------------------+--------------------+----------+\n|col1|col2| col3| col4| col5|target|col1_index|col2_index| features| rawPrediction| probability|prediction|\n+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+--------------------+--------------------+----------+\n| a| a|6.646390515|148.4131591|157.7424017| 1| 4.0| 2.0|[4.0,2.0,6.646390...|[-0.0039150571071...|[0.49804248144779...| 1.0|\n| a| c|5.950642553|54.59815003| 6.21892211| 1| 4.0| 4.0|[4.0,4.0,5.950642...|[0.04040159315686...|[0.52018981257247...| 0.0|\n| a| g|6.436150368|148.4131591|56.60413081| 0| 4.0| 18.0|[4.0,18.0,6.43615...|[0.01749729007042...|[0.50874775233026...| 0.0|\n| a| g|6.864847778|2980.957987|389.8896251| 1| 4.0| 18.0|[4.0,18.0,6.86484...|[-0.1194541418324...|[0.44055540457489...| 1.0|\n| a| o|6.364750757|20.08553692|0.010761534| 1| 4.0| 11.0|[4.0,11.0,6.36475...|[0.05392532673939...|[0.52693655845702...| 0.0|\n| a| p|5.505331536|7.389056099| 307.215333| 0| 4.0| 6.0|[4.0,6.0,5.505331...|[-0.0414205705856...|[0.47930155054604...| 1.0|\n| a| q|6.440946541|403.4287935|167.3800662| 0| 4.0| 22.0|[4.0,22.0,6.44094...|[0.09141613676747...|[0.54558116649773...| 0.0|\n+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+--------------------+--------------------+----------+\nonly showing top 7 rows\n\nNone\n"
],
[
"model.saveNativeModel('catboost_native')",
"_____no_output_____"
],
[
"model.write().overwrite().save('catboost_spark')",
"_____no_output_____"
]
],
[
[
"### Pipeline model with CatBoost",
"_____no_output_____"
]
],
[
[
"col1_indexer = StringIndexer(inputCol='col1', outputCol=\"col1_index\")\ncol2_indexer = StringIndexer(inputCol='col2', outputCol=\"col2_index\")\nfeatures = [\"col1_index\", \"col2_index\", \"col3\", \"col4\", \"col5\"]\nassembler = VectorAssembler(inputCols=features, outputCol='features')",
"_____no_output_____"
],
[
"classifier = catboost_spark.CatBoostClassifier(featuresCol='features', labelCol=TARGET_LABEL)\nclassifier.setIterations(50)\nclassifier.setDepth(5)",
"_____no_output_____"
],
[
"pipeline = Pipeline(stages=[col1_indexer, col2_indexer, assembler, classifier])",
"_____no_output_____"
],
[
"p_model = pipeline.fit(train_df)",
"_____no_output_____"
],
[
"print(test_df.show(7))",
"+----+----+-----------+-----------+-----------+------+\n|col1|col2| col3| col4| col5|target|\n+----+----+-----------+-----------+-----------+------+\n| a| a|6.646390515|148.4131591|157.7424017| 1|\n| a| c|5.950642553|54.59815003| 6.21892211| 1|\n| a| g|6.436150368|148.4131591|56.60413081| 0|\n| a| g|6.864847778|2980.957987|389.8896251| 1|\n| a| o|6.364750757|20.08553692|0.010761534| 1|\n| a| p|5.505331536|7.389056099| 307.215333| 0|\n| a| q|6.440946541|403.4287935|167.3800662| 0|\n+----+----+-----------+-----------+-----------+------+\nonly showing top 7 rows\n\nNone\n"
],
[
"predictions = p_model.transform(test_df)",
"_____no_output_____"
],
[
"print(predictions.show(7))",
"+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+--------------------+--------------------+----------+\n|col1|col2| col3| col4| col5|target|col1_index|col2_index| features| rawPrediction| probability|prediction|\n+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+--------------------+--------------------+----------+\n| a| a|6.646390515|148.4131591|157.7424017| 1| 8.0| 23.0|[8.0,23.0,6.64639...|[0.22310705457457...|[0.60973872836073...| 0.0|\n| a| c|5.950642553|54.59815003| 6.21892211| 1| 8.0| 5.0|[8.0,5.0,5.950642...|[0.28321941745872...|[0.63794104949937...| 0.0|\n| a| g|6.436150368|148.4131591|56.60413081| 0| 8.0| 13.0|[8.0,13.0,6.43615...|[0.26712929527296...|[0.63047581171129...| 0.0|\n| a| g|6.864847778|2980.957987|389.8896251| 1| 8.0| 13.0|[8.0,13.0,6.86484...|[-0.0924605930198...|[0.45390099488431...| 1.0|\n| a| o|6.364750757|20.08553692|0.010761534| 1| 8.0| 1.0|[8.0,1.0,6.364750...|[0.23582041567198...|[0.61577204556464...| 0.0|\n| a| p|5.505331536|7.389056099| 307.215333| 0| 8.0| 16.0|[8.0,16.0,5.50533...|[0.16208223154408...|[0.58033882709176...| 0.0|\n| a| q|6.440946541|403.4287935|167.3800662| 0| 8.0| 21.0|[8.0,21.0,6.44094...|[0.20460077252328...|[0.60089640888479...| 0.0|\n+----+----+-----------+-----------+-----------+------+----------+----------+--------------------+--------------------+--------------------+----------+\nonly showing top 7 rows\n\nNone\n"
],
[
"print(f'Model F1 = {evaluator.evaluate(predictions)}')",
"Model F1 = 0.521987688164286\n"
],
[
"type(p_model)",
"_____no_output_____"
],
[
"p_model.write().overwrite().save('catboost_pipeline')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7d8a4361dbd1b3a3c22125f3edde8d53b993ee
| 13,692 |
ipynb
|
Jupyter Notebook
|
neurons-fermi-math.ipynb
|
RyanPersson/neural-networks-fermi-math
|
e14da9d50c4da5a7272eb9121497ad9575f2ffa9
|
[
"MIT"
] | null | null | null |
neurons-fermi-math.ipynb
|
RyanPersson/neural-networks-fermi-math
|
e14da9d50c4da5a7272eb9121497ad9575f2ffa9
|
[
"MIT"
] | null | null | null |
neurons-fermi-math.ipynb
|
RyanPersson/neural-networks-fermi-math
|
e14da9d50c4da5a7272eb9121497ad9575f2ffa9
|
[
"MIT"
] | null | null | null | 36.414894 | 470 | 0.644683 |
[
[
[
"import numpy as np\nfrom numpy import format_float_scientific\n",
"_____no_output_____"
],
[
"# prints large floats in readable format.\ndef sci(number):\n print('{:0.3e}'.format(number))",
"_____no_output_____"
]
],
[
[
"### Synapse Firings as FLOPS",
"_____no_output_____"
],
[
"The brain is a massive computational substrate that performs countless computations per second.\nMany people have speculated about the raw computational power of the brain in terms of actual bit calculations. But I believe a better analogy, would be computation in terms of FLOPS.",
"_____no_output_____"
],
[
"This is because of the way we run digital neural networks.\n\nWe run large amounts of matrix computations in which float vector *inputs* are multiplied by *weight* matrices of floats, to produce a vector *output* of floats, which is then ran through an *activation function*.\n\nEach input element in a vector, being multiplied by a weight in the matrix, is analagous to an impulse firing into a synapse, from a neuron.\nEach element in the input & output vectors, can be thought of as individual neurons, and each weight in the matrix, is the connection between one input neuron and another output neuron. So each floating point multiplication of an input, by a weight, is analogous to the firing of a synapse from one neuron to another. \n\nThis allows us to actually compare quantitatively, the computational power of biological and digital networks, if we weigh a synapse firing, as the ONE floating point operation which simulates/represents it in a digital neural network.\n\n#### This idea leads to some interesting math below:",
"_____no_output_____"
],
[
"There are ~85 billion *neurons_per_brain*, $( \\frac{neurons}{brain} )$",
"_____no_output_____"
]
],
[
[
"neurons_per_brain = 85*1e9\nsci(neurons_per_brain)",
"8.500e+10\n"
]
],
[
[
"There are ~7000 *synapses_per_neuron* $ (\\frac{synapse}{neuron}) $",
"_____no_output_____"
]
],
[
[
"synapses_per_neuron = 7000",
"_____no_output_____"
]
],
[
[
"The number of synapses *synapses_per_brain* is therefore 85 billion x 7000 = 5.95e14 synapes.",
"_____no_output_____"
]
],
[
[
"synapses_per_brain = neurons_per_brain*synapses_per_neuron\nsci(synapses_per_brain)",
"5.950e+14\n"
]
],
[
[
"According to [the best research I've found](https://aiimpacts.org/rate-of-neuron-firing/#:~:text='But%20generally%2C%20the%20range%20for,'),\n\n\n\nThe **average** firing rate per neuron is between .3 & 1.8 firings per second\n\nThe commonly cited figures for neuron firing rate are ~200Hz but these are considered to be outdated/innacurate, because these are measurements of INDIVIDUAL neurons in highly active parts of the brain.\n\nThe majority of neurons are *likely much quieter* than this (see footnote). for global calculation on brain performace, we want the *average* firing rate per neuron.\nThis is calculated in the above link, by brain energy consumption per volume, neuron density & the [metabolic cost](https://www.nature.com/articles/s41598-019-43460-8) of each individual neuron firing.\n\n$$ .3Hz < FiringRate < 1.8Hz $$\n\nThis variable is set here as 1Hz & can be updated when better info is found.",
"_____no_output_____"
],
[
"(footnote from above) The AVERAGE firing rate throughout the brain, is likely much lower than the firing rate of neurons in highly active areas, because much of the brain is most likely long term memory & information that isn't constantly being accessed.",
"_____no_output_____"
]
],
[
[
"firing_rate = 1",
"_____no_output_____"
]
],
[
[
"If we then make the approximation, that a *Synapse* between two neurons, is equivalent to a weight in a digital neural network,\nthen a single synapse performs ONE floating point operation per firing of it's parent neuron.\n\nTherefore, the FLOPS (floating point operations per second) rate of a neuron is ~7000 $\\frac{operations}{second}$",
"_____no_output_____"
],
[
"We can then calculate the global, computational power of a human brain, as *neurons_per_brain* x *synapses_per_neuron* x *firing_rate* $\\frac{operations}{second}$ or FLOPS\n\nas 5.95e14 or 595 TeraFlops",
"_____no_output_____"
]
],
[
[
"brain_flops = neurons_per_brain*synapses_per_neuron*firing_rate\nsci(brain_flops)",
"5.950e+14\n"
]
],
[
[
"Therefore, the human brain has a computational power of \n\n*number of neurons* X *synapses per neuron* X *average firing rate* = $ 5.95x10^{14} $ FLOPS Or\n595 TFLOPS (teraflops)\n\n",
"_____no_output_____"
],
[
"In comparison, the NVIDIA GeForce 3090 (A new, modern GPU) has a theoretical performance of 35.6 TFLOPS (or\n3.56e13 Flops) in float32 computations.\n\n& 69 TFLOPS in float16 computations. [source](https://www.tomshardware.com/news/nvidia-geforce-rtx-3090-ga102-everything-we-know)\n\nI have no idea, how *precise* a firing synapse in a neuron is, and if so, what precision it could be analogous to in terms of bits. #ResearchThis",
"_____no_output_____"
]
],
[
[
"sci(35.6*1e12)",
"3.560e+13\n"
]
],
[
[
"IF all the above calculations are true, then computational power is actually approuching that of the human brain.\n\nThe reason the human brain is still more powerful, is likely it's MASSIVE (possibly *maximal*) Parralelization. Due to being a physical neural network.",
"_____no_output_____"
],
[
"IF we can build better algorithms, & implement parallelization on a MASSIVE scale, we can build more intelligent software NOW!",
"_____no_output_____"
],
[
"The brain is a sparse, VERY slow (1Hz) MASSIVELY distributed computing system. Could probably be better be thought of,\nas 85 Billion Networked computers, each operating at 1Hz with 7000 compuational (cores?)\n\nMassive distributed nework of 85 billion 7000 FLOP computers LOL.",
"_____no_output_____"
],
[
"---\n\nThe computers we build in sillicon are performing calculations at speeds like ~3GigaHz (3e9 Hz)",
"_____no_output_____"
],
[
"In comparison to the ~1Hz firing rate of neurons in the brain, this is insane.\nThe brain is still more powerful because 85 billion massively parrallel computers is nothing to sneeze at, even if they are small and slow. The massively parrallel, asyncronous nature of that many computing \"cores\" is the reason that their slow speed ends up not mattering that much in practice.",
"_____no_output_____"
],
[
"---\n\n**BUT**\nWE can potentially do the same thing with sillicon computers, which are operating at 3GHz & sending signals at close to the speed of light, vs the human brains 1Hz, 200 mph signal propagation.",
"_____no_output_____"
],
[
"### So we're close to there in terms of raw computational. What are the roadblocks?",
"_____no_output_____"
],
[
"First of all, let's look at the actual memory storage in the synapses of the human brain:\n\nA synapse in a bioligical neural network is analagous to a weight (between neurons) in a digital neural network.\n\nA single layer in a neural network, is represnted as a Matrix tranform, usually followed by an activation function.\nNeural network computation is simulated by multiplying an input vector (representing the set of input neurons), then multiplying this vector by the matrix of weights. Each weight, multiplied by an element of the input vector, then summed as part of one of the output vectors, represents the impulse from one neuron to another. Therefore, that single, floating point operation, of multiplying an element in the input vector by a weight, represents a synapse firing.",
"_____no_output_____"
],
[
"The output vector is then ran through an activation function which attempts to map it to an output in the next layer in a sensible way.\n\nThe compuationally **hard** part of this, is the actual matrix computation, because it is $ O(n^2) $ space complexity to store a matrix representing weights from n input, to n output neurons. & the time complexity of multiplying the input vector by the matrix is also $O(n^2)$. This can be parrallelized, but still is a bottleneck. ",
"_____no_output_____"
],
[
"---\n\nIn this method of representing a neural network digitally, information is stored in the float values of the weights. So the theoretical, ACTUAL amount of information in a human neural network, is $ 5.95x10^{14} $ synapse weights or floats.\n\nIt's unclear how accurate each of these floats needs to be, as the actualy physical property they represent, is (#double check this) the ease with which a signal propagates through the synapse. This is likely a messy biological process (voltage front, propagating through a partially insulated tube of ionized liquid), & not precise in practice. So a lower accuracy float is probably sufficient to simulate it accurately. \n\n\nFor the sake of getting a ballpark figure, we'll say that a weight can be accurately represented by a 32 bit float, then the amount of data in a brain is 4bytes x $ 5.95x10^{14} $ = 2380 TB of floats. This is a MASSIVE amount of data, and too much to store in RAM needed to run matrix computations.\n\nHOWEVER, \nThe majority of this data is not accessed often/i.e. the neurons fire very rarely and the data does not need to be quickly accessible.\n\nThe more important parts of the brain (i.e. regions of neurons which ARE firing at ~200Hz) will nescessarily be less than the 2380TB total, though how much less is a big unknown.\n\nThe sets of weights representing THESE regions in a brain, would need to be held in some sort of RAM like memory, in order to quickly pass weights to GPU's in order to crunch large numbers of floats.\n\nThe addtional ~2380 TB of rarely accessed data could be stored in some sort of distributed database which pulled in sections of memory as needed.\n\n---\n\nThis is all an extremely hard technical challenge.\n\nBut if my math is right (& please double check it, let me know if you see issues or am wrong), we're ACTUALLY THERE in terms of raw computational power.\n\n600 FLOPS is doable with 4 or 5 modern, high performance GPUs. The remaining roadblock is no longer computational power, but information retrieval/distributed massive databases, LARGE amounts of RAM, and structuring it all in a form that actually mimics the complex architecture of the human brain.",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
cb7d8c7581b32059138b13513b2a53d48ea935a4
| 21,977 |
ipynb
|
Jupyter Notebook
|
hw1/2-warmup/behavior-cloning-multinomial-regression.ipynb
|
zyxue/berkeley-cs294-hw
|
30d50c7c46c106dbfd12d78e561eb2410be1e6d1
|
[
"MIT"
] | 1 |
2019-09-20T00:49:04.000Z
|
2019-09-20T00:49:04.000Z
|
hw1/2-warmup/behavior-cloning-multinomial-regression.ipynb
|
zyxue/berkeley-cs294-hw
|
30d50c7c46c106dbfd12d78e561eb2410be1e6d1
|
[
"MIT"
] | null | null | null |
hw1/2-warmup/behavior-cloning-multinomial-regression.ipynb
|
zyxue/berkeley-cs294-hw
|
30d50c7c46c106dbfd12d78e561eb2410be1e6d1
|
[
"MIT"
] | 2 |
2018-09-11T19:19:47.000Z
|
2020-01-17T16:55:40.000Z
| 74.751701 | 15,866 | 0.829003 |
[
[
[
"import pickle\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nimport gym\n\n%matplotlib inline",
"_____no_output_____"
],
[
"with open('./train_test.pkl', 'rb') as inf:\n X_tv, y_tv, X_test, y_test = pickle.load(inf)",
"_____no_output_____"
]
],
[
[
"### Build a network",
"_____no_output_____"
],
[
"* observation is an 11-dim array\n* action is a (1, 3) shaped array",
"_____no_output_____"
]
],
[
[
"sess = tf.InteractiveSession()",
"_____no_output_____"
],
[
"# None: batch size could vary\nx_plh = tf.placeholder(tf.float32, shape=[None, 11])\ny_plh = tf.placeholder(tf.float32, shape=[None, 3])",
"_____no_output_____"
],
[
"W_var = tf.Variable(tf.zeros([11, 3]))\nb_var = tf.Variable(tf.zeros([3]))",
"_____no_output_____"
],
[
"sess.run(tf.global_variables_initializer())",
"_____no_output_____"
],
[
"y = tf.matmul(x_plh, W_var) + b_var",
"_____no_output_____"
],
[
"# cross_entropy = tf.reduce_mean(\n# tf.nn.softmax_cross_entropy_with_logits(labels=y_plh, logits=y))\n\nloss_mse = tf.losses.mean_squared_error(labels=y_plh, predictions=y)",
"_____no_output_____"
],
[
"train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss_mse)",
"_____no_output_____"
],
[
"train_step",
"_____no_output_____"
],
[
"# equivalently, \"metric_mse = tf.reduce_mean(tf.square(y_plh - y))\"\nmetric_mse = tf.cast(tf.reduce_mean(tf.squared_difference(y_plh, y)), tf.float32)\ntv_mse, test_mse = [], []\n\nbs = 100 # batch size\nfor k in range(100): # num. epochs\n for i in range(X_tv.shape[0] // bs):\n _x = X_tv[i * bs : (i+1) * bs, :]\n _y = y_tv[i * bs : (i+1) * bs, :]\n train_step.run(feed_dict={x_plh: _x, y_plh: _y})\n\n tv_mse.append(metric_mse.eval(feed_dict={x_plh: X_tv, y_plh: y_tv}))\n test_mse.append(metric_mse.eval(feed_dict={x_plh: X_test, y_plh: y_test}))",
"_____no_output_____"
],
[
"plt.plot(tv_mse, label='tv')\nplt.plot(test_mse, label='test')\nplt.legend()\nplt.xlabel('# iterations')\nplt.ylabel('MSE')\nplt.grid()",
"_____no_output_____"
],
[
"print(tv_mse[-1], test_mse[-1])",
"0.241921 0.241962\n"
]
],
[
[
"# Visualize performance",
"_____no_output_____"
]
],
[
[
"def pred_action(obs):\n return y.eval(feed_dict={x_plh: obs.reshape(1, -1)})\n\nenv = gym.make('Hopper-v1')\n\nobs = env.reset()\ntotalr = 0\ndone = False\nmax_timesteps = 600\nfor k in range(max_timesteps):\n if (k + 1) % 20 == 0:\n print(k + 1, end=',')\n action = pred_action(obs[None,:])\n obs, r, done, _ = env.step(action)\n totalr += r\n env.render()\nenv.render(close=True)\nprint()\nprint(totalr)\nprint(np.mean(totalr))",
"20,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380,400,420,440,460,480,500,520,540,560,580,600,\n1164.2923704\n1164.2923704\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cb7d92a194dea629f41d314fa874242680218255
| 19,065 |
ipynb
|
Jupyter Notebook
|
Py4.ipynb
|
Ka-812/mpss
|
b0dd358057d7b7d63c7f653ca8d70ca9ed1c9e41
|
[
"CC0-1.0"
] | 1 |
2020-10-17T21:05:17.000Z
|
2020-10-17T21:05:17.000Z
|
Py4.ipynb
|
Ka-812/mpss
|
b0dd358057d7b7d63c7f653ca8d70ca9ed1c9e41
|
[
"CC0-1.0"
] | null | null | null |
Py4.ipynb
|
Ka-812/mpss
|
b0dd358057d7b7d63c7f653ca8d70ca9ed1c9e41
|
[
"CC0-1.0"
] | null | null | null | 23.712687 | 541 | 0.536533 |
[
[
[
"---\n### Universidad de Costa Rica\n#### IE0405 - Modelos Probabilísticos de Señales y Sistemas\n---\n\n# `Py4` - *Librerías de manipulación de datos*\n\n> **Pandas**, en particular, es una útil librería de manipulación de datos que ofrece estructuras de datos para el análisis de tablas numéricas y series de tiempo. Esta es una introducción al objeto `DataFrame` y otras características básicas.\n\n---",
"_____no_output_____"
],
[
"## Librería Pandas\n\nPara trabajar con una gran cantidad de datos, es deseable un conjunto de herramientas que nos permitan efectuar operaciones comunes de forma intuitiva y eficiente. Pandas, es la solución por defecto para hacerlo en Python.\n\nEsta guía está basada en [\"10 minutes to pandas\"](https://pandas.pydata.org/docs/getting_started/10min.html).",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport datetime",
"_____no_output_____"
]
],
[
[
"---\n## 4.1 - `Series`\n\nEn Python, las `Series` corresponden a un arreglo de una dimensión que admite diversos tipos de datos (números enteros, palabras, números flotantes, objetos de Python, etc.) que además están etiquetados mediante un índice que el usuario puede definir o permitir que Python lo cree por defecto. De manera que para crear una lista de valores y dejando que Python los etiqute, se utiliza el siguiente comando:",
"_____no_output_____"
]
],
[
[
"s = pd.Series([1, 3, 5, np.nan, \"modelos\", 8.5])\nprint(s)",
"_____no_output_____"
]
],
[
[
"Utilizado el comando de numpy `random.randn` para generar datos aleatorios para la lista y si se desea agregar indices distintos a los numéricos se utiliza el siguiente comando:",
"_____no_output_____"
]
],
[
[
"s = pd.Series(np.random.randn(5), index = ['a', 'b', 'c', 'd', 'e'])\ns",
"_____no_output_____"
]
],
[
[
"Una vez creada la `Serie` se pueden ejecutar operaciones vetoriales con la misma o agregar atributos como un nombre, como se muestra a continuación:",
"_____no_output_____"
]
],
[
[
"d= pd.Series(s+s, name = 'suma')\nd",
"_____no_output_____"
]
],
[
[
"---\n## 4.2 - `DataFrame`\n\nEn Python, la asignación de `DataFrames` corresponde a un arreglo de 2 dimensiones etiquetado, semejante a concatenar varias `Series` y de igual forma admite varios tipos de datos, algo así como una hoja de cálculo o una tabla SQL. De igual forma la asignación de las etiquetas puede ser decidida por el usuario y Python hará coincidir los valores, en caso de diferencias en los tamaños de las listas agregadas, rellenará esos espacios siguiendo reglas de sentido común. A continuación un ejemplo de dos `Series` de diferentes tamaños:",
"_____no_output_____"
]
],
[
[
"d = {'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),\n 'two': pd.Series([1., 2., 3., 4.], index=['a', 'c', 'd', 'b'])}\ndf1 = pd.DataFrame(d)\ndf1",
"_____no_output_____"
]
],
[
[
"Estos indices también pueden indicar una estampa de tiempo, tal como se muestra en el siguiente ejemplo:",
"_____no_output_____"
]
],
[
[
"dates = pd.date_range('20200501', periods=6)\ndf = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))\ndf ",
"_____no_output_____"
]
],
[
[
"De igual forma que las `Series`, los `DataFrame` pueden asignarse como diccionarios, utilizando diferentes tipos de datos en cada columna, como se muestra a continuación:",
"_____no_output_____"
]
],
[
[
"df2 = pd.DataFrame({'A': 1.,\n 'B': pd.Timestamp('20200521'),\n 'C': pd.Series(1, index=list(range(4)), dtype='float32'),\n 'D': np.array([3] * 4, dtype='int32'),\n 'E': pd.Categorical([\"ceviche\", \"pizza\", \"nachos\", \"chifrijo\"]),\n 'F': 'foo'})\ndf2",
"_____no_output_____"
]
],
[
[
"Una vez incializada, se pueden ejecutar acciones como extraer, eliminar e insertar de la misma manera que los diccionarios. A continuación un ejemplo: ",
"_____no_output_____"
]
],
[
[
"df2['E']",
"_____no_output_____"
],
[
"del df2['C']\ndf2",
"_____no_output_____"
],
[
"df2['A']=pd.Series(np.random.randn(4), index=list(range(4)))\ndf2['mayorA1']=df2['A']>1\ndf2",
"_____no_output_____"
]
],
[
[
"---\n## 4.3 - Visualizar datos\n\nEn Python, la visualización de datos permite decidir cuáles datos se quieren ver, por ejemplo del `DataFrame` llamado `df`, para ver las primeras filas de datos se utiliza el comando `head`:",
"_____no_output_____"
]
],
[
[
"df.head(2)",
"_____no_output_____"
]
],
[
[
"Pero si sólo se desea visualizar las útimas tres líneas se utiliza el comando `tail`:",
"_____no_output_____"
]
],
[
[
"df.tail(3)",
"_____no_output_____"
]
],
[
[
"Si bien solo se desean visualizar los indices, se utiliza:",
"_____no_output_____"
]
],
[
[
"df.index",
"_____no_output_____"
]
],
[
[
"Además, en el caso de un `DataFrame` con elementos del mismo tipo de datos, se puede transformar en un dato compatible con Numpy:",
"_____no_output_____"
]
],
[
[
"df.to_numpy()",
"_____no_output_____"
]
],
[
[
"Incluso si el `DataFrame` tiene diversos tipos de datos, también se puede transferir los datos a un arreglo de Numpy:",
"_____no_output_____"
]
],
[
[
"df2.to_numpy()",
"_____no_output_____"
]
],
[
[
"Sin embargo, si todos los elementos son del mismo tipo, se pueden ejecutar más funciones como una rápida revisión de las principales características estadísticas de cada columna:",
"_____no_output_____"
]
],
[
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"O también reordenar los datos con alguna columna de referencia:",
"_____no_output_____"
]
],
[
[
"df.sort_values(by='B')",
"_____no_output_____"
]
],
[
[
"---\n## 4.4 - Seleccionar datos\n\nEn Python, la selección de datos utilizando Pandas es más eficiente que las expresiones para seleccionar y obtener datos en Numpy. Por ejemplo, para ubicar una fila de datos, se puede utilizar el comando `loc`:",
"_____no_output_____"
]
],
[
[
"df2.loc[2]",
"_____no_output_____"
]
],
[
[
"También se pueden seleccionar un rango de columnas al mismo tiempo:",
"_____no_output_____"
]
],
[
[
"df[0:3]",
"_____no_output_____"
]
],
[
[
"Para obtener una posición en específico, se debe indicar la fila y la columna mediante el comando `at`:",
"_____no_output_____"
]
],
[
[
"df.at[dates[2], 'A']",
"_____no_output_____"
]
],
[
[
"De igual forma se puede ubicar ese mismo elemento por medio de la posición en lugar de los indices, utilizando el comando `iloc`:",
"_____no_output_____"
]
],
[
[
"df.iloc[2, 0]",
"_____no_output_____"
]
],
[
[
"De igual manera se pueden ubicar los datos que cumplan con cierta condición booleana:",
"_____no_output_____"
]
],
[
[
"df[df['A']>0]",
"_____no_output_____"
]
],
[
[
"---\n## 4.5 - Operaciones sobre datos\n\nEn Python, las operaciones se ejecutan sobre todos los datos arrojando el valor de salida por filas o columnas, por ejemplo para calcular la media estadística de los datos de cada columna, se utiliza el comando `mean` de la siguiente manera:",
"_____no_output_____"
]
],
[
[
"df.mean()",
"_____no_output_____"
]
],
[
[
"Si en cambio se desea conocer la media de los valores por filas, se utiliza la siguiente variación:",
"_____no_output_____"
]
],
[
[
"df.mean(1)",
"_____no_output_____"
]
],
[
[
"También se pueden aplicar operaciones tales como el conteo sobre dichos datos:",
"_____no_output_____"
]
],
[
[
"f = pd.Series(np.random.randint(0, 7, size=10))\nf",
"_____no_output_____"
],
[
"f.value_counts()",
"_____no_output_____"
]
],
[
[
"También existen operaciones que se pueden aplicar sobre `Series` de palabras:",
"_____no_output_____"
]
],
[
[
"g = pd.Series(['ARbOL', 'BLanCO', 'AvE', 'BuRRo', np.nan])\ng.str.lower()",
"_____no_output_____"
]
],
[
[
"---\n## 4.6 - Fusionar datos\n\nEn Python, para concatenar datos se utiliza el comando `concat()` de la siguiente forma:",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame(np.random.randn(10,2))\ndf2 = pd.DataFrame(np.random.randn(10,2))\npieces = [df[:], df2[:]]\npd.concat(pieces)",
"_____no_output_____"
]
],
[
[
"---\n## 4.7 - Agrupar datos\n\nEn Python, la agrupación se refiere a:\n- Separar los datos en grupos basandose en un criterio.\n- Aplicar una función a cada grupo independientemente.\n- Combinar los resultados en una estructura de datos.\nA continuación un ejemplo de agrupación aplicando una suma a los datos:",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo',\n 'bar', 'foo', 'foo'],\n 'B': ['one', 'one', 'two', 'three', 'two',\n 'two', 'one', 'three'],\n 'C': np.random.randn(8),\n 'D': np.random.randn(8)})\ndf",
"_____no_output_____"
],
[
"df.groupby('A').sum()",
"_____no_output_____"
],
[
"df.groupby(['A', 'B']).sum()",
"_____no_output_____"
]
],
[
[
"---\n## 4.8 - Reacomodar datos\n\nEn Python, una forma de reacomodar los datos es comprimiendolos mediante el comando `stack`:",
"_____no_output_____"
]
],
[
[
"stacked = df.stack()\nstacked",
"_____no_output_____"
]
],
[
[
"También se puede cambiar la forma de ordenar los datos como tablas de pivot:",
"_____no_output_____"
]
],
[
[
"df=pd.DataFrame({'A': ['one', 'one', 'two', 'three']*3,\n 'B': ['A', 'B', 'C']*4,\n 'C': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar']*2,\n 'D': np.random.randn(12),\n 'E': np.random.randn(12)})\ndf",
"_____no_output_____"
],
[
"pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])",
"_____no_output_____"
]
],
[
[
"---\n## 4.9 - Series de tiempo\n\nEn Python, la asignación de series de tiempo permite generar secuencias con una frecuencia fija y un lapso de tiempo, como por ejemplo:",
"_____no_output_____"
]
],
[
[
"dti = pd.date_range('1-5-2020', periods=3, freq='H')\ndti",
"_____no_output_____"
]
],
[
[
"Cuya hora se puede convertir a una zona horaria diferente, como Central Time:",
"_____no_output_____"
]
],
[
[
"dti = dti.tz_localize('UTC')\ndti",
"_____no_output_____"
]
],
[
[
"O el Pacífico de los Estados Unidos:",
"_____no_output_____"
]
],
[
[
"dti.tz_convert('US/Pacific')",
"_____no_output_____"
]
],
[
[
"También se pueden convertir una serie de tiempo a una frecuencia particular:",
"_____no_output_____"
]
],
[
[
"idx = pd.date_range('2020-05-01', periods=5, freq='H')\nts = pd.Series(range(len(idx)), index=idx)\nts",
"_____no_output_____"
],
[
"ts.resample('2H').mean()",
"_____no_output_____"
]
],
[
[
"---\n## 4.10 - Gráficas\n\nEn Python, se utiliza la asignación estándar para utilizar los comandos del API de `matplotlib`, con el cuál se puede graficar una `Serie` de datos:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nplt.close('all')\nts = pd.Series(np.random.randn(1000),\n index=pd.date_range('1/5/2020', periods=1000))\nts = ts.cumsum()\nts.plot()",
"_____no_output_____"
]
],
[
[
"También se pueden graficar arreglos del tipo `DataFrame` de manera que se grafican varias curvas en una misma gráfica como se muestra a continuación:",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,\n columns=['A', 'B', 'C', 'D'])\ndf=df.cumsum()\nplt.figure()\ndf.plot()\nplt.legend(loc='best')",
"_____no_output_____"
]
],
[
[
"---\n## 4.11 - Importar y exportar datos\n\nEn Python, se puede escribir en un archivo de excel mediante el siguiente comando:",
"_____no_output_____"
]
],
[
[
"df.to_csv('modelos')",
"_____no_output_____"
]
],
[
[
"Cuyo contenido se puede llamar desde python utilizando el comando:",
"_____no_output_____"
]
],
[
[
"pd.read_csv('modelos')",
"_____no_output_____"
]
],
[
[
"---\n### Más información\n\n* [Página web](https://www.google.com/)\n* Libro o algo\n* Tutorial [w3schools](https://www.w3schools.com/python/)\n---",
"_____no_output_____"
],
[
"---\n\n**Universidad de Costa Rica**\n\nFacultad de Ingeniería\n\nEscuela de Ingeniería Eléctrica\n\n---",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"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",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cb7da0e9df02e97f1c4105ffe2ddb49175ce5f7d
| 7,001 |
ipynb
|
Jupyter Notebook
|
lastfm_demo.ipynb
|
xjdeng/Item-Item-Collaborative-Filtering
|
7dab6eee8eb7b7576e7cc3f4d1621dd7510b56cf
|
[
"MIT"
] | null | null | null |
lastfm_demo.ipynb
|
xjdeng/Item-Item-Collaborative-Filtering
|
7dab6eee8eb7b7576e7cc3f4d1621dd7510b56cf
|
[
"MIT"
] | null | null | null |
lastfm_demo.ipynb
|
xjdeng/Item-Item-Collaborative-Filtering
|
7dab6eee8eb7b7576e7cc3f4d1621dd7510b56cf
|
[
"MIT"
] | null | null | null | 25.458182 | 121 | 0.545065 |
[
[
[
"import pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom scipy import sparse",
"_____no_output_____"
],
[
"#Based off of https://medium.com/radon-dev/item-item-collaborative-filtering-with-binary-or-unary-data-e8f0b465b2c3",
"_____no_output_____"
],
[
"data = pd.read_csv(\"lastfm.csv\")",
"_____no_output_____"
],
[
"data_items = data.drop('user', 1)",
"_____no_output_____"
],
[
"magnitude = np.sqrt(np.square(data_items).sum(axis=1))",
"_____no_output_____"
],
[
"data_items = data_items.divide(magnitude, axis='index')",
"_____no_output_____"
],
[
"def calculate_similarity(data_items):\n \"\"\"Calculate the column-wise cosine similarity for a sparse\n matrix. Return a new dataframe matrix with similarities.\n \"\"\"\n data_sparse = sparse.csr_matrix(data_items)\n similarities = cosine_similarity(data_sparse.transpose())\n sim = pd.DataFrame(data=similarities, index= data_items.columns, columns= data_items.columns)\n return sim",
"_____no_output_____"
],
[
"data_matrix = calculate_similarity(data_items)",
"_____no_output_____"
],
[
"print(data_matrix.loc['beyonce'].nlargest(11))",
"beyonce 1.000000\nthe pussycat dolls 0.351871\nrihanna 0.334919\nchristina aguilera 0.308388\nalicia keys 0.297264\njustin timberlake 0.279726\nbritney spears 0.269557\nleona lewis 0.259237\nmaria mena 0.248751\nkelly clarkson 0.245713\nnelly furtado 0.230789\nName: beyonce, dtype: float64\n"
],
[
"# Construct a new dataframe with the 10 closest neighbours (most similar)\n# for each artist.\ndata_neighbours = pd.DataFrame(index=data_matrix.columns, columns=range(1,11))\nfor i in range(0, len(data_matrix.columns)):\n data_neighbours.iloc[i,:10] = data_matrix.iloc[0:,i].sort_values(ascending=False)[:10].index\n\nuser = 5985\nuser_index = data[data.user == user].index.tolist()[0]",
"_____no_output_____"
],
[
"print(user_index)",
"358\n"
],
[
"# Get the artists the user has played.\nknown_user_likes = data_items.loc[user_index]\nknown_user_likes = known_user_likes[known_user_likes >0].index.values",
"_____no_output_____"
],
[
"# Construct the neighbourhood from the most similar items to the\n# ones our user has already liked.\nmost_similar_to_likes = data_neighbours.loc[known_user_likes]\nsimilar_list = most_similar_to_likes.values.tolist()\nsimilar_list = list(set([item for sublist in similar_list for item in sublist]))\nneighbourhood = data_matrix[similar_list].loc[similar_list]",
"_____no_output_____"
],
[
"# A user vector containing only the neighbourhood items and\n# the known user likes.\nuser_vector = data_items.ix[user_index].loc[similar_list]",
"d:\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:3: FutureWarning: \n.ix is deprecated. Please use\n.loc for label based indexing or\n.iloc for positional indexing\n\nSee the documentation here:\nhttp://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#ix-indexer-is-deprecated\n This is separate from the ipykernel package so we can avoid doing imports until\n"
],
[
"# Calculate the score.\nscore = neighbourhood.dot(user_vector).div(neighbourhood.sum(axis=1))\n\n# Drop the known likes.\nscore = score.drop(known_user_likes)",
"_____no_output_____"
],
[
"print(known_user_likes)\nprint(score.nlargest(20))",
"['bob dylan' 'the cure']\njoy division 0.087840\nthe smiths 0.087004\nthe rolling stones 0.084162\ndavid bowie 0.081768\ntom waits 0.075365\nbelle and sebastian 0.070918\neric clapton 0.069710\nmisfits 0.069017\nthe beatles 0.067101\nelliott smith 0.067058\nramones 0.064136\njimi hendrix 0.060558\ndepeche mode 0.057806\njohnny cash 0.055420\nthe doors 0.047377\ndtype: float64\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7da70cfe25dfea8c6bc23a05de2b1ecd93ff57
| 40,874 |
ipynb
|
Jupyter Notebook
|
CS2/Plotting_Examples/Trig Plotting Example.ipynb
|
dmason44/SwosuCsPythonExamples
|
a9c09a44c5040488b2265033d5641af7ea1948c9
|
[
"Apache-2.0"
] | 1 |
2022-03-28T18:27:10.000Z
|
2022-03-28T18:27:10.000Z
|
CS2/Plotting_Examples/Trig Plotting Example.ipynb
|
dmason44/SwosuCsPythonExamples
|
a9c09a44c5040488b2265033d5641af7ea1948c9
|
[
"Apache-2.0"
] | 1 |
2022-01-11T16:27:40.000Z
|
2022-01-11T16:27:40.000Z
|
CS2/Plotting_Examples/Trig Plotting Example.ipynb
|
dmason44/SwosuCsPythonExamples
|
a9c09a44c5040488b2265033d5641af7ea1948c9
|
[
"Apache-2.0"
] | 7 |
2022-03-25T21:01:42.000Z
|
2022-03-28T18:51:24.000Z
| 530.831169 | 39,312 | 0.947815 |
[
[
[
"#https://pythonforundergradengineers.com/plotting-sin-cos-with-matplotlib.html",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\n# if using a jupyter notebook\n%matplotlib inline \nx = np.arange(0,4*np.pi,0.1) # start,stop,step\ny = np.sin(x)\ncosine_output = np.cos(x)\n\nplt.scatter(x,y, s=80, facecolors='none', edgecolors='b')\nplt.scatter(x,cosine_output, color='darkgreen', marker='x')\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cb7dab993f231e90a2d6dd8eefc6e2b56a7ebf8d
| 264,793 |
ipynb
|
Jupyter Notebook
|
models/mask_rcnn/kfold_validation/maskrcnn_kfold_eval.ipynb
|
chrisorozco1097/brain_segmentation
|
4edbbe0da30671b1c4e197bd4634f6f5a6196ef8
|
[
"MIT"
] | 3 |
2019-09-14T11:30:05.000Z
|
2020-04-15T14:43:44.000Z
|
models/mask_rcnn/kfold_validation/maskrcnn_kfold_eval.ipynb
|
chrisorozco1097/brain_segmentation
|
4edbbe0da30671b1c4e197bd4634f6f5a6196ef8
|
[
"MIT"
] | 9 |
2019-05-21T11:00:48.000Z
|
2022-03-11T23:48:56.000Z
|
models/mask_rcnn/kfold_validation/maskrcnn_kfold_eval.ipynb
|
chrisorozco1097/brain_segmentation
|
4edbbe0da30671b1c4e197bd4634f6f5a6196ef8
|
[
"MIT"
] | 3 |
2019-04-06T02:28:06.000Z
|
2021-06-30T17:33:34.000Z
| 43.394461 | 280 | 0.46161 |
[
[
[
"import os\nimport sys\nimport numpy as np\nimport cv2\n\nfrom data_loader import *\nfrom fbs_config import TrainFBSConfig, InferenceFBSConfig\nfrom fbs_dataset import FBSDataset\n\nfrom mrcnn import model as modellib\nfrom datahandler import DataHandler\n\nfrom sklearn.metrics import f1_score\nfrom scipy.ndimage import _ni_support\nfrom scipy.ndimage.morphology import distance_transform_edt, binary_erosion,\\\n generate_binary_structure\nfrom tqdm import tqdm\n\nfrom medpy.io import save\nfrom math import ceil, floor\n\nimport skimage.color\n\nfrom skimage.morphology import cube, binary_closing\nfrom skimage.measure import label\n\nROOT_DIR = os.path.abspath('../../../')\nsys.path.append(ROOT_DIR)\n\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, 'logs')\nDEFAULT_MODEL_DIR = os.path.join(DEFAULT_LOGS_DIR, 'mask_rcnn/kfold')\n\nkernel = np.ones((5,5),np.uint8)\n\ndh = DataHandler()",
"Using TensorFlow backend.\n"
],
[
"def destiny_directory(dice_score, post_processing = False):\n if post_processing:\n pre = './data/eval_pp/mask_rcnn/'\n else:\n pre = './data/eval/mask_rcnn/'\n\n if dice_score >= 98:\n return pre + 'dice_98_100/'\n elif dice_score >= 96:\n return pre + 'dice_96_98/'\n elif dice_score >= 94:\n return pre + 'dice_94_96/'\n elif dice_score >= 92:\n return pre + 'dice_92_94/'\n elif dice_score >= 90:\n return pre + 'dice_90_92/'\n elif dice_score >= 88:\n return pre + 'dice_88_90/'\n elif dice_score >= 85:\n return pre + 'dice_85_88'\n elif dice_score >= 80:\n return pre + 'dice_80_85/'\n elif dice_score >= 70:\n return pre + 'dice_70_80/'\n elif dice_score >= 60:\n return pre + 'dice_60_70/'\n else:\n return pre + 'dice_less_60'\n\ndef getFileName(fname):\n original_name = fname.split('/')[-1]\n original_name = original_name[:original_name.index('.')]\n return original_name",
"_____no_output_____"
],
[
"image_files, mask_files = load_data_files('data/kfold_data/')\n\nskf = getKFolds(image_files, mask_files, n=10)\n\nkfold_indices = []\nfor train_index, test_index in skf.split(image_files, mask_files):\n kfold_indices.append({'train': train_index, 'val': test_index})",
"_____no_output_____"
],
[
"def getDataset(val_index):\n image_val_files = np.take(image_files, val_index)\n mask_val_files = np.take(mask_files, val_index)\n\n val_files = ([image_val_files], [mask_val_files])\n\n dataset_val = FBSDataset()\n len_dataset_val = dataset_val.load_data(val_files)\n dataset_val.prepare()\n return dataset_val",
"_____no_output_____"
],
[
"def getDiceScore(ground_truth, prediction):\n #convert to boolean values and flatten\n ground_truth = np.asarray(ground_truth, dtype=np.bool).flatten()\n prediction = np.asarray(prediction, dtype=np.bool).flatten() \n return f1_score(ground_truth, prediction)",
"_____no_output_____"
],
[
" def hd(result, reference, voxelspacing=None, connectivity=1):\n hd1 = __surface_distances(result, reference, voxelspacing, connectivity).max()\n hd2 = __surface_distances(reference, result, voxelspacing, connectivity).max()\n hd = max(hd1, hd2)\n return hd\n\ndef hd95(result, reference, voxelspacing=None, connectivity=1):\n hd1 = __surface_distances(result, reference, voxelspacing, connectivity)\n hd2 = __surface_distances(reference, result, voxelspacing, connectivity)\n hd95 = np.percentile(np.hstack((hd1, hd2)), 95)\n return hd95\n\ndef __surface_distances(result, reference, voxelspacing=None, connectivity=1):\n result = np.atleast_1d(result.astype(np.bool))\n reference = np.atleast_1d(reference.astype(np.bool))\n if voxelspacing is not None:\n voxelspacing = _ni_support._normalize_sequence(voxelspacing, result.ndim)\n voxelspacing = np.asarray(voxelspacing, dtype=np.float64)\n if not voxelspacing.flags.contiguous:\n voxelspacing = voxelspacing.copy()\n\n footprint = generate_binary_structure(result.ndim, connectivity)\n\n if 0 == np.count_nonzero(result):\n raise RuntimeError('The first supplied array does not contain any binary object.')\n if 0 == np.count_nonzero(reference):\n raise RuntimeError('The second supplied array does not contain any binary object.')\n\n result_border = result ^ binary_erosion(result, structure=footprint, iterations=1)\n reference_border = reference ^ binary_erosion(reference, structure=footprint, iterations=1)\n\n dt = distance_transform_edt(~reference_border, sampling=voxelspacing)\n sds = dt[result_border]\n\n return sds",
"_____no_output_____"
],
[
"def evaluateMask(gt_mask, pred_mask):\n return getDiceScore(gt_mask, pred_mask), hd(gt_mask, pred_mask), hd95(gt_mask, pred_mask)\n ",
"_____no_output_____"
],
[
"import random\ndef prepareForSaving(image):\n #image = np.swapaxes(image, -1, 0)\n image = np.moveaxis(image, 0, -1)\n \n return image\n\ndef predictAll(inferenceFBSConfig, val_indices, post_processing = False):\n model = modellib.MaskRCNN(mode='inference', config=inferenceFBSConfig, model_dir=DEFAULT_MODEL_DIR)\n inferenceFBSConfig.display()\n print(DEFAULT_MODEL_DIR)\n weights_path = model.find_last()\n print('Loading weights from %s'%weights_path)\n model.load_weights(weights_path, by_name=True)\n \n dice_scores = []\n hd_scores = []\n hd95_scores = []\n names = []\n \n for image_index in tqdm(val_indices):\n #for saving\n fname = getFileName(image_files[image_index])\n not_used_full_image, hdr = dh.getImageData(image_files[image_index])\n dataset = getDataset(image_index)\n \n prediction = []\n gt_mask = []\n \n for img_id in dataset.image_ids:\n image, image_meta, class_ids, bbox, mask = modellib.load_image_gt(\n dataset, inferenceFBSConfig, img_id, use_mini_mask=False)\n \n results = model.detect([image], verbose=0)\n r = results[0]\n \n pred = r['masks']\n \n if(len(pred.shape) > 2 and pred.shape[2] == 0):\n pred = np.zeros((pred.shape[0],pred.shape[1],1))\n \n if(mask.shape[2] == 0):\n mask = np.zeros((pred.shape[0],pred.shape[1],1))\n \n pred[pred>=0.5] = 1\n pred[pred<0.5] = 0\n \n pred = np.asarray(pred, dtype=np.uint8)\n pred = cv2.dilate(pred,kernel,iterations = 1)\n \n prediction.append(pred)\n gt_mask.append(mask)\n \n pred_mask = np.asarray(prediction)\n gt_mask = np.asarray(gt_mask)\n \n gt_mask = np.squeeze(gt_mask)\n pred_mask = np.squeeze(pred_mask)\n \n if post_processing:\n pred_mask = binary_closing(pred_mask, cube(2))\n\n try:\n labels = label(pred_mask)\n pred_mask = (labels == np.argmax(np.bincount(labels.flat)[1:])+1).astype(int)\n except:\n pred_mask = pred_mask\n \n pred_mask = np.array(pred_mask, dtype=np.uint16)\n \n dice_score, hd_score, hd95_score = evaluateMask(np.squeeze(gt_mask), pred_mask)\n \n \n if dice_score == 0:\n dice_scores.append(dice_score)\n hd_scores.append(200)\n hd95_scores.append(200) \n names.append(fname)\n \n pred_mask = prepareForSaving(pred_mask)\n save_path = destiny_directory(int_dice_score, post_processing=post_processing)\n save_path = os.path.join(ROOT_DIR, save_path)\n \n save(pred, os.path.join(save_path, fname + '_mask_rcnn_' \n + str(int_dice_score) + '.nii'), hdr)\n continue\n \n names.append(fname)\n dice_scores.append(dice_score)\n hd_scores.append(hd_score)\n hd95_scores.append(hd95_score)\n \n int_dice_score = floor(dice_score * 100)\n \n pred_mask = prepareForSaving(pred_mask)\n save_path = destiny_directory(int_dice_score, post_processing=post_processing)\n save_path = os.path.join(ROOT_DIR, save_path) \n save(pred_mask, os.path.join(save_path, fname + '_mask_rcnn_' \n + str(int_dice_score) + '.nii'), hdr)\n \n return dice_scores, hd_scores, hd95_scores, names",
"_____no_output_____"
],
[
"all_dice = []\nall_hd = []\nall_hd95 = []\nall_names = []\n\nfor post_processing in [False, True]:\n\n for i in range(10):#len(kfold_indices)): \n\n configParams = {'da': True,'tl': True, 'mask_dim': 28, 'wl': True, 'kfold_i': i}\n\n trainFBSConfig = TrainFBSConfig(**configParams)\n inferenceFBSConfig = InferenceFBSConfig(**configParams) \n print(inferenceFBSConfig.display())\n dice_scores, hd_scores, hd95_scores, names = predictAll(inferenceFBSConfig, \n kfold_indices[i]['val'],\n post_processing = post_processing)\n\n print('Finished K%d'%i)\n \n all_dice += dice_scores\n all_hd += hd_scores\n all_hd95 += hd95_scores\n all_names.extend(names)\n\n\n if post_processing:\n report_name = 'data/eval_pp/mask_rcnn/mask_rcnn_report.txt'\n\n else:\n report_name = 'data/eval/mask_rcnn/mask_rcnn_report.txt'\n \n report_name = os.path.join(ROOT_DIR, report_name)\n \n with open(report_name, 'w+') as f:\n for i in range(len(all_dice)):\n f.write(\"%s, %f, %f, %f\\n\"%(all_names[i],\n all_dice[i],\n all_hd[i],\n all_hd95[i]))\n\n f.write('\\n')\n f.write('Final results for mask_rcnn\\n')\n f.write('dice %f\\n'%np.mean(all_dice))\n f.write('hd %f\\n'%np.mean(all_hd))\n f.write('hd95 %f\\n'%np.mean(all_hd95))",
"\nConfigurations:\nBACKBONE resnet50\nBACKBONE_STRIDES [4, 8, 16, 32, 64]\nBATCH_SIZE 1\nBBOX_STD_DEV [0.1 0.1 0.2 0.2]\nCOMPUTE_BACKBONE_SHAPE None\nDETECTION_MAX_INSTANCES 1\nDETECTION_MIN_CONFIDENCE 0\nDETECTION_NMS_THRESHOLD 0.3\nFPN_CLASSIF_FC_LAYERS_SIZE 1024\nGPU_COUNT 1\nGRADIENT_CLIP_NORM 5.0\nIMAGES_PER_GPU 1\nIMAGE_CHANNEL_COUNT 1\nIMAGE_MAX_DIM 256\nIMAGE_META_SIZE 14\nIMAGE_MIN_DIM 256\nIMAGE_MIN_SCALE 0\nIMAGE_RESIZE_MODE square\nIMAGE_SHAPE [256 256 1]\nLEARNING_MOMENTUM 0.9\nLEARNING_RATE 0.001\nLOSS_WEIGHTS {'rpn_class_loss': 0.5, 'rpn_bbox_loss': 0.5, 'mrcnn_class_loss': 0.5, 'mrcnn_bbox_loss': 0.5, 'mrcnn_mask_loss': 1.0}\nMASK_POOL_SIZE 14\nMASK_SHAPE [28, 28]\nMAX_GT_INSTANCES 1\nMEAN_PIXEL [73.99]\nMINI_MASK_SHAPE (56, 56)\nNAME FBM_resnet50_da_tl_wl_25_28_10K_0_\nNUM_CLASSES 2\nNUM_DECONV_LAYERS 1\nPOOL_SIZE 7\nPOST_NMS_ROIS_INFERENCE 1000\nPOST_NMS_ROIS_TRAINING 2000\nPRE_NMS_LIMIT 6000\nROI_POSITIVE_RATIO 0.33\nRPN_ANCHOR_RATIOS [0.75, 1, 1.5]\nRPN_ANCHOR_SCALES (16, 32, 64, 128)\nRPN_ANCHOR_STRIDE 1\nRPN_BBOX_STD_DEV [0.1 0.1 0.2 0.2]\nRPN_NMS_THRESHOLD 0.7\nRPN_TRAIN_ANCHORS_PER_IMAGE 256\nSTEPS_PER_EPOCH 500\nTOP_DOWN_PYRAMID_SIZE 256\nTRAIN_BN False\nTRAIN_ROIS_PER_IMAGE 100\nUSE_MINI_MASK True\nUSE_RPN_ROIS True\nVALIDATION_STEPS 25\nWEIGHT_DECAY 0.0001\n\n\nNone\nWARNING:tensorflow:From /neuro/users/alejandro.valdes/.conda/envs/alex_tensorflow_gpuenv/lib/python3.6/site-packages/tensorflow/python/ops/sparse_ops.py:1165: sparse_to_dense (from tensorflow.python.ops.sparse_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nCreate a `tf.sparse.SparseTensor` and use `tf.sparse.to_dense` instead.\n\nConfigurations:\nBACKBONE resnet50\nBACKBONE_STRIDES [4, 8, 16, 32, 64]\nBATCH_SIZE 1\nBBOX_STD_DEV [0.1 0.1 0.2 0.2]\nCOMPUTE_BACKBONE_SHAPE None\nDETECTION_MAX_INSTANCES 1\nDETECTION_MIN_CONFIDENCE 0\nDETECTION_NMS_THRESHOLD 0.3\nFPN_CLASSIF_FC_LAYERS_SIZE 1024\nGPU_COUNT 1\nGRADIENT_CLIP_NORM 5.0\nIMAGES_PER_GPU 1\nIMAGE_CHANNEL_COUNT 1\nIMAGE_MAX_DIM 256\nIMAGE_META_SIZE 14\nIMAGE_MIN_DIM 256\nIMAGE_MIN_SCALE 0\nIMAGE_RESIZE_MODE square\nIMAGE_SHAPE [256 256 1]\nLEARNING_MOMENTUM 0.9\nLEARNING_RATE 0.001\nLOSS_WEIGHTS {'rpn_class_loss': 0.5, 'rpn_bbox_loss': 0.5, 'mrcnn_class_loss': 0.5, 'mrcnn_bbox_loss': 0.5, 'mrcnn_mask_loss': 1.0}\nMASK_POOL_SIZE 14\nMASK_SHAPE [28, 28]\nMAX_GT_INSTANCES 1\nMEAN_PIXEL [73.99]\nMINI_MASK_SHAPE (56, 56)\nNAME FBM_resnet50_da_tl_wl_25_28_10K_0_\nNUM_CLASSES 2\nNUM_DECONV_LAYERS 1\nPOOL_SIZE 7\nPOST_NMS_ROIS_INFERENCE 1000\nPOST_NMS_ROIS_TRAINING 2000\nPRE_NMS_LIMIT 6000\nROI_POSITIVE_RATIO 0.33\nRPN_ANCHOR_RATIOS [0.75, 1, 1.5]\nRPN_ANCHOR_SCALES (16, 32, 64, 128)\nRPN_ANCHOR_STRIDE 1\nRPN_BBOX_STD_DEV [0.1 0.1 0.2 0.2]\nRPN_NMS_THRESHOLD 0.7\nRPN_TRAIN_ANCHORS_PER_IMAGE 256\nSTEPS_PER_EPOCH 500\nTOP_DOWN_PYRAMID_SIZE 256\nTRAIN_BN False\nTRAIN_ROIS_PER_IMAGE 100\nUSE_MINI_MASK True\nUSE_RPN_ROIS True\nVALIDATION_STEPS 25\nWEIGHT_DECAY 0.0001\n\n\n/net/rc-fs-nfs/ifs/data/NoSync/FNNDSC-NR/neuro/labs/grantlab/users/alejandro.valdes/projects/fetal-brain-segmentation/logs/mask_rcnn/kfold\nLoading weights from /net/rc-fs-nfs/ifs/data/NoSync/FNNDSC-NR/neuro/labs/grantlab/users/alejandro.valdes/projects/fetal-brain-segmentation/logs/mask_rcnn/kfold/fbm_resnet50_da_tl_wl_25_28_10k_0_20190812T1756/mask_rcnn_fbm_resnet50_da_tl_wl_25_28_10k_0__0023.h5\n"
],
[
"print('dice')\nfor score in all_dice:\n print(score)\n\nprint()\nprint('hd')\nfor score in all_hd:\n print(score)\n\nprint()\nprint('hd95')\nfor score in all_hd95:\n print(score)\n ",
"dice\n0.8667874675370065\n0.9023389743259765\n0.7726390412693054\n0.8380440336290585\n0.7104639260359914\n0.9327499728422717\n0.9336195695158466\n0.8736065362604198\n0.9111669938819459\n0.8891609323631913\n0.9176977470037441\n0.8985425390619829\n0.8762968531844055\n0.9267180202583853\n0.9180760020049381\n0.903923979304339\n0.9057285160629064\n0.6320465273095077\n0.8800461730849392\n0.902440304382052\n0.22591043939358543\n0.9318017405791701\n0.9393663145222497\n0.92815591711231\n0.9242727070841661\n0.8801207196749855\n0.9163887212995322\n0.8898514642348183\n0.8789906985590464\n0.8631725738374166\n0.8926971108381133\n0.9093438441919777\n0.917081131488965\n0.9172673614170005\n0.9124013475023919\n0.9353343896678525\n0.7687518205651034\n0.9293593349979455\n0.5854852459918048\n0.9069019398326204\n0.8985705113539921\n0.911144340664708\n0.9077334453678539\n0.7915429771393118\n0.901391440002013\n0.8734693877551021\n0.9468165350835959\n0.9517858709960509\n0.9227259873692147\n0.9322151760001814\n0.9419780202509165\n0.944007629778315\n0.9372444361207354\n0.9243312618211295\n0.890121226402744\n0.9069931431871756\n0.8813186056914766\n0.9240006143621106\n0.9308379003079135\n0.8090923237135367\n0.8618322664614269\n0.9193639977285633\n0.9060632085194091\n0.8871602683211035\n0.9435960680474446\n0.9140411305845406\n0.9455118878887147\n0.858485821898829\n0.7833899307573857\n0.8930915056507474\n0.8949636366733091\n0.8585927887368666\n0.9329746985653058\n0.9184864045795099\n0.8452594817550769\n0.6863990806862021\n0.947667108013357\n0.9021287732178153\n0.9381757372054903\n0.9336718653618856\n0.832086072209331\n0.6955788601772005\n0.9347912869912349\n0.9537189860848329\n0.8591186602544425\n0.9224004846305669\n0.8796337827497955\n0.9287786930648793\n0.8282949253009132\n0.8726484782822811\n0.8983468884404492\n0.9358085156805436\n0.8928194236505229\n0.8576633210701148\n0.89528107785226\n0.8844266607931672\n0.8372555152808698\n0.9040705082825995\n0.8973662535299656\n0.8707716276746175\n0.7113803060387215\n0.8908833736766893\n0.835357708037898\n0.9174938635626843\n0.9366673673326781\n0.8990974205470457\n0.9223158937343814\n0.9238556442255322\n0.9060644794773469\n0.5455998383407887\n0.8571135679025974\n0.8736963438960251\n0.8119191191682055\n0.6892112674595313\n0.32098856104144097\n0.8279502497306827\n0.794319022945966\n0.7901351539640519\n0.9139606263807158\n0.8455355087731724\n0.9041441966671525\n0.8947934081681396\n0.9071904777391134\n0.8774433604255801\n0.7189933911044567\n0.8945662823121561\n0.8830837424921909\n0.8713814986994871\n0.9220896389669041\n0.9063295063878681\n0.9271731372952524\n0.9148512405626148\n0.7971092077087794\n0.5064941679824785\n0.9324277963692241\n0.9425544337621268\n0.9289233637392635\n0.9295042948478549\n0.9295828243737418\n0.927469201668445\n0.7499683258930235\n0.8850549719364527\n0.8750140489365781\n0.8606287521786844\n0.9211923508051254\n0.8852713022305841\n0.8792061375404812\n0.9136532743056018\n0.910061492438092\n0.9074682136363333\n0.8364276541277927\n0.917607542196967\n0.9172163253708927\n0.8745002546695226\n0.9227977674336518\n0.8454275184810973\n0.8881681293844844\n0.8717824542866368\n0.9538441088014888\n0.9031594549221857\n0.9152225010955739\n0.8885494442861214\n0.7590372641947775\n0.9183123807429859\n0.8955654234453096\n0.9370869394736693\n0.923436033720004\n0.9056844547563805\n0.8936702123369973\n0.9240982791031438\n0.9292610125882333\n0.9246330741964873\n0.6766573506509851\n0.9489797026530988\n0.9165802597146102\n0.8769043954010121\n0.8933312563822974\n0.8840283579056694\n0.8710260379101599\n0.8527065809005443\n0.8850467801061442\n0.8811484141007807\n0.8861423424894962\n0.6756231852473832\n0.7374079369789841\n0.8313298954096456\n0.9304467798105378\n0.8275521334616618\n0.4531090656247931\n0.6337654320987655\n0.9170325056453051\n0.7838016286405987\n0.8838955571989306\n0.8675840978593272\n0.8934884653961885\n0.8790375491204928\n0.8758461760046089\n0.9208906626039006\n0.9128637840294282\n0.841131997638708\n0.8919306389950846\n0.9138226909131169\n0.6947973694177598\n0.8389077596324999\n0.8838733047945658\n0.917402469575324\n0.8978095401257985\n0.9381262328605985\n0.8986051038062284\n0.9240601760121838\n0.881114441175065\n0.8874077130785033\n0.8974912319976122\n0.7344722469198527\n0.8877443875891035\n0.9132024606736739\n0.5772044195513115\n0.9477616019532461\n0.8047774630596991\n0.9274771494197396\n0.6484822560686843\n0.9198592419480485\n0.9532296278729492\n0.9287790637401461\n0.9422710269096174\n0.8195434333978682\n0.9103918498404454\n0.5837499330123028\n0.8618681543861503\n0.7177431687391846\n0.71885244822456\n0.9445817228409865\n0.9360809005914902\n0.6014142165984369\n0.8885661838664253\n0.8820310124657951\n0.9220892790563672\n0.8890492146708777\n0.8281416463928508\n0.9176194256738216\n0.8855101467392239\n0.9055132631837788\n0.92949472287853\n0.5196310759542961\n0.8174035993668065\n0.9123367395276443\n0.8550495088956628\n0.7152562814070351\n0.9383848287066865\n0.9227053140096618\n0.9333841415007462\n0.8433970712615466\n0.8988691744551573\n0.821645631589631\n0.911653855817698\n0.9049770112165938\n0.6435219551190544\n0.9009208813461261\n0.9242945977676539\n0.8292685780473965\n0.9329840553915381\n0.7629612198031372\n0.5302984022556392\n0.6768906146332974\n0.8935972780699042\n0.9015176794117985\n0.8172927746088595\n0.8923345617856048\n0.8230439859867653\n0.9258137579889063\n0.8040876143700241\n0.9272156056107531\n0.8849437900078202\n0.8791953216374269\n0.7899042004421518\n0.3008282449670516\n0.8750283220537675\n0.6856084346578643\n0.9209514923776183\n0.89907712646503\n0.9188397922233801\n0.9396774724646094\n0.9321244683232595\n0.9310326283198758\n0.931859810578985\n0.9021473858192478\n0.6670770714865962\n0.8975966658098632\n0.8743288544874764\n0.8733765998856836\n0.8785406617836797\n0.8747488278633624\n0.9009757773853002\n0.8949397355194456\n0.8093025309330125\n0.7843314413121252\n0.9253592815482797\n0.9268794902976\n0.8638815334292059\n0.9235287603695733\n0.9166048831661396\n0.919782243918438\n0.912290117990142\n0.870664703916256\n0.9264715669488089\n0.9139378982651294\n0.902887384364461\n0.9001028155646948\n0.8572679696678416\n0.9196769573520049\n0.8907899621032278\n0.0\n0.9314738202412857\n0.9400924661178347\n0.930421497963021\n0.926914355485784\n0.8941914256387182\n0.9070045609014489\n0.9224369468833203\n0.8685013380909902\n0.8510977207230811\n0.9045903068805665\n0.900574847843265\n0.9203722968635871\n0.9153895060037319\n0.9156052049908293\n0.9373806663243482\n0.8907362919880305\n0.9211919257793482\n0.8701982835158332\n0.9108044799063025\n0.9002103432905648\n0.9017090206568583\n0.9076266733917576\n0.8823651431788774\n0.9231895162874768\n0.8676819678216612\n0.9406608094883685\n0.9494069644833617\n0.9195199534591313\n0.9394645895961558\n0.9391406902907844\n0.9412577059902336\n0.9270926954424293\n0.9223652805324907\n0.9254754154531437\n0.8991715740093822\n0.9255249136788584\n0.9220637426371898\n0.9419113774032131\n0.9124640253906775\n0.8422978500963415\n0.9296150790147435\n0.9009598826999472\n0.8786666666666666\n0.9503496528953298\n0.906666762242349\n0.9429164956276199\n0.9081904678147209\n0.8565289641084262\n0.900363114306551\n0.8933564374758163\n0.8568566930555634\n0.9265919988186052\n0.9366204425855774\n0.8455302796555496\n0.8703860965735164\n0.9444734335528223\n0.8886695511087075\n0.9363902519483733\n0.933540113331345\n0.9178457212854642\n0.6767757382282522\n0.9288194643409696\n0.9531032823692933\n0.8352790090724552\n0.9188964301016511\n0.8762607206367747\n0.9262012399243503\n0.8851093630804245\n0.8725360882928536\n0.9164577967537295\n0.9275846293419627\n0.9070046744928116\n0.8467227336396073\n0.8832389003022729\n0.8803176265695599\n0.8156129367403786\n0.8958513593515188\n0.8922448462277166\n0.8789433570215067\n0.8576148791591601\n0.8872732007986804\n0.8364363809221993\n0.9129240206711267\n0.9338308864355713\n0.8986242658876568\n0.9169629667076713\n0.9224387782640836\n0.9087963154483654\n0.3223087693541591\n0.8692577322771421\n0.8801938436686709\n0.8945051608986034\n0.9085339228208067\n0.36382187407431793\n0.826365744801107\n0.8037882467217095\n0.7839057113446221\n0.9034449109561777\n0.8546400267887041\n0.9124360609264115\n0.8869411034605041\n0.9080037274798094\n0.8810375140751863\n0.8647268829316594\n0.8910074336548646\n0.8891232971742714\n0.88719689452887\n0.9374384899874648\n0.917280367254378\n0.9166774474544405\n0.9223066996284031\n0.8664634146341464\n0.0\n0.9302407410438112\n0.9456078021019022\n0.9380030381616604\n0.9298050263342501\n0.9392226067687809\n0.9275327623887007\n0.9027870979286897\n0.9080848741215801\n0.870000585964204\n0.8747920469045274\n0.9290535979478872\n0.9385320905686074\n0.871456008393052\n0.9113467488706308\n0.9097333846991777\n0.9074247144340604\n0.8202021543210901\n0.9157291990889643\n0.9137465354732203\n0.8720294792463326\n0.9307076991445394\n0.9176171970455388\n0.8821345910301761\n0.8993913030344225\n0.9471731501064037\n0.8971771924955179\n0.9193350051801432\n0.8812727837906575\n0.775047258979206\n0.937232513573938\n0.8841507923426499\n0.9392544058866279\n0.9175364407011297\n0.8985902334806147\n0.8957574880857664\n0.930012585281844\n0.9333668117397611\n0.9212167712832453\n0.9355557484735365\n0.9447569283254342\n0.9077126831739367\n0.8836216876330736\n0.8996640966287833\n0.8908164482541197\n0.860158438025126\n0.8403824971488171\n0.9122470833568167\n0.8722985524839524\n0.885601238603131\n0.9045900655723653\n0.8907991241137351\n0.8113254291275881\n0.9325684731187209\n0.8608916927318031\n0.5075549102696132\n0.8992822341422929\n0.9306144606928375\n0.8534123918186447\n0.8628375006930199\n0.8502884806684794\n0.8934373587688209\n0.8814581676062669\n0.8644939965694682\n0.9023440061912195\n0.9120095124851367\n0.8225097399178687\n0.8870194857159386\n0.9136797162827531\n0.914867589425277\n0.8625618777462594\n0.9136969601635928\n0.8980922086538001\n0.9258796142991998\n0.9263441626294291\n0.892810576752821\n0.9175158017859955\n0.8644680566693398\n0.8854818690787652\n0.9107115806732349\n0.8581865936667652\n0.8884880675740474\n0.9193622215440953\n0.5714605183710894\n0.9462819461868379\n0.8004650780711898\n0.9369930890598512\n0.6493263811447\n0.9149957548605513\n0.954034213437322\n0.9143447776317342\n0.9445633802816902\n0.8105794078271428\n0.9108706649060223\n0.885794130265889\n0.8530081216698566\n0.8121097891388855\n0.935560696207394\n0.9370324828363563\n0.9291245442239917\n0.7764890783939928\n0.9282638296208947\n0.9045352475779673\n0.9114102143225623\n0.9086119443686937\n0.8067167503956\n0.910836155815522\n0.8690518084066472\n0.9026665169961119\n0.9253141101652509\n0.784483588410819\n0.8974486332555174\n0.9072542755121219\n0.8457773235600455\n0.7066207787755318\n0.9391112965415664\n0.9195414450427831\n0.9230615169893038\n0.8387187203693779\n0.9057544682408738\n0.8553430708226673\n0.9086674159474758\n0.8991363676309629\n0.8966179557245257\n0.8983008445066499\n0.908855629343289\n0.9279670139681752\n0.9500201380125124\n0.88020053876085\n0.5225027063131953\n0.910349966033353\n0.888060714366503\n0.8920054985628756\n0.8093587256983155\n0.9186168392230684\n0.8170357283751566\n0.9241193303292438\n0.8637616741171781\n0.9265173088652974\n0.8984997228331814\n0.8594836169545312\n0.7769767492410355\n0.0\n0.8693627859370164\n0.8620191722194193\n0.9373293211111304\n0.895904580602773\n0.9214775815631361\n0.9384695853457677\n0.9280770672256077\n0.9383768834087178\n0.9264539538639814\n0.9006050795853086\n0.8784732100521575\n0.8878591120139292\n0.8645908954677146\n0.8348025327397082\n0.867214914956441\n\nhd\n57.18391382198319\n23.895606290697042\n115.13904637437292\n23.280893453645632\n127.69103335786738\n15.297058540778355\n6.324555320336759\n17.804493814764857\n123.47064428438041\n105.82060290888538\n75.05331438384317\n39.02563260217571\n23.430749027719962\n93.31130692472375\n54.735728733616035\n20.71231517720798\n37.013511046643494\n205.50912388504798\n118.15667564721005\n19.05255888325765\n120.61923561356207\n21.307275752662516\n48.02082881417188\n40.84115571332428\n51.97114584074513\n8.0\n43.9089968002003\n54.8270006474912\n14.177446878757825\n11.704699910719626\n62.13694553162394\n22.15851980616034\n43.8520238985614\n7.211102550927978\n9.0\n25.41653005427767\n106.2449998823474\n5.0990195135927845\n104.00480758118829\n34.36568055487916\n25.573423705088842\n6.708203932499369\n31.400636936215164\n107.61505470890214\n75.8023746329889\n17.26267650163207\n5.0\n9.695359714832659\n67.91906948714772\n25.865034312755125\n9.433981132056603\n6.6332495807108\n7.3484692283495345\n8.54400374531753\n62.24949798994366\n4.242640687119285\n100.91580649234291\n4.69041575982343\n89.66604708583958\n99.12618221237011\n40.024992192379\n49.1121166312347\n14.352700094407323\n12.165525060596439\n66.76825593049439\n13.416407864998739\n5.196152422706632\n138.59292911256333\n103.4456378974\n70.8590149522275\n18.466185312619388\n65.62011886609167\n17.69180601295413\n49.20365840057018\n11.575836902790225\n74.22263805605402\n15.0\n21.400934559032695\n13.19090595827292\n18.627936010197157\n105.76388797694608\n52.21110992882645\n6.0\n5.196152422706632\n27.0\n13.0\n14.035668847618199\n6.0\n68.36665854054884\n37.14835124201342\n58.45511098270193\n77.13624310270757\n60.241181927316134\n38.0\n5.0990195135927845\n36.51027252705737\n20.049937655763422\n7.0\n19.339079605813716\n40.47221268969612\n85.95929269136641\n8.94427190999916\n7.483314773547883\n64.10928169929842\n10.246950765959598\n8.06225774829855\n58.44655678480983\n6.928203230275509\n17.233687939614086\n118.71394189394942\n46.357307945997036\n24.61706725018234\n91.25787637239867\n97.98979538707079\n166.667333332\n39.331920878594275\n17.804493814764857\n47.80167361086848\n5.385164807134504\n46.861498055439924\n60.18305409332431\n43.42810150121693\n42.2965719651132\n126.49505919204908\n116.62332528272378\n7.280109889280518\n25.865034312755125\n22.561028345356956\n91.34549797335389\n40.2119385257662\n34.438350715445125\n49.20365840057018\n51.64300533470143\n73.1983606373804\n8.602325267042627\n11.661903789690601\n35.35533905932738\n59.21148537234985\n68.1248853210044\n66.2872536767062\n106.83164325236227\n40.3732584763727\n14.89966442575134\n122.15154522149935\n59.983331017875294\n112.0044641967453\n71.17583859709698\n18.49324200890693\n50.53711507397311\n8.54400374531753\n24.919871588754223\n19.026297590440446\n60.08327554319921\n74.87322618933953\n108.05091392487155\n72.42927584892728\n102.4792661956554\n75.75618786607468\n10.198039027185569\n12.083045973594572\n6.708203932499369\n12.529964086141668\n23.323807579381203\n21.840329667841555\n39.534794801541594\n28.75760768909681\n10.246950765959598\n20.904544960366874\n71.63099887618489\n67.30527468185537\n32.264531609803356\n16.186414056238647\n105.38026380684383\n40.2119385257662\n6.324555320336759\n48.27007354458868\n80.71554992688831\n78.19207120929845\n12.36931687685298\n16.431676725154983\n123.38557452149745\n71.65193647069142\n81.44937077718895\n121.4701609449827\n147.45168700289597\n68.3593446428504\n83.7973746605465\n66.17401302626281\n173.07512819582138\n88.02272433866155\n15.0\n41.80908992073375\n6.4031242374328485\n7.0710678118654755\n32.155870381627054\n96.42095207992918\n11.0\n9.9498743710662\n7.0\n9.433981132056603\n12.0\n12.84523257866513\n103.00970828033637\n24.124676163629637\n55.35341001239219\n13.564659966250536\n50.24937810560445\n5.0\n16.0312195418814\n16.73320053068151\n38.61346915261564\n21.37755832643195\n77.15568676384133\n110.92790451459904\n30.692018506445613\n9.695359714832659\n66.15889962809237\n6.164414002968976\n51.43928459844674\n27.018512172212592\n53.53503525729669\n13.152946437965905\n20.074859899884732\n23.958297101421877\n23.958297101421877\n13.416407864998739\n5.916079783099616\n108.94952959971879\n48.28043081829324\n115.6460116043783\n116.91449867317569\n6.4031242374328485\n9.055385138137417\n101.1236866416568\n72.69112738154499\n49.07137658554119\n10.770329614269007\n108.45275469069469\n66.63332499583073\n12.041594578792296\n13.416407864998739\n9.38083151964686\n62.112800613078136\n157.17824276915684\n115.95257651298655\n12.083045973594572\n50.85272854036448\n32.01562118716424\n46.69047011971501\n16.911534525287763\n8.602325267042627\n38.79432948254165\n40.422765862815474\n90.03888049059695\n14.212670403551895\n10.04987562112089\n140.43503836293846\n9.0\n13.856406460551018\n97.94386147176351\n68.52736679604726\n105.49407566304374\n72.74613391789285\n112.80957406177899\n9.0\n8.48528137423857\n9.0\n50.049975024968795\n51.95190083144215\n32.341923257592455\n62.81719509815764\n62.25752966509352\n86.07554821202127\n29.274562336608895\n25.80697580112788\n171.29506706265653\n13.114877048604\n99.58915603618699\n130.5679899515957\n59.77457653551382\n26.758176320519304\n9.433981132056603\n7.3484692283495345\n61.48170459575759\n14.071247279470288\n7.3484692283495345\n101.95096860746347\n19.6468827043885\n28.930952282978865\n54.70831746635972\n67.29784543356496\n12.727922061357855\n23.895606290697042\n8.0\n9.16515138991168\n74.0\n16.0312195418814\n8.246211251235321\n17.804493814764857\n7.874007874011811\n7.615773105863909\n10.198039027185569\n7.0710678118654755\n23.430749027719962\n7.0710678118654755\n17.944358444926362\n20.71231517720798\n18.788294228055936\n51.59457335805772\n6.708203932499369\n19.519221295943137\n200\n16.15549442140351\n6.708203932499369\n7.0710678118654755\n6.0\n14.594519519326424\n43.9089968002003\n4.47213595499958\n14.177446878757825\n11.704699910719626\n7.0710678118654755\n22.15851980616034\n6.0\n7.615773105863909\n9.0\n4.123105625617661\n8.54400374531753\n6.0\n5.916079783099616\n6.4031242374328485\n8.0\n6.708203932499369\n8.0\n7.211102550927978\n7.0710678118654755\n17.26267650163207\n6.324555320336759\n7.0\n22.561028345356956\n8.602325267042627\n9.433981132056603\n7.54983443527075\n7.3484692283495345\n8.54400374531753\n7.0710678118654755\n5.0990195135927845\n4.0\n4.69041575982343\n5.744562646538029\n6.0\n40.4103947023535\n20.049937655763422\n14.352700094407323\n12.165525060596439\n3.7416573867739413\n14.317821063276353\n5.744562646538029\n6.0\n17.72004514666935\n16.0312195418814\n12.083045973594572\n46.62617290749907\n18.547236990991408\n6.324555320336759\n11.575836902790225\n7.280109889280518\n16.0\n21.400934559032695\n13.19090595827292\n7.280109889280518\n10.723805294763608\n52.21110992882645\n8.0\n4.242640687119285\n27.53179979587241\n6.0\n14.035668847618199\n6.0\n6.48074069840786\n20.615528128088304\n10.677078252031311\n9.219544457292887\n8.06225774829855\n38.3275357934736\n6.164414002968976\n36.51027252705737\n10.488088481701515\n7.0\n7.0710678118654755\n40.85339643163099\n7.0710678118654755\n8.94427190999916\n7.483314773547883\n5.0990195135927845\n10.246950765959598\n8.06225774829855\n10.488088481701515\n6.928203230275509\n5.830951894845301\n18.81488772222678\n46.357307945997036\n24.61706725018234\n6.782329983125268\n17.0\n13.416407864998739\n19.209372712298546\n12.206555615733702\n33.97057550292606\n5.916079783099616\n40.7308237088326\n22.293496809607955\n11.045361017187261\n5.0\n12.68857754044952\n14.45683229480096\n7.280109889280518\n9.273618495495704\n22.561028345356956\n17.4928556845359\n12.083045973594572\n7.0710678118654755\n7.280109889280518\n10.44030650891055\n200\n8.602325267042627\n8.0\n9.486832980505138\n21.0\n5.0990195135927845\n6.708203932499369\n5.477225575051661\n5.65685424949238\n14.89966442575134\n7.14142842854285\n14.560219778561036\n7.0710678118654755\n22.561028345356956\n19.313207915827967\n5.830951894845301\n8.48528137423857\n24.919871588754223\n19.026297590440446\n16.278820596099706\n11.357816691600547\n6.164414002968976\n6.082762530298219\n31.76476034853718\n7.211102550927978\n10.198039027185569\n12.083045973594572\n6.708203932499369\n12.529964086141668\n23.323807579381203\n6.0\n39.534794801541594\n28.75760768909681\n10.246950765959598\n21.400934559032695\n7.0\n6.164414002968976\n11.445523142259598\n16.186414056238647\n7.211102550927978\n7.3484692283495345\n7.211102550927978\n26.476404589747453\n20.248456731316587\n39.91240408695021\n12.36931687685298\n16.431676725154983\n5.385164807134504\n17.69180601295413\n6.4031242374328485\n9.433981132056603\n5.830951894845301\n68.46897107449476\n7.0\n18.788294228055936\n10.0\n35.52463933666322\n6.324555320336759\n15.588457268119896\n6.4031242374328485\n7.0710678118654755\n31.89043743820395\n21.118712081942874\n12.0\n9.9498743710662\n7.0\n11.0\n12.0\n12.68857754044952\n5.196152422706632\n24.124676163629637\n46.73328578219169\n13.564659966250536\n6.48074069840786\n5.0\n16.0312195418814\n16.73320053068151\n38.61346915261564\n21.37755832643195\n6.708203932499369\n40.84115571332428\n30.692018506445613\n6.48074069840786\n66.15889962809237\n6.164414002968976\n17.916472867168917\n6.4031242374328485\n53.53503525729669\n13.152946437965905\n5.830951894845301\n23.958297101421877\n6.4031242374328485\n13.416407864998739\n5.916079783099616\n24.43358344574123\n48.28043081829324\n49.49747468305833\n8.06225774829855\n6.4031242374328485\n9.055385138137417\n11.916375287812984\n6.708203932499369\n6.4031242374328485\n10.770329614269007\n18.788294228055936\n26.115129714401192\n12.041594578792296\n14.317821063276353\n9.38083151964686\n25.80697580112788\n8.774964387392123\n5.830951894845301\n12.083045973594572\n50.85272854036448\n32.01562118716424\n8.366600265340756\n16.911534525287763\n8.602325267042627\n20.46948949045872\n6.4031242374328485\n16.0312195418814\n8.246211251235321\n10.04987562112089\n4.123105625617661\n9.0\n13.856406460551018\n5.0990195135927845\n5.0\n14.696938456699069\n72.74613391789285\n6.082762530298219\n9.0\n8.48528137423857\n9.0\n5.830951894845301\n15.297058540778355\n32.341923257592455\n23.53720459187964\n34.07345007480164\n14.071247279470288\n12.328828005937952\n24.71841418861655\n200\n13.114877048604\n10.198039027185569\n9.695359714832659\n19.0\n7.211102550927978\n9.433981132056603\n7.280109889280518\n10.816653826391969\n14.071247279470288\n7.3484692283495345\n14.7648230602334\n19.6468827043885\n10.0\n54.70831746635972\n35.9722114972099\n\nhd95\n26.90724809414742\n9.433981132056603\n96.23876556549645\n5.0\n108.11406011770211\n3.7416573867739413\n2.449489742783178\n9.695359714832659\n93.86186658410419\n72.97944916207575\n29.571944956843524\n16.583123951777\n13.674794331177344\n3.4641016151377544\n6.324555320336759\n7.0710678118654755\n5.0990195135927845\n175.045279846421\n97.02576977277738\n9.695359714832659\n82.5838965156626\n7.3484692283495345\n4.0\n5.385164807134504\n3.0\n4.58257569495584\n12.884098726725126\n31.89043743820395\n10.686341501951889\n7.0\n10.198039027185569\n5.477225575051661\n4.0\n2.82842712474619\n4.358898943540673\n2.23606797749979\n87.89141025769918\n2.23606797749979\n70.80254232723568\n5.385164807134504\n8.0\n2.449489742783178\n5.196152422706632\n82.30431337420902\n7.0\n8.246211251235321\n2.23606797749979\n2.23606797749979\n3.605551275463989\n3.0\n3.1622776601683795\n2.23606797749979\n2.0\n2.449489742783178\n14.563649752637525\n2.23606797749979\n76.35607216253135\n2.23606797749979\n69.32532004974806\n78.77182237323191\n22.0\n29.816103031751148\n5.385164807134504\n8.12403840463596\n24.596747752497688\n3.6055512754639887\n2.23606797749979\n93.42911751697112\n41.15823125451335\n48.36320915737499\n4.0\n34.219877264537345\n6.4031242374328485\n30.086541107703034\n5.0\n49.45502970568492\n4.0\n4.47213595499958\n2.449489742783178\n2.449489742783178\n90.60905032059435\n38.65229618017538\n2.0\n1.7320508075688772\n11.0\n7.874007874011811\n6.708203932499369\n4.0\n41.78456644739525\n13.152946437965905\n9.055385138137417\n2.449489742783178\n36.359317925395686\n13.213583919217193\n3.0\n12.529964086141668\n4.0\n3.0\n3.4641016151377544\n17.0\n75.21303078589507\n4.0\n3.3166247903554\n5.0\n3.1622776601683795\n5.385164807134504\n5.0\n3.2008644427151345\n5.385164807134503\n92.74022856640875\n19.0\n11.445523142259598\n75.26619427073486\n82.516664983505\n139.08720285337884\n10.04987562112089\n9.16515138991168\n24.55605831561735\n3.0\n30.773365106858236\n10.099504938362077\n7.0\n3.0\n87.69121940868479\n79.96249120681522\n3.0\n8.12403840463596\n12.0\n30.35045247454564\n17.349351572897472\n3.0\n23.790754506740637\n23.09112221230079\n63.7102817447859\n3.3166247903554\n3.3166247903554\n9.433981132056603\n10.0\n39.726565100188104\n3.6055512754639887\n85.70880934886446\n16.30950643030009\n10.0\n99.33076040943503\n9.9498743710662\n91.07140056021979\n9.273618495495704\n9.899494936611665\n23.733937177299268\n3.6055512754639887\n10.435495205104173\n4.47213595499958\n5.744562646538029\n38.91015291668744\n80.06247560499239\n55.91064299397745\n23.08787512399791\n52.24940191045253\n2.0\n3.605551275463989\n3.0\n3.605551275463989\n7.874007874011811\n11.357816691600547\n12.36931687685298\n8.54400374531753\n4.0\n8.774964387392123\n3.7416573867739413\n37.8549864614954\n6.6332495807108\n5.65685424949238\n88.27117237777347\n2.0\n3.0\n19.662142425498963\n56.089214649520635\n32.89376840679705\n5.385164807134504\n5.0\n95.71050067041564\n12.806248474865697\n61.263773859530204\n92.61209424259879\n125.21900811881494\n36.90528417449187\n49.26860306191975\n49.48737212663448\n145.77585532994323\n70.61161377563892\n9.695359714832659\n29.8496231131986\n2.449489742783178\n3.0\n17.029386365926403\n17.705914293165936\n8.0\n3.0\n3.1622776601683795\n4.123105625617661\n6.0\n5.0\n90.91204540653565\n12.083045973594572\n29.563490998188964\n5.0990195135927845\n25.495097567963924\n2.23606797749979\n6.0\n5.0990195135927845\n14.0\n9.0\n39.8484610009415\n87.03648617959017\n10.816653826391969\n3.1622776601683795\n47.50789408087881\n2.0\n12.165525060596439\n8.734947837174538\n36.742346141747674\n3.6055512754639887\n2.82842712474619\n5.477225575051661\n3.0\n8.0\n3.0\n88.2269800004511\n29.0\n90.8795906364536\n93.87225271488859\n2.23606797749979\n2.374792124933526\n78.49203781276162\n52.05669968856889\n22.205833481472915\n2.449489742783178\n79.25969969927101\n31.256999216175565\n6.0\n8.12403840463596\n4.123105625617661\n13.038404810405297\n141.32055749903364\n89.48547329290838\n3.0\n30.298514815086236\n17.478552440554438\n3.605551275463989\n3.6055512754639887\n2.23606797749979\n16.55294535724685\n21.20259093476571\n68.26382398206042\n6.0\n3.605551275463989\n112.41885962773328\n3.0\n3.0\n75.7495874576225\n34.249084467635505\n91.33454987024352\n58.90670590009256\n93.83496150156401\n3.0\n4.898979485566356\n7.0\n29.816103031751148\n18.49324200890693\n7.280109889280517\n40.70626302087814\n24.269322199023193\n59.142624146095734\n6.708203932499369\n11.0\n120.70625501605126\n9.0\n78.3007024234138\n99.30709943261051\n12.041594578792296\n8.306623862918075\n3.0\n4.0\n15.425626405431375\n4.58257569495584\n3.0\n85.76129663198896\n4.47213595499958\n4.47213595499958\n19.235384061671343\n20.12833627981491\n6.082762530298219\n9.672090685604754\n3.0\n5.0990195135927845\n49.366991993038226\n5.0\n2.82842712474619\n10.0\n3.0\n3.0\n3.605551275463989\n3.0\n14.071247279470288\n3.0\n5.024754878398197\n7.280109889280518\n5.0\n26.291632361125323\n2.82842712474619\n11.180339887498949\n200\n3.1622776601683795\n3.0\n2.449489742783178\n2.449489742783178\n6.082762530298219\n13.892443989449804\n2.0\n10.954451150103322\n7.211102550927978\n2.449489742783178\n5.830951894845301\n3.0\n3.0\n5.0\n2.0\n3.0\n2.82842712474619\n3.0\n4.0\n5.385164807134504\n3.0\n3.3166247903554\n3.1622776601683795\n3.0\n9.0\n2.82842712474619\n2.449489742783178\n3.3166247903554\n2.449489742783178\n3.3166247903554\n2.23606797749979\n2.23606797749979\n2.449489742783178\n2.82842712474619\n2.82842712474619\n2.0\n2.23606797749979\n2.449489742783178\n4.0\n24.596747752497688\n3.0\n5.385164807134504\n8.717797887081346\n2.0\n4.242640687119285\n2.82842712474619\n4.123105625617661\n5.744562646538029\n5.385164807134504\n4.0\n30.033314835362415\n10.246950765959598\n2.23606797749979\n5.0\n5.0990195135927845\n5.385164807134504\n5.0\n2.449489742783178\n2.23606797749979\n2.82842712474619\n39.344631145812\n2.82842712474619\n1.7320508075688772\n14.730919862656235\n3.0\n7.0\n4.0\n3.7416573867739413\n9.0\n4.242640687119285\n3.1622776601683795\n3.0\n17.69180601295413\n3.162277660168379\n12.569805089976535\n5.0\n3.1622776601683795\n3.0\n21.37755832643195\n4.0\n4.0\n3.605551275463989\n4.0\n3.0\n5.744562646538029\n5.0\n3.605551275463989\n2.449489742783178\n16.0\n21.18962010041709\n3.7416573867739413\n3.0\n3.0\n11.0\n8.831760866327846\n5.385164807134504\n19.29244801288025\n3.0\n28.948229652260252\n5.830951894845301\n6.0\n2.82842712474619\n5.0\n7.0710678118654755\n3.0\n4.123105625617661\n6.0\n3.0\n3.1622776601683795\n3.0\n2.449489742783178\n4.47213595499958\n200\n3.7416573867739413\n3.0\n3.0\n5.0\n2.82842712474619\n3.0\n2.82842712474619\n3.0\n10.44030650891055\n4.0\n3.1622776601683795\n2.23606797749979\n7.3484692283495345\n7.0\n2.82842712474619\n3.1622776601683795\n11.180339887498949\n4.898979485566356\n4.0\n5.0\n2.449489742783178\n2.449489742783178\n17.146428199482248\n3.0\n2.23606797749979\n4.0\n2.23606797749979\n4.123105625617661\n9.848857801796104\n3.0\n13.19090595827292\n6.324555320336759\n4.123105625617661\n9.9498743710662\n3.0\n2.23606797749979\n3.0\n5.744562646538029\n2.23606797749979\n2.23606797749979\n3.4641016151377544\n11.31370849898476\n4.0\n12.806248474865697\n5.0\n5.385164807134503\n2.82842712474619\n5.995803989154736\n3.0\n2.82842712474619\n3.0\n48.9218762542661\n2.82842712474619\n6.0\n10.0\n7.0710678118654755\n2.449489742783178\n6.0\n3.0\n3.4641016151377544\n16.881943016134134\n11.180339887498949\n8.0\n4.0\n3.7416573867739413\n6.164414002968976\n6.0\n3.3166247903554\n2.23606797749979\n7.0\n20.024984394500787\n6.082762530298219\n3.0\n2.449489742783178\n6.0\n5.744562646538029\n14.2828568570857\n9.055385138137417\n5.0\n22.374089481358762\n10.0\n4.0\n48.176757881783615\n2.0\n11.090536506409418\n2.23606797749979\n37.36308338453881\n4.0\n2.449489742783178\n7.54983443527075\n2.23606797749979\n8.0\n3.0\n9.433981132056603\n28.653097563788805\n30.083217912982647\n2.23606797749979\n2.82842712474619\n3.0\n6.4031242374328485\n2.23606797749979\n4.69041575982343\n3.0\n4.0\n12.083045973594572\n6.0\n9.695359714832659\n4.123105625617661\n9.433981132056605\n5.0\n3.0\n3.0\n31.400636936215164\n18.027756377319946\n2.82842712474619\n4.123105625617661\n2.82842712474619\n12.206555615733702\n3.16227766016838\n3.605551275463989\n5.0\n4.0\n3.0\n4.0\n3.6055512754639887\n2.449489742783178\n2.0\n7.3484692283495345\n59.51470406546604\n3.0\n3.3166247903554\n5.0\n7.211102550927978\n2.82842712474619\n7.0\n5.0\n7.3484692283495345\n3.7416573867739413\n4.123105625617661\n7.0\n12.144905643670032\n200\n9.0\n4.0\n3.1622776601683795\n11.789826122551595\n3.0\n3.0\n4.0\n3.7416573867739413\n5.0\n3.0\n4.123105625617661\n5.0\n4.123105625617661\n21.93171219946131\n12.083045973594572\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cb7dadfddaede60079ee3b0d0bbd1ee562ae43d9
| 39,455 |
ipynb
|
Jupyter Notebook
|
module3-cross-validation/LS_DS_223_assignment.ipynb
|
nastyalolpro/DS-Unit-2-Kaggle-Challenge
|
47e7bcd6be40a58b6f6e02075e4aae1bc80547a0
|
[
"MIT"
] | null | null | null |
module3-cross-validation/LS_DS_223_assignment.ipynb
|
nastyalolpro/DS-Unit-2-Kaggle-Challenge
|
47e7bcd6be40a58b6f6e02075e4aae1bc80547a0
|
[
"MIT"
] | null | null | null |
module3-cross-validation/LS_DS_223_assignment.ipynb
|
nastyalolpro/DS-Unit-2-Kaggle-Challenge
|
47e7bcd6be40a58b6f6e02075e4aae1bc80547a0
|
[
"MIT"
] | null | null | null | 35.900819 | 452 | 0.432772 |
[
[
[
"Lambda School Data Science\n\n*Unit 2, Sprint 2, Module 3*\n\n---",
"_____no_output_____"
],
[
"# Cross-Validation\n\n\n## Assignment\n- [ ] [Review requirements for your portfolio project](https://lambdaschool.github.io/ds/unit2), then submit your dataset.\n- [ ] Continue to participate in our Kaggle challenge. \n- [ ] Use scikit-learn for hyperparameter optimization with RandomizedSearchCV.\n- [ ] Submit your predictions to our Kaggle competition. (Go to our Kaggle InClass competition webpage. Use the blue **Submit Predictions** button to upload your CSV file. Or you can use the Kaggle API to submit your predictions.)\n- [ ] Commit your notebook to your fork of the GitHub repo.\n\n\n**You can't just copy** from the lesson notebook to this assignment.\n\n- Because the lesson was **regression**, but the assignment is **classification.**\n- Because the lesson used [TargetEncoder](https://contrib.scikit-learn.org/categorical-encoding/targetencoder.html), which doesn't work as-is for _multi-class_ classification.\n\nSo you will have to adapt the example, which is good real-world practice.\n\n1. Use a model for classification, such as [RandomForestClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html)\n2. Use hyperparameters that match the classifier, such as `randomforestclassifier__ ...`\n3. Use a metric for classification, such as [`scoring='accuracy'`](https://scikit-learn.org/stable/modules/model_evaluation.html#common-cases-predefined-values)\n4. If you’re doing a multi-class classification problem — such as whether a waterpump is functional, functional needs repair, or nonfunctional — then use a categorical encoding that works for multi-class classification, such as [OrdinalEncoder](https://contrib.scikit-learn.org/categorical-encoding/ordinal.html) (not [TargetEncoder](https://contrib.scikit-learn.org/categorical-encoding/targetencoder.html))\n\n\n\n## Stretch Goals\n\n### Reading\n- Jake VanderPlas, [Python Data Science Handbook, Chapter 5.3](https://jakevdp.github.io/PythonDataScienceHandbook/05.03-hyperparameters-and-model-validation.html), Hyperparameters and Model Validation\n- Jake VanderPlas, [Statistics for Hackers](https://speakerdeck.com/jakevdp/statistics-for-hackers?slide=107)\n- Ron Zacharski, [A Programmer's Guide to Data Mining, Chapter 5](http://guidetodatamining.com/chapter5/), 10-fold cross validation\n- Sebastian Raschka, [A Basic Pipeline and Grid Search Setup](https://github.com/rasbt/python-machine-learning-book/blob/master/code/bonus/svm_iris_pipeline_and_gridsearch.ipynb)\n- Peter Worcester, [A Comparison of Grid Search and Randomized Search Using Scikit Learn](https://blog.usejournal.com/a-comparison-of-grid-search-and-randomized-search-using-scikit-learn-29823179bc85)\n\n### Doing\n- Add your own stretch goals!\n- Try other [categorical encodings](https://contrib.scikit-learn.org/categorical-encoding/). See the previous assignment notebook for details.\n- In additon to `RandomizedSearchCV`, scikit-learn has [`GridSearchCV`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html). Another library called scikit-optimize has [`BayesSearchCV`](https://scikit-optimize.github.io/notebooks/sklearn-gridsearchcv-replacement.html). Experiment with these alternatives.\n- _[Introduction to Machine Learning with Python](http://shop.oreilly.com/product/0636920030515.do)_ discusses options for \"Grid-Searching Which Model To Use\" in Chapter 6:\n\n> You can even go further in combining GridSearchCV and Pipeline: it is also possible to search over the actual steps being performed in the pipeline (say whether to use StandardScaler or MinMaxScaler). This leads to an even bigger search space and should be considered carefully. Trying all possible solutions is usually not a viable machine learning strategy. However, here is an example comparing a RandomForestClassifier and an SVC ...\n\nThe example is shown in [the accompanying notebook](https://github.com/amueller/introduction_to_ml_with_python/blob/master/06-algorithm-chains-and-pipelines.ipynb), code cells 35-37. Could you apply this concept to your own pipelines?\n",
"_____no_output_____"
],
[
"### BONUS: Stacking!\n\nHere's some code you can use to \"stack\" multiple submissions, which is another form of ensembling:\n\n```python\nimport pandas as pd\n\n# Filenames of your submissions you want to ensemble\nfiles = ['submission-01.csv', 'submission-02.csv', 'submission-03.csv']\n\ntarget = 'status_group'\nsubmissions = (pd.read_csv(file)[[target]] for file in files)\nensemble = pd.concat(submissions, axis='columns')\nmajority_vote = ensemble.mode(axis='columns')[0]\n\nsample_submission = pd.read_csv('sample_submission.csv')\nsubmission = sample_submission.copy()\nsubmission[target] = majority_vote\nsubmission.to_csv('my-ultimate-ensemble-submission.csv', index=False)\n```",
"_____no_output_____"
]
],
[
[
"%%capture\nimport sys\n\n# If you're on Colab:\nif 'google.colab' in sys.modules:\n DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/master/data/'\n !pip install category_encoders==2.*\n\n# If you're working locally:\nelse:\n DATA_PATH = '../data/'",
"_____no_output_____"
],
[
"import pandas as pd\n\n# Merge train_features.csv & train_labels.csv\ntrain = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'), \n pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))\n\n# Read test_features.csv & sample_submission.csv\ntest = pd.read_csv(DATA_PATH+'waterpumps/test_features.csv')\nsample_submission = pd.read_csv(DATA_PATH+'waterpumps/sample_submission.csv')",
"_____no_output_____"
],
[
"import numpy as np \n\ndef wrangle(X):\n\n #prevent SettingWithCopy warning\n X = X.copy()\n\n #replace really small nums in latitude with zeros\n X['latitude'] = X['latitude'].replace(-2.000000e-08, 0)\n\n #for both cols replace zeros with nans:\n cols_with_zeros = ['longitude', 'latitude', 'construction_year', 'public_meeting', ]\n for col in cols_with_zeros:\n X[col] = X[col].replace(0, np.nan)\n\n X['date_recorded'] = pd.to_datetime(X['date_recorded'])\n X['day_recorded'] = pd.DatetimeIndex(X['date_recorded']).day\n X['month_recorded'] = pd.DatetimeIndex(X['date_recorded']).month\n X['year_recorded'] = pd.DatetimeIndex(X['date_recorded']).year\n X['years_since_construction'] = X['year_recorded'] - X['construction_year']\n\n # Reduce cardinality for funder feature ...\n top49 = train['funder'].value_counts()[:49].index\n X.loc[~X['funder'].isin(top49), 'funder'] = 'other'\n\n #enough water?\n X['enough'] = np.where(X['quantity'] == 'enough', 1, 0)\n\n\n #peple per water\n X['pop_per_water'] = X['amount_tsh'] / X['population']\n\n #drop one of the same/almost same cols, cols with a lot of missing data\n X = X.drop(columns= ['quantity_group', 'date_recorded', 'payment_type', 'num_private', \n 'source_class', 'source_type', 'waterpoint_type_group', 'quality_group',\n 'extraction_type_group', 'extraction_type_class', 'management_group', 'scheme_management'])\n\n #return wrangled dataset\n return X",
"_____no_output_____"
],
[
"train = wrangle(train)\ntest = wrangle(test)",
"_____no_output_____"
],
[
"#select features\ntarget = 'status_group'\n\n#get a data frame with all features\ntrain_features = train.drop(columns = [target,'id', 'recorded_by'])\n\n#get numeric features\nnumeric = train_features.select_dtypes(include='number').columns.tolist()\n\n#get cardinality of categorical colummns\ncardinality = train_features.select_dtypes(exclude = 'number').nunique()\n\n#exlude columns with cardinality more than 50 \ncategorical = cardinality[cardinality <= 50 ].index.tolist()\n\n#combine\nfeatures = categorical + numeric\n\nprint(features)",
"['funder', 'basin', 'region', 'public_meeting', 'permit', 'extraction_type', 'management', 'payment', 'water_quality', 'quantity', 'source', 'waterpoint_type', 'amount_tsh', 'gps_height', 'longitude', 'latitude', 'region_code', 'district_code', 'population', 'construction_year', 'day_recorded', 'month_recorded', 'year_recorded', 'years_since_construction', 'enough', 'pop_per_water']\n"
],
[
"X_train = train[features]\ny_train = train[target]",
"_____no_output_____"
],
[
"X_train['quantity'].value_counts()",
"_____no_output_____"
],
[
"y_train",
"_____no_output_____"
],
[
"X_train.head()",
"_____no_output_____"
],
[
"X_train = X_train.replace([np.inf, -np.inf], np.nan)",
"_____no_output_____"
],
[
"# imports\nimport category_encoders as ce\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import SelectKBest, f_regression\nfrom sklearn.model_selection import cross_val_score\n\npipeline = make_pipeline(\n ce.OrdinalEncoder(),\n SimpleImputer(strategy='mean'),\n #StandardScaler(),\n #SelectKBest(f_regression, k = 40),\n RandomForestClassifier(random_state=0, n_jobs=-1)\n)\n\nk = 5 \nscores = cross_val_score(pipeline, X_train, y_train, cv=k, \n scoring='accuracy')\nprint(f'Accuracy for {k} folds:', scores)",
"/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.\n import pandas.util.testing as tm\n"
],
[
"print('Model Hyperparameters:')\nprint(pipeline.named_steps['randomforestclassifier'])\nprint(pipeline.named_steps['ordinalencoder'])\nprint(pipeline.named_steps['simpleimputer'])",
"Model Hyperparameters:\nRandomForestClassifier(bootstrap=True, ccp_alpha=0.0, class_weight=None,\n criterion='gini', max_depth=None, max_features='auto',\n max_leaf_nodes=None, max_samples=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=-1, oob_score=False, random_state=0, verbose=0,\n warm_start=False)\nOrdinalEncoder(cols=None, drop_invariant=False, handle_missing='value',\n handle_unknown='value', mapping=None, return_df=True, verbose=0)\nSimpleImputer(add_indicator=False, copy=True, fill_value=None,\n missing_values=nan, strategy='mean', verbose=0)\n"
],
[
"from sklearn.model_selection import RandomizedSearchCV\nfrom scipy.stats import randint, uniform\n\nparam_distributions = {\n #'simpleimputer__strategy' : ['mean', 'median'], \n 'randomforestclassifier__max_depth': [5, 10, 15, 20, 30, 40, None],\n 'randomforestclassifier__n_estimators': randint(50, 500),\n 'randomforestclassifier__max_features': uniform(0, 1),\n 'randomforestclassifier__min_samples_leaf': [10,20,30,40,50],\n}\n\nsearch = RandomizedSearchCV(\n pipeline,\n param_distributions= param_distributions,\n n_iter = 10,\n cv = 5,\n scoring = 'accuracy', \n verbose=10, \n return_train_score=True, \n n_jobs=-1\n)\n\nsearch.fit(X_train, y_train);",
"Fitting 5 folds for each of 10 candidates, totalling 50 fits\n"
],
[
"print('Best hyperparameters: ', search.best_params_)\nprint('Best accuracy: ', search.best_score_)",
"Best hyperparameters: {'randomforestclassifier__max_depth': 20, 'randomforestclassifier__max_features': 0.23666788577357034, 'randomforestclassifier__min_samples_leaf': 10, 'randomforestclassifier__n_estimators': 254}\nBest accuracy: 0.7966161616161616\n"
],
[
"pipeline = search.best_estimator_",
"_____no_output_____"
],
[
"X_test = test[features]",
"_____no_output_____"
],
[
"X_test = X_test.replace([np.inf, -np.inf], np.nan)",
"_____no_output_____"
],
[
"y_pred = pipeline.predict(X_test)",
"_____no_output_____"
],
[
"print(len(test))\nprint(len(y_pred))",
"14358\n14358\n"
],
[
"test.index",
"_____no_output_____"
],
[
"sample_submission.head()",
"_____no_output_____"
],
[
"submission=pd.DataFrame(y_pred, columns=['status_group'])\nsubmission['id']=sample_submission.id\nsubmission=submission[['id', 'status_group']]\nsubmission.tail()",
"_____no_output_____"
],
[
"submission.to_csv('submission_file.csv',index=False)",
"_____no_output_____"
]
]
] |
[
"markdown",
"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"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.