hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
sequence | cell_types
sequence | cell_type_groups
sequence |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e7af4797a44b2ff9d3f2d9cd35645e2ddbc84d80 | 54,954 | ipynb | Jupyter Notebook | notebooks/Malo2014.ipynb | BrownDwarf/ApJdataFrames | 15fee28b1201d963b6911cd292342f2c8baaa75f | [
"MIT"
] | 4 | 2016-09-28T02:36:48.000Z | 2020-10-06T21:35:29.000Z | notebooks/Malo2014.ipynb | BrownDwarf/ApJdataFrames | 15fee28b1201d963b6911cd292342f2c8baaa75f | [
"MIT"
] | null | null | null | notebooks/Malo2014.ipynb | BrownDwarf/ApJdataFrames | 15fee28b1201d963b6911cd292342f2c8baaa75f | [
"MIT"
] | 1 | 2019-10-05T04:42:12.000Z | 2019-10-05T04:42:12.000Z | 195.565836 | 34,532 | 0.786804 | [
[
[
"`ApJdataFrames` Malo et al. 2014\n---\n`Title`: BANYAN. III. Radial velocity, Rotation and X-ray emission of low-mass star candidates in nearby young kinematic groups \n`Authors`: Malo L., Artigau E., Doyon R., Lafreniere D., Albert L., Gagne J.\n\nData is from this paper: \nhttp://iopscience.iop.org/article/10.1088/0004-637X/722/1/311/",
"_____no_output_____"
]
],
[
[
"import warnings\nwarnings.filterwarnings(\"ignore\")",
"_____no_output_____"
],
[
"from astropy.io import ascii",
"_____no_output_____"
],
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"## Table 1 - Target Information for Ophiuchus Sources",
"_____no_output_____"
]
],
[
[
"#! mkdir ../data/Malo2014\n#! wget http://iopscience.iop.org/0004-637X/788/1/81/suppdata/apj494919t7_mrt.txt",
"_____no_output_____"
],
[
"! head ../data/Malo2014/apj494919t7_mrt.txt",
"Title: BANYAN. III. Radial velocity, Rotation and X-ray emission of low-mass \r\n star candidates in nearby young kinematic groups \r\nAuthors: Malo L., Artigau E., Doyon R., Lafreniere D., Albert L., Gagne J.\r\nTable:\r\n================================================================================\r\nByte-by-byte Description of file: apj494919t7_mrt.txt\r\n--------------------------------------------------------------------------------\r\n Bytes Format Units Label Explanations\r\n--------------------------------------------------------------------------------\r\n 1- 29 A29 --- Mem Member identifier\r\n"
],
[
"from astropy.table import Table, Column",
"_____no_output_____"
],
[
"t1 = Table.read(\"../data/Malo2014/apj494919t7_mrt.txt\", format='ascii') ",
"_____no_output_____"
],
[
"sns.distplot(t1['Jmag'].data.data)",
"//anaconda/lib/python3.4/site-packages/numpy/lib/function_base.py:564: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n n = np.zeros(bins, ntype)\n//anaconda/lib/python3.4/site-packages/numpy/lib/function_base.py:600: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n n += np.bincount(indices, weights=tmp_w, minlength=bins).astype(ntype)\n//anaconda/lib/python3.4/site-packages/statsmodels/nonparametric/kdetools.py:20: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future\n y = X[:m/2+1] + np.r_[0,X[m/2+1:],0]*1j\n"
],
[
"t1",
"_____no_output_____"
]
],
[
[
"The end.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7af486de5efe77676d3c23f349b49a89239cb7d | 30,845 | ipynb | Jupyter Notebook | 2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb | aosokin/DL_CSHSE_spring2018 | 8ca09fddecca0acb3e8364bb9f8441a5750e5d44 | [
"Apache-2.0"
] | 79 | 2018-04-02T21:03:55.000Z | 2018-11-15T19:33:34.000Z | 2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb | aosokin/DL_CSHSE | 8ca09fddecca0acb3e8364bb9f8441a5750e5d44 | [
"Apache-2.0"
] | null | null | null | 2020-fall/seminars/seminar3/DL20_fall_seminar3.ipynb | aosokin/DL_CSHSE | 8ca09fddecca0acb3e8364bb9f8441a5750e5d44 | [
"Apache-2.0"
] | 24 | 2019-09-26T11:54:55.000Z | 2021-12-16T09:28:23.000Z | 33.673581 | 606 | 0.484779 | [
[
[
"# Основные виды нейросетей (CNN и RNN)\n\n**Разработчик: Алексей Умнов**",
"_____no_output_____"
],
[
"Этот семинар будет состоять из двух частей: сначала мы позанимаемся реализацией сверточных и рекуррентных сетей, а потом поисследуем проблему затухающих и взрывающихся градиентов.",
"_____no_output_____"
],
[
"## Сверточные сети\n\nВернемся в очередной раз к датасету MNIST. Для начала загрузим данные и определим несколько полезных функций как на прошлом семинаре.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nfrom IPython.display import clear_output\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nrandom.seed(42)\nnp.random.seed(42)\ntorch.manual_seed(42)\nif torch.cuda.is_available():\n torch.cuda.manual_seed_all(42)",
"_____no_output_____"
],
[
"from util import load_mnist\nX_train, y_train, X_val, y_val, X_test, y_test = load_mnist(flatten=True)\n\nplt.figure(figsize=[6, 6])\nfor i in range(4):\n plt.subplot(2, 2, i + 1)\n plt.title(\"Label: %i\" % y_train[i])\n plt.imshow(X_train[i].reshape([28, 28]), cmap='gray');",
"_____no_output_____"
],
[
"from util import iterate_minibatches\n\ndef train_epoch(model, optimizer, batchsize=32):\n loss_log, acc_log = [], []\n model.train()\n for x_batch, y_batch in iterate_minibatches(X_train, y_train, batchsize=batchsize, shuffle=True):\n data = torch.from_numpy(x_batch.astype(np.float32))\n target = torch.from_numpy(y_batch.astype(np.int64))\n\n optimizer.zero_grad()\n output = model(data)\n \n pred = torch.max(output, 1)[1].numpy()\n acc = np.mean(pred == y_batch)\n acc_log.append(acc)\n \n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n loss = loss.item()\n loss_log.append(loss)\n return loss_log, acc_log\n\ndef test(model):\n loss_log, acc_log = [], []\n model.eval()\n for x_batch, y_batch in iterate_minibatches(X_val, y_val, batchsize=32, shuffle=True):\n data = torch.from_numpy(x_batch.astype(np.float32))\n target = torch.from_numpy(y_batch.astype(np.int64))\n\n output = model(data)\n loss = F.nll_loss(output, target)\n \n pred = torch.max(output, 1)[1].numpy()\n acc = np.mean(pred == y_batch)\n acc_log.append(acc)\n \n loss = loss.item()\n loss_log.append(loss)\n return loss_log, acc_log\n\ndef plot_history(train_history, val_history, title='loss'):\n plt.figure()\n plt.title('{}'.format(title))\n plt.plot(train_history, label='train', zorder=1)\n \n points = np.array(val_history)\n \n plt.scatter(points[:, 0], points[:, 1], marker='+', s=180, c='orange', label='val', zorder=2)\n plt.xlabel('train steps')\n \n plt.legend(loc='best')\n plt.grid()\n\n plt.show()\n \ndef train(model, opt, n_epochs):\n train_log, train_acc_log = [], []\n val_log, val_acc_log = [], []\n\n batchsize = 32\n\n for epoch in range(n_epochs):\n print(\"Epoch {} of {}\".format(epoch, n_epochs))\n train_loss, train_acc = train_epoch(model, opt, batchsize=batchsize)\n\n val_loss, val_acc = test(model)\n\n train_log.extend(train_loss)\n train_acc_log.extend(train_acc)\n\n steps = len(X_train) / batchsize\n val_log.append((steps * (epoch + 1), np.mean(val_loss)))\n val_acc_log.append((steps * (epoch + 1), np.mean(val_acc)))\n\n clear_output()\n plot_history(train_log, val_log) \n plot_history(train_acc_log, val_acc_log, title='accuracy')\n print(\"Epoch {} error = {:.2%}\".format(epoch, 1 - val_acc_log[-1][1]))\n \n print(\"Final error: {:.2%}\".format(1 - val_acc_log[-1][1]))",
"_____no_output_____"
]
],
[
[
"**Задание 1:** Реализуйте сверточную сеть, которая состоит из двух последовательных применений свертки, relu и max-пулинга, а потом полносвязного слоя. Подберите параметры так, чтобы на выходе последнего слоя размерность тензора была 4 x 4 x 16. В коде ниже используется обертка nn.Sequential, ознакомьтесь с ее интерфейсом.\n\nДобейтесь, чтобы ошибка классификации после обучения (см. ниже) была не выше 1.5%.",
"_____no_output_____"
]
],
[
[
"class ConvNet(nn.Module):\n def __init__(self):\n super().__init__()\n \n self.features = nn.Sequential(\n # <your code here>\n )\n \n self.classifier = nn.Linear(4 * 4 * 16, 10)\n \n def forward(self, x):\n # <your code here>\n return F.log_softmax(out, dim=-1)",
"_____no_output_____"
]
],
[
[
"Посчитаем количество обучаемых параметров сети (полносвязные сети с прошлого семинара имеют 30-40 тысяч параметров).",
"_____no_output_____"
]
],
[
[
"def count_parameters(model):\n model_parameters = filter(lambda p: p.requires_grad, model.parameters())\n return sum([np.prod(p.size()) for p in model_parameters])\n\nmodel = ConvNet()\nprint(\"Total number of trainable parameters:\", count_parameters(model))",
"_____no_output_____"
],
[
"%%time\n\nopt = torch.optim.RMSprop(model.parameters(), lr=0.001)\ntrain(model, opt, 5)",
"_____no_output_____"
]
],
[
[
"Мы с легкостью получили качество классификаци лучше, чем было раньше с помощью полносвязных сетей. На самом деле для более честного сравнения нужно поисследовать обе архитектуры и подождать побольше итераций до сходимости, но в силу ограниченности вычислительных ресурсов мы это сделать не можем. Результаты из которых \"выжали максимум\" можно посмотреть например, на этой странице: http://yann.lecun.com/exdb/mnist/, и там видно, что качество сверточных сетей гораздо выше. А если работать с более сложными изоражениями (например, с ImageNet), то сверточные сети побеждают с большим отрывом.\n\n**Упражнение:** Вспомните материалы лекции и ответьте на вопросы ниже:\n* Почему сверточные сети обладают таким преимуществом именно для изображений?\n* Почему несмотря на малое количество параметров обучение сверточных сетей занимает так много времени?",
"_____no_output_____"
],
[
"## Рекуррентные сети\n\nДля рекуррентных сетей используем датасет с именами и будем определять из какого языка произошло данное имя. Для этого построим рекуррентную сеть, которая с именами на уровне символов. Для начала скачаем файлы и конвертируем их к удобному формату (можно не особо вникать в этот код).",
"_____no_output_____"
]
],
[
[
"# На Windows придется скачать архив по ссылке (~3Mb) и распаковать самостоятельно\n! wget -nc https://download.pytorch.org/tutorial/data.zip\n! unzip -n ./data.zip",
"_____no_output_____"
],
[
"from io import open\nimport glob\n\ndef findFiles(path): return glob.glob(path)\n\nprint(findFiles('data/names/*.txt'))\n\nimport unicodedata\nimport string\n\nall_letters = string.ascii_letters + \" .,;'\"\nn_letters = len(all_letters)\n\n# Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427\ndef unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n and c in all_letters\n )\n\nprint(unicodeToAscii('Ślusàrski'))\n\n# Build the category_lines dictionary, a list of names per language\ncategory_lines = {}\nall_categories = []\n\n# Read a file and split into lines\ndef readLines(filename):\n lines = open(filename, encoding='utf-8').read().strip().split('\\n')\n return [unicodeToAscii(line) for line in lines]\n\nfor filename in findFiles('data/names/*.txt'):\n category = filename.split('/')[-1].split('.')[0]\n all_categories.append(category)\n lines = readLines(filename)\n category_lines[category] = lines\n\nn_categories = len(all_categories)\n\ndef categoryFromOutput(output):\n top_n, top_i = output.topk(1)\n category_i = top_i[0][0]\n return all_categories[category_i], category_i",
"_____no_output_____"
]
],
[
[
"Определим несколько удобных функций для конвертации букв и слов в тензоры.\n\n**Задание 2**: напишите последнюю функцию для конвертации слова в тензор.",
"_____no_output_____"
]
],
[
[
"# Find letter index from all_letters, e.g. \"a\" = 0\ndef letterToIndex(letter):\n return all_letters.find(letter)\n\n# Just for demonstration, turn a letter into a <1 x n_letters> Tensor\ndef letterToTensor(letter):\n tensor = torch.zeros(1, n_letters)\n tensor[0][letterToIndex(letter)] = 1\n return tensor\n\n# Turn a line into a <line_length x 1 x n_letters>,\n# or an array of one-hot letter vectors\ndef lineToTensor(line):\n # <your code here>\n\nprint(letterToTensor('J'))\nprint(lineToTensor('Jones').size())",
"_____no_output_____"
]
],
[
[
"**Задание 3:** Реализуйте однослойную рекуррентную сеть.",
"_____no_output_____"
]
],
[
[
"class RNNCell(nn.Module):\n def __init__(self, input_size, hidden_size):\n super(RNNCell, self).__init__()\n \n self.hidden_size = hidden_size\n # <your code here>\n # <end>\n\n def forward(self, input, hidden):\n # <your code here>\n # <end>\n return hidden\n\n def initHidden(self):\n return torch.zeros(1, self.hidden_size)\n\nn_hidden = 128\nrnncell = RNNCell(n_letters, n_hidden)",
"_____no_output_____"
]
],
[
[
"Предсказание будем осуществлять при помощи линейного класссификатора поверх скрытых состояний сети.",
"_____no_output_____"
]
],
[
[
"classifier = nn.Sequential(nn.Linear(n_hidden, n_categories), nn.LogSoftmax(dim=1))",
"_____no_output_____"
]
],
[
[
"Проверим, что все корректно работает: выходы классификаторы должны быть лог-вероятностями.",
"_____no_output_____"
]
],
[
[
"input = letterToTensor('A')\nhidden = torch.zeros(1, n_hidden)\n\noutput = classifier(rnncell(input, hidden))\nprint(output)\nprint(torch.exp(output).sum())",
"_____no_output_____"
],
[
"input = lineToTensor('Albert')\nhidden = torch.zeros(1, n_hidden)\n\noutput = classifier(rnncell(input[0], hidden))\nprint(output)\nprint(torch.exp(output).sum())",
"_____no_output_____"
]
],
[
[
"Для простоты в этот раз будем оптимизировать не по мини-батчам, а по отдельным примерам. Ниже несколько полезных функций для этого.",
"_____no_output_____"
]
],
[
[
"import random\n\ndef randomChoice(l):\n return l[random.randint(0, len(l) - 1)]\n\ndef randomTrainingExample():\n category = randomChoice(all_categories)\n line = randomChoice(category_lines[category])\n category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long)\n line_tensor = lineToTensor(line)\n return category, line, category_tensor, line_tensor\n\nfor i in range(10):\n category, line, category_tensor, line_tensor = randomTrainingExample()\n print('category =', category, '/ line =', line)",
"_____no_output_____"
]
],
[
[
"**Задание 4:** Реализуйте вычисление ответа в функции train. Если все сделано правильно, то точность на обучающей выборке должна быть не менее 70%.",
"_____no_output_____"
]
],
[
[
"from tqdm import trange\n\ndef train(category, category_tensor, line_tensor, optimizer):\n hidden = rnncell.initHidden()\n\n rnncell.zero_grad()\n classifier.zero_grad()\n\n # <your code here>\n # use rnncell and classifier\n # <end>\n\n loss = F.nll_loss(output, category_tensor)\n loss.backward()\n optimizer.step()\n \n acc = (categoryFromOutput(output)[0] == category)\n\n return loss.item(), acc\n\nn_iters = 50000\nplot_every = 1000\n\ncurrent_loss = 0\nall_losses = []\ncurrent_acc = 0\nall_accs = []\n\nn_hidden = 128\n\nrnncell = RNNCell(n_letters, n_hidden)\nclassifier = nn.Sequential(nn.Linear(n_hidden, n_categories), nn.LogSoftmax(dim=1))\nparams = list(rnncell.parameters()) + list(classifier.parameters())\nopt = torch.optim.RMSprop(params, lr=0.001)\nfor iter in trange(1, n_iters + 1):\n category, line, category_tensor, line_tensor = randomTrainingExample()\n loss, acc = train(category, category_tensor, line_tensor, opt)\n current_loss += loss\n current_acc += acc\n\n # Add current loss avg to list of losses\n if iter % plot_every == 0:\n all_losses.append(current_loss / plot_every)\n current_loss = 0\n all_accs.append(current_acc / plot_every)\n current_acc = 0\n \nplt.figure()\nplt.title(\"Loss\")\nplt.plot(all_losses)\nplt.grid()\nplt.show()\n\nplt.figure()\nplt.title(\"Accuracy\")\nplt.plot(all_accs)\nplt.grid()\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Затухающие и взрывающиеся градиенты\n\nЭксперименты будем проводить опять на датасете MNIST, но будем работать с полносвязными сетями. В этом разделе мы не будем пытаться подобрать более удачную архитектуру, нам интересно только посмотреть на особенности обучения глубоких сетей.",
"_____no_output_____"
]
],
[
[
"from util import load_mnist\nX_train, y_train, X_val, y_val, X_test, y_test = load_mnist(flatten=True)",
"_____no_output_____"
]
],
[
[
"Для экспериментов нам понадобится реализовать сеть, в которой можно легко менять количество слоев. Также эта сеть должна сохранять градиенты на всех слоях, чтобы потом мы могли посмотреть на их величины.\n\n**Задание 5:** допишите недостающую часть кода ниже.",
"_____no_output_____"
]
],
[
[
"class DeepDenseNet(nn.Module):\n def __init__(self, n_layers, hidden_size, activation):\n super().__init__()\n self.activation = activation\n \n l0 = nn.Linear(X_train.shape[1], hidden_size)\n self.weights = [l0.weight]\n self.layers = [l0]\n \n # <your code here>\n \n self.seq = nn.Sequential(*self.layers)\n \n for l in self.weights:\n l.retain_grad()\n \n def forward(self, x):\n out = self.seq(x)\n return F.log_softmax(out, dim=-1)",
"_____no_output_____"
]
],
[
[
"Модифицируем наши функции обучения, чтобы они также рисовали графики изменения градиентов.",
"_____no_output_____"
]
],
[
[
"import scipy.sparse.linalg\n\ndef train_epoch_grad(model, optimizer, batchsize=32):\n loss_log, acc_log = [], []\n grads = [[] for l in model.weights]\n model.train()\n for x_batch, y_batch in iterate_minibatches(X_train, y_train, batchsize=batchsize, shuffle=True):\n # data preparation\n data = torch.from_numpy(x_batch.astype(np.float32))\n target = torch.from_numpy(y_batch.astype(np.int64))\n\n optimizer.zero_grad()\n output = model(data)\n \n pred = torch.max(output, 1)[1].numpy()\n acc = np.mean(pred == y_batch)\n acc_log.append(acc)\n \n loss = F.nll_loss(output, target)\n # compute gradients\n loss.backward()\n # make a step\n optimizer.step()\n loss = loss.item()\n loss_log.append(loss)\n \n for g, l in zip(grads, model.weights):\n g.append(np.linalg.norm(l.grad.numpy()))\n return loss_log, acc_log, grads\n\n\ndef train_grad(model, opt, n_epochs):\n train_log, train_acc_log = [], []\n val_log, val_acc_log = [], []\n grads_log = None\n\n batchsize = 32\n\n for epoch in range(n_epochs):\n print(\"Epoch {} of {}\".format(epoch, n_epochs))\n train_loss, train_acc, grads = train_epoch_grad(model, opt, batchsize=batchsize)\n if grads_log is None:\n grads_log = grads\n else:\n for a, b in zip(grads_log, grads):\n a.extend(b)\n\n val_loss, val_acc = test(model)\n\n train_log.extend(train_loss)\n train_acc_log.extend(train_acc)\n\n steps = len(X_train) / batchsize\n val_log.append((steps * (epoch + 1), np.mean(val_loss)))\n val_acc_log.append((steps * (epoch + 1), np.mean(val_acc)))\n\n # display all metrics\n clear_output()\n plot_history(train_log, val_log) \n plot_history(train_acc_log, val_acc_log, title='accuracy') \n\n plt.figure()\n all_vals = []\n for i, g in enumerate(grads_log):\n w = np.ones(100)\n w /= w.sum()\n vals = np.convolve(w, g, mode='valid')\n plt.semilogy(vals, label=str(i+1), color=plt.cm.coolwarm((i / len(grads_log))))\n all_vals.extend(vals)\n plt.legend(loc='best')\n plt.grid()\n plt.show()",
"_____no_output_____"
]
],
[
[
"**Задание 6:**\n* Обучите сети глубины 10 и больше с сигмоидой в качестве активации. Исследуйте, как глубина влияет на качество обучения и поведение градиентов на далеких от выхода слоях.\n* Теперь замените активацию на ReLU и посмотрите, что получится.",
"_____no_output_____"
]
],
[
[
"# ...",
"_____no_output_____"
]
],
[
[
"Теперь попробуем добавить в сеть skip-connections (по примеру ResNet) вместо замены сигмоиды на relu и посмотрим, что получится. Запихнуть все слои в nn.Sequential и просто их применить теперь не получится - вместо этого мы их применим вручную. Но положить их в отдельный модуль nn.Sequential все равно нужно, иначе torch не сможет их найти и оптимизировать.\n\n**Задание 7:** допишите недостающую часть кода ниже.",
"_____no_output_____"
]
],
[
[
"class DeepDenseResNet(nn.Module):\n def __init__(self, n_layers, hidden_size, activation):\n super().__init__()\n self.activation = activation\n \n l0 = nn.Linear(X_train.shape[1], hidden_size)\n self.weights = [l0.weight]\n self.layers = [l0]\n \n for i in range(1, n_layers - 1):\n l = nn.Linear(hidden_size, hidden_size)\n self.layers.append(l)\n self.weights.append(l.weight)\n \n l = nn.Linear(hidden_size, 10)\n self.layers.append(l)\n self.weights.append(l.weight)\n \n self.seq = nn.Sequential(*self.layers)\n \n for l in self.weights:\n l.retain_grad()\n \n def forward(self, x):\n \n # <your code here>\n \n return F.log_softmax(x, dim=-1)",
"_____no_output_____"
]
],
[
[
"Убедимся, что такая сеть отлично учится даже на большом числе слоев.",
"_____no_output_____"
]
],
[
[
"model = DeepDenseResNet(n_layers=20, hidden_size=10, activation=nn.Sigmoid)\nopt = torch.optim.RMSprop(model.parameters(), lr=0.001)\n\ntrain_grad(model, opt, 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",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"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"
]
] |
e7af49a9d0a88fe36dbb52cd23acdb8c0a4a1803 | 17,729 | ipynb | Jupyter Notebook | commandments.ipynb | DavidLeoni/softpython- | f832762e60556b2b3be13f2befbfb5343716a81a | [
"CC-BY-4.0"
] | 2 | 2021-04-28T08:31:14.000Z | 2021-08-13T19:43:55.000Z | commandments.ipynb | DavidLeoni/softpython- | f832762e60556b2b3be13f2befbfb5343716a81a | [
"CC-BY-4.0"
] | 14 | 2020-07-13T16:36:31.000Z | 2021-12-08T16:47:54.000Z | commandments.ipynb | DavidLeoni/softpython-it | f832762e60556b2b3be13f2befbfb5343716a81a | [
"CC-BY-4.0"
] | null | null | null | 23.958108 | 216 | 0.50973 | [
[
[
"# Comandamenti\n\n",
"_____no_output_____"
],
[
"Il Comitato Supremo per la Dottrina del Coding ha emanato importanti comandamenti che seguirai scrupolosamente.\n\nSe accetti le loro sagge parole, diventerai un vero Jedi Python.\n",
"_____no_output_____"
],
[
"<div class=\"alert alert-warning\">\n\n**ATTENZIONE**: se non segui i Comandamenti, finirai nel _Debugging Hell_ !\n</div>\n",
"_____no_output_____"
],
[
"## I COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Scriverai codice Python**\n</div>\n\nChi non scrive codice Python, non impara Python",
"_____no_output_____"
],
[
"## II COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Quando inserisci una variabile in un ciclo** `for`**, questa variabile deve essere nuova**\n</div>",
"_____no_output_____"
],
[
"Se hai definito la variabile prima, non la reintrodurrai in un `for`, perchè ciò portebbe confusione nelle menti di chi legge.\n\nPerciò evita questi peccati:",
"_____no_output_____"
]
],
[
[
"i = 7\nfor i in range(3): # peccato, perdi la variabile i\n print(i)\n \nprint(i) # stampa 2 e non 7 !!",
"0\n1\n2\n2\n"
],
[
"def f(i):\n for i in range(3): # altro peccato, perdi il parametro i\n print(i)\n \n print(i) # stampa 2, e non il 7 che gli abbiamo passato !\n \nf(7)",
"0\n1\n2\n2\n"
],
[
"for i in range(2): \n \n for i in range(5): # inferno da debuggare, perdi l'i del ciclo for esterno\n print(i)\n \n print(i) # stampa 4 !!",
"0\n1\n2\n3\n4\n4\n0\n1\n2\n3\n4\n4\n"
]
],
[
[
"## III COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Noi riassegnerai mai parametri di funzione**\n\n</div>\n\nNon farai mai nessuna di queste assegnazioni, pena la perdita del parametro passato quando viene chiamata la funzione:",
"_____no_output_____"
]
],
[
[
"def peccato(intero):\n intero = 666 # peccato, hai perso il 5 passato dall'esterno !\n print(intero) # stampa 666\n \nx = 5\npeccato(x)",
"666\n"
]
],
[
[
"Lo stesso discorso si applica per tutti gli altri tipi:",
"_____no_output_____"
]
],
[
[
"def male(stringa):\n stringa = \"666\" ",
"_____no_output_____"
],
[
"def disgrazia(lista):\n lista = [666]",
"_____no_output_____"
],
[
"def delirio(dizionario):\n dizionario = {\"evil\":666}",
"_____no_output_____"
]
],
[
[
"Per il solo caso di parametri compositi come liste o dizionari, puoi scrivere come sotto \nSE E SOLO SE le specifiche della funzione ti richiedono di MODIFICARE gli elementi interni del \nparametro (come per esempio ordinare una lista o cambiare il campo di un dizionario)",
"_____no_output_____"
]
],
[
[
"# MODIFICA lista in qualche modo\ndef consentito(lista): \n lista[2] = 9 # OK, lo richiede il testo della funzione\n \nfuori = [8,5,7]\nconsentito(fuori)\nprint(fuori)",
"[8, 5, 9]\n"
],
[
"# MODIFICA dizionario in qualche modo\ndef daccordo(dizionario):\n dizionario[\"mio campo\"] = 5 # OK, lo richiede il testo",
"_____no_output_____"
],
[
"# MODIFICA istanza in qualche modo\ndef va_bene(istanza_di_classe):\n istanza_di_classe.mio_campo = 7 # OK, lo richiede il testo",
"_____no_output_____"
]
],
[
[
"Se invece il testo di una funzione ti chiede di RITORNARE un NUOVO oggetto, non cadrai nella tentazione di modificare l'input:",
"_____no_output_____"
]
],
[
[
"\n# RITORNA una NUOVA lista ordinata\ndef dolore(lista):\n lista.sort() # MALE, stai modificando la lista di input invece di crearne una nuova!\n return lista",
"_____no_output_____"
],
[
"# RITORNA una NUOVA lista \ndef crisi(lista):\n lista[0] = 5 # MALE, come sopra\n return lista",
"_____no_output_____"
],
[
"# RITORNA un NUOVO dizionario \ndef tormento(dizionario):\n dizionario['a'] = 6 # MALE, stai modificando il dizionario di input \n # invece di crearne uno nuovo!\n return dizionario",
"_____no_output_____"
],
[
"# RITORNA una NUOVA istanza di classe\ndef disperazione(istanza):\n istanza.mio_campo = 6 # MALE, stai modificando l'oggetto di input\n # invece di crearne uno nuovo!\n return istanza",
"_____no_output_____"
]
],
[
[
"## IV COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Non riassegnerai mai valori a chiamate a funzioni o metodi**\n\n</div>\n\n\n```python\n\nmia_funzione() = 666 # SBAGLIATO \nmia_funzione() = 'evil' # SBAGLIATO\nmia_funzione() = [666] # SBAGLIATO\n\n```\n\n```python\nx = 5 # OK\ny = my_fun() # OK\nz = [] # OK\nz[0] = 7 # OK\nd = dict() # OK\nd[\"a\"] = 6 # OK\n```\n\nChiamate a funzione come `mia_funzione()` ritornano risultati di calcoli e li mettono in una scatola che è creata solo per lo scopo della chiamata e Python non ci consentirà di riusarla come una variabile. \n\nQuando vedi `nome()` alla parte sinistra, _non può_ essere seguito da un segno di uguaglianza `=` (ma può essere seguito da due segni di uguaglianza `==` se stai eseguendo una comparazione).\n",
"_____no_output_____"
],
[
"## V COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Non ridifinerai mai funzioni di sistema**\n</div>\n\nPython ha diverse funzioni di sistema predefinite. Per esempio `list` è un tipo Python: come tale, puoi usarlo per esempio come funzione per convertire un qualche tipo a lista:",
"_____no_output_____"
]
],
[
[
"list(\"ciao\")",
"_____no_output_____"
]
],
[
[
"Quando consenti alle Forze del Male di prendere il sopravvento, potresti essere tentato di usare tipi e funzioni di sistema (per es. `list`) come una variabile per i tuoi miserabili propositi personali:\n\n```python\nlist = ['la', 'mia', 'lista', 'raccapricciante']\n```",
"_____no_output_____"
],
[
"Python ti permette di farlo, ma **noi no**, poichè le conseguenze sono disastrose. \n\nPer esempio, se adesso usi `list` per il proposito per cui è stata creata, cioè conversione a lista, non funzionerà più:",
"_____no_output_____"
],
[
"```python\nlist(\"ciao\")\n```\n```\n---------------------------------------------------------------------------\nTypeError Traceback (most recent call last)\n<ipython-input-4-c63add832213> in <module>()\n----> 1 list(\"ciao\")\n\nTypeError: 'list' object is not callable\n\n```",
"_____no_output_____"
],
[
"\nIn particolare, raccomandiamo di **non ridefinire** queste preziose funzioni:\n\n* `bool`, `int`,`float`,`tuple`,`str`,`list`,`set`,`dict`\n* `max`, `min`, `sum`\n* `next`, `iter`\n* `id`, `dir`, `vars`,`help`",
"_____no_output_____"
],
[
"## VI COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Userai il comando** `return` **solo se vedi scritto RITORNA nella descrizione di funzione!**\n</div>\n\nSe non c'è un RITORNA nella descrizione di funzione, si intende che la funzione ritorni `None`. In questo caso non devi nemmeno scrivere `return None`, perchè Python lo farà implicitamente per te.\n",
"_____no_output_____"
],
[
"## VII COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Scriverai anche su carta!**\n</div>\n\nSe fissare il monitor non funziona, aiutati e disegna su carta una rappresentazione dello stato del programma. Tabelle, nodi, frecce, tutto può aiutare nel trovare una soluzione al problema.\n",
"_____no_output_____"
],
[
"## VIII COMANDAMENTO\n\n<div class=\"alert alert-info\">\n\n**Non riassegnerai mai** `self` **!** \n</div>\n\nNon scriverai mai empietà come questa:\n\n",
"_____no_output_____"
]
],
[
[
"class MiaClasse:\n def mio_metodo(self):\n self = {'mio_campo':666}",
"_____no_output_____"
]
],
[
[
"Dato che `self` è una specie di dizionario, potresti essere tentato di scrivere come sopra, ma al mondo esterno questo non porterà alcun effetto. \n\nPer esempio, supponiamo che qualcuno da fuori faccia una chiamata come questa:",
"_____no_output_____"
]
],
[
[
"mc = MiaClasse()\nmc.mio_metodo()",
"_____no_output_____"
]
],
[
[
"Dopo la chiamata `mc` non punterà a `{'mio_campo':666}`",
"_____no_output_____"
]
],
[
[
"mc",
"_____no_output_____"
]
],
[
[
"e non avrà `mio_campo`:",
"_____no_output_____"
],
[
"```python\nmc.mio_campo\n\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n<ipython-input-26-5c4e6630908d> in <module>()\n----> 1 mc.mio_campo\n\nAttributeError: 'MiaClasse' object has no attribute 'mio_campo'\n\n```",
"_____no_output_____"
],
[
"Per lo stesso ragionamento, non devi riassegnare `self` a liste o altro:",
"_____no_output_____"
]
],
[
[
"class MiaClasse:\n def mio_metodo(self):\n self = ['evil'] \n self = 666 ",
"_____no_output_____"
]
],
[
[
"## IX COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Testerai il codice!**\n</div>\n\n\nIl codice non testato per definizione _non funziona_. Per idee su come testare, guarda [Gestione degli errori e testing](errors-and-testing/errors-and-testing-sol.ipynb)\n",
"_____no_output_____"
],
[
"## X COMANDAMENTO\n\n<div class=\"alert alert-info\" >\n\n**Non aggiungerai o toglierai mai elementi da una sequenza che iteri con un** `for` **!**\n</div>\n\n\nAbbandonarti in simil tentazioni **produrrebbe comportamenti del tutto imprevedibili** (conosci forse l'espressione _tirare il tappeto da sotto i piedi?_ )",
"_____no_output_____"
],
[
"**Non aggiungere**, poichè rischi di camminare su un tapis roulant che mai si spegne:\n\n```python\nlista = ['a','b','c','d','e']\nfor el in lista:\n lista.append(el) # STAI INTASANDO LA MEMORIA DEL COMPUTER\n```",
"_____no_output_____"
],
[
"**Non togliere**, poichè rischi di corrompere l'ordine naturale delle cose:",
"_____no_output_____"
]
],
[
[
"lista = ['a','b','c','d','e']\n\nfor el in lista:\n lista.remove(el) # PESSIMA IDEA",
"_____no_output_____"
]
],
[
[
"Guarda bene il codice. Credi che abbiamo rimosso tutto, eh?",
"_____no_output_____"
]
],
[
[
"lista",
"_____no_output_____"
]
],
[
[
"`O_o'` Non provar a capacitarti di cotal sortilegio - nessuno capirlo può, poichè esso è legato all'implementazione interna di Python.\n\nLa mia versione di Python dà questo risultato assurdo, la vostra potrebbe darne un'altro. Il discorso vale anche per iterazione su insiemi e dizionari. **Siete avvertiti**.",
"_____no_output_____"
],
[
"**Se proprio devi rimuovere elementi dalla sequenza su cui stai iterando**, usa [un ciclo while](https://it.softpython.org/control-flow/flow3-while-sol.html) o effettua prima una copia della sequenza originale.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e7af51b9ff37e76cfe8e32da236e84d07925d0e2 | 2,375 | ipynb | Jupyter Notebook | notebooks/index.ipynb | MonashBioinformaticsPlatform/intro_programming | a39512c59b93d44b80611213d621c049714c5b68 | [
"MIT"
] | 2 | 2017-06-19T06:28:00.000Z | 2017-06-21T04:05:54.000Z | notebooks/index.ipynb | MonashBioinformaticsPlatform/intro_programming | a39512c59b93d44b80611213d621c049714c5b68 | [
"MIT"
] | null | null | null | notebooks/index.ipynb | MonashBioinformaticsPlatform/intro_programming | a39512c59b93d44b80611213d621c049714c5b68 | [
"MIT"
] | null | null | null | 35.447761 | 333 | 0.658526 | [
[
[
"Introduction to Python\n===\n\nThis material is derived from work that is copyright © [introtopyhthon](http://introtopython.org/) with a [MIT license.](https://opensource.org/licenses/MIT)\n\nIntroduction to Python is a resource for students who want to learn Python as their first language, and for teachers who want a free and open curriculum to use with their students.\n\nIf you are viewing the project through IPython Notebook Viewer, you might want to visit the student-facing pages at [introtopython.org](http://introtopython.org). There is a cleaner navigation there, and some better overall styling.",
"_____no_output_____"
],
[
"Start Learning Python\n---\nIf your computer is already set up to run Python programs, you can get started with [Hello World](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/hello_world.ipynb), your very first Python program.",
"_____no_output_____"
],
[
"Set Up Your Programming Environment\n---\nIf your computer is not yet set up to run Python programs, we can show you how to [get Python up and running](http://nbviewer.ipython.org/urls/raw.github.com/ehmatthes/intro_programming/master/notebooks/programming_environment.ipynb).",
"_____no_output_____"
],
[
"Contribute\n---\nIf you already know Python and would like to help build Introduction to Python, see the project's [GitHub page](https://github.com/ehmatthes/intro_programming). You might want to look at [Issue 17](https://github.com/ehmatthes/intro_programming/issues/17), which discusses a few specific ways you can contribute to the project.",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7af54fe4ac8f4af527cd4b9a2ce22c2ffb42330 | 6,483 | ipynb | Jupyter Notebook | JupyterNotebooks/Labs/Lab 3 Solution.ipynb | owenbres01/CMPT-120L-910-20F | c9840f5316688f023b7cca555ffc97ccb429aae8 | [
"MIT"
] | 1 | 2020-08-25T23:50:45.000Z | 2020-08-25T23:50:45.000Z | JupyterNotebooks/Labs/Lab 3 Solution.ipynb | owenbres01/CMPT-120L-910-20F | c9840f5316688f023b7cca555ffc97ccb429aae8 | [
"MIT"
] | null | null | null | JupyterNotebooks/Labs/Lab 3 Solution.ipynb | owenbres01/CMPT-120L-910-20F | c9840f5316688f023b7cca555ffc97ccb429aae8 | [
"MIT"
] | 21 | 2020-08-25T03:52:56.000Z | 2020-09-09T01:32:45.000Z | 25.828685 | 186 | 0.534783 | [
[
[
"# Lab Three\n---\n\nFor this lab we're going to be making and using a bunch of functions. \n\nOur Goals are:\n- Searching our Documentation\n- Using built in functions\n- Making our own functions\n- Combining functions\n- Structuring solutions",
"_____no_output_____"
]
],
[
[
"# For the following built in functions we didn't touch on them in class. I want you to look for them in the python documentation and implement them.",
"_____no_output_____"
],
[
"# I want you to find a built in function to SWAP CASE on a string. Print it.\n\n# For example the string \"HeY thERe HowS iT GoING\" turns into \"hEy THerE hOWs It gOing\"\nsample_string = \"HeY thERe HowS iT GoING\"\n\nprint(sample_string.swapcase())",
"hEy THerE hOWs It gOing\n"
],
[
"# I want you to find a built in function to CENTER a string and pad the sides with 4 dashes(-) a side. Print it.\n\n# For example the string \"Hey There\" becomes \"----Hey There----\"\n\nsample_string = \"Hey There\"\n\nprint(sample_string.center(17, \"-\"))",
"----Hey There----\n"
],
[
"# I want you to find a built in function to PARTITION a string. Print it.\n\n# For example the string \"abcdefg.hijklmnop\" would come out to be [\"abcdefg\",\".\",\"hijklmnop\"]\n\nsample_string = \"abcdefg.hijklmnop\"\n\nprint(sample_string.partition(\".\"))",
"('abcdefg', '.', 'hijklmnop')\n"
],
[
"# I want you to write a function that will take in a number and raise it to the power given. \n\n# For example if given the numbers 2 and 3. The math that the function should do is 2^3 and should print out or return 8. Print the output.\ndef power(number, exponent) -> int:\n return number ** exponent\n\nexample = power(2, 3)\nprint(example)",
"8\n"
],
[
"# I want you to write a function that will take in a list and see how many times a given number is in the list. \n\n# For example if the array given is [2,3,5,2,3,6,7,8,2] and the number given is 2 the function should print out or return 3. Print the output.\narray = [2,3,5,2,3,6,7,8,2]\n\ndef number_counter(array, target):\n count = 0\n for number in array:\n if number == target:\n count += 1\n return count\n\nexample = number_counter(array, 2)\nprint(example)\n",
"3\n"
],
[
"# Use the functions given to create a slope function. The function should be named slope and have 4 parameters.\n\n# If you don't remember the slope formula is (y2 - y1) / (x2 - x1) If this doesn't make sense look up `Slope Formula` on google.\n\ndef division(x, y):\n return x / y\n\ndef subtraction(x, y):\n return x - y\n\ndef slope(x1, x2, y1, y2):\n return division(subtraction(y2, y1), subtraction(x2, x1))\n\nexample = slope(1, 2, 1, 2)\nprint(example)\n",
"1.0\n"
],
[
"# Use the functions given to create a distance function. The function should be named function and have 4 parameters.\n\n# HINT: You'll need a built in function here too. You'll also be able to use functions written earlier in the notebook as long as you've run those cells.\n\n# If you don't remember the distance formula it is the square root of the following ((x2 - x1)^2 + (y2 - y1)^2). If this doesn't make sense look up `Distance Formula` on google.\n\nimport math\n\ndef addition(x, y):\n return x + y\n\ndef distance(x1, x2, y1, y2):\n x_side = power(subtraction(x2, x1), 2)\n y_side = power(subtraction(y2, y1), 2)\n combined_sides = addition(x_side, y_side)\n\n return math.sqrt(combined_sides)\n\nprint(distance(1, 2, 1, 2))\n",
"1.4142135623730951\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7af5879ad9e59b0abd1c90c983bed31a1774334 | 28,773 | ipynb | Jupyter Notebook | notebook/eda/Suraiya-Project/DATAMAINING2020/5:quran:notebook/.ipynb_checkpoints/5.english-translation-checkpoint.ipynb | langsari/quran-dataset | b41e2930216ef68b16771a96c62665565fc37c85 | [
"MIT"
] | 5 | 2020-10-08T05:16:39.000Z | 2020-12-09T03:47:17.000Z | notebook/eda/Suraiya-Project/DATAMAINING2020/5:quran:notebook/.ipynb_checkpoints/5.english-translation-checkpoint.ipynb | langsari/quran-dataset | b41e2930216ef68b16771a96c62665565fc37c85 | [
"MIT"
] | 4 | 2020-09-16T09:59:43.000Z | 2020-12-01T14:18:34.000Z | notebook/eda/Suraiya-Project/DATAMAINING2020/5:quran:notebook/.ipynb_checkpoints/5.english-translation-checkpoint.ipynb | langsari/quran-dataset | b41e2930216ef68b16771a96c62665565fc37c85 | [
"MIT"
] | 6 | 2020-09-09T09:29:58.000Z | 2022-03-17T08:59:34.000Z | 32.771071 | 119 | 0.341188 | [
[
[
"import json\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport nltk",
"_____no_output_____"
],
[
"data = pd.read_json('https://raw.githubusercontent.com/risan/quran-json/master/json/translations/en.pretty.json')",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"data.describe()",
"_____no_output_____"
],
[
"data.head(27)",
"_____no_output_____"
],
[
"data.rename(columns={'content':'translation'},inplace=True)",
"_____no_output_____"
],
[
"data",
"_____no_output_____"
],
[
"data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 6236 entries, 0 to 6235\nData columns (total 3 columns):\nsurah_number 6236 non-null int64\nverse_number 6236 non-null int64\ntranslation 6236 non-null object\ndtypes: int64(2), object(1)\nmemory usage: 146.3+ KB\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7af63a03f12ab50309b186369ab4e56d381c1da | 17,341 | ipynb | Jupyter Notebook | notebooks/PET/reconstruct_measured_data.ipynb | KrisThielemans/SIRF-Exercises | 7e101a92bf9a96fc538aa9ba347d89d1ff435945 | [
"Apache-2.0"
] | null | null | null | notebooks/PET/reconstruct_measured_data.ipynb | KrisThielemans/SIRF-Exercises | 7e101a92bf9a96fc538aa9ba347d89d1ff435945 | [
"Apache-2.0"
] | null | null | null | notebooks/PET/reconstruct_measured_data.ipynb | KrisThielemans/SIRF-Exercises | 7e101a92bf9a96fc538aa9ba347d89d1ff435945 | [
"Apache-2.0"
] | null | null | null | 30.52993 | 492 | 0.621879 | [
[
[
"# Reconstruct phantom data\nThis exercise shows how to handle data from the Siemens mMR. It shows how to get from listmode data to sinograms, get a randoms estimate, and reconstruct using normalisation, randoms and attenuation.\n(Scatter is not yet available from in SIRF).\n\nIt is recommended you complete the first part of `ML_reconstruct.ipynb` exercise first.\n\nThis exercise uses data from a phantom acquisition at UCL on a Siemens mMR. The phantom is the NEMA phantom (essentially a torso-shaped perspex box, with some spherical inserts). You will need to download that data. Please use the `SIRF-Exercises/scripts/download_PET_data.sh` script which will get the data, and make symbolic links in the location expected in this script. \n\nThe script should work for other data of course, but you will need to adapt filenames.\n\nNote that we currently don't show how to extract the data from the console. Please\n[check our wiki for more information](https://github.com/CCPPETMR/SIRF/wiki/PET-raw-data).",
"_____no_output_____"
],
[
"Authors: Kris Thielemans and Evgueni Ovtchinnikov \nFirst version: 8th of September 2016 \nSecond Version: 17th of May 2018\n\nCCP PETMR Synergistic Image Reconstruction Framework (SIRF). \nCopyright 2015 - 2017 Rutherford Appleton Laboratory STFC. \nCopyright 2015 - 2018 University College London.\n\nThis is software developed for the Collaborative Computational\nProject in Positron Emission Tomography and Magnetic Resonance imaging\n(http://www.ccppetmr.ac.uk/).\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.",
"_____no_output_____"
],
[
"# Initial set-up",
"_____no_output_____"
]
],
[
[
"#%% make sure figures appears inline and animations works\n%matplotlib notebook",
"_____no_output_____"
],
[
"import os\nimport sys\nimport matplotlib.pyplot as plt\nfrom sirf.Utilities import show_2D_array, examples_data_path\nfrom sirf.STIR import *\n\ndata_path = examples_data_path('PET') + '/mMR'\n#data_path='/home/sirfuser/data/NEMA'\nprint('Finding files in %s' % data_path)\nos.chdir(data_path)",
"_____no_output_____"
],
[
"# check content of current directory using an iPython \"magic\" command\n%ls",
"_____no_output_____"
],
[
"#%% set filenames \n# input files\nlist_file = '20170809_NEMA_60min_UCL.l.hdr';\nnorm_file = 'norm.n.hdr'\nattn_file = 'mu_map.hv'\n# output filename prefixes\nsino_file = 'sino'",
"_____no_output_____"
],
[
"# redirect STIR messages to some files\n# you can check these if things go wrong\nmsg_red = MessageRedirector('info.txt', 'warn.txt')",
"_____no_output_____"
]
],
[
[
"# Creating sinograms from listmode data\nModern PET scanners can store data in listmode format. This is essentially a long list of all events detected by the scanner. We are interested here in the *prompts* (the coincidence events) and the *delayed events* (which form an estimate of the *accidental coincidences* in the prompts.\n\nWe show how to histogram the prompts into a sinogram etc.",
"_____no_output_____"
],
[
"## First create a template for the sinogram\nThis template is used to specify the sizes of the output sinogram.\n\nIt is often the case in PET that we use sinograms with \"larger\" bins, i.e. combine data from several detector pairs into a single bin. This reduces size of the final sinogram, and decreases computation time. The terminology here is somewhat complicated, but *span* uses \"axial compression\" (higher span means smaller data size), *max_ring_diff* specifies the maximum ring difference to store, and *view_mash_factor* can be used to reduce the number of views (or azimutal angles).\n\nSiemens uses span=1, max_ring_diff=60 and view_mash_factor=1. Here we will use a smaller data size to reduce computation time for the exercise. Feel free to change these numbers (if you know what you are doing...).",
"_____no_output_____"
]
],
[
[
"template_acq_data = AcquisitionData('Siemens_mMR', span=11, max_ring_diff=15, view_mash_factor=2)\ntemplate_acq_data.write('template.hs')",
"_____no_output_____"
],
[
"# create listmode-to-sinograms converter object\nlm2sino = ListmodeToSinograms()\n\n# set input, output and template files\nlm2sino.set_input(list_file)\nlm2sino.set_output_prefix(sino_file)\nlm2sino.set_template('template.hs')",
"_____no_output_____"
],
[
"# set timing interval (in secs) since start of acquisition\n# (the listmode file provided is for 1 hour).\n# you can vary this to see the effect on noise. Increasing it will mean somewhat longer\n# processing time in the following steps (but not in the reconstruction).\nlm2sino.set_time_interval(0, 500)\n# set up the converter\nlm2sino.set_up()\n# create the prompts sinogram\nlm2sino.process()",
"_____no_output_____"
],
[
"# check the content of the directory. there should be a `sino*.hs`, `'.s` pair.\n# The `.hs` file is an Interfile header pointing to the binary data.\n%ls",
"_____no_output_____"
]
],
[
[
"## Check the prompts sinograms\nThe 3D PET data returned by `as_array` are organised by 2D sinogram. The exact order of the sinograms\nis complicated for 3D PET, but they by *segment* (roughly: average ring difference). The first\nsegment corresponds to \"segment 0\", i.e. detector pairs which are (roughly) in the same \ndetector ring. For a scanner with `N` rings, there will be `2N-1` (2D) sinograms in segment 0.",
"_____no_output_____"
]
],
[
[
"# get access to the sinograms\nacq_data = lm2sino.get_output()\n# copy the acquisition data into a Python array\nacq_array = acq_data.as_array()[0,:,:,:]\n# print the data sizes. \nprint('acquisition data dimensions: %dx%dx%d' % acq_array.shape)\n# use a slice number for display that is appropriate for the NEMA phantom\nz = 71\nshow_2D_array('Acquisition data', acq_array[z,:,:])",
"_____no_output_____"
]
],
[
[
"## Estimate the *randoms* background\nSiemens stores *delayed coincidences*. These form a very noisy estimate of the\nbackground due to accidental coincidences in the data. However, that estimate is too noisy\nto be used in iterative image reconstruction.\n\nSIRF uses an algorithm from STIR that gives a much less noisy estimate. The help message \ngives some information.",
"_____no_output_____"
]
],
[
[
"help(lm2sino)",
"_____no_output_____"
],
[
"# Get the randoms estimate\n# This will take a while\nrandoms = lm2sino.estimate_randoms()",
"_____no_output_____"
]
],
[
[
"## Plot the randoms-estimate\nA (2D) sinogram of the randoms has diagonal lines. This is related to the\ndetector efficiencies, but we cannot get into that here.",
"_____no_output_____"
]
],
[
[
"randoms_array=randoms.as_array()[0,:,:,:]\nshow_2D_array('randoms', randoms_array[z,:,:])",
"_____no_output_____"
]
],
[
[
"# Reconstruct the data\nWe will reconstruct the data with increasingly accurate models for the acquisition as illustration.\n\nFor simplicity, we will use OSEM and use only a few sub-iterations for speed.",
"_____no_output_____"
]
],
[
[
"# First just select an acquisition model that implements the geometric\n# forward projection by a ray tracing matrix multiplication\nacq_model = AcquisitionModelUsingRayTracingMatrix()\nacq_model.set_num_tangential_LORs(10);",
"_____no_output_____"
],
[
"# define objective function to be maximized as\n# Poisson logarithmic likelihood (with linear model for mean)\nobj_fun = make_Poisson_loglikelihood(acq_data)\nobj_fun.set_acquisition_model(acq_model)",
"_____no_output_____"
],
[
"# create the reconstruction object\nrecon = OSMAPOSLReconstructor()\nrecon.set_objective_function(obj_fun)\n \nnum_subsets = 7\n# Feel free to increase these\nnum_subiterations = 4\nrecon.set_num_subsets(num_subsets)\nrecon.set_num_subiterations(num_subiterations)",
"_____no_output_____"
],
[
"# create initial image estimate of dimensions and voxel sizes\n# compatible with the scanner geometry (included in the AcquisitionData\n# object acq_data) and initialize each voxel to 1.0\nnxny = (127, 127)\ninitial_image = acq_data.create_uniform_image(1.0, nxny)",
"_____no_output_____"
],
[
"image = initial_image\nrecon.set_up(image)\n# set the initial image estimate\nrecon.set_current_estimate(image)\n# reconstruct\nrecon.process()\n# show reconstructed image\nimage_array = recon.get_current_estimate().as_array()\nshow_2D_array('Reconstructed image', image_array[z,:,:])",
"_____no_output_____"
]
],
[
[
"## Add detector sensitivity modelling\nEach crystal pair will have different detection efficiency. We need to take that into account\nin our acquisition model. The scanner provides a *normalisation file* to do this (the terminology\noriginates from the days that we were \"normalising\" by dividing by the detected counts \nby the sensitivities.)\n\nIn SIRF, you can incorporate this effect in the acquisition model by using an `AcquisitionSensitivityModel`.",
"_____no_output_____"
]
],
[
[
"# create it from the supplied file\nasm_norm = AcquisitionSensitivityModel(norm_file)",
"_____no_output_____"
],
[
"# add it to the acquisition model\nacq_model.set_acquisition_sensitivity(asm_norm)",
"_____no_output_____"
],
[
"# update the objective function\nobj_fun.set_acquisition_model(acq_model)\nrecon.set_objective_function(obj_fun)",
"_____no_output_____"
],
[
"# reconstruct\nimage = initial_image\nrecon.set_up(image)\nrecon.set_current_estimate(image)\nrecon.process()\n# show reconstructed image\nimage_array = recon.get_current_estimate().as_array()\nshow_2D_array('Reconstructed image', image_array[z,:,:])",
"_____no_output_____"
]
],
[
[
"## Add attenuation modeling",
"_____no_output_____"
]
],
[
[
"# read attenuation image\nattn_image = ImageData(attn_file)\nz = 71\nattn_image.show(z)",
"_____no_output_____"
],
[
"attn_acq_model = AcquisitionModelUsingRayTracingMatrix()\nasm_attn = AcquisitionSensitivityModel(attn_image, attn_acq_model)\n# converting attenuation into attenuation factors (see previous exercise)\nasm_attn.set_up(acq_data)\nattn_factors = AcquisitionData(acq_data)\nattn_factors.fill(1.0)\nprint('applying attenuation (please wait, may take a while)...')\nasm_attn.unnormalise(attn_factors)",
"_____no_output_____"
],
[
"# use these in the final attenuation model\nasm_attn = AcquisitionSensitivityModel(attn_factors)",
"_____no_output_____"
]
],
[
[
"We now have two acquisition_sensitivity_models: for detection sensitivity and for\ncount loss due to attenuation. We combine them by \"chaning\" them together (which will\nmodel the multiplication of both sensitivities).",
"_____no_output_____"
]
],
[
[
"# chain attenuation and normalisation\nasm = AcquisitionSensitivityModel(asm_norm, asm_attn)",
"_____no_output_____"
],
[
"# update the acquisition model etc\nacq_model.set_acquisition_sensitivity(asm)\nobj_fun.set_acquisition_model(acq_model)\nrecon.set_objective_function(obj_fun)",
"_____no_output_____"
],
[
"# reconstruct\nimage = initial_image\nrecon.set_up(image)\nrecon.set_current_estimate(image)\nrecon.process()\n# show reconstructed image\nimage_array = recon.get_current_estimate().as_array()\nshow_2D_array('Reconstructed image', image_array[z,:,:])",
"_____no_output_____"
]
],
[
[
"## Add a background term for modelling the randoms",
"_____no_output_____"
]
],
[
[
"acq_model.set_background_term(randoms)\nobj_fun.set_acquisition_model(acq_model)\nrecon.set_objective_function(obj_fun)",
"_____no_output_____"
],
[
"image = initial_image\nrecon.set_up(image)",
"_____no_output_____"
],
[
"recon.set_current_estimate(image)\nrecon.process()\n# show reconstructed image\nimage_array = recon.get_current_estimate().as_array()\nshow_2D_array('Reconstructed image', image_array[z,:,:])",
"_____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"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7af7eb48ade1638486868afc5dacf2ecb834191 | 677,580 | ipynb | Jupyter Notebook | docs/Fast Python.ipynb | liuzhenhai/numba | 855a2b262ae3d82bd6ac1c3e1c0acb36ee2e2acf | [
"BSD-2-Clause"
] | 3 | 2015-08-28T21:13:58.000Z | 2022-01-21T17:02:14.000Z | docs/Fast Python.ipynb | glycerine/numba | 4cb9e4f0b3cabd9e6a144fa4f3f7e5d6bee45635 | [
"BSD-2-Clause"
] | null | null | null | docs/Fast Python.ipynb | glycerine/numba | 4cb9e4f0b3cabd9e6a144fa4f3f7e5d6bee45635 | [
"BSD-2-Clause"
] | null | null | null | 827.326007 | 84,376 | 0.936748 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7af7f6c1c09fe06ddd13a20ae547f8adc25b2da | 344,385 | ipynb | Jupyter Notebook | slides/2022-02-09-projections.ipynb | cu-numcomp/spring22 | f4c1f9287bff2c10645809e65c21829064493a66 | [
"MIT"
] | null | null | null | slides/2022-02-09-projections.ipynb | cu-numcomp/spring22 | f4c1f9287bff2c10645809e65c21829064493a66 | [
"MIT"
] | null | null | null | slides/2022-02-09-projections.ipynb | cu-numcomp/spring22 | f4c1f9287bff2c10645809e65c21829064493a66 | [
"MIT"
] | 2 | 2022-02-09T21:05:12.000Z | 2022-03-11T20:34:46.000Z | 142.190339 | 10,136 | 0.614045 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7af808c20ed0b2fedc0433f5a7be7f30640312e | 19,457 | ipynb | Jupyter Notebook | notebooks/shakura-sunyaev.ipynb | lzkelley/bhem | 711cda6c6aa433d52793a8ecff4bbdb01c026150 | [
"MIT"
] | null | null | null | notebooks/shakura-sunyaev.ipynb | lzkelley/bhem | 711cda6c6aa433d52793a8ecff4bbdb01c026150 | [
"MIT"
] | null | null | null | notebooks/shakura-sunyaev.ipynb | lzkelley/bhem | 711cda6c6aa433d52793a8ecff4bbdb01c026150 | [
"MIT"
] | null | null | null | 30.884127 | 119 | 0.524284 | [
[
[
"# Initialization",
"_____no_output_____"
]
],
[
[
"# %load init.ipy\n%reload_ext autoreload\n%autoreload 2\n\nimport os, sys\n\nimport numpy as np\nimport scipy as sp\nimport scipy.integrate\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nCWD = os.path.abspath(os.path.curdir)\nprint(\"CWD: '{}'\".format(CWD))\n\nODIR = os.path.join(CWD, \"output\", \"\")\nif not os.path.exists(ODIR):\n os.makedirs(ODIR)\n print(\"Created output directory: '{}'\".format(ODIR))\n\npar_dir = os.path.join(CWD, os.path.pardir)\nif par_dir not in sys.path:\n sys.path.append(par_dir)\n print(\"Added parent directory: '{}'\".format(par_dir))\n\nimport bhem\nimport bhem.basics\nimport bhem.utils\nimport bhem.disks\nimport bhem.radiation\nimport bhem.spectra\nfrom bhem.constants import MSOL, H_PLNK, K_BLTZ, SPLC, MPRT, MELC, QELC, BANDS, SIGMA_SB, NWTG\n\nnp.seterr(over='ignore');\n\n# Plotting settings\nmpl.rc('font', **{'family': 'serif', 'sans-serif': ['Times']})\nmpl.rc('lines', solid_capstyle='round')\nmpl.rc('mathtext', fontset='cm')\nplt.rcParams.update({'grid.alpha': 0.5})\n\nFS_TITLE = 20\nFS_LABEL = 16\n\nplt.rcParams.update({'axes.titlesize': FS_TITLE})\nplt.rcParams.update({'axes.labelsize': FS_LABEL})\nplt.rcParams.update({'xtick.labelsize': FS_LABEL})\nplt.rcParams.update({'ytick.labelsize': FS_LABEL})\n",
"_____no_output_____"
]
],
[
[
"## Parameters",
"_____no_output_____"
]
],
[
[
"MASS = 1e7 * MSOL\nFEDD = 0.1\n\nPATH_OUTPUT = os.path.join(ODIR, 'shakura-sunyaev', '')\n\nif not os.path.exists(PATH_OUTPUT):\n os.makedirs(PATH_OUTPUT)",
"_____no_output_____"
],
[
"thin = bhem.disks.Thin(MASS, fedd=FEDD)",
"_____no_output_____"
]
],
[
[
"### Derived",
"_____no_output_____"
]
],
[
[
"mdot = bhem.basics.eddington_accretion(MASS)\nrsch = bhem.basics.radius_schwarzschild(MASS)\n# rads = np.logspace(np.log10(6), 4, 200) * rsch\nrads = thin.rads\nfreqs = np.logspace(10, 18, 120)",
"_____no_output_____"
]
],
[
[
"# Disk Primitives Profiles",
"_____no_output_____"
]
],
[
[
"# temp = bhem.basics.temperature_profile(MASS, mdot, rads)",
"_____no_output_____"
],
[
"mu = 1.2\npres_over_dens = (K_BLTZ * thin.temp / (mu * MPRT)) + (4*SIGMA_SB*thin.temp**4 / (3*SPLC) )\nhh = np.sqrt(pres_over_dens * 2 * (thin.rads**3) / (NWTG * thin.mass))",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=[6, 4])\nax.set(xscale='log', yscale='log')\n\nax.plot(thin.rads, hh/thin.rads)\nIND = 1/8\nnorm = hh[0]/thin.rads[0]\nax.plot(thin.rads, np.power(thin.rads/thin.rads[0], IND) * norm, 'k--')\n\nplt.show()",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=[10, 5])\nax.set(xscale='log', xlabel='Radius [$R_s$]', yscale='log', ylabel='Temperature [K]')\n\nax.plot(rads/rsch, thin.temp, 'r-', lw=2.0, alpha=0.8)\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Blackbody Spectrum",
"_____no_output_____"
]
],
[
[
"# erg/s/Hz/cm^2/steradian\n# bb_spec_rad = bhem.basics.blackbody_spectral_radiance(MASS, mdot, rads[:, np.newaxis], freqs[np.newaxis, :])\nrr = rads[np.newaxis, :]\nff = freqs[:, np.newaxis]\nbb_spec_rad = thin._blackbody_spectral_radiance(rr, ff)",
"_____no_output_____"
],
[
"xx, yy = np.meshgrid(rr, ff)\n\nnorm = mpl.colors.LogNorm(vmin=1e-10, vmax=np.max(bb_spec_rad))\nsmap = mpl.cm.ScalarMappable(norm=norm, cmap='hot')\nsmap.cmap.set_under('0.5')\n\nfig, axes = plt.subplots(figsize=[14, 6], ncols=2)\nfor ax in axes:\n ax.set(xscale='log', xlabel='Radius [$R_s$]', yscale='log', ylabel='Freq [Hz]')\n for nn, band in bhem.constants.BANDS.items():\n ax.axhline(band.freq, color=band.color, lw=2.0, alpha=0.5)\n\npcm = axes[0].pcolormesh(xx/rsch, yy, bb_spec_rad, norm=norm, cmap=smap.cmap)\nplt.colorbar(pcm, ax=axes[0], orientation='horizontal')\n\nfinds = (1e14 < freqs) & (freqs < 1e16)\n\nnorm = mpl.colors.Normalize(0.0, np.max(bb_spec_rad[finds, :]))\nsmap = mpl.cm.ScalarMappable(norm=norm, cmap='hot')\npcm = axes[1].pcolormesh(xx[finds, :]/rsch, yy[finds, :], bb_spec_rad[finds, :], norm=norm, cmap=smap.cmap)\nplt.colorbar(pcm, ax=axes[1], orientation='horizontal')\n\nplt.show()",
"_____no_output_____"
],
[
"# bb_lum = bhem.basics.blackbody_spectral_luminosity(MASS, mdot, freqs)\nbb_lum = thin.blackbody_spectral_luminosity(freqs)",
"_____no_output_____"
],
[
"fig, ax = plt.subplots(figsize=[10, 5])\nax.set(xscale='log', xlabel='Frequency [Hz]',\n yscale='log', ylabel='Spectral Luminosity [erg/s/Hz]', ylim=[1e20, 1e30])\n\nax.plot(freqs, bb_lum, 'r-', lw=2.0, alpha=0.6)\n\nfor nn, band in bhem.constants.BANDS.items():\n ax.axvline(band.freq, color=band.color, lw=1.0, alpha=0.5)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Varying Eddington Ratios : Spectra and Efficiencies",
"_____no_output_____"
]
],
[
[
"_MASS = 1e9 * MSOL\n\nfig, axes = plt.subplots(figsize=[12, 5], ncols=2)\nplt.subplots_adjust(wspace=0.55, left=0.08, right=0.92, top=0.96)\n\nfor ax in axes:\n ax.set(xscale='log', yscale='log')\n ax.grid(True, which='major', axis='both', c='0.5', alpha=0.5)\n\n\nax = axes[0]\nax.set(xlabel='Frequency [Hz]', # xlim=[1e5, 1e22], \n ylabel='$\\\\nu \\, F_\\\\nu [\\mathrm{erg \\,\\, s}^{-1}]$')\ntw = ax.twinx(); tw.set(yscale='log', ylabel='Cumulative Luminosity $[\\mathrm{erg \\,\\, s}^{-1}]$')\n\nfedds = np.logspace(-6, 0, 7)[::-1]\nlums = np.zeros_like(fedds)\n\ncmap = mpl.cm.get_cmap('gist_heat_r')\ncolors = [cmap(xx) for xx in np.linspace(0.1, 0.9, fedds.size)]\nymax = 0.0\n\nfor ii, fe in enumerate(fedds):\n label = '${:+.1f}$'.format(np.log10(fe))\n cc = colors[ii]\n kw = dict(color=cc, lw=2.0, label=label)\n\n _thin = bhem.disks.Thin(_MASS, 100, fedd=fe)\n bb_lum = _thin.blackbody_spectral_luminosity(freqs)\n lum = bb_lum\n \n ax.plot(freqs, freqs*lum, ls='--', alpha=0.5, **kw)\n ymax = np.maximum(np.max(freqs*lum), ymax)\n \n lum_mid = bhem.utils.log_midpoints(lum)\n freqs_mid = bhem.utils.log_midpoints(freqs)\n df = np.diff(freqs)\n cumlum = np.cumsum(df * lum_mid)\n lums[ii] = cumlum[-1]\n tw.plot(freqs_mid, cumlum, alpha=0.8, **kw) \n \ntw.set_ylim([1e32, 1e50])\nax.set_ylim([1e30, 3*ymax])\nax.text(0.02, 0.98, \"$M = {:.1e} \\,\\, M_\\odot$\".format(_MASS/MSOL), transform=ax.transAxes,\n ha='left', va='top')\n \nfor nn, band in bhem.constants.BANDS.items():\n ax.axvline(band.freq, color=band.color, lw=1.0, alpha=0.5)\n\nax.legend(title=\"$\\log(\\dot{M}/\\dot{M}_\\mathrm{edd})$\", fontsize=12, loc='center left')\n\n\nax = axes[1]\nax.set(xlabel='Eddington Fraction', \n ylabel='$L_\\mathrm{bol} [\\mathrm{erg \\,\\, s}^{-1}]$')\ntw = ax.twinx(); tw.set(yscale='log', ylabel='Efficiency')\n\nmdot_edd = bhem.basics.eddington_accretion(_MASS)\neffs = lums/(mdot_edd * fedds * SPLC**2)\n\nax.plot(fedds, lums, 'r-', alpha=0.8)\ntw.plot(fedds, effs, 'r--', alpha=0.8)\ntw.plot(fedds, np.minimum(10*fedds, 0.1), color='0.5', ls='--', alpha=0.5)\n\nplt.show()\n\nfname = 'lum-eff_thin_mdot'\nfname = os.path.join(PATH_OUTPUT, fname)\nfig.savefig(fname + '.pdf')\nfig.savefig(fname + '.png')\nprint(\"Saved to '{}'\".format(fname))",
"_____no_output_____"
]
],
[
[
"# Disk Truncation",
"_____no_output_____"
]
],
[
[
"_MASS = 1e6 * MSOL\n_FEDD = 1e-1\nVAR_LABEL = \"$\\log(R_\\mathrm{max}/R_s)$\"\nBAND = \"v\"\nNRAD = 100\n\nfig, axes = plt.subplots(figsize=[12, 5], ncols=2)\nplt.subplots_adjust(wspace=0.55, left=0.08, right=0.92, top=0.96)\n\nfor ax in axes:\n ax.set(xscale='log', yscale='log')\n ax.grid(True, which='major', axis='both', c='0.5', alpha=0.5)\n\n\nax = axes[0]\nax.set(xlabel='Frequency [Hz]', # xlim=[1e5, 1e22], \n ylabel='$\\\\nu \\, F_\\\\nu [\\mathrm{erg \\,\\, s}^{-1}]$')\ntw = ax.twinx(); tw.set(yscale='log', ylabel='Cumulative Luminosity $[\\mathrm{erg \\,\\, s}^{-1}]$')\n\n# fedds = np.logspace(-6, 0, 7)[::-1]\nrad_max = np.logspace(1, 5, 9)\nlums = np.zeros_like(rad_max)\nlums_spec = np.zeros_like(rad_max)\n\ncmap = mpl.cm.get_cmap('gist_heat_r')\ncolors = [cmap(xx) for xx in np.linspace(0.1, 0.9, rad_max.size)]\nymax = 0.0\n\nfor ii, rm in enumerate(rad_max):\n label = '${:.1f}$'.format(np.log10(rm))\n cc = colors[ii]\n kw = dict(color=cc, lw=2.0, label=label)\n\n _thin = bhem.disks.Thin(_MASS, fedd=_FEDD, rmax=rm, nrad=NRAD)\n bb_lum = _thin.blackbody_spectral_luminosity(freqs)\n lum = bb_lum\n \n ax.plot(freqs, freqs*lum, ls='--', alpha=0.5, **kw)\n ymax = np.maximum(np.max(freqs*lum), ymax)\n \n _slum = bhem.utils.log_interp1d(freqs, lum*freqs)(BANDS[BAND].freq)\n lums_spec[ii] = _slum\n \n lum_mid = bhem.utils.log_midpoints(lum)\n freqs_mid = bhem.utils.log_midpoints(freqs)\n df = np.diff(freqs)\n cumlum = np.cumsum(df * lum_mid)\n lums[ii] = cumlum[-1]\n tw.plot(freqs_mid, cumlum, alpha=0.8, **kw) \n \ntw.set_ylim([1e32, 1e50])\nax.set_ylim([1e30, 3*ymax])\nax.text(0.02, 0.98, \"$M = {:.1e} \\,\\, M_\\odot$\".format(_MASS/MSOL), transform=ax.transAxes,\n ha='left', va='top')\n \nfor nn, band in bhem.constants.BANDS.items():\n ax.axvline(band.freq, color=band.color, lw=1.0, alpha=0.5)\n\nax.legend(title=VAR_LABEL, fontsize=12, loc='center left')\n\n\nax = axes[1]\nax.set(xlabel=VAR_LABEL, \n ylabel='$L_\\mathrm{bol} [\\mathrm{erg \\,\\, s}^{-1}]$')\ntw = ax.twinx(); tw.set(yscale='log', ylabel='Efficiency')\n\nmdot_edd = bhem.basics.eddington_accretion(_MASS)\neffs = lums/(mdot_edd * _FEDD * SPLC**2)\n\nax.plot(rad_max, lums, 'r-', alpha=0.8, lw=2.0)\nax.plot(rad_max, lums_spec, 'b-', alpha=0.8)\ntw.plot(rad_max, effs, 'r--', alpha=0.8)\n# tw.plot(rad_max, np.minimum(10*fedds, 0.1), color='0.5', ls='--', alpha=0.5)\n\nplt.show()\n\nfname = 'spec-eff_thin_rmax'\nfname = os.path.join(PATH_OUTPUT, fname)\nfig.savefig(fname + '.pdf')\nprint(\"Saved to '{}'\".format(fname))",
"_____no_output_____"
],
[
"_MASS = 1e7 * MSOL\n_FEDD = 1e-1\nVAR_LABEL = \"$\\log(R_\\mathrm{max}/R_s)$\"\nBAND = \"v\"\nRAD_MAX = 1e3\n\nfig, axes = plt.subplots(figsize=[12, 5], ncols=2)\nplt.subplots_adjust(wspace=0.55, left=0.08, right=0.92, top=0.96)\n\nfor ax in axes:\n ax.set(xscale='log', yscale='log')\n ax.grid(True, which='major', axis='both', c='0.5', alpha=0.5)\n\n\nax = axes[0]\nax.set(xlabel='Frequency [Hz]', # xlim=[1e5, 1e22], \n ylabel='$\\\\nu \\, F_\\\\nu [\\mathrm{erg \\,\\, s}^{-1}]$')\ntw = ax.twinx(); tw.set(yscale='log', ylabel='Cumulative Luminosity $[\\mathrm{erg \\,\\, s}^{-1}]$')\n\n# fedds = np.logspace(-6, 0, 7)[::-1]\nrad_max = np.logspace(1, 5, 8)\nlums = np.zeros_like(rad_max)\nlums_spec = np.zeros_like(rad_max)\n\ncmap = mpl.cm.get_cmap('gist_heat_r')\ncolors = [cmap(xx) for xx in np.linspace(0.1, 0.9, rad_max.size)]\nymax = 0.0\n\nfor ii, rm in enumerate(rad_max):\n label = '${:.1f}$'.format(np.log10(rm))\n cc = colors[ii]\n kw = dict(color=cc, lw=2.0, label=label)\n\n _thin = bhem.disks.Thin(_MASS, fedd=_FEDD, rmax=rm, nrad=NRAD)\n bb_lum = _thin.blackbody_spectral_luminosity(freqs)\n lum = bb_lum\n \n ax.plot(freqs, freqs*lum, ls='--', alpha=0.5, **kw)\n ymax = np.maximum(np.max(freqs*lum), ymax)\n \n _slum = bhem.utils.log_interp1d(freqs, lum*freqs)(BANDS[BAND].freq)\n lums_spec[ii] = _slum\n \n lum_mid = bhem.utils.log_midpoints(lum)\n freqs_mid = bhem.utils.log_midpoints(freqs)\n df = np.diff(freqs)\n cumlum = np.cumsum(df * lum_mid)\n lums[ii] = cumlum[-1]\n tw.plot(freqs_mid, cumlum, alpha=0.8, **kw) \n \ntw.set_ylim([1e32, 1e50])\nax.set_ylim([1e30, 3*ymax])\nax.text(0.02, 0.98, \"$M = {:.1e} \\,\\, M_\\odot$\".format(_MASS/MSOL), transform=ax.transAxes,\n ha='left', va='top')\n \nfor nn, band in bhem.constants.BANDS.items():\n ax.axvline(band.freq, color=band.color, lw=1.0, alpha=0.5)\n\nax.legend(title=VAR_LABEL, fontsize=12, loc='center left')\n\n\nax = axes[1]\nax.set(xlabel=VAR_LABEL, \n ylabel='$L_\\mathrm{bol} [\\mathrm{erg \\,\\, s}^{-1}]$')\ntw = ax.twinx(); tw.set(yscale='log', ylabel='Efficiency')\n\nmdot_edd = bhem.basics.eddington_accretion(_MASS)\neffs = lums/(mdot_edd * _FEDD * SPLC**2)\n\nax.plot(rad_max, lums, 'r-', alpha=0.8, lw=2.0)\nax.plot(rad_max, lums_spec, 'b-', alpha=0.8)\ntw.plot(rad_max, effs, 'r--', alpha=0.8)\n# tw.plot(rad_max, np.minimum(10*fedds, 0.1), color='0.5', ls='--', alpha=0.5)\n\nplt.show()\n\nfname = 'spec-eff_thin_rmax'\nfname = os.path.join(PATH_OUTPUT, fname)\nfig.savefig(fname + '.pdf')\nprint(\"Saved to '{}'\".format(fname))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7af8d5a151f35fbfba12fe2783e0d1a267a13a9 | 45,762 | ipynb | Jupyter Notebook | lectures/4-Casadi-MSD MODIFY.ipynb | winstonlevin/aae497-f19 | 1226f924d054e7448a91142c1637816c24388fc8 | [
"BSD-3-Clause"
] | null | null | null | lectures/4-Casadi-MSD MODIFY.ipynb | winstonlevin/aae497-f19 | 1226f924d054e7448a91142c1637816c24388fc8 | [
"BSD-3-Clause"
] | null | null | null | lectures/4-Casadi-MSD MODIFY.ipynb | winstonlevin/aae497-f19 | 1226f924d054e7448a91142c1637816c24388fc8 | [
"BSD-3-Clause"
] | null | null | null | 62.17663 | 16,524 | 0.752546 | [
[
[
"import casadi as ca\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"$m \\ddot{x} + c \\dot{x} + k x + sin(x) = u$",
"_____no_output_____"
],
[
"$\\vec{x} = \\begin{bmatrix}\nx \\\\\n\\dot{x}\n\\end{bmatrix}$",
"_____no_output_____"
],
[
"$\\vec{u} = \\begin{bmatrix} u\\end{bmatrix}$",
"_____no_output_____"
],
[
"$\\vec{y} = \\vec{g}(\\vec{x}) = \\begin{bmatrix} x\\end{bmatrix}$",
"_____no_output_____"
],
[
"$\\ddot{x} = (-c \\dot{x} - kx + u)/m$",
"_____no_output_____"
],
[
"$\\dot{\\vec{x}} = \\vec{f}(\\vec{x}) = \\begin{bmatrix}\n\\dot{x} \\\\\n(-c \\dot{x} - kx - sin(x) + u)/m\n\\end{bmatrix}$",
"_____no_output_____"
],
[
"$\\dot{\\vec{x}} = A \\vec{x} + B \\vec{u}$\n\n$\\vec{y} = C \\vec{x} + D \\vec{u}$",
"_____no_output_____"
],
[
"$A = \\dfrac{\\partial \\vec{f}}{\\partial \\vec{x}}$\n\n$B = \\dfrac{\\partial \\vec{f}}{\\partial \\vec{u}}$\n\n$C = \\dfrac{\\partial \\vec{g}}{\\partial \\vec{x}}$\n\n$D = \\dfrac{\\partial \\vec{g}}{\\partial \\vec{u}}$",
"_____no_output_____"
]
],
[
[
"m = ca.SX.sym('m')\nc = ca.SX.sym('c')\nk = ca.SX.sym('k')\np = ca.vertcat(m, c, k)\n\nu = ca.SX.sym('u')\nxv = ca.SX.sym('x', 2)\nx = xv[0]\nxd = xv[1]\n\ny = x\n\nxv_dot = ca.vertcat(xd, (-c*xd - k*x - ca.sin(x) + u + 3)/m)\nxv_dot",
"_____no_output_____"
],
[
"f_rhs = ca.Function('rhs', [xv, u, p], [xv_dot], ['x', 'u', 'p'], ['x_dot'], {'jit': True})\nf_rhs",
"_____no_output_____"
],
[
"f_rhs([1, 2], [0], [1, 2, 3])",
"_____no_output_____"
],
[
"import scipy.integrate\nimport numpy as np\ntf = 10\nres = scipy.integrate.solve_ivp(\n fun=lambda t, x: np.array(f_rhs(x, 0.0, [1, 2, 3])).reshape(-1),\n t_span=[0, tf],\n y0=[0, 0], t_eval=np.arange(0, tf, 0.1))\nplt.plot(res['t'], res['y'][0, :]);",
"_____no_output_____"
],
[
"A = ca.jacobian(xv_dot, xv)\nA",
"_____no_output_____"
],
[
"B = ca.jacobian(xv_dot, u)\nB",
"_____no_output_____"
],
[
"C = ca.jacobian(y, xv)\nC",
"_____no_output_____"
],
[
"D = ca.jacobian(y, u)\nD",
"_____no_output_____"
],
[
"f_ss = ca.Function('f_ss', [xv, p], [A, B, C, D], ['x', 'p'], ['A', 'B', 'C', 'D'])\nf_ss",
"_____no_output_____"
],
[
"import control\nsys = control.ss(*f_ss([0, 0], [1, 2, 3]))\nsys",
"_____no_output_____"
],
[
"f_rhs.generate('rhs.c')\n#!cat rhs.c",
"_____no_output_____"
],
[
"s = control.TransferFunction([1, 0], [0, 1])\nH = (s + 2)\ncontrol.rlocus(H*sys);",
"_____no_output_____"
],
[
"H*sys",
"_____no_output_____"
]
],
[
[
"# Linear Time Invariant Systems (LTI)",
"_____no_output_____"
],
[
"* Transfer Functions: $G(s) = s/(s+1)$\n* State-space: $\\dot{x} = Ax + Bu$, $y = Cx + Du$\n* Impulse response function: $g(t)$",
"_____no_output_____"
],
[
"* $\\dot{x} = a_1 x + a_2 x + b u$, $y = c x + du$ Linear? (Yes) Because A = A1 + A2\n* $\\dot{x} = a_1 x + 3 + b u$, $y = c x + du$ Linear? (No, not a linear system)",
"_____no_output_____"
],
[
"* What u would balance this equation at x=0? -> u0 = -3/b (trim input)",
"_____no_output_____"
],
[
"For compensated dynamcis to be $G(s) = 1/(s+1)$, u(x)=?",
"_____no_output_____"
],
[
"* LTI $\\implies$ zero in -> zero out",
"_____no_output_____"
],
[
"$u(x) = (-a1 x - x - 3)/b$\n\n$\\dot{x} = -x$",
"_____no_output_____"
],
[
"# Trimming the MSD",
"_____no_output_____"
]
],
[
[
"f_rhs([0, 0], [-3], [1, 2, 3])",
"_____no_output_____"
]
],
[
[
"$\\dot{x} = Ax + Bu$, $y = Cx + Du + 3$ (non-linear -> violates zero in zero out law)",
"_____no_output_____"
],
[
"Trimming an aircraft means, finding where the rhs = 0, or $f(t, x) = 0$, in order to do this we want to minimize\n$dot(f(t, x), f(t, x))$.",
"_____no_output_____"
]
],
[
[
"def trim_function(xv_dot):\n# return xv_dot[0] + xv_dot[1] # BAD, will drive to -inf\n return xv_dot[0]**2 + xv_dot[1]**2",
"_____no_output_____"
]
],
[
[
"This design problems find the state at which a given input will drive the sytem to.\n\n* x is the design vector\n* f is the objective function\n* p is a list of constant parameters\n* S is the solver itself",
"_____no_output_____"
]
],
[
[
"nlp = {'x':xv, 'f':trim_function(xv_dot), 'p': ca.vertcat(p, u)}\nS = ca.nlpsol('S', 'ipopt', nlp)\nprint(S)",
"S:(x0[2],p[4],lbx[2],ubx[2],lbg[0],ubg[0],lam_x0[2],lam_g0[0])->(x[2],f,g[0],lam_x[2],lam_g[0],lam_p[4]) IpoptInterface\n"
],
[
"S(x0=(0, 0), p=(1, 2, 3, 0))",
"\n******************************************************************************\nThis program contains Ipopt, a library for large-scale nonlinear optimization.\n Ipopt is released as open source code under the Eclipse Public License (EPL).\n For more information visit http://projects.coin-or.org/Ipopt\n******************************************************************************\n\nThis is Ipopt version 3.12.3, running with linear solver mumps.\nNOTE: Other linear solvers might be more efficient (see Ipopt documentation).\n\nNumber of nonzeros in equality constraint Jacobian...: 0\nNumber of nonzeros in inequality constraint Jacobian.: 0\nNumber of nonzeros in Lagrangian Hessian.............: 3\n\nTotal number of variables............................: 2\n variables with only lower bounds: 0\n variables with lower and upper bounds: 0\n variables with only upper bounds: 0\nTotal number of equality constraints.................: 0\nTotal number of inequality constraints...............: 0\n inequality constraints with only lower bounds: 0\n inequality constraints with lower and upper bounds: 0\n inequality constraints with only upper bounds: 0\n\niter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls\n 0 9.0000000e+00 0.00e+00 2.40e+01 -1.0 0.00e+00 - 0.00e+00 0.00e+00 0\n 1 4.6732591e-03 0.00e+00 5.10e-01 -1.0 7.50e-01 - 1.00e+00 1.00e+00f 1\n 2 3.1560062e-07 0.00e+00 2.50e-03 -1.7 1.80e-02 - 1.00e+00 1.00e+00f 1\n 3 5.2554628e-15 0.00e+00 4.41e-07 -3.8 4.50e-04 - 1.00e+00 1.00e+00f 1\n 4 1.5117267e-30 0.00e+00 6.61e-15 -8.6 4.18e-08 - 1.00e+00 1.00e+00f 1\n\nNumber of Iterations....: 4\n\n (scaled) (unscaled)\nObjective...............: 1.5117267303341599e-30 1.5117267303341599e-30\nDual infeasibility......: 6.6063745872867690e-15 6.6063745872867690e-15\nConstraint violation....: 0.0000000000000000e+00 0.0000000000000000e+00\nComplementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00\nOverall NLP error.......: 6.6063745872867690e-15 6.6063745872867690e-15\n\n\nNumber of objective function evaluations = 5\nNumber of objective gradient evaluations = 5\nNumber of equality constraint evaluations = 0\nNumber of inequality constraint evaluations = 0\nNumber of equality constraint Jacobian evaluations = 0\nNumber of inequality constraint Jacobian evaluations = 0\nNumber of Lagrangian Hessian evaluations = 4\nTotal CPU secs in IPOPT (w/o function evaluations) = 0.003\nTotal CPU secs in NLP function evaluations = 0.000\n\nEXIT: Optimal Solution Found.\n t_proc [s] t_wall [s] n_eval\n S 0.00478 0.00356 1\n nlp_f 1.6e-05 1.5e-05 5\n nlp_grad 5e-06 3.82e-06 1\n nlp_grad_f 2.1e-05 3.45e-05 6\n nlp_hess_l 9e-06 8.92e-06 4\n"
],
[
"nlp = {'x':u, 'f':trim_function(xv_dot), 'p': ca.vertcat(p, xv)}\nS2 = ca.nlpsol('S', 'ipopt', nlp)\nprint(S2)",
"S:(x0,p[5],lbx,ubx,lbg[0],ubg[0],lam_x0,lam_g0[0])->(x,f,g[0],lam_x,lam_g[0],lam_p[5]) IpoptInterface\n"
],
[
"res = S2(x0=(0), p=(1, 2, 3, 0, 0))\n#print('we need a trim input of {:f}'.format(float(res['x'])))",
"This is Ipopt version 3.12.3, running with linear solver mumps.\nNOTE: Other linear solvers might be more efficient (see Ipopt documentation).\n\nNumber of nonzeros in equality constraint Jacobian...: 0\nNumber of nonzeros in inequality constraint Jacobian.: 0\nNumber of nonzeros in Lagrangian Hessian.............: 1\n\nTotal number of variables............................: 1\n variables with only lower bounds: 0\n variables with lower and upper bounds: 0\n variables with only upper bounds: 0\nTotal number of equality constraints.................: 0\nTotal number of inequality constraints...............: 0\n inequality constraints with only lower bounds: 0\n inequality constraints with lower and upper bounds: 0\n inequality constraints with only upper bounds: 0\n\niter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls\n 0 9.0000000e+00 0.00e+00 6.00e+00 -1.0 0.00e+00 - 0.00e+00 0.00e+00 0\n 1 0.0000000e+00 0.00e+00 0.00e+00 -1.0 3.00e+00 - 1.00e+00 1.00e+00f 1\n\nNumber of Iterations....: 1\n\n (scaled) (unscaled)\nObjective...............: 0.0000000000000000e+00 0.0000000000000000e+00\nDual infeasibility......: 0.0000000000000000e+00 0.0000000000000000e+00\nConstraint violation....: 0.0000000000000000e+00 0.0000000000000000e+00\nComplementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00\nOverall NLP error.......: 0.0000000000000000e+00 0.0000000000000000e+00\n\n\nNumber of objective function evaluations = 2\nNumber of objective gradient evaluations = 2\nNumber of equality constraint evaluations = 0\nNumber of inequality constraint evaluations = 0\nNumber of equality constraint Jacobian evaluations = 0\nNumber of inequality constraint Jacobian evaluations = 0\nNumber of Lagrangian Hessian evaluations = 1\nTotal CPU secs in IPOPT (w/o function evaluations) = 0.001\nTotal CPU secs in NLP function evaluations = 0.000\n\nEXIT: Optimal Solution Found.\n t_proc [s] t_wall [s] n_eval\n S 0.00183 0.00212 1\n nlp_f 5e-06 5.23e-06 2\n nlp_grad 6e-06 4.32e-06 1\n nlp_grad_f 8e-06 8.68e-06 3\n nlp_hess_l 2e-06 1.93e-06 1\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7af9b4bb4b9881d4aa5e6ae53e3c41f70b3c0b1 | 82,053 | ipynb | Jupyter Notebook | K-means/1.K-means.ipynb | CoderSLZhang/sklearn_demo | 744b4cbf8adce9418a58e75535044ce7b3c8dd69 | [
"MIT"
] | null | null | null | K-means/1.K-means.ipynb | CoderSLZhang/sklearn_demo | 744b4cbf8adce9418a58e75535044ce7b3c8dd69 | [
"MIT"
] | null | null | null | K-means/1.K-means.ipynb | CoderSLZhang/sklearn_demo | 744b4cbf8adce9418a58e75535044ce7b3c8dd69 | [
"MIT"
] | null | null | null | 279.091837 | 54,988 | 0.916895 | [
[
[
"import numpy as np\nimport pandas as pd\nfrom matplotlib import pylab as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import MiniBatchKMeans\nfrom scipy import io as sio\n\n%matplotlib inline",
"_____no_output_____"
],
[
"mat = sio.loadmat('./data/ex7data2.mat')\nmat.keys()",
"_____no_output_____"
],
[
"df = pd.DataFrame(mat.get('X'), columns=['X1', 'X2'])\ndf.head()",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 10))\nplt.scatter(df['X1'], df['X2'])",
"_____no_output_____"
],
[
"kmeans = KMeans(n_clusters=3, n_init=500, max_iter=2000)",
"_____no_output_____"
],
[
"kmeans.fit(df.values)\nkmeans.inertia_",
"_____no_output_____"
],
[
"classes = kmeans.predict(df.values)\nclasses.shape",
"_____no_output_____"
],
[
"centers = kmeans.cluster_centers_\ncenters",
"_____no_output_____"
],
[
"plt.figure(figsize=(10, 10))\nplt.scatter(df['X1'], df['X2'], c=classes)\nplt.scatter(centers[:, 0], centers[:, 1], marker='X', linewidths=10)\nplt.xlim((-1, 9))\nplt.ylim((-1, 9))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7afd331881822d723614bcdb7a5603f6fc64955 | 4,119 | ipynb | Jupyter Notebook | Section 1/1.3_TensorFlow_Graphs.ipynb | manpreet-kau-r/Hands-on-Machine-Learning-with-TensorFlow | b93941cb76ee3b0f00bad8877e0f437fc7db7eb4 | [
"MIT"
] | 1 | 2021-07-20T04:44:42.000Z | 2021-07-20T04:44:42.000Z | Section 1/1.3_TensorFlow_Graphs.ipynb | manpreet-kau-r/Hands-on-Machine-Learning-with-TensorFlow | b93941cb76ee3b0f00bad8877e0f437fc7db7eb4 | [
"MIT"
] | null | null | null | Section 1/1.3_TensorFlow_Graphs.ipynb | manpreet-kau-r/Hands-on-Machine-Learning-with-TensorFlow | b93941cb76ee3b0f00bad8877e0f437fc7db7eb4 | [
"MIT"
] | null | null | null | 16.410359 | 74 | 0.477786 | [
[
[
"# TensorFlow Graphs",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf",
"_____no_output_____"
],
[
"n1 = tf.constant(1)",
"_____no_output_____"
],
[
"n2 = tf.constant(2)",
"_____no_output_____"
],
[
"n3 = n1 + n2",
"_____no_output_____"
],
[
"with tf.Session() as sess:\n result = sess.run(n3)",
"_____no_output_____"
],
[
"print(result)",
"3\n"
],
[
"print(tf.get_default_graph())",
"<tensorflow.python.framework.ops.Graph object at 0x7f6fce64a518>\n"
],
[
"g = tf.Graph()",
"_____no_output_____"
],
[
"print(g)",
"<tensorflow.python.framework.ops.Graph object at 0x7f6fce651c50>\n"
],
[
"graph_one = tf.get_default_graph()",
"_____no_output_____"
],
[
"print(graph_one)",
"<tensorflow.python.framework.ops.Graph object at 0x7f6fce64a518>\n"
],
[
"graph_two = tf.Graph()",
"_____no_output_____"
],
[
"print(graph_two)",
"<tensorflow.python.framework.ops.Graph object at 0x7f6fce651ba8>\n"
],
[
"with graph_two.as_default():\n print(graph_two is tf.get_default_graph())",
"True\n"
],
[
"print(graph_two is tf.get_default_graph())",
"False\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7afd84edb246413cee18282c89d38aa038b1685 | 196,538 | ipynb | Jupyter Notebook | notebooks/220_tfs_from_human_ensembl_protein_coding.ipynb | czbiohub/kh-analysis | bf598b54b18a10344a08a65889b54fa11d52701c | [
"MIT"
] | 1 | 2019-08-19T23:05:43.000Z | 2019-08-19T23:05:43.000Z | notebooks/220_tfs_from_human_ensembl_protein_coding.ipynb | czbiohub/kh-analysis | bf598b54b18a10344a08a65889b54fa11d52701c | [
"MIT"
] | 5 | 2019-10-08T23:05:57.000Z | 2020-03-03T17:39:26.000Z | notebooks/220_tfs_from_human_ensembl_protein_coding.ipynb | czbiohub/kh-analysis | bf598b54b18a10344a08a65889b54fa11d52701c | [
"MIT"
] | null | null | null | 66.510321 | 4,691 | 0.55432 | [
[
[
"%load_ext autoreload\n%autoreload 2\n\nfolder = '/home/olga/data_sm/kmer-hashing/classify_coding_vs_noncoding/'\n",
"The autoreload extension is already loaded. To reload it, use:\n %reload_ext autoreload\n"
],
[
"cd $folder",
"/mnt/data_sm/olga/kmer-hashing/classify_coding_vs_noncoding\n"
],
[
"import re\n\nimport pandas as pd\nimport screed",
"_____no_output_____"
]
],
[
[
"Read supplementary material csvs from https://www.ncbi.nlm.nih.gov/pubmed/29425488",
"_____no_output_____"
]
],
[
[
"\n\nhuman_tfs = pd.read_csv(\"http://humantfs.ccbr.utoronto.ca/download/v_1.01/DatabaseExtract_v_1.01.csv\", index_col=0)\nprint(human_tfs.shape)\nhuman_tfs.head()",
"(2765, 28)\n"
],
[
"human_tfs.to_csv(\"Lambert_Jolma_Campitelli_etal_2018_human_transcription_factors.csv\", index=False)",
"_____no_output_____"
],
[
"true_tfs = human_tfs.loc[human_tfs['Is TF?'] == \"Yes\"]\nprint(true_tfs.shape)\ntrue_tfs.head()",
"(1639, 28)\n"
],
[
"\ntf_records = []\n\n# with open(\"Homo_sapiens.GRCh38.pep.transcription_factors.fa\") as f:\nwith screed.open(\"Homo_sapiens.GRCh38.pep.all.fa.gz\") as records:\n for record in records:\n if '*' in record['sequence']:\n continue\n if any(x in record['name'] for x in true_tfs['Ensembl ID']):\n tf_records.append(record)",
"_____no_output_____"
],
[
"len(tf_records)",
"_____no_output_____"
],
[
"r = tf_records[0]\nr",
"_____no_output_____"
],
[
"r['name']",
"_____no_output_____"
]
],
[
[
"regex made with: https://regex101.com/r/7IzJgx/1",
"_____no_output_____"
]
],
[
[
"pattern = \"(?P<protein_id>ENSP\\d+\\.\\d+) (?P<seqtype>\\w+) (?P<location>chromosome:GRCh38:[\\dXY]+:\\d+:\\d+:\\d+) gene:(?P<gene_id>ENSG\\d+\\.\\d+) transcript:(?P<transcript_id>ENST\\d+\\.\\d+) gene_biotype:(?P<gene_biotype>\\w+) transcript_biotype:(?P<transcript_biotype>\\w+) gene_symbol:(?P<gene_symbol>\\w+) description:(?P<description>[\\w ]+) (?P<source>\\[Source:[\\w ]+ Symbol;Acc:HGNC:\\d+\\])\"\nm = re.match(pattern, r['name'])\n",
"_____no_output_____"
],
[
"m.groupdict()",
"_____no_output_____"
]
],
[
[
"Updated regex to work with all fasta entries of TFs: https://regex101.com/r/7IzJgx/2",
"_____no_output_____"
]
],
[
[
"lines = []\n\nPATTERN = r\"(?P<protein_id>ENSP\\d+\\.\\d+) (?P<seqtype>\\w+) (?P<location>chromosome:GRCh38:[\\dXY]+:\\d+:\\d+:-?\\d+) gene:(?P<gene_id>ENSG\\d+\\.\\d+) transcript:(?P<transcript_id>ENST\\d+\\.\\d+) gene_biotype:(?P<gene_biotype>\\w+) transcript_biotype:(?P<transcript_biotype>\\w+) gene_symbol:(?P<gene_symbol>[\\w\\.\\-]+) description:(?P<description>[\\w\\d\\-',/ \\.]+)(?P<source>\\[Source:[\\w ]+;Acc:[\\w:\\d]+\\])?\"\npattern = re.compile(PATTERN.strip())\n\nfor record in tf_records:\n m = re.match(pattern, record['name'])\n\n try:\n series = pd.Series(m.groupdict())\n except AttributeError:\n # If it doesn't work, break on the record it didn't work on\n print(record['name'])\n break\n lines.append(series)\ntf_metadata = pd.DataFrame.from_records(lines)\nprint(tf_metadata.shape)",
"(8337, 10)\n"
],
[
"PATTERN",
"_____no_output_____"
],
[
"re.findall(PATTERN, record['name'])",
"_____no_output_____"
],
[
"record['name']",
"_____no_output_____"
],
[
"m",
"_____no_output_____"
],
[
"tf_metadata.head()",
"_____no_output_____"
],
[
"tf_metadata.gene_id.nunique()",
"_____no_output_____"
],
[
"tf_metadata['gene_id_no_version'] = tf_metadata.gene_id.str.split('.').str[0]\n",
"_____no_output_____"
],
[
"rows = true_tfs['Ensembl ID'].isin(tf_metadata['gene_id_no_version'])\ntrue_tfs_not_in_ensembl97 = true_tfs.loc[~rows]\ntrue_tfs_not_in_ensembl97",
"_____no_output_____"
],
[
"print(true_tfs_not_in_ensembl97.loc[:, ['Ensembl ID', 'HGNC symbol','DBD', 'Is TF?', 'Final Comments']].to_csv(index=False))",
"Ensembl ID,HGNC symbol,DBD,Is TF?,Final Comments\nENSG00000214189,ZNF788,C2H2 ZF,Yes,Virtually nothing is known for this protein except that it has a decent cassette of znfC2H2 domains\nENSG00000228623,ZNF883,C2H2 ZF,Yes,None\nDUX1_HUMAN,DUX1,Homeodomain,Yes,Not included in Ensembl. Binds GATCTGAGTCTAATTGAGAATTACTGTAC in EMSA (PMID: 9736770)\nDUX3_HUMAN,DUX3,Homeodomain,Yes,Not included in Ensembl.\n\n"
]
],
[
[
"Are these TFs in the fasta file? `DUX1` and `DUX3` are likely not",
"_____no_output_____"
]
],
[
[
"! zcat Homo_sapiens.GRCh38.pep.all.fa.gz | grep ZNF788",
"_____no_output_____"
],
[
"for i, (ensembl_id, gene_symbol) in true_tfs_not_in_ensembl97[['Ensembl ID', 'HGNC symbol']].iterrows():\n print(f\"Grep for {ensembl_id}\")\n ! zcat Homo_sapiens.GRCh38.pep.all.fa.gz | grep $ensembl_id\n \n print(f\"Grep for {gene_symbol}\")\n ! zcat Homo_sapiens.GRCh38.pep.all.fa.gz | grep $gene_symbol",
"Grep for ENSG00000214189\nGrep for ZNF788\nGrep for ENSG00000228623\nGrep for ZNF883\n>ENSP00000490059.1 pep chromosome:GRCh38:9:112997120:113050043:-1 gene:ENSG00000285447.1 transcript:ENST00000619044.1 gene_biotype:protein_coding transcript_biotype:protein_coding gene_symbol:ZNF883 description:zinc finger protein 883 [Source:NCBI gene;Acc:169834]\nGrep for DUX1_HUMAN\nGrep for DUX1\nGrep for DUX3_HUMAN\nGrep for DUX3\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7afdc1c972f49d985fd2e031413f21f5920efbb | 8,833 | ipynb | Jupyter Notebook | lectures/ch19-documentation.ipynb | CMSC6950/CMSC6950.github.io | 69fbcc24430431986fd983861c4f2eb3638119a7 | [
"CC-BY-4.0"
] | null | null | null | lectures/ch19-documentation.ipynb | CMSC6950/CMSC6950.github.io | 69fbcc24430431986fd983861c4f2eb3638119a7 | [
"CC-BY-4.0"
] | null | null | null | lectures/ch19-documentation.ipynb | CMSC6950/CMSC6950.github.io | 69fbcc24430431986fd983861c4f2eb3638119a7 | [
"CC-BY-4.0"
] | 1 | 2020-05-23T00:59:08.000Z | 2020-05-23T00:59:08.000Z | 36.651452 | 347 | 0.566399 | [
[
[
"# Documentation\n\n## 1. Readable Code\n\n### 1.1 Good choice of names for variables, functions, classes, etc.\nConsider these two functions:\n\n#### Bad Example:\n```python\ndef s(p):\n a = 0\n for v in p:\n a += v\n m = a / len(p)\n d = 0\n for v in p:\n d += (v - m) * (v - m)\n return numpy.sqrt(d / (len(p) - 1))\n```\n\n#### Improved Example:\n```python\ndef std_dev(sample):\n sample_sum = 0\n for value in sample:\n sample_sum += value\n\n sample_mean = sample_sum / len(sample)\n\n sum_squared_devs = 0\n for value in sample:\n sum_squared_devs += (value - sample_mean) * (value - sample_mean)\n\n return numpy.sqrt(sum_squared_devs / (len(sample) - 1))\n```\n\nIt is appearent that using descriptive names for variables and functions makes the code more readable and it is much easier to understand and follow what the code is supposed to be doing.\n\nThis not only helps when trying to expand the code to add new functionality, but also\nto find bugs easier and faster.\n\nDeciding on a good name for a function or variable is not always an easy or obvious task. However finding a proper and concise name helps in the long run.\n\n1. **Take your time when finding a concise name for variables, functions, etc.!**\n It will pay of in the long run.",
"_____no_output_____"
],
[
"### 1.2 Comments\n\nComments in Python start with a hash `#` character. Unless inside a literal string, hash characters and everything until the end of a line is ignored by Python.\n\nComments are an important part for code documentation, however too many comments or comments with redundant information are more distracting than helpful.\n\n2. **Don't state the obvious.** A line from the above example:\n```python\na += v # increment a by v\n```\n For sure this is not a wrong statement but is just a repitation of what the code says.\n In this case the question is, what are `a` and `v`?\n\n3. **Focus on the _why_ not the _what_.**\n The code says _what_ it is doing, but at times where it is not obvious\n why something is done, add a clarifies comment.\n\n4. **Less is more.**\n Too many comments can distract from reading the code. Also code changes over time and\n more often than not the comments are not immedeately changed to match the code.\n\n5. **A superseeded comment is worse than no comment at all.**\n",
"_____no_output_____"
],
[
"### 1.3 Documentation Strings (Docstrings)\n<https://docs.python.org/3/tutorial/controlflow.html#documentation-strings>\n\nDocumentation Strings (or short Docstrings) are used to add pieces of documentation to functions, classes, modules and packages.\n\nDocstrings are placed immedeately placed after the function- or class- declaration or\nat the very top of a Python module (\\*.py file that is imported). It should be enclosed\nin sets of either three single-quotes or three double-quotes. E.g.:\n\n def <name>(<args>):\n \"\"\"<docstring>\"\"\"\n <body>\n \n class <name>(object):\n '''<docstring>'''\n <body>\n\n\nThe first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation). This line should begin with a capital letter and end with a period.\n\nIf there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description. The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.\n\n```python\ndef std_dev(sample):\n '''Return corrected sample standard deviation.\n \n Sample can be a list, tuple, numpy.ndarray or any other \n collection of numerical values.\n\n The corrected sample standard deviation is calculated as:\n $s = \\sqrt{ \\frac{1}{N} \\sum_{i=1}^{N}(x_i - \\overline{x}) }$\n\n Example:\n >>> std_dev([2, 3, 4, 4, 4, 5, 5, 6, 7])\n 5\n\n See [1] for more detail.\n [1]: https://en.wikipedia.org/wiki/Standard_deviation\n '''\n sample_sum = 0\n for value in sample:\n sample_sum += value\n\n sample_mean = sample_sum / len(sample)\n\n sum_squared_devs = 0\n for value in sample:\n sum_squared_devs += (value - sample_mean) * (value - sample_mean)\n\n return numpy.sqrt(sum_squared_devs / (len(sample) - 1))\n```\n",
"_____no_output_____"
],
[
"## A Case Study\n\nThis example contains too many comments that are long and repeat in words\nwhat the code tells us already.\n\nAlso variable names like `mylist` and `d` don't tell us what they are.\n\n```python\ndef decay(index, database):\n # first, retrieve the decay constants from the database\n mylist = database.decay_constants()\n # next, try to access an element of the list\n try:\n d = mylist[index] # gets decay constant at index in the list\n # if the index doesn't exist\n except IndexError:\n # throw an informative error message\n raise Exception(\"value not found in the list\")\n return d\n```\n\n### Step 1: Improve names and remove extranous comments.\n\n```python\ndef decay(index, database):\n lambdas = database.decay_constants()\n try:\n lambda_i = lambdas[index] # gets decay constant at index in the list\n except IndexError:\n raise Exception(\"value not found in the list\")\n return lambda_i\n```\n\n### Step 2: Add more specific information to the error-message\n\nAn error message `\"value not found in the list\"` is not particulary helpful,\nwhen thrown in a larger project. Adding a bit of context makes it easier\nto find the piece of code where the error has occured.\n\n```python\ndef decay(index, database):\n lambdas = database.decay_constants()\n try:\n lambda_i = lambdas[index] # gets decay constant at index in the list\n except LookupError:\n raise Exception(\"value not found in the decay constants object\")\n return lambda_i\n```\n\n### Step 3: Add Docstring\n\n```python\ndef decay(index, database):\n '''Retrieve decay constant for `index` from `database`.\n \n raises Exception if `index` is not present in the database.\n '''\n lambdas = database.decay_constants()\n try:\n lambda_i = lambdas[index] # gets decay constant at index in the list\n except LookupError:\n raise Exception(\"value not found in the decay constants object\")\n return lambda_i\n```\n",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7afdc2395058d0e9366692d67c501a8d3d2154d | 24,398 | ipynb | Jupyter Notebook | chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb | sgeos/mxnet_the_straight_dope | 5af16ade3dad964eb48d4c4fd6c09176cfe68f66 | [
"Apache-2.0"
] | null | null | null | chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb | sgeos/mxnet_the_straight_dope | 5af16ade3dad964eb48d4c4fd6c09176cfe68f66 | [
"Apache-2.0"
] | 1 | 2020-03-30T20:36:17.000Z | 2020-03-30T20:36:17.000Z | chapter04_convolutional-neural-networks/cnn-batch-norm-scratch.ipynb | sgeos/mxnet_the_straight_dope | 5af16ade3dad964eb48d4c4fd6c09176cfe68f66 | [
"Apache-2.0"
] | null | null | null | 37.248855 | 714 | 0.540413 | [
[
[
"# Batch Normalization from scratch\n\nWhen you train a linear model, you update the weights\nin order to optimize some objective.\nAnd for the linear model, \nthe distribution of the inputs stays the same throughout training.\nSo all we have to worry about is how to map \nfrom these well-behaved inputs to some appropriate outputs.\nBut if we focus on some layer in the middle of a deep neural network,\nfor example the third,\nthings look a bit different. \nAfter each training iteration, \nwe update the weights in all the layers, including the first and the second.\nThat means that over the course of training,\nas the weights for the first two layers are learned,\nthe inputs to the third layer might look dramatically different than they did at the beginning.\nFor starters, they might take values on a scale orders of magnitudes different from when we started training.\nAnd this shift in feature scale might have serious implications, say for the ideal learning rate at each time. \n\nTo explain, let us consider the Taylor's expansion for the objective function $f$ with respect to the updated parameter $\\mathbf{w}$, such as $f(\\mathbf{w} - \\eta \\nabla f(\\mathbf{w}))$. Coefficients of those higher-order terms with respect to the learning rate $\\eta$ may be so large in scale (usually due to many layers) that these terms cannot be ignored. However, the effect of common lower-order optimization algorithms, such as gradient descent, in iteratively reducing the objective function is based on an important assumption: all those higher-order terms with respect to the learning rate in the aforementioned Taylor's expansion are ignored.\n\n\nMotivated by this sort of intuition, \nSergey Ioffe and Christian Szegedy proposed [Batch Normalization](https://arxiv.org/abs/1502.03167),\na technique that normalizes the mean and variance of each of the features at every level of representation during training. \nThe technique involves normalization of the features across the examples in each mini-batch.\nWhile competing explanations for the technique's effect abound,\nits success is hard to deny.\nEmpirically it appears to stabilize the gradient (less exploding or vanishing values)\nand batch-normalized models appear to overfit less.\nIn fact, batch-normalized models seldom even use dropout. \nIn this notebooks, we'll explain how it works.\n\n## Import dependencies and grab the MNIST dataset\nWe'll get going by importing the typical packages and grabbing the MNIST data.",
"_____no_output_____"
]
],
[
[
"from __future__ import print_function\nimport mxnet as mx\nimport numpy as np\nfrom mxnet import nd, autograd\nmx.random.seed(1)\nctx = mx.gpu()",
"_____no_output_____"
]
],
[
[
"## The MNIST dataset",
"_____no_output_____"
]
],
[
[
"batch_size = 64\nnum_inputs = 784\nnum_outputs = 10\ndef transform(data, label):\n return nd.transpose(data.astype(np.float32), (2,0,1))/255, label.astype(np.float32)\ntrain_data = mx.gluon.data.DataLoader(mx.gluon.data.vision.MNIST(train=True, transform=transform),\n batch_size, shuffle=True)\ntest_data = mx.gluon.data.DataLoader(mx.gluon.data.vision.MNIST(train=False, transform=transform),\n batch_size, shuffle=False)",
"_____no_output_____"
]
],
[
[
"## Batch Normalization layer\n\nThe layer, unlike Dropout, is usually used **before** the activation layer \n(according to the authors' original paper), instead of after activation layer.\n\nThe basic idea is doing the normalization then applying a linear scale and shift to the mini-batch:\n\nFor input mini-batch $B = \\{x_{1, ..., m}\\}$, we want to learn the parameter $\\gamma$ and $\\beta$.\nThe output of the layer is $\\{y_i = BN_{\\gamma, \\beta}(x_i)\\}$, where:\n\n$$\\mu_B \\leftarrow \\frac{1}{m}\\sum_{i = 1}^{m}x_i$$\n$$\\sigma_B^2 \\leftarrow \\frac{1}{m} \\sum_{i=1}^{m}(x_i - \\mu_B)^2$$\n$$\\hat{x_i} \\leftarrow \\frac{x_i - \\mu_B}{\\sqrt{\\sigma_B^2 + \\epsilon}}$$\n$$y_i \\leftarrow \\gamma \\hat{x_i} + \\beta \\equiv \\mbox{BN}_{\\gamma,\\beta}(x_i)$$\n\n* formulas taken from Ioffe, Sergey, and Christian Szegedy. \"Batch normalization: Accelerating deep network training by reducing internal covariate shift.\" International Conference on Machine Learning. 2015.\n\nWith gluon, this is all actually implemented for us, \nbut we'll do it this one time by ourselves,\nusing the formulas from the original paper\nso you know how it works, and perhaps you can improve upon it!\n\nPay attention that, when it comes to (2D) CNN, we normalize `batch_size * height * width` over each channel.\nSo that `gamma` and `beta` have the lengths the same as `channel_count`.\nIn our implementation, we need to manually reshape `gamma` and `beta` \nso that they could (be automatically broadcast and) multipy the matrices in the desired way.",
"_____no_output_____"
]
],
[
[
"def pure_batch_norm(X, gamma, beta, eps = 1e-5):\n if len(X.shape) not in (2, 4):\n raise ValueError('only supports dense or 2dconv')\n\n # dense\n if len(X.shape) == 2:\n # mini-batch mean\n mean = nd.mean(X, axis=0)\n # mini-batch variance\n variance = nd.mean((X - mean) ** 2, axis=0)\n # normalize\n X_hat = (X - mean) * 1.0 / nd.sqrt(variance + eps)\n # scale and shift\n out = gamma * X_hat + beta\n \n # 2d conv\n elif len(X.shape) == 4:\n # extract the dimensions\n N, C, H, W = X.shape\n # mini-batch mean\n mean = nd.mean(X, axis=(0, 2, 3))\n # mini-batch variance\n variance = nd.mean((X - mean.reshape((1, C, 1, 1))) ** 2, axis=(0, 2, 3))\n # normalize\n X_hat = (X - mean.reshape((1, C, 1, 1))) * 1.0 / nd.sqrt(variance.reshape((1, C, 1, 1)) + eps)\n # scale and shift\n out = gamma.reshape((1, C, 1, 1)) * X_hat + beta.reshape((1, C, 1, 1))\n \n return out",
"_____no_output_____"
]
],
[
[
"Let's do some sanity checks. We expect each **column** of the input matrix to be normalized.",
"_____no_output_____"
]
],
[
[
"A = nd.array([1,7,5,4,6,10], ctx=ctx).reshape((3,2))\nA",
"_____no_output_____"
],
[
"pure_batch_norm(A,\n gamma = nd.array([1,1], ctx=ctx), \n beta=nd.array([0,0], ctx=ctx))",
"_____no_output_____"
],
[
"ga = nd.array([1,1], ctx=ctx)\nbe = nd.array([0,0], ctx=ctx)\n\nB = nd.array([1,6,5,7,4,3,2,5,6,3,2,4,5,3,2,5,6], ctx=ctx).reshape((2,2,2,2))\nB",
"_____no_output_____"
],
[
"pure_batch_norm(B, ga, be)",
"_____no_output_____"
]
],
[
[
"Our tests seem to support that we've done everything correctly.\nNote that for batch normalization, implementing **backward** pass is a little bit tricky. \nFortunately, you won't have to worry about that here, \nbecause the MXNet's `autograd` package can handle differentiation for us automatically.",
"_____no_output_____"
],
[
"Besides that, in the testing process, we want to use the mean and variance of the **complete dataset**, instead of those of **mini batches**. In the implementation, we use moving statistics as a trade off, because we don't want to or don't have the ability to compute the statistics of the complete dataset (in the second loop).\n\nThen here comes another concern: we need to maintain the moving statistics **along with multiple runs of the BN**. It's an engineering issue rather than a deep/machine learning issue. On the one hand, the moving statistics are similar to `gamma` and `beta`; on the other hand, they are **not** updated by the gradient backwards. In this quick-and-dirty implementation, we use the global dictionary variables to store the statistics, in which each key is the name of the layer (`scope_name`), and the value is the statistics. (**Attention**: always be very careful if you have to use global variables!) Moreover, we have another parameter `is_training` to indicate whether we are doing training or testing.\n\nNow we are ready to define our complete `batch_norm()`:",
"_____no_output_____"
]
],
[
[
"def batch_norm(X,\n gamma,\n beta,\n momentum = 0.9,\n eps = 1e-5,\n scope_name = '',\n is_training = True,\n debug = False):\n \"\"\"compute the batch norm \"\"\"\n global _BN_MOVING_MEANS, _BN_MOVING_VARS\n \n #########################\n # the usual batch norm transformation\n #########################\n \n if len(X.shape) not in (2, 4):\n raise ValueError('the input data shape should be one of:\\n' + \n 'dense: (batch size, # of features)\\n' + \n '2d conv: (batch size, # of features, height, width)'\n )\n \n # dense\n if len(X.shape) == 2:\n # mini-batch mean\n mean = nd.mean(X, axis=0)\n # mini-batch variance\n variance = nd.mean((X - mean) ** 2, axis=0)\n # normalize\n if is_training:\n # while training, we normalize the data using its mean and variance\n X_hat = (X - mean) * 1.0 / nd.sqrt(variance + eps)\n else:\n # while testing, we normalize the data using the pre-computed mean and variance\n X_hat = (X - _BN_MOVING_MEANS[scope_name]) *1.0 / nd.sqrt(_BN_MOVING_VARS[scope_name] + eps)\n # scale and shift\n out = gamma * X_hat + beta\n \n # 2d conv\n elif len(X.shape) == 4:\n # extract the dimensions\n N, C, H, W = X.shape\n # mini-batch mean\n mean = nd.mean(X, axis=(0,2,3))\n # mini-batch variance\n variance = nd.mean((X - mean.reshape((1, C, 1, 1))) ** 2, axis=(0, 2, 3))\n # normalize\n X_hat = (X - mean.reshape((1, C, 1, 1))) * 1.0 / nd.sqrt(variance.reshape((1, C, 1, 1)) + eps)\n if is_training:\n # while training, we normalize the data using its mean and variance\n X_hat = (X - mean.reshape((1, C, 1, 1))) * 1.0 / nd.sqrt(variance.reshape((1, C, 1, 1)) + eps)\n else:\n # while testing, we normalize the data using the pre-computed mean and variance\n X_hat = (X - _BN_MOVING_MEANS[scope_name].reshape((1, C, 1, 1))) * 1.0 \\\n / nd.sqrt(_BN_MOVING_VARS[scope_name].reshape((1, C, 1, 1)) + eps)\n # scale and shift\n out = gamma.reshape((1, C, 1, 1)) * X_hat + beta.reshape((1, C, 1, 1))\n \n #########################\n # to keep the moving statistics\n #########################\n \n # init the attributes\n try: # to access them\n _BN_MOVING_MEANS, _BN_MOVING_VARS\n except: # error, create them\n _BN_MOVING_MEANS, _BN_MOVING_VARS = {}, {}\n \n # store the moving statistics by their scope_names, inplace \n if scope_name not in _BN_MOVING_MEANS:\n _BN_MOVING_MEANS[scope_name] = mean\n else:\n _BN_MOVING_MEANS[scope_name] = _BN_MOVING_MEANS[scope_name] * momentum + mean * (1.0 - momentum)\n if scope_name not in _BN_MOVING_VARS:\n _BN_MOVING_VARS[scope_name] = variance\n else:\n _BN_MOVING_VARS[scope_name] = _BN_MOVING_VARS[scope_name] * momentum + variance * (1.0 - momentum)\n \n #########################\n # debug info\n #########################\n if debug:\n print('== info start ==')\n print('scope_name = {}'.format(scope_name))\n print('mean = {}'.format(mean))\n print('var = {}'.format(variance))\n print('_BN_MOVING_MEANS = {}'.format(_BN_MOVING_MEANS[scope_name]))\n print('_BN_MOVING_VARS = {}'.format(_BN_MOVING_VARS[scope_name]))\n print('output = {}'.format(out))\n print('== info end ==')\n \n #########################\n # return\n #########################\n return out",
"_____no_output_____"
]
],
[
[
"## Parameters and gradients",
"_____no_output_____"
]
],
[
[
"#######################\n# Set the scale for weight initialization and choose \n# the number of hidden units in the fully-connected layer \n####################### \nweight_scale = .01\nnum_fc = 128\n\nW1 = nd.random_normal(shape=(20, 1, 3,3), scale=weight_scale, ctx=ctx) \nb1 = nd.random_normal(shape=20, scale=weight_scale, ctx=ctx)\n\ngamma1 = nd.random_normal(shape=20, loc=1, scale=weight_scale, ctx=ctx)\nbeta1 = nd.random_normal(shape=20, scale=weight_scale, ctx=ctx)\n\nW2 = nd.random_normal(shape=(50, 20, 5, 5), scale=weight_scale, ctx=ctx)\nb2 = nd.random_normal(shape=50, scale=weight_scale, ctx=ctx)\n\ngamma2 = nd.random_normal(shape=50, loc=1, scale=weight_scale, ctx=ctx)\nbeta2 = nd.random_normal(shape=50, scale=weight_scale, ctx=ctx)\n\nW3 = nd.random_normal(shape=(800, num_fc), scale=weight_scale, ctx=ctx)\nb3 = nd.random_normal(shape=num_fc, scale=weight_scale, ctx=ctx)\n\ngamma3 = nd.random_normal(shape=num_fc, loc=1, scale=weight_scale, ctx=ctx)\nbeta3 = nd.random_normal(shape=num_fc, scale=weight_scale, ctx=ctx)\n\nW4 = nd.random_normal(shape=(num_fc, num_outputs), scale=weight_scale, ctx=ctx)\nb4 = nd.random_normal(shape=10, scale=weight_scale, ctx=ctx)\n\nparams = [W1, b1, gamma1, beta1, W2, b2, gamma2, beta2, W3, b3, gamma3, beta3, W4, b4]",
"_____no_output_____"
],
[
"for param in params:\n param.attach_grad()",
"_____no_output_____"
]
],
[
[
"## Activation functions",
"_____no_output_____"
]
],
[
[
"def relu(X):\n return nd.maximum(X, 0)",
"_____no_output_____"
]
],
[
[
"## Softmax output",
"_____no_output_____"
]
],
[
[
"def softmax(y_linear):\n exp = nd.exp(y_linear-nd.max(y_linear))\n partition = nd.nansum(exp, axis=0, exclude=True).reshape((-1,1))\n return exp / partition",
"_____no_output_____"
]
],
[
[
"## The *softmax* cross-entropy loss function",
"_____no_output_____"
]
],
[
[
"def softmax_cross_entropy(yhat_linear, y):\n return - nd.nansum(y * nd.log_softmax(yhat_linear), axis=0, exclude=True)",
"_____no_output_____"
]
],
[
[
"## Define the model\n\nWe insert the BN layer right after each linear layer.",
"_____no_output_____"
]
],
[
[
"def net(X, is_training = True, debug=False):\n ########################\n # Define the computation of the first convolutional layer\n ########################\n h1_conv = nd.Convolution(data=X, weight=W1, bias=b1, kernel=(3,3), num_filter=20)\n h1_normed = batch_norm(h1_conv, gamma1, beta1, scope_name='bn1', is_training=is_training)\n h1_activation = relu(h1_normed)\n h1 = nd.Pooling(data=h1_activation, pool_type=\"avg\", kernel=(2,2), stride=(2,2))\n if debug:\n print(\"h1 shape: %s\" % (np.array(h1.shape)))\n \n ########################\n # Define the computation of the second convolutional layer\n ########################\n h2_conv = nd.Convolution(data=h1, weight=W2, bias=b2, kernel=(5,5), num_filter=50)\n h2_normed = batch_norm(h2_conv, gamma2, beta2, scope_name='bn2', is_training=is_training)\n h2_activation = relu(h2_normed)\n h2 = nd.Pooling(data=h2_activation, pool_type=\"avg\", kernel=(2,2), stride=(2,2))\n if debug:\n print(\"h2 shape: %s\" % (np.array(h2.shape)))\n \n ########################\n # Flattening h2 so that we can feed it into a fully-connected layer\n ########################\n h2 = nd.flatten(h2)\n if debug:\n print(\"Flat h2 shape: %s\" % (np.array(h2.shape)))\n \n ########################\n # Define the computation of the third (fully-connected) layer\n ########################\n h3_linear = nd.dot(h2, W3) + b3\n h3_normed = batch_norm(h3_linear, gamma3, beta3, scope_name='bn3', is_training=is_training)\n h3 = relu(h3_normed)\n if debug:\n print(\"h3 shape: %s\" % (np.array(h3.shape)))\n \n ########################\n # Define the computation of the output layer\n ########################\n yhat_linear = nd.dot(h3, W4) + b4\n if debug:\n print(\"yhat_linear shape: %s\" % (np.array(yhat_linear.shape)))\n \n return yhat_linear\n",
"_____no_output_____"
]
],
[
[
"## Test run\n\nCan data be passed into the `net()`?",
"_____no_output_____"
]
],
[
[
"for data, _ in train_data:\n data = data.as_in_context(ctx)\n break",
"_____no_output_____"
],
[
"output = net(data, is_training=True, debug=True)",
"_____no_output_____"
]
],
[
[
"## Optimizer",
"_____no_output_____"
]
],
[
[
"def SGD(params, lr): \n for param in params:\n param[:] = param - lr * param.grad",
"_____no_output_____"
]
],
[
[
"## Evaluation metric",
"_____no_output_____"
]
],
[
[
"def evaluate_accuracy(data_iterator, net):\n numerator = 0.\n denominator = 0.\n for i, (data, label) in enumerate(data_iterator):\n data = data.as_in_context(ctx)\n label = label.as_in_context(ctx)\n label_one_hot = nd.one_hot(label, 10)\n output = net(data, is_training=False) # attention here!\n predictions = nd.argmax(output, axis=1)\n numerator += nd.sum(predictions == label)\n denominator += data.shape[0]\n return (numerator / denominator).asscalar()",
"_____no_output_____"
]
],
[
[
"## Execute the training loop\n\nNote: you may want to use a gpu to run the code below. (And remember to set the `ctx = mx.gpu()` accordingly in the very beginning of this article.)",
"_____no_output_____"
]
],
[
[
"epochs = 1\nmoving_loss = 0.\nlearning_rate = .001\n\nfor e in range(epochs):\n for i, (data, label) in enumerate(train_data):\n data = data.as_in_context(ctx)\n label = label.as_in_context(ctx)\n label_one_hot = nd.one_hot(label, num_outputs)\n with autograd.record():\n # we are in training process,\n # so we normalize the data using batch mean and variance\n output = net(data, is_training=True)\n loss = softmax_cross_entropy(output, label_one_hot)\n loss.backward()\n SGD(params, learning_rate)\n \n ##########################\n # Keep a moving average of the losses\n ##########################\n if i == 0:\n moving_loss = nd.mean(loss).asscalar()\n else:\n moving_loss = .99 * moving_loss + .01 * nd.mean(loss).asscalar()\n \n test_accuracy = evaluate_accuracy(test_data, net)\n train_accuracy = evaluate_accuracy(train_data, net)\n print(\"Epoch %s. Loss: %s, Train_acc %s, Test_acc %s\" % (e, moving_loss, train_accuracy, test_accuracy)) ",
"_____no_output_____"
]
],
[
[
"## Next\n[Batch normalization with gluon](../chapter04_convolutional-neural-networks/cnn-batch-norm-gluon.ipynb)",
"_____no_output_____"
],
[
"For whinges or inquiries, [open an issue on GitHub.](https://github.com/zackchase/mxnet-the-straight-dope)",
"_____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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e7afdfe7a77b4b7c5e1b507c308d56d67e9c684c | 6,016 | ipynb | Jupyter Notebook | Examples/rllib/Untitled.ipynb | alexanderkell/reinforcement-learning-examples | cd154b13ab8247823b71a799dac17008061d56d0 | [
"MIT"
] | null | null | null | Examples/rllib/Untitled.ipynb | alexanderkell/reinforcement-learning-examples | cd154b13ab8247823b71a799dac17008061d56d0 | [
"MIT"
] | null | null | null | Examples/rllib/Untitled.ipynb | alexanderkell/reinforcement-learning-examples | cd154b13ab8247823b71a799dac17008061d56d0 | [
"MIT"
] | null | null | null | 31.830688 | 155 | 0.462766 | [
[
[
"import ray",
"_____no_output_____"
],
[
"from ray.tune import run_experiments, grid_search",
"_____no_output_____"
],
[
"\"\"\"The two-step game from QMIX: https://arxiv.org/pdf/1803.11485.pdf\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nfrom gym.spaces import Tuple, Discrete\n\nimport ray\nfrom ray.tune import register_env, run_experiments, grid_search\nfrom ray.rllib.env.multi_agent_env import MultiAgentEnv\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--stop\", type=int, default=50000)\nparser.add_argument(\"--run\", type=str, default=\"QMIX\")\n\n\nclass TwoStepGame(MultiAgentEnv):\n action_space = Discrete(2)\n\n # Each agent gets a separate [3] obs space, to ensure that they can\n # learn meaningfully different Q values even with a shared Q model.\n observation_space = Discrete(6)\n\n def __init__(self, env_config):\n self.state = None\n\n def reset(self):\n self.state = 0\n return {\"agent_1\": self.state, \"agent_2\": self.state + 3}\n\n def step(self, action_dict):\n if self.state == 0:\n action = action_dict[\"agent_1\"]\n assert action in [0, 1], action\n if action == 0:\n self.state = 1\n else:\n self.state = 2\n global_rew = 0\n done = False\n elif self.state == 1:\n global_rew = 7\n done = True\n else:\n if action_dict[\"agent_1\"] == 0 and action_dict[\"agent_2\"] == 0:\n global_rew = 0\n elif action_dict[\"agent_1\"] == 1 and action_dict[\"agent_2\"] == 1:\n global_rew = 8\n else:\n global_rew = 1\n done = True\n\n rewards = {\"agent_1\": global_rew / 2.0, \"agent_2\": global_rew / 2.0}\n obs = {\"agent_1\": self.state, \"agent_2\": self.state + 3}\n dones = {\"__all__\": done}\n infos = {}\n return obs, rewards, dones, infos\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n grouping = {\n \"group_1\": [\"agent_1\", \"agent_2\"],\n }\n obs_space = Tuple([\n TwoStepGame.observation_space,\n TwoStepGame.observation_space,\n ])\n act_space = Tuple([\n TwoStepGame.action_space,\n TwoStepGame.action_space,\n ])\n register_env(\n \"grouped_twostep\",\n lambda config: TwoStepGame(config).with_agent_groups(\n grouping, obs_space=obs_space, act_space=act_space))\n\n if args.run == \"QMIX\":\n config = {\n \"sample_batch_size\": 4,\n \"train_batch_size\": 32,\n \"exploration_final_eps\": 0.0,\n \"num_workers\": 0,\n \"mixer\": grid_search([None, \"qmix\", \"vdn\"]),\n }\n elif args.run == \"APEX_QMIX\":\n config = {\n \"num_gpus\": 0,\n \"num_workers\": 2,\n \"optimizer\": {\n \"num_replay_buffer_shards\": 1,\n },\n \"min_iter_time_s\": 3,\n \"buffer_size\": 1000,\n \"learning_starts\": 1000,\n \"train_batch_size\": 128,\n \"sample_batch_size\": 32,\n \"target_network_update_freq\": 500,\n \"timesteps_per_iteration\": 1000,\n }\n else:\n config = {}\n\n ray.init()\n run_experiments({\n \"two_step\": {\n \"run\": args.run,\n \"env\": \"grouped_twostep\",\n \"stop\": {\n \"timesteps_total\": args.stop,\n },\n \"config\": config,\n },\n })\n \n %tb",
"usage: ipykernel_launcher.py [-h] [--stop STOP] [--run RUN]\nipykernel_launcher.py: error: unrecognized arguments: -f /Users/b1017579/Library/Jupyter/runtime/kernel-8f41b4da-9001-41cc-81b4-03d9e0f14641.json\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
e7afebcc54604ba857d4da8a1b2099a446ce1832 | 7,369 | ipynb | Jupyter Notebook | jeffs_helpful.ipynb | guyvani/t81_558_deep_learning | 73c15aae939172cc3c59f091f4a38942dfb6a80f | [
"Apache-2.0"
] | 1 | 2019-10-15T13:10:51.000Z | 2019-10-15T13:10:51.000Z | jeffs_helpful.ipynb | codeslord/t81_558_deep_learning | 561f5bfd61a485ed6730c75abd169c93baa4165d | [
"Apache-2.0"
] | null | null | null | jeffs_helpful.ipynb | codeslord/t81_558_deep_learning | 561f5bfd61a485ed6730c75abd169c93baa4165d | [
"Apache-2.0"
] | 1 | 2019-09-01T11:11:09.000Z | 2019-09-01T11:11:09.000Z | 40.938889 | 136 | 0.558692 | [
[
[
"# Collection of Helpful Functions for [Class](https://sites.wustl.edu/jeffheaton/t81-558/)\n\nThis is a collection of helpful functions that I will introduce during this course. ",
"_____no_output_____"
]
],
[
[
"import base64\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom sklearn import preprocessing\n\n\n# Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue)\ndef encode_text_dummy(df, name):\n dummies = pd.get_dummies(df[name])\n for x in dummies.columns:\n dummy_name = f\"{name}-{x}\"\n df[dummy_name] = dummies[x]\n df.drop(name, axis=1, inplace=True)\n\n\n# Encode text values to a single dummy variable. The new columns (which do not replace the old) will have a 1\n# at every location where the original column (name) matches each of the target_values. One column is added for\n# each target value.\ndef encode_text_single_dummy(df, name, target_values):\n for tv in target_values:\n l = list(df[name].astype(str))\n l = [1 if str(x) == str(tv) else 0 for x in l]\n name2 = f\"{name}-{tv}\"\n df[name2] = l\n\n\n# Encode text values to indexes(i.e. [1],[2],[3] for red,green,blue).\ndef encode_text_index(df, name):\n le = preprocessing.LabelEncoder()\n df[name] = le.fit_transform(df[name])\n return le.classes_\n\n\n# Encode a numeric column as zscores\ndef encode_numeric_zscore(df, name, mean=None, sd=None):\n if mean is None:\n mean = df[name].mean()\n\n if sd is None:\n sd = df[name].std()\n\n df[name] = (df[name] - mean) / sd\n\n\n# Convert all missing values in the specified column to the median\ndef missing_median(df, name):\n med = df[name].median()\n df[name] = df[name].fillna(med)\n\n\n# Convert all missing values in the specified column to the default\ndef missing_default(df, name, default_value):\n df[name] = df[name].fillna(default_value)\n\n\n# Convert a Pandas dataframe to the x,y inputs that TensorFlow needs\ndef to_xy(df, target):\n result = []\n for x in df.columns:\n if x != target:\n result.append(x)\n # find out the type of the target column. Is it really this hard? :(\n target_type = df[target].dtypes\n target_type = target_type[0] if hasattr(\n target_type, '__iter__') else target_type\n # Encode to int for classification, float otherwise. TensorFlow likes 32 bits.\n if target_type in (np.int64, np.int32):\n # Classification\n dummies = pd.get_dummies(df[target])\n return df.as_matrix(result).astype(np.float32), dummies.as_matrix().astype(np.float32)\n # Regression\n return df.as_matrix(result).astype(np.float32), df.as_matrix([target]).astype(np.float32)\n\n# Nicely formatted time string\ndef hms_string(sec_elapsed):\n h = int(sec_elapsed / (60 * 60))\n m = int((sec_elapsed % (60 * 60)) / 60)\n s = sec_elapsed % 60\n return f\"{h}:{m:>02}:{s:>05.2f}\"\n\n\n# Regression chart.\ndef chart_regression(pred, y, sort=True):\n t = pd.DataFrame({'pred': pred, 'y': y.flatten()})\n if sort:\n t.sort_values(by=['y'], inplace=True)\n plt.plot(t['y'].tolist(), label='expected')\n plt.plot(t['pred'].tolist(), label='prediction')\n plt.ylabel('output')\n plt.legend()\n plt.show()\n\n# Remove all rows where the specified column is +/- sd standard deviations\ndef remove_outliers(df, name, sd):\n drop_rows = df.index[(np.abs(df[name] - df[name].mean())\n >= (sd * df[name].std()))]\n df.drop(drop_rows, axis=0, inplace=True)\n\n\n# Encode a column to a range between normalized_low and normalized_high.\ndef encode_numeric_range(df, name, normalized_low=-1, normalized_high=1,\n data_low=None, data_high=None):\n if data_low is None:\n data_low = min(df[name])\n data_high = max(df[name])\n\n df[name] = ((df[name] - data_low) / (data_high - data_low)) \\\n * (normalized_high - normalized_low) + normalized_low\n\n\n# This function submits an assignment. You can submit an assignment as much as you like, only the final\n# submission counts. The paramaters are as follows:\n# data - Pandas dataframe output.\n# key - Your student key that was emailed to you.\n# no - The assignment class number, should be 1 through 1.\n# source_file - The full path to your Python or IPYNB file. This must have \"_class1\" as part of its name. \n# . The number must match your assignment number. For example \"_class2\" for class assignment #2.\ndef submit(data,key,no,source_file=None):\n if source_file is None and '__file__' not in globals(): raise Exception('Must specify a filename when a Jupyter notebook.')\n if source_file is None: source_file = __file__\n suffix = '_class{}'.format(no)\n if suffix not in source_file: raise Exception('{} must be part of the filename.'.format(suffix))\n with open(source_file, \"rb\") as image_file:\n encoded_python = base64.b64encode(image_file.read()).decode('ascii')\n ext = os.path.splitext(source_file)[-1].lower()\n if ext not in ['.ipynb','.py']: raise Exception(\"Source file is {} must be .py or .ipynb\".format(ext))\n r = requests.post(\"https://api.heatonresearch.com/assignment-submit\",\n headers={'x-api-key':key}, json={'csv':base64.b64encode(data.to_csv(index=False).encode('ascii')).decode(\"ascii\"),\n 'assignment': no, 'ext':ext, 'py':encoded_python})\n if r.status_code == 200:\n print(\"Success: {}\".format(r.text))\n else: print(\"Failure: {}\".format(r.text))\n",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
e7afef8b578399bbd178596cc927a5ab5f550e67 | 17,435 | ipynb | Jupyter Notebook | docs/seaman/04.1_seaman_rudder_equation.ipynb | martinlarsalbert/wPCC | 16e0d4cc850d503247916c9f5bd9f0ddb07f8930 | [
"MIT"
] | null | null | null | docs/seaman/04.1_seaman_rudder_equation.ipynb | martinlarsalbert/wPCC | 16e0d4cc850d503247916c9f5bd9f0ddb07f8930 | [
"MIT"
] | null | null | null | docs/seaman/04.1_seaman_rudder_equation.ipynb | martinlarsalbert/wPCC | 16e0d4cc850d503247916c9f5bd9f0ddb07f8930 | [
"MIT"
] | null | null | null | 24.081492 | 171 | 0.477947 | [
[
[
"# Rudder equations",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2\n%matplotlib inline",
"_____no_output_____"
],
[
"import sympy as sp\nfrom sympy.plotting import plot as plot\nfrom sympy.plotting import plot3d as plot3d\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nsp.init_printing()\nfrom IPython.core.display import HTML,Latex",
"_____no_output_____"
],
[
"import seaman_symbol as ss\nfrom rudder_equations import *\nfrom bis_system import BisSystem\n\nfrom seaman_symbols import *\nimport seaman_symbol as ss\n\nimport sys\nsys.path.append(\"../\")\nimport seaman",
"_____no_output_____"
]
],
[
[
"## Coordinate system\n",
"_____no_output_____"
],
[
"## Symbols",
"_____no_output_____"
]
],
[
[
"#HTML(ss.create_html_table(symbols=equations.total_sway_hull_equation_SI.free_symbols))",
"_____no_output_____"
]
],
[
[
"## Rudder equation\nThe rudder forces consist of mainly two parts, one that is\ndepending on the ship axial speed and one that is depending on the thrust.\n\nThe stalling effect is represented by a third degree term with a stall coefficient s.\nThe total expression for the rudder force is thus written as:",
"_____no_output_____"
]
],
[
[
"\n\nrudder_equation_no_stall",
"_____no_output_____"
]
],
[
[
"If we also consider stall",
"_____no_output_____"
]
],
[
[
"rudder_equation",
"_____no_output_____"
]
],
[
[
"## Effective rudder angle",
"_____no_output_____"
]
],
[
[
"effective_rudder_angle_equation",
"_____no_output_____"
],
[
"delta_e_expanded",
"_____no_output_____"
]
],
[
[
"### Speed dependent part",
"_____no_output_____"
]
],
[
[
"Latex(sp.latex(rudder_u_equation))",
"_____no_output_____"
]
],
[
[
"### Thrust dependent part\nThis part is assumed to be proportional to the propeller thrust",
"_____no_output_____"
]
],
[
[
"rudder_T_equation",
"_____no_output_____"
],
[
"sp.latex(rudder_total_sway_equation)",
"_____no_output_____"
],
[
"rudder_total_sway_equation_SI",
"_____no_output_____"
]
],
[
[
"## Rudder resistance\nThe rudder resistance is taken to be proportional to the rudder side force (without stall) and the\nrudder angle, thus:",
"_____no_output_____"
]
],
[
[
"rudder_drag_equation",
"_____no_output_____"
],
[
"sp.latex(rudder_drag_equation_expanded)",
"_____no_output_____"
],
[
"rudder_drag_equation_expanded_SI",
"_____no_output_____"
]
],
[
[
"## Rudder yawing moment",
"_____no_output_____"
]
],
[
[
"rudder_yaw_equation",
"_____no_output_____"
],
[
"rudder_yaw_equation_expanded_SI",
"_____no_output_____"
]
],
[
[
"## Rudder roll moment",
"_____no_output_____"
]
],
[
[
"rudder_roll_equation",
"_____no_output_____"
],
[
"rudder_roll_equation_expanded_SI = ss.expand_bis(rudder_roll_equation_expanded)\nrudder_roll_equation_expanded_SI",
"_____no_output_____"
]
],
[
[
"## Lambda functions",
"_____no_output_____"
]
],
[
[
"from rudder_lambda_functions import *",
"_____no_output_____"
]
],
[
[
"## Plotting effective rudder angle equation",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame()\nV = 5.0\nbeta = np.deg2rad(np.linspace(-10,10,20))\ndf['u_w'] = V*np.cos(beta)\ndf['v_w'] = -V*np.sin(beta)\ndf['delta'] = np.deg2rad(5)\ndf['r_w'] = 0.0\ndf['L'] = 50.0\ndf['k_r'] = 0.5\ndf['k_v'] = -1.0\ndf['g'] = 9.81\ndf['xx_rud'] = -1\ndf['l_cg'] = 0\n\n\nresult = df.copy()\nresult['delta_e'] = effective_rudder_angle_function(**df)\nresult['delta_e_deg'] = np.rad2deg(result['delta_e'])\nresult['beta_deg'] = np.rad2deg(beta)\n\nresult.plot(x = 'beta_deg',y = 'delta_e_deg');",
"_____no_output_____"
],
[
"df = pd.DataFrame()\nV = 5.0\nbeta = np.deg2rad(np.linspace(-10,10,20))\ndf['u_w'] = V*np.cos(beta)\ndf['v_w'] = -V*np.sin(beta)\ndf['delta'] = np.deg2rad(5)\ndf['r_w'] = 0.0\ndf['L'] = 50.0\ndf['k_r'] = 0\ndf['k_v'] = 0\ndf['g'] = 9.81\ndf['xx_rud'] = -1\ndf['l_cg'] = 0\n\n\nresult = df.copy()\nresult['delta_e'] = effective_rudder_angle_function(**df)\nresult['delta_e_deg'] = np.rad2deg(result['delta_e'])\nresult['beta_deg'] = np.rad2deg(beta)\n\nresult.plot(x = 'beta_deg',y = 'delta_e_deg');",
"_____no_output_____"
],
[
"df = pd.DataFrame()\ndf['r_w'] = np.linspace(-0.3,0.3,20)\ndf['delta'] = 0.1\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['L'] = 50.0\ndf['k_r'] = 0.5\ndf['k_v'] = 0.5\ndf['g'] = 9.81\ndf['xx_rud'] = -1\ndf['l_cg'] = 0\n\n\nresult = df.copy()\nresult['delta_e'] = effective_rudder_angle_function(**df)\n\nresult.plot(x = 'r_w',y = 'delta_e');",
"_____no_output_____"
]
],
[
[
"## Plotting the total sway rudder equation",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame()\ndf['delta'] = np.linspace(-0.3,0.3,10)\ndf['T_prop'] = 1.0\ndf['n_prop'] = 1.0\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['r_w'] = 0.0\ndf['rho'] = 1025\ndf['L'] = 1.0\ndf['k_r'] = 1.0\ndf['k_v'] = 1.0\ndf['g'] = 9.81\ndf['disp'] = 23.0\ndf['s'] = 0\ndf['Y_Tdelta'] = 1.0\ndf['Y_uudelta'] = 1.0\ndf['xx_rud'] = -1\ndf['l_cg'] = 0\n\n\nresult = df.copy()\nresult['fy'] = rudder_total_sway_function(**df)\n\nresult.plot(x = 'delta',y = 'fy');",
"_____no_output_____"
]
],
[
[
"### Plotting with coefficients from a real seaman ship model",
"_____no_output_____"
]
],
[
[
"import generate_input\nship_file_path='test_ship.ship'\nshipdict = seaman.ShipDict.load(ship_file_path)",
"_____no_output_____"
],
[
"df = pd.DataFrame()\ndf['delta'] = np.deg2rad(np.linspace(-35,35,20))\ndf['T_prop'] = 10*10**6\ndf['n_prop'] = 1\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['r_w'] = 0.0\ndf['rho'] = 1025\ndf['g'] = 9.81\n\ndf_input = generate_input.add_shipdict_inputs(lambda_function=rudder_total_sway_function,\n shipdict = shipdict,\n df = df,)\ndf_input",
"_____no_output_____"
],
[
"result = df_input.copy()\nresult['fy'] = rudder_total_sway_function(**df_input)",
"_____no_output_____"
],
[
"result.plot(x = 'delta',y = 'fy');",
"_____no_output_____"
]
],
[
[
"## Plotting the total rudder drag equation",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame()\ndf['delta'] = np.linspace(-0.3,0.3,20)\ndf['T'] = 1.0\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['r_w'] = 0.0\ndf['rho'] = 1025\ndf['L'] = 1.0\ndf['k_r'] = 1.0\ndf['k_v'] = 1.0\ndf['g'] = 9.81\ndf['disp'] = 23.0\ndf['s'] = 0\ndf['Y_Tdelta'] = 1.0\ndf['Y_uudelta'] = 1.0\ndf['X_Yrdelta'] = -1.0\ndf['xx_rud'] = -1\ndf['l_cg'] = 0\n\n\n\nresult = df.copy()\nresult['fx'] = rudder_drag_function(**df)\n\nresult.plot(x = 'delta',y = 'fx');",
"_____no_output_____"
]
],
[
[
"Real seaman has a maximum effective rudder angle 0.61 rad for the rudder drag, which is why seaman gives different result for really large drift angles or yaw rates:",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame()\ndf['delta'] = np.deg2rad(np.linspace(-45,45,50))\ndf['T'] = 10*10**6\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['r_w'] = 0.0\ndf['rho'] = 1025\ndf['g'] = 9.81\n\nresult_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_drag_function,\n shipdict = shipdict,\n df = df,\n label='fx',\n seaman_function = run_real_seaman.calculate_static_ship_rudder)\n\nfig,ax = plt.subplots()\nresult_comparison.plot(x = 'delta',y = ['fx','fx_seaman'],ax = ax)\nax.set_title('Rudder angle variation');",
"_____no_output_____"
],
[
"df = pd.DataFrame()\ndf['v_w'] = (np.linspace(-10,10,20))\ndf['delta'] = 0\ndf['T'] = 10*10**6\ndf['u_w'] = 5.0\ndf['r_w'] = 0.0\ndf['rho'] = 1025\ndf['g'] = 9.81\n\nresult_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_drag_function,\n shipdict = shipdict,\n df = df,\n label='fx',\n seaman_function = run_real_seaman.calculate_static_ship_rudder)\n\nfig,ax = plt.subplots()\nresult_comparison.plot(x = 'v_w',y = ['fx','fx_seaman'],ax = ax)\nax.set_title('Rudder drift angle variation');",
"_____no_output_____"
],
[
"df = pd.DataFrame()\ndf['r_w'] = (np.linspace(-0.05,0.05,20))\ndf['delta'] = 0\ndf['T'] = 10*10**6\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['rho'] = 1025\ndf['g'] = 9.81\n\nresult_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_drag_function,\n shipdict = shipdict,\n df = df,\n label='fx',\n seaman_function = run_real_seaman.calculate_static_ship_rudder)\n\nfig,ax = plt.subplots()\nresult_comparison.plot(x = 'r_w',y = ['fx','fx_seaman'],ax = ax)\nax.set_title('Rudder yaw rate variation');",
"_____no_output_____"
]
],
[
[
"## Plotting the rudder yawing moment equation",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame()\ndf['delta'] = np.deg2rad(np.linspace(-35,35,20))\ndf['T'] = 10*10**6\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['r_w'] = 0.0\ndf['rho'] = 1025\ndf['g'] = 9.81\n\nresult_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_yawing_moment_function,\n shipdict = shipdict,\n df = df,\n label='mz',\n seaman_function = run_real_seaman.calculate_static_ship)\n\nfig,ax = plt.subplots()\nresult_comparison.plot(x = 'delta',y = ['mz','mz_seaman'],ax = ax)\nax.set_title('Rudder angle variation');",
"_____no_output_____"
]
],
[
[
"## Plotting the rudder roll moment equation",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame()\ndf['delta'] = np.deg2rad(np.linspace(-35,35,20))\ndf['T'] = 10*10**6\ndf['u_w'] = 5.0\ndf['v_w'] = 0.0\ndf['r_w'] = 0.0\ndf['rho'] = 1025\ndf['g'] = 9.81\n\nresult_comparison = run_real_seaman.compare_with_seaman(lambda_function=rudder_roll_moment_function,\n shipdict = shipdict,\n df = df,\n label='mx',\n seaman_function = run_real_seaman.calculate_static_ship)\n\nfig,ax = plt.subplots()\nresult_comparison.plot(x = 'delta',y = ['mx','mx_seaman'],ax = ax)\nax.set_title('Rudder angle variation');",
"_____no_output_____"
],
[
"shipdict.rudder_particulars",
"_____no_output_____"
],
[
"%connect_info",
"_____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",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7affa5fb6d9c4ebbbc5945e4129a33ea2d8811d | 5,312 | ipynb | Jupyter Notebook | M220P - MongoDB for Python Developers/Files/notebooks/updates.ipynb | ReynerGonzalez/mongodb-university-course | 75175a90a0c94340dd3c0b55f562569cfc80c096 | [
"MIT"
] | null | null | null | M220P - MongoDB for Python Developers/Files/notebooks/updates.ipynb | ReynerGonzalez/mongodb-university-course | 75175a90a0c94340dd3c0b55f562569cfc80c096 | [
"MIT"
] | null | null | null | M220P - MongoDB for Python Developers/Files/notebooks/updates.ipynb | ReynerGonzalez/mongodb-university-course | 75175a90a0c94340dd3c0b55f562569cfc80c096 | [
"MIT"
] | null | null | null | 22.413502 | 136 | 0.524096 | [
[
[
"import pymongo\nfrom bson.json_util import dumps\nfrom faker import Faker\nimport random\nfake = Faker()\nfake.seed(42)\nrandom.seed(42)\n# replace \"uri\" with your Atlas URI string - should look like mongodb+srv://...\nuri = \"<your_atlas_uri>\"\nclient = pymongo.MongoClient(uri)\nmflix = client.sample_mflix",
"_____no_output_____"
],
[
"fake_users = mflix.fake_users\nfake_users.drop()",
"_____no_output_____"
],
[
"def make_user(iter_count):\n account_type = \"premium\" if iter_count % 2 == 0 else \"standard\"\n return {\n \"name\": fake.name(),\n \"address\": fake.address(),\n \"email\": fake.email(),\n \"age\": random.randrange(18, 65),\n \"favorite_colors\": [fake.color_name(), fake.color_name(), fake.color_name()],\n \"account_type\": account_type\n }",
"_____no_output_____"
],
[
"to_insert = [make_user(i) for i in range(10)]",
"_____no_output_____"
],
[
"fake_users.insert_many(to_insert)",
"_____no_output_____"
],
[
"print(dumps(fake_users.find_one(), indent=2))",
"_____no_output_____"
],
[
"allison = {\"name\": \"Allison Hill\"}\nfake_users.update_one(allison, { \"$inc\": { \"age\": 1 }})",
"_____no_output_____"
],
[
"print(dumps(fake_users.find_one(allison), indent=2))",
"_____no_output_____"
],
[
"fake_users.update_one(allison, {\"$push\": { \"favorite_colors\": \"Black\"}})",
"_____no_output_____"
],
[
"print(dumps(fake_users.find_one(allison), indent=2))",
"_____no_output_____"
],
[
"print(fake_users.count({\"account_type\": \"standard\"}))",
"_____no_output_____"
],
[
"print(dumps(fake_users.find({\"account_type\": \"standard\"}, { \"_id\": 0, \"name\": 1, \"account_type\": 1}), indent=2))",
"_____no_output_____"
],
[
"u_r = fake_users.update_many({\"account_type\": \"standard\"}, {\"$set\": { \"account_type\": \"premium\", \"free_trial\": True}})",
"_____no_output_____"
],
[
"print(fake_users.count({\"account_type\": \"standard\"}))",
"_____no_output_____"
],
[
"print(dumps(fake_users.find({\"free_trial\": True}, { \"_id\": 0, \"name\": 1, \"account_type\": 1}), indent=2))",
"_____no_output_____"
],
[
"print(dir(u_r))",
"_____no_output_____"
],
[
"print(u_r.acknowledged, u_r.matched_count, u_r.modified_count, u_r.upserted_id)",
"_____no_output_____"
],
[
"new_or_updated_user = make_user(0)\nu_r = fake_users.update_one({\"email\": new_or_updated_user[\"email\"]}, {\"$set\": new_or_updated_user}, upsert=True)",
"_____no_output_____"
],
[
"print(dumps(fake_users.find_one({\"email\": new_or_updated_user[\"email\"]}), indent=2))",
"_____no_output_____"
],
[
"print(u_r.acknowledged, u_r.matched_count, u_r.modified_count, u_r.upserted_id)",
"_____no_output_____"
],
[
"fake_users.drop()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b021c012fba453ea5d4f75267806949fc0326e | 765 | ipynb | Jupyter Notebook | testbook/tests/resources/datamodel.ipynb | MSeal/testbook | 7fa5fca60c954c9d2bea8e54e7b3201403910dd6 | [
"BSD-3-Clause"
] | 291 | 2020-03-01T14:22:12.000Z | 2022-03-28T21:31:00.000Z | testbook/tests/resources/datamodel.ipynb | MSeal/testbook | 7fa5fca60c954c9d2bea8e54e7b3201403910dd6 | [
"BSD-3-Clause"
] | 125 | 2020-02-26T19:54:58.000Z | 2022-03-23T15:30:36.000Z | testbook/tests/resources/datamodel.ipynb | MSeal/testbook | 7fa5fca60c954c9d2bea8e54e7b3201403910dd6 | [
"BSD-3-Clause"
] | 30 | 2020-02-26T20:00:42.000Z | 2022-02-15T20:54:59.000Z | 17.386364 | 34 | 0.513725 | [
[
[
"mylist = [1, 2, 3, 4, 5]",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e7b026c1a17da88cf6df7efb07feb08c0318c4be | 353,065 | ipynb | Jupyter Notebook | doc/source/examples/03xComposedPulses.ipynb | lankes-fzj/qupulse | 46f00f70bc998b98ac1ae4721d1a9a1c10b675aa | [
"MIT"
] | 30 | 2018-09-13T02:59:55.000Z | 2022-03-21T04:25:22.000Z | doc/source/examples/03xComposedPulses.ipynb | lankes-fzj/qupulse | 46f00f70bc998b98ac1ae4721d1a9a1c10b675aa | [
"MIT"
] | 319 | 2015-03-10T09:37:20.000Z | 2018-09-06T10:11:32.000Z | doc/source/examples/03xComposedPulses.ipynb | lankes-fzj/qupulse | 46f00f70bc998b98ac1ae4721d1a9a1c10b675aa | [
"MIT"
] | 14 | 2019-01-08T14:42:36.000Z | 2021-05-21T08:53:06.000Z | 84.74916 | 41,067 | 0.712733 | [
[
[
"# Combining Pulse Templates\n\nSo far we have seen how to define simple pulses using the `TablePulseTemplate` ([Modelling a Simple TablePulseTemplate](00SimpleTablePulse.ipynb)), `FunctionPulseTemplate` ([Modelling Pulses Using Functions And Expressions](02FunctionPulse.ipynb)) and `PointPulseTemplate` ([The PointPulseTemplate](03PointPulse.ipynb)) classes. These are the elementary building blocks to create pulses and we call them *atomic* pulse templates.\n\nWe will now have a look at how to compose more complex pulse structures.\n\n## SequencePulseTemplate: Putting Pulses in a Sequence\n\nAs the name suggests `SequencePulseTemplate` allows us to define a pulse as a sequence of already existing pulse templates which are run one after another. In the following example we have two templates created using `PointPulseTemplate` and want to define a higher-level pulse template that puts them in sequence.",
"_____no_output_____"
]
],
[
[
"from qupulse.pulses import PointPT, SequencePT\n# create our atomic \"low-level\" PointPTs\nfirst_point_pt = PointPT([(0, 'v_0'),\n (1, 'v_1', 'linear'),\n ('t', 'v_0+v_1', 'jump')],\n channel_names={'A'},\n measurements={('M', 1, 't-1')})\nsecond_point_pt = PointPT([(0, 'v_0+v_1'),\n ('t_2', 'v_0', 'linear')],\n channel_names={'A'},\n measurements={('M', 0, 1)})\n\n# define the SequencePT\nsequence_pt = SequencePT(first_point_pt, second_point_pt)\n\nprint(\"sequence parameters: {}\".format(sequence_pt.parameter_names))\nprint(\"sequence measurements: {}\".format(sequence_pt.measurement_names))",
"sequence parameters: {'t_2', 'v_1', 'v_0', 't'}\nsequence measurements: {'M'}\n"
]
],
[
[
"It is important to note that all of the pulse templates used to create a `SequencePT` (we call those *subtemplates*) are defined on the same channels, in this case the channel `A` (otherwise we would encounter an exception). The `SequencePT` will also be defined on the same channel.\n\nThe `SequencePT` will further have the union of all parameters defined in its subtemplates as its own parameter set. If two subtemplates defined parameters with the same name, they will be treated as the same parameters in the `SequencePT`.\n\nFinally, `SequencePT` will also expose all measurements defined in subtemplates. It is also possible to define additional measurements in the constructor of `SequencePT`. See [Definition of Measurements](08Measurements.ipynb) for me info about measurements.\n\nThere are several cases where the above constraints represent a problem: Subtemplates might not all be defined on the same channel, subtemplates might define parameters with the same name which should still be treated as different parameters in the sequence or names of measurements defined by different subtemplates might collide. To deal with these, we can wrap a subtemplate with the `MappingPulseTemplate` class which allows us to rename parameters, channels and measurements or even derive parameter values from other parameters using mathematical expressions. You can learn how to do all this in [Mapping with the MappingPulseTemplate](05MappingTemplate.ipynb).\n\nIn our example above, however, we were taking care not to encounter these problems yet. Let's plot all of them with some parameters to see the results.",
"_____no_output_____"
]
],
[
[
"%matplotlib notebook\nfrom qupulse.pulses.plotting import plot\n\nparameters = dict(t=3,\n t_2=2,\n v_0=1,\n v_1=1.4)\n\n_ = plot(first_point_pt, parameters, sample_rate=100)\n_ = plot(second_point_pt, parameters, sample_rate=100)\n_ = plot(sequence_pt, parameters, sample_rate=100)\n",
"_____no_output_____"
]
],
[
[
"## RepetitionPulseTemplate: Repeating a Pulse\n\nIf we simply want to repeat some pulse template a fixed number of times, we can make use of the `RepetitionPulseTemplate`. In the following, we will reuse one of our `PointPT`s, `first_point_pt` and use it to create a new pulse template that repeats it `n_rep` times, where `n_rep` will be a parameter.",
"_____no_output_____"
]
],
[
[
"from qupulse.pulses import RepetitionPT\n\nrepetition_pt = RepetitionPT(first_point_pt, 'n_rep')\n\nprint(\"repetition parameters: {}\".format(repetition_pt.parameter_names))\nprint(\"repetition measurements: {}\".format(repetition_pt.measurement_names))\n\n# let's plot to see the results\nparameters['n_rep'] = 5 # add a value for our n_rep parameter\n_ = plot(repetition_pt, parameters, sample_rate=100)",
"repetition parameters: {'v_1', 'n_rep', 'v_0', 't'}\nrepetition measurements: {'M'}\n"
]
],
[
[
"The same remarks that were made about `SequencePT` also hold for `RepetitionPT`: it will expose all parameters and measurements defined by its subtemplate and will be defined on the same channels.\n\n## ForLoopPulseTemplate: Repeat a Pulse with a Varying Loop Parameter\n\nThe `RepetitionPT` simple repeats the exact same subtemplate a given number of times. Sometimes, however, it is rather required to vary the parameters of a subtemplate in a loop, for example when trying to determine the best value for a parameter of a given pulse. This is what the `ForLoopPulseTemplate` is intended for. As the name suggests, its behavior mimics that for `for-loop` constructs in programming languages by repeating its content - the subtemplate - for a number of times while at the same time supplying a loop parameter that iterates over a range of values.\n\nIn the following we make use of this to vary the value of parameter `t` in `first_point_pt` over several iterations. More specifically, we will have all a `first_point_pt` pulse for all even values of `t` between `t_start` and `t_end` which are new parameters. For the plot we will set them to `t_start = 4` and `t_end = 13`, i.e., `t = 4, 6, 8, 10, 12`.",
"_____no_output_____"
]
],
[
[
"from qupulse.pulses import ForLoopPT\n\nfor_loop_pt = ForLoopPT(first_point_pt, 't', ('t_start', 't_end', 2))\n\nprint(\"for loop parameters: {}\".format(for_loop_pt.parameter_names))\nprint(\"for loop measurements: {}\".format(for_loop_pt.measurement_names))\n\n# plot it\nparameters['t_start'] = 4\nparameters['t_end'] = 13\n_ = plot(for_loop_pt, parameters, sample_rate=100)",
"for loop parameters: {'t_start', 'v_1', 'v_0', 't_end'}\nfor loop measurements: {'M'}\n"
]
],
[
[
"The second argument to `ForLoopPT`'s constructor is the name of the loop parameter. This has to be a parameter that is defined by the subtemplate. The third argument defined the range of the loop. The syntax of the range is similar to that of the `range()` command in Python, i.e., a tuple `(start_value, end_value, step)`. As seen above, inserting parameter values or even expressions is okay. As in `range()`, the `end_value` is exclusive.\n\nAs for `SequencePT` and `RepetitionPT`, `ForLoopPT` exposes all parameters defined by the subtemplate except for the loop parameter, `t` in the above example. If expressions are used in the range definition and they make use of additional parameters, these are also exposed by `ForLoopPT`. \n\n`ForLoopPT` also exposes measurements defined by subtemplates.\n\n## AtomicMultiChannelPulseTemplate: Run Pulses in Parallel on Different Channels\n\nSo far we have only looked at pulses that affect the time-domain aspect of combining pulses. Another way to combine pulses is to parallelise them by executing them on different channels at the same time. This is of course already supported by simply creating atomic pulse templates (`TablePT`, `PointPT`, `FunctionPT`) on multiple channels. However, sometimes it is necessary to put already existing pulses in parallel. Instead of having to define a new atomic pulse template for this, we can make use of the `AtomicMuliChannelPulseTemplate` class. To learn more about how this works, see [Multi-Channel Pulses](07MultiChannelTemplates.ipynb).\n\n## Combining Combined Pulses\n\nOur examples above have build combined higher-level pulses (`SequencePT`, `RepetitionPT`, `ForLoopPT`) on atomic subtemplates only. However, this is not a requirement. We can use `SequencePT`, `RepetitionPT` and `ForLoopPT` using any `PulseTemplate` objects as subtemplates allowing us to build arbitrarily complex pulses out of only a handful of primitives.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b033879617c61b62f8409afda384a5be818bea | 49,002 | ipynb | Jupyter Notebook | notebooks/batch_results.ipynb | GOTO-OBS/goto-astromtools | 6741386c9d0312ea7f1550f5c1a5c49ee1806ee9 | [
"MIT"
] | null | null | null | notebooks/batch_results.ipynb | GOTO-OBS/goto-astromtools | 6741386c9d0312ea7f1550f5c1a5c49ee1806ee9 | [
"MIT"
] | null | null | null | notebooks/batch_results.ipynb | GOTO-OBS/goto-astromtools | 6741386c9d0312ea7f1550f5c1a5c49ee1806ee9 | [
"MIT"
] | null | null | null | 185.613636 | 12,376 | 0.862761 | [
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom astropy.table import Table",
"_____no_output_____"
],
[
"results = Table.read(\"../data/batchfit_results.csv\", format='ascii.ecsv')\nresults.sort(\"JD\")",
"_____no_output_____"
],
[
"### APMs\nfor i in range(1, 5):\n temp_UT = results[results[\"UT\"] == \"UT%s\" % i]\n plt.hist(temp_UT[\"RMS_AFT\"], bins='stone', label = \"UT%s\" % i, density=True, alpha=0.9)\n plt.legend()\n plt.savefig(\"APMTubes2.png\", bbox_inches='tight')\n plt.xlim(0, 2)\n plt.xlabel(\"RMS of astrometric solution (\\\")\")\n plt.ylabel(\"Number of frames\")\n plt.minorticks_on()\n plt.tick_params(axis='both', which='both', direction='in')\n plt.title(\"APM\")\nplt.show()\nfor i in range(5, 9):\n temp_UT = results[results[\"UT\"] == \"UT%s\" % i]\n plt.hist(temp_UT[\"RMS_AFT\"], bins='stone', label = \"UT%s\" % i, density=True, alpha=0.9)\n plt.legend()\n plt.title(\"RASA\")\n plt.xlim(0, 2)\n plt.xlabel(\"RMS of astrometric solution (\\\")\")\n plt.ylabel(\"Number of frames\")\n plt.minorticks_on()\n plt.tick_params(axis='both', which='both', direction='in')\n plt.savefig(\"RASATubes2.png\", bbox_inches='tight')",
"_____no_output_____"
],
[
"indiv_UT = results[results[\"UT\"] == \"UT2\"]",
"_____no_output_____"
],
[
"plt.hist(results[\"FITTIME\"], bins='auto', color='orange')\nplt.xlabel(\"Fit time (s)\")\nplt.ylabel(\"Number of frames\")\nplt.axvline(np.median(results[\"FITTIME\"]), c='k', ls='--')\nplt.minorticks_on()\nplt.tick_params(axis='both', which='both', direction='in')\nplt.savefig(\"solvetime_histogram.png\", bbox_inches='tight', dpi=120)",
"_____no_output_____"
],
[
"## If it has a bad solution coming in we can't do too much about it\nbad_astromnet = (results[\"RMS_BEF\"] > 3)\n\n### Excluding bad input sols, does my code make both the offset and rms of the frame far worse?\nbad_mycode1 = (np.abs(results[\"MED_BEF\"]) - np.abs(results[\"MED_AFT\"]) < 0) & (results[\"RMS_BEF\"] - results[\"RMS_AFT\"] < 0) & ~bad_astromnet\nprint(\"Frames borked by refitting: %s\" % np.sum(bad_mycode1))\nprint(\"%s%% of frames affected\" % np.round((100*np.sum(bad_mycode1)/len(results)),2))",
"Frames borked by refitting: 0\n0.0% of frames affected\n"
],
[
"100*(np.sum(bad_astromnet) / len(bad_astromnet))",
"_____no_output_____"
],
[
"results",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b039b5db900c3f0e65b751c98837781a3a5aef | 266,071 | ipynb | Jupyter Notebook | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks | bf08d41b788664380676ba8dfd4805d0f5bf86b2 | [
"MIT"
] | 1 | 2018-12-28T05:53:31.000Z | 2018-12-28T05:53:31.000Z | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks | bf08d41b788664380676ba8dfd4805d0f5bf86b2 | [
"MIT"
] | null | null | null | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks | bf08d41b788664380676ba8dfd4805d0f5bf86b2 | [
"MIT"
] | null | null | null | 364.480822 | 239,668 | 0.930364 | [
[
[
"Copyright (c) Microsoft Corporation. All rights reserved. \nLicensed under the MIT License.",
"_____no_output_____"
],
[
"# 02. Facial Expression Recognition using ONNX Runtime GPU on AzureML\n\nThis example shows how to deploy an image classification neural network using the Facial Expression Recognition ([FER](https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/data)) dataset and Open Neural Network eXchange format ([ONNX](http://aka.ms/onnxdocarticle)) on the Azure Machine Learning platform. This tutorial will show you how to deploy a FER+ model from the [ONNX model zoo](https://github.com/onnx/models), use it to make predictions using ONNX Runtime Inference, and deploy it as a web service in Azure.\n\nThroughout this tutorial, we will be referring to ONNX, a neural network exchange format used to represent deep learning models. With ONNX, AI developers can more easily move models between state-of-the-art tools (CNTK, PyTorch, Caffe, MXNet, TensorFlow) and choose the combination that is best for them. ONNX is developed and supported by a community of partners including Microsoft AI, Facebook, and Amazon. For more information, explore the [ONNX website](http://onnx.ai) and [open source files](https://github.com/onnx).\n\n[ONNX Runtime](https://aka.ms/onnxruntime) is the runtime engine that enables evaluation of trained machine learning (Traditional ML and Deep Learning) models with high performance and low resource utilization.\n\n#### Tutorial Objectives:\n\n1. Describe the FER+ dataset and pretrained Convolutional Neural Net ONNX model for Emotion Recognition, stored in the ONNX model zoo.\n2. Deploy and run the pretrained FER+ ONNX model on an Azure Machine Learning instance\n3. Predict labels for test set data points in the cloud using ONNX Runtime and Azure ML",
"_____no_output_____"
],
[
"## Prerequisites\n\n### 1. Install Azure ML SDK and create a new workspace\nPlease follow [00.configuration.ipynb](https://github.com/Azure/MachineLearningNotebooks/blob/master/00.configuration.ipynb) notebook.\n\n\n### 2. Install additional packages needed for this Notebook\nYou need to install the popular plotting library `matplotlib` and the `onnx` library in the conda environment where Azure Maching Learning SDK is installed.\n\n```sh\n(myenv) $ pip install matplotlib onnx\n```\n\n### 3. Download sample data and pre-trained ONNX model from ONNX Model Zoo.\n\n[Download the ONNX Emotion FER+ model and corresponding test data](https://www.cntk.ai/OnnxModels/emotion_ferplus/opset_7/emotion_ferplus.tar.gz) and place them in the same folder as this tutorial notebook. You can unzip the file through the following line of code.\n\n```sh\n(myenv) $ tar xvzf emotion_ferplus.tar.gz\n```\n\nMore information can be found about the ONNX FER+ model on [github](https://github.com/onnx/models/tree/master/emotion_ferplus). For more information about the FER+ dataset, please visit Microsoft Researcher Emad Barsoum's [FER+ source data repository](https://github.com/ebarsoum/FERPlus).",
"_____no_output_____"
],
[
"## Load Azure ML workspace\n\nWe begin by instantiating a workspace object from the existing workspace created earlier in the configuration notebook.",
"_____no_output_____"
]
],
[
[
"# Check core SDK version number\nimport azureml.core\n\nprint(\"SDK version:\", azureml.core.VERSION)",
"_____no_output_____"
],
[
"from azureml.core import Workspace\n\nws = Workspace.from_config()\nprint(ws.name, ws.location, ws.resource_group, ws.location, sep = '\\n')",
"_____no_output_____"
]
],
[
[
"### Registering your model with Azure ML",
"_____no_output_____"
]
],
[
[
"model_dir = \"emotion_ferplus\" # replace this with the location of your model files\n\n# leave as is if it's in the same folder as this notebook",
"_____no_output_____"
],
[
"from azureml.core.model import Model\n\nmodel = Model.register(model_path = model_dir + \"/\" + \"model.onnx\",\n model_name = \"onnx_emotion\",\n tags = {\"onnx\": \"demo\"},\n description = \"FER+ emotion recognition CNN from ONNX Model Zoo\",\n workspace = ws)",
"_____no_output_____"
]
],
[
[
"### Optional: Displaying your registered models\n\nThis step is not required, so feel free to skip it.",
"_____no_output_____"
]
],
[
[
"models = ws.models()\nfor m in models:\n print(\"Name:\", m.name,\"\\tVersion:\", m.version, \"\\tDescription:\", m.description, m.tags)",
"_____no_output_____"
]
],
[
[
"### ONNX FER+ Model Methodology\n\nThe image classification model we are using is pre-trained using Microsoft's deep learning cognitive toolkit, [CNTK](https://github.com/Microsoft/CNTK), from the [ONNX model zoo](http://github.com/onnx/models). The model zoo has many other models that can be deployed on cloud providers like AzureML without any additional training. To ensure that our cloud deployed model works, we use testing data from the famous FER+ data set, provided as part of the [trained Emotion Recognition model](https://github.com/onnx/models/tree/master/emotion_ferplus) in the ONNX model zoo.\n\nThe original Facial Emotion Recognition (FER) Dataset was released in 2013, but some of the labels are not entirely appropriate for the expression. In the FER+ Dataset, each photo was evaluated by at least 10 croud sourced reviewers, creating a better basis for ground truth. \n\nYou can see the difference of label quality in the sample model input below. The FER labels are the first word below each image, and the FER+ labels are the second word below each image.\n\n\n\n***Input: Photos of cropped faces from FER+ Dataset***\n\n***Task: Classify each facial image into its appropriate emotions in the emotion table***\n\n``` emotion_table = {'neutral':0, 'happiness':1, 'surprise':2, 'sadness':3, 'anger':4, 'disgust':5, 'fear':6, 'contempt':7} ```\n\n***Output: Emotion prediction for input image***\n\n\nRemember, once the application is deployed in Azure ML, you can use your own images as input for the model to classify.",
"_____no_output_____"
]
],
[
[
"# for images and plots in this notebook\nimport matplotlib.pyplot as plt \nfrom IPython.display import Image\n\n# display images inline\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Model Description\n\nThe FER+ model from the ONNX Model Zoo is summarized by the graphic below. You can see the entire workflow of our pre-trained model in the following image from Barsoum et. al's paper [\"Training Deep Networks for Facial Expression Recognition\nwith Crowd-Sourced Label Distribution\"](https://arxiv.org/pdf/1608.01041.pdf), with our (64,64) input images and our output probabilities for each of the labels.",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"## Deploy our model on Azure ML",
"_____no_output_____"
],
[
"We are now going to deploy our ONNX Model on AML with inference in ONNX Runtime. We begin by writing a score.py file, which will help us run the model in our Azure ML virtual machine (VM), and then specify our environment by writing a yml file.\n\nYou will also notice that we import the onnxruntime library to do runtime inference on our ONNX models (passing in input and evaluating out model's predicted output). More information on the API and commands can be found in the [ONNX Runtime documentation](https://aka.ms/onnxruntime).\n\n### Write Score File\n\nA score file is what tells our Azure cloud service what to do. After initializing our model using azureml.core.model, we start an ONNX Runtime GPU inference session to evaluate the data passed in on our function calls.",
"_____no_output_____"
]
],
[
[
"%%writefile score.py\nimport json\nimport numpy as np\nimport onnxruntime\nimport sys\nimport os\nfrom azureml.core.model import Model\nimport time\n\ndef init():\n global session\n model = Model.get_model_path(model_name = 'onnx_emotion')\n session = onnxruntime.InferenceSession(model, None)\n \ndef run(input_data):\n '''Purpose: evaluate test input in Azure Cloud using onnxruntime.\n We will call the run function later from our Jupyter Notebook \n so our azure service can evaluate our model input in the cloud. '''\n\n try:\n # load in our data, convert to readable format\n start = time.time()\n data = np.array(json.loads(input_data)['data']).astype('float32')\n\n r = session.run([\"Plus214_Output_0\"], {\"Input3\": data})[0]\n result = emotion_map(postprocess(r[0]))\n end = time.time()\n result_dict = {\"result\": np.array(result).tolist(),\n \"time\": np.array(end - start).tolist()}\n except Exception as e:\n result_dict = {\"error\": str(e)}\n \n return json.dumps(result_dict)\n\ndef emotion_map(classes, N=1):\n \"\"\"Take the most probable labels (output of postprocess) and returns the top N emotional labels that fit the picture.\"\"\"\n \n emotion_table = {'neutral':0, 'happiness':1, 'surprise':2, 'sadness':3, 'anger':4, 'disgust':5, 'fear':6, 'contempt':7}\n emotion_keys = list(emotion_table.keys())\n emotions = []\n for i in range(N):\n emotions.append(emotion_keys[classes[i]])\n return emotions\n\ndef softmax(x):\n \"\"\"Compute softmax values (probabilities from 0 to 1) for each possible label.\"\"\"\n x = x.reshape(-1)\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0)\n\ndef postprocess(scores):\n \"\"\"This function takes the scores generated by the network and returns the class IDs in decreasing \n order of probability.\"\"\"\n prob = softmax(scores)\n prob = np.squeeze(prob)\n classes = np.argsort(prob)[::-1]\n return classes",
"_____no_output_____"
]
],
[
[
"### Write Environment File",
"_____no_output_____"
]
],
[
[
"from azureml.core.conda_dependencies import CondaDependencies \n\nmyenv = CondaDependencies()\nmyenv.add_pip_package(\"numpy\")\nmyenv.add_pip_package(\"azureml-core\")\nmyenv.add_pip_package(\"onnxruntime-gpu\")\n\n\nwith open(\"myenv.yml\",\"w\") as f:\n f.write(myenv.serialize_to_string())",
"_____no_output_____"
]
],
[
[
"### Create the Container Image\n\nThis step will likely take a few minutes.",
"_____no_output_____"
]
],
[
[
"from azureml.core.image import ContainerImage\n\n# enable_gpu = True to install CUDA 9.1 and cuDNN 7.0\n\nimage_config = ContainerImage.image_configuration(execution_script = \"score.py\",\n runtime = \"python\",\n conda_file = \"myenv.yml\",\n description = \"test\",\n tags = {\"demo\": \"onnx\"},\n enable_gpu = True\n )\n\n\nimage = ContainerImage.create(name = \"onnxtest\",\n # this is the model object\n models = [model],\n image_config = image_config,\n workspace = ws)\n\nimage.wait_for_creation(show_output = True)",
"_____no_output_____"
]
],
[
[
"### Debugging\n\nIn case you need to debug your code, the next line of code accesses the log file.",
"_____no_output_____"
]
],
[
[
"print(image.image_build_log_uri)",
"_____no_output_____"
]
],
[
[
"We're all set! Let's get our model chugging.\n\n## Deploy the container image",
"_____no_output_____"
]
],
[
[
"from azureml.core.webservice import AciWebservice\n\naciconfig = AciWebservice.deploy_configuration(cpu_cores = 1, \n memory_gb = 1, \n tags = {'demo': 'onnx'}, \n description = 'ONNX for facial emotion recognition model')",
"_____no_output_____"
]
],
[
[
"The following cell will likely take a few minutes to run as well.",
"_____no_output_____"
]
],
[
[
"from azureml.core.webservice import Webservice\n\naci_service_name = 'onnx-emotion-demo'\nprint(\"Service\", aci_service_name)\n\naci_service = Webservice.deploy_from_image(deployment_config = aciconfig,\n image = image,\n name = aci_service_name,\n workspace = ws)\n\naci_service.wait_for_deployment(True)\nprint(aci_service.state)",
"_____no_output_____"
],
[
"if aci_service.state != 'Healthy':\n # run this command for debugging.\n print(aci_service.get_logs())\n\n # If your deployment fails, make sure to delete your aci_service before trying again!\n # aci_service.delete()",
"_____no_output_____"
]
],
[
[
"### Success!\n\nIf you've made it this far, you've deployed a working VM with a facial emotion recognition model running in the cloud using Azure ML. Congratulations!\n\nLet's see how well our model deals with our test images.",
"_____no_output_____"
],
[
"# Testing and Evaluation",
"_____no_output_____"
],
[
"#### Useful Helper Functions\n\nWe preprocess and postprocess our data (see score.py file) using the helper functions specified in the [ONNX FER+ Model page in the Model Zoo repository](https://github.com/onnx/models/tree/master/emotion_ferplus).",
"_____no_output_____"
]
],
[
[
"def preprocess(img):\n \"\"\"Convert image to the write format to be passed into the model\"\"\"\n input_shape = (1, 64, 64)\n img = np.reshape(img, input_shape)\n img = np.expand_dims(img, axis=0)\n return img",
"_____no_output_____"
],
[
"# to manipulate our arrays\nimport numpy as np \n\n# read in test data protobuf files included with the model\nimport onnx\nfrom onnx import numpy_helper\n\n# to use parsers to read in our model/data\nimport json\nimport os\n\ntest_inputs = []\ntest_outputs = []\n\n# read in 3 testing images from .pb files\ntest_data_size = 3\n\nfor i in np.arange(test_data_size):\n input_test_data = os.path.join(model_dir, 'test_data_set_{0}'.format(i), 'input_0.pb')\n output_test_data = os.path.join(model_dir, 'test_data_set_{0}'.format(i), 'output_0.pb')\n \n # convert protobuf tensors to np arrays using the TensorProto reader from ONNX\n tensor = onnx.TensorProto()\n with open(input_test_data, 'rb') as f:\n tensor.ParseFromString(f.read())\n \n input_data = preprocess(numpy_helper.to_array(tensor))\n test_inputs.append(input_data)\n \n with open(output_test_data, 'rb') as f:\n tensor.ParseFromString(f.read())\n \n output_data = numpy_helper.to_array(tensor)\n test_outputs.append(output_data)",
"_____no_output_____"
]
],
[
[
"### Show some sample images\nWe use `matplotlib` to plot 3 images from the dataset with their labels over them.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (20, 20))\nfor test_image in np.arange(3):\n test_inputs[test_image].reshape(1, 64, 64)\n plt.subplot(1, 8, test_image+1)\n plt.axhline('')\n plt.axvline('')\n plt.text(x = 10, y = -10, s = test_outputs[test_image][0], fontsize = 18)\n plt.imshow(test_inputs[test_image].reshape(64, 64))\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Run evaluation / prediction",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize = (16, 6), frameon=False)\nplt.subplot(1, 8, 1)\n\nplt.text(x = 0, y = -30, s = \"True Label: \", fontsize = 13, color = 'black')\nplt.text(x = 0, y = -20, s = \"Result: \", fontsize = 13, color = 'black')\nplt.text(x = 0, y = -10, s = \"Inference Time: \", fontsize = 13, color = 'black')\nplt.text(x = 3, y = 14, s = \"Model Input\", fontsize = 12, color = 'black')\nplt.text(x = 6, y = 18, s = \"(64 x 64)\", fontsize = 12, color = 'black')\nplt.imshow(np.ones((28,28)), cmap=plt.cm.Greys) \n\n\nfor i in np.arange(test_data_size):\n \n input_data = json.dumps({'data': test_inputs[i].tolist()})\n\n # predict using the deployed model\n r = json.loads(aci_service.run(input_data))\n \n if len(r) == 1:\n print(r['error'])\n break\n \n result = r['result']\n time_ms = np.round(r['time'] * 1000, 2)\n \n ground_truth = int(np.argmax(test_outputs[i]))\n \n # compare actual value vs. the predicted values:\n plt.subplot(1, 8, i+2)\n plt.axhline('')\n plt.axvline('')\n\n # use different color for misclassified sample\n font_color = 'red' if ground_truth != result else 'black'\n clr_map = plt.cm.gray if ground_truth != result else plt.cm.Greys\n\n # ground truth labels are in blue\n plt.text(x = 10, y = -30, s = ground_truth, fontsize = 18, color = 'blue')\n \n # predictions are in black if correct, red if incorrect\n plt.text(x = 10, y = -20, s = result, fontsize = 18, color = font_color)\n plt.text(x = 5, y = -10, s = str(time_ms) + ' ms', fontsize = 14, color = font_color)\n\n \n plt.imshow(test_inputs[i].reshape(64, 64), cmap = clr_map)\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Try classifying your own images!",
"_____no_output_____"
]
],
[
[
"# Replace the following string with your own path/test image\n# Make sure the dimensions are 28 * 28 pixels\n\n# Any PNG or JPG image file should work\n# Make sure to include the entire path with // instead of /\n\n# e.g. your_test_image = \"C://Users//vinitra.swamy//Pictures//emotion_test_images//img_1.jpg\"\n\nyour_test_image = \"<path to file>\"\n\nimport matplotlib.image as mpimg\n\nif your_test_image != \"<path to file>\":\n img = mpimg.imread(your_test_image)\n plt.subplot(1,3,1)\n plt.imshow(img, cmap = plt.cm.Greys)\n img = img.reshape(1, 1, 64, 64)\nelse:\n img = None",
"_____no_output_____"
],
[
"if img is None:\n print(\"Add the path for your image data.\")\nelse:\n input_data = json.dumps({'data': img.tolist()})\n\n try:\n r = json.loads(aci_service.run(input_data))\n result = r['result']\n time_ms = np.round(r['time'] * 1000, 2)\n except Exception as e:\n print(json.loads(r)['error'])\n\n plt.figure(figsize = (16, 6))\n plt.subplot(1, 15,1)\n plt.axhline('')\n plt.axvline('')\n plt.text(x = -100, y = -20, s = \"Model prediction: \", fontsize = 14)\n plt.text(x = -100, y = -10, s = \"Inference time: \", fontsize = 14)\n plt.text(x = 0, y = -20, s = str(result), fontsize = 14)\n plt.text(x = 0, y = -10, s = str(time_ms) + \" ms\", fontsize = 14)\n plt.text(x = -100, y = 14, s = \"Input image: \", fontsize = 14)\n plt.imshow(img.reshape(28, 28), cmap = plt.cm.Greys) ",
"_____no_output_____"
],
[
"# remember to delete your service after you are done using it!\n\n# aci_service.delete()",
"_____no_output_____"
]
],
[
[
"## Conclusion\n\nCongratulations!\n\nIn this tutorial, you have managed to:\n- familiarize yourself with the ONNX standard, ONNX Runtime inference, and the pretrained models in the ONNX model zoo\n- understand a state-of-the-art convolutional neural net image classification model (FER+ in ONNX) and deploy it in the Azure ML cloud\n- ensure that your deep learning model is working correctly (in the cloud) on test data, and check it against some of your own!\n\nNext steps:\n- If you have not already, check out another interesting ONNX/AML application that lets you set up a state-of-the-art [handwritten image classification model (MNIST)](https://github.com/Azure/MachineLearningNotebooks/tree/master/onnx/onnx-inference-mnist.ipynb) in the cloud! This tutorial deploys a pre-trained ONNX Computer Vision model for handwritten digit classification in an Azure ML virtual machine.\n- Contribute to our [open source ONNX repository on github](http://github.com/onnx/onnx) and/or add to our [ONNX model zoo](http://github.com/onnx/models)",
"_____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"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7b04b1f28874c6033ed05bbdeadf88dca6c0825 | 100,737 | ipynb | Jupyter Notebook | Chapter 14/Section21_01_Canny_Edge_Detection.ipynb | bpbpublications/Soft-Skill-For-Personality-Development | b394d547c4c20c085f786b0339618077e395bf0a | [
"MIT"
] | null | null | null | Chapter 14/Section21_01_Canny_Edge_Detection.ipynb | bpbpublications/Soft-Skill-For-Personality-Development | b394d547c4c20c085f786b0339618077e395bf0a | [
"MIT"
] | null | null | null | Chapter 14/Section21_01_Canny_Edge_Detection.ipynb | bpbpublications/Soft-Skill-For-Personality-Development | b394d547c4c20c085f786b0339618077e395bf0a | [
"MIT"
] | 2 | 2021-06-12T21:18:52.000Z | 2021-11-29T10:54:15.000Z | 746.2 | 79,636 | 0.956213 | [
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import feature, data\n\noriginal = data.camera()\n\nplt.imshow(original, cmap='gray')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
],
[
"edges1 = feature.canny(original)\n# by default sigma = 1\n\nplt.imshow(edges1, cmap='gray')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
],
[
"edges2 = feature.canny(original, sigma=3)\n\nplt.imshow(edges2, cmap='gray')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
],
[
"edges3 = feature.canny(original, sigma=5)\n\nplt.imshow(edges3, cmap='gray')\nplt.axis('off')\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
e7b052be57704da6121ce24f2e7c82a7dcecebb6 | 7,839 | ipynb | Jupyter Notebook | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst | 774446719316599cf221bdc5a67b00ec4c0b3ad0 | [
"Apache-2.0"
] | 2 | 2019-08-21T11:38:17.000Z | 2019-08-21T11:38:19.000Z | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst | 774446719316599cf221bdc5a67b00ec4c0b3ad0 | [
"Apache-2.0"
] | 10 | 2019-11-20T07:24:52.000Z | 2022-03-12T00:06:02.000Z | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst | 774446719316599cf221bdc5a67b00ec4c0b3ad0 | [
"Apache-2.0"
] | 4 | 2020-05-15T06:23:05.000Z | 2021-12-20T06:00:15.000Z | 27.996429 | 553 | 0.59676 | [
[
[
"<h1> 2d. Distributed training and monitoring </h1>\n\nIn this notebook, we refactor to call ```train_and_evaluate``` instead of hand-coding our ML pipeline. This allows us to carry out evaluation as part of our training loop instead of as a separate step. It also adds in failure-handling that is necessary for distributed training capabilities.\n\nWe also use TensorBoard to monitor the training.",
"_____no_output_____"
]
],
[
[
"from google.cloud import bigquery\nimport tensorflow as tf\nimport numpy as np\nimport shutil\nprint(tf.__version__)",
"_____no_output_____"
]
],
[
[
"<h2> Input </h2>\n\nRead data created in Lab1a, but this time make it more general, so that we are reading in batches. Instead of using Pandas, we will use add a filename queue to the TensorFlow graph.",
"_____no_output_____"
]
],
[
[
"CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']\nLABEL_COLUMN = 'fare_amount'\nDEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']]\n\ndef read_dataset(filename, mode, batch_size = 512):\n def decode_csv(value_column):\n columns = tf.decode_csv(value_column, record_defaults = DEFAULTS)\n features = dict(zip(CSV_COLUMNS, columns))\n label = features.pop(LABEL_COLUMN)\n return features, label\n\n # Create list of file names that match \"glob\" pattern (i.e. data_file_*.csv)\n filenames_dataset = tf.data.Dataset.list_files(filename)\n # Read lines from text files\n textlines_dataset = filenames_dataset.flat_map(tf.data.TextLineDataset)\n # Parse text lines as comma-separated values (CSV)\n dataset = textlines_dataset.map(decode_csv)\n\n # Note:\n # use tf.data.Dataset.flat_map to apply one to many transformations (here: filename -> text lines)\n # use tf.data.Dataset.map to apply one to one transformations (here: text line -> feature list)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = None # indefinitely\n dataset = dataset.shuffle(buffer_size = 10 * batch_size)\n else:\n num_epochs = 1 # end-of-input after this\n\n dataset = dataset.repeat(num_epochs).batch(batch_size)\n\n return dataset",
"_____no_output_____"
]
],
[
[
"<h2> Create features out of input data </h2>\n\nFor now, pass these through. (same as previous lab)",
"_____no_output_____"
]
],
[
[
"INPUT_COLUMNS = [\n tf.feature_column.numeric_column('pickuplon'),\n tf.feature_column.numeric_column('pickuplat'),\n tf.feature_column.numeric_column('dropofflat'),\n tf.feature_column.numeric_column('dropofflon'),\n tf.feature_column.numeric_column('passengers'),\n]\n\ndef add_more_features(feats):\n # Nothing to add (yet!)\n return feats\n\nfeature_cols = add_more_features(INPUT_COLUMNS)",
"_____no_output_____"
]
],
[
[
"<h2> Serving input function </h2>\nDefines the expected shape of the JSON feed that the modelwill receive once deployed behind a REST API in production.",
"_____no_output_____"
]
],
[
[
"## TODO: Create serving input function\ndef serving_input_fn():\n #ADD CODE HERE\n return tf.estimator.export.ServingInputReceiver(features, json_feature_placeholders)",
"_____no_output_____"
]
],
[
[
"<h2> tf.estimator.train_and_evaluate </h2>",
"_____no_output_____"
]
],
[
[
"## TODO: Create train and evaluate function using tf.estimator\ndef train_and_evaluate(output_dir, num_train_steps):\n #ADD CODE HERE\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)",
"_____no_output_____"
]
],
[
[
"<h2> Monitoring with TensorBoard </h2>\nStart the TensorBoard by opening up a new Launcher (File > New Launcher) and selecting TensorBoard.",
"_____no_output_____"
]
],
[
[
"OUTDIR = './taxi_trained'",
"_____no_output_____"
]
],
[
[
"<h2>Run training</h2>",
"_____no_output_____"
]
],
[
[
"# Run training \nshutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time\ntf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file\ntrain_and_evaluate(OUTDIR, num_train_steps = 2000)",
"_____no_output_____"
]
],
[
[
"<h4> You can now shut Tensorboard down </h4>",
"_____no_output_____"
],
[
"## Challenge Exercise\n\nModify your solution to the challenge exercise in c_dataset.ipynb appropriately.",
"_____no_output_____"
],
[
"Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
e7b06243ce7995519bc46cb0b23e92c6b1333e52 | 9,479 | ipynb | Jupyter Notebook | tutorial_resnet.ipynb | ElHouas/cnn-deep-learning | cab4cf00288b3eadedd4d275b6150657ef4ecd7e | [
"MIT"
] | null | null | null | tutorial_resnet.ipynb | ElHouas/cnn-deep-learning | cab4cf00288b3eadedd4d275b6150657ef4ecd7e | [
"MIT"
] | null | null | null | tutorial_resnet.ipynb | ElHouas/cnn-deep-learning | cab4cf00288b3eadedd4d275b6150657ef4ecd7e | [
"MIT"
] | null | null | null | 29.808176 | 306 | 0.446988 | [
[
[
"<a href=\"https://colab.research.google.com/github/ElHouas/cnn-deep-learning/blob/main/tutorial_resnet.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Description\n\nResnet from scratch tutorial from medium post: \nhttps://towardsdatascience.com/building-a-resnet-in-keras-e8f1322a49ba\n\nNet structure:\n\n - Input with shape (32, 32, 3)\n - 1 Conv2D layer, with 64 filters\n - 2, 5, 5, 2 residual blocks with 64, 128, 256, and 512 filters\n - AveragePooling2D layer with pool size = 4\n - Flatten layer\n - Dense layer with 10 output nodes\n",
"_____no_output_____"
],
[
"## Import libraries\n\n",
"_____no_output_____"
]
],
[
[
"from tensorflow import Tensor\nfrom tensorflow.keras.layers import Input, Conv2D, ReLU, BatchNormalization,\\\n Add, AveragePooling2D, Flatten, Dense\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard\nimport datetime\nimport os",
"_____no_output_____"
]
],
[
[
"## Function definitions",
"_____no_output_____"
]
],
[
[
"def relu_bn(inputs: Tensor) -> Tensor: # Specifying return type\n relu = ReLU()(inputs)\n bn = BatchNormalization()(relu)\n return bn",
"_____no_output_____"
],
[
"def residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor:\n y = Conv2D(kernel_size=kernel_size,\n strides= (1 if not downsample else 2),\n filters=filters,\n padding=\"same\")(x)\n y = relu_bn(y)\n y = Conv2D(kernel_size=kernel_size,\n strides=1,\n filters=filters,\n padding=\"same\")(y)\n\n if downsample:\n x = Conv2D(kernel_size=1,\n strides=2,\n filters=filters,\n padding=\"same\")(x)\n out = Add()([x, y])\n out = relu_bn(out)\n return out",
"_____no_output_____"
],
[
"def create_res_net():\n \n inputs = Input(shape=(32, 32, 3))\n num_filters = 64\n \n t = BatchNormalization()(inputs)\n t = Conv2D(kernel_size=3,\n strides=1,\n filters=num_filters,\n padding=\"same\")(t)\n t = relu_bn(t)\n \n num_blocks_list = [2, 5, 5, 2]\n for i in range(len(num_blocks_list)):\n num_blocks = num_blocks_list[i]\n for j in range(num_blocks):\n t = residual_block(t, downsample=(j==0 and i!=0), filters=num_filters)\n num_filters *= 2\n \n t = AveragePooling2D(4)(t)\n t = Flatten()(t)\n outputs = Dense(10, activation='softmax')(t)\n \n model = Model(inputs, outputs)\n\n model.compile(\n optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy']\n )\n\n return model",
"_____no_output_____"
]
],
[
[
"## Main function\n",
"_____no_output_____"
]
],
[
[
"(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\nmodel = create_res_net()\nmodel.summary",
"Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n170500096/170498071 [==============================] - 6s 0us/step\n"
],
[
"timestr= datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\nname = 'cifar-10_res_net_30-'+timestr # or 'cifar-10_plain_net_30-'+timestr",
"_____no_output_____"
],
[
"checkpoint_path = \"checkpoints/\"+name+\"/cp-{epoch:04d}.ckpt\"\ncheckpoint_dir = os.path.dirname(checkpoint_path)\nos.system('mkdir {}'.format(checkpoint_dir))",
"_____no_output_____"
],
[
"# save model after each epoch\ncp_callback = ModelCheckpoint(\n filepath=checkpoint_path,\n verbose=1\n)\ntensorboard_callback = TensorBoard(\n log_dir='tensorboard_logs/'+name,\n histogram_freq=1\n)",
"_____no_output_____"
],
[
"model.fit(\n x=x_train,\n y=y_train,\n epochs=20,\n verbose=1,\n validation_data=(x_test, y_test),\n batch_size=128,\n callbacks=[cp_callback, tensorboard_callback]\n)",
"Epoch 1/20\n 1/391 [..............................] - ETA: 0s - loss: 2.3458 - accuracy: 0.0938WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/summary_ops_v2.py:1277: stop (from tensorflow.python.eager.profiler) is deprecated and will be removed after 2020-07-01.\nInstructions for updating:\nuse `tf.profiler.experimental.stop` instead.\n 30/391 [=>............................] - ETA: 2:22:53 - loss: 2.1849 - accuracy: 0.2419"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
e7b0653e101766cd834ea89c58392d207d90d497 | 12,058 | ipynb | Jupyter Notebook | doc/source/cd/methods/onlinemmddrift.ipynb | arnaudvl/alibi-detect | 573ef3be3435c834489a7b4f2d23e580c8a0a2a2 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2022-02-22T03:02:42.000Z | 2022-02-22T03:02:42.000Z | doc/source/cd/methods/onlinemmddrift.ipynb | arnaudvl/alibi-detect | 573ef3be3435c834489a7b4f2d23e580c8a0a2a2 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-11-08T09:29:08.000Z | 2021-11-09T11:44:05.000Z | doc/source/cd/methods/onlinemmddrift.ipynb | arnaudvl/alibi-detect | 573ef3be3435c834489a7b4f2d23e580c8a0a2a2 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 53.830357 | 810 | 0.677061 | [
[
[
"[source](../../api/alibi_detect.cd.mmd_online.rst)",
"_____no_output_____"
],
[
"# Online Maximum Mean Discrepancy\n\n## Overview\n\nThe online [Maximum Mean Discrepancy (MMD)](http://jmlr.csail.mit.edu/papers/v13/gretton12a.html) detector is a kernel-based method for online drift detection. The MMD is a distance-based measure between 2 distributions *p* and *q* based on the mean embeddings $\\mu_{p}$ and $\\mu_{q}$ in a reproducing kernel Hilbert space $F$:\n\n$$\nMMD(F, p, q) = || \\mu_{p} - \\mu_{q} ||^2_{F}\n$$\n\nGiven reference samples $\\{X_i\\}_{i=1}^{N}$ and test samples $\\{Y_i\\}_{i=t}^{t+W}$ we may compute an unbiased estimate $\\widehat{MMD}^2(F, \\{X_i\\}_{i=1}^N, \\{Y_i\\}_{i=t}^{t+W})$ of the squared MMD between the two underlying distributions. The estimate can be updated at low-cost as new data points enter into the test-window. We use by default a [radial basis function kernel](https://en.wikipedia.org/wiki/Radial_basis_function_kernel), but users are free to pass their own kernel of preference to the detector.\n\nOnline detectors assume the reference data is large and fixed and operate on single data points at a time (rather than batches). These data points are passed into the test-window and a two-sample test-statistic (in this case squared MMD) between the reference data and test-window is computed at each time-step. When the test-statistic exceeds a preconfigured threshold, drift is detected. Configuration of the thresholds requires specification of the expected run-time (ERT) which specifies how many time-steps that the detector, on average, should run for in the absence of drift before making a false detection. It also requires specification of a test-window size, with smaller windows allowing faster response to severe drift and larger windows allowing more power to detect slight drift.\n\nFor high-dimensional data, we typically want to reduce the dimensionality before passing it to the detector. Following suggestions in [Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift](https://arxiv.org/abs/1810.11953), we incorporate Untrained AutoEncoders (UAE) and black-box shift detection using the classifier's softmax outputs ([BBSDs](https://arxiv.org/abs/1802.03916)) as out-of-the box preprocessing methods and note that [PCA](https://en.wikipedia.org/wiki/Principal_component_analysis) can also be easily implemented using `scikit-learn`. Preprocessing methods which do not rely on the classifier will usually pick up drift in the input data, while BBSDs focuses on label shift.\n\nDetecting input data drift (covariate shift) $\\Delta p(x)$ for text data requires a custom preprocessing step. We can pick up changes in the semantics of the input by extracting (contextual) embeddings and detect drift on those. Strictly speaking we are not detecting $\\Delta p(x)$ anymore since the whole training procedure (objective function, training data etc) for the (pre)trained embeddings has an impact on the embeddings we extract. The library contains functionality to leverage pre-trained embeddings from [HuggingFace's transformer package](https://github.com/huggingface/transformers) but also allows you to easily use your own embeddings of choice. Both options are illustrated with examples in the [Text drift detection on IMDB movie reviews](../../examples/cd_text_imdb.nblink) notebook.",
"_____no_output_____"
],
[
"## Usage\n\n### Initialize\n\n\nArguments:\n\n* `x_ref`: Data used as reference distribution.\n* `ert`: The expected run-time (ERT) in the absence of drift.\n* `window_size`: The size of the sliding test-window used to compute the test-statistic. Smaller windows focus on responding quickly to severe drift, larger windows focus on ability to detect slight drift.\n\n\nKeyword arguments:\n\n* `backend`: Backend used for the MMD implementation and configuration.\n* `preprocess_x_ref`: Whether to already preprocess and store the reference data.\n* `preprocess_fn`: Function to preprocess the data before computing the data drift metrics.\n* `kernel`: Kernel used for the MMD computation, defaults to Gaussian RBF kernel.\n* `sigma`: Optionally set the GaussianRBF kernel bandwidth. Can also pass multiple bandwidth values as an array. The kernel evaluation is then averaged over those bandwidths. If `sigma` is not specified, the 'median heuristic' is adopted whereby `sigma` is set as the median pairwise distance between reference samples.\n* `n_bootstraps`: The number of bootstrap simulations used to configure the thresholds. The larger this is the more accurately the desired ERT will be targeted. Should ideally be at least an order of magnitude larger than the ERT.\n* `input_shape`: Shape of input data.\n* `data_type`: Optionally specify the data type (tabular, image or time-series). Added to metadata.\n\n\nAdditional PyTorch keyword arguments:\n\n* `device`: Device type used. The default None tries to use the GPU and falls back on CPU if needed. Can be specified by passing either 'cuda', 'gpu' or 'cpu'. Only relevant for 'pytorch' backend.\n\n\nInitialized drift detector example:\n\n\n```python\nfrom alibi_detect.cd import MMDDriftOnline\n\ncd = MMDDriftOnline(x_ref, ert, window_size, backend='tensorflow')\n```\n\nThe same detector in PyTorch:\n\n```python\ncd = MMDDriftOnline(x_ref, ert, window_size, backend='pytorch')\n```\n\nWe can also easily add preprocessing functions for both frameworks. The following example uses a randomly initialized image encoder in PyTorch:\n\n```python\nfrom functools import partial\nimport torch\nimport torch.nn as nn\nfrom alibi_detect.cd.pytorch import preprocess_drift\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# define encoder\nencoder_net = nn.Sequential(\n nn.Conv2d(3, 64, 4, stride=2, padding=0),\n nn.ReLU(),\n nn.Conv2d(64, 128, 4, stride=2, padding=0),\n nn.ReLU(),\n nn.Conv2d(128, 512, 4, stride=2, padding=0),\n nn.ReLU(),\n nn.Flatten(),\n nn.Linear(2048, 32)\n).to(device).eval()\n\n# define preprocessing function\npreprocess_fn = partial(preprocess_drift, model=encoder_net, device=device, batch_size=512)\n\ncd = MMDDriftOnline(x_ref, ert, window_size, backend='pytorch', preprocess_fn=preprocess_fn)\n```\nThe same functionality is supported in TensorFlow and the main difference is that you would import from `alibi_detect.cd.tensorflow import preprocess_drift`. Other preprocessing steps such as the output of hidden layers of a model or extracted text embeddings using transformer models can be used in a similar way in both frameworks. TensorFlow example for the hidden layer output:\n\n```python\nfrom alibi_detect.cd.tensorflow import HiddenOutput, preprocess_drift\n\nmodel = # TensorFlow model; tf.keras.Model or tf.keras.Sequential\npreprocess_fn = partial(preprocess_drift, model=HiddenOutput(model, layer=-1), batch_size=128)\n\ncd = MMDDriftOnline(x_ref, ert, window_size, backend='tensorflow', preprocess_fn=preprocess_fn)\n```\n\nCheck out the [Online Drift Detection on the Wine Quality Dataset](../../examples/cd_online_wine.nblink) example for more details.\n\nAlibi Detect also includes custom text preprocessing steps in both TensorFlow and PyTorch based on Huggingface's [transformers](https://github.com/huggingface/transformers) package:\n\n```python\nimport torch\nimport torch.nn as nn\nfrom transformers import AutoTokenizer\nfrom alibi_detect.cd.pytorch import preprocess_drift\nfrom alibi_detect.models.pytorch import TransformerEmbedding\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nmodel_name = 'bert-base-cased'\ntokenizer = AutoTokenizer.from_pretrained(model_name)\n\nembedding_type = 'hidden_state'\nlayers = [5, 6, 7]\nembed = TransformerEmbedding(model_name, embedding_type, layers)\nmodel = nn.Sequential(embed, nn.Linear(768, 256), nn.ReLU(), nn.Linear(256, enc_dim)).to(device).eval()\npreprocess_fn = partial(preprocess_drift, model=model, tokenizer=tokenizer, max_len=512, batch_size=32)\n\n# initialise drift detector\ncd = MMDDriftOnline(x_ref, ert, window_size, backend='pytorch', preprocess_fn=preprocess_fn)\n```\n\nAgain the same functionality is supported in TensorFlow but with `from alibi_detect.cd.tensorflow import preprocess_drift` and `from alibi_detect.models.tensorflow import TransformerEmbedding` imports.",
"_____no_output_____"
],
[
"### Detect Drift\n\nWe detect data drift by sequentially calling `predict` on single instances `x_t` (no batch dimension) as they each arrive. We can return the test-statistic and the threshold by setting `return_test_stat` to *True*.\n\nThe prediction takes the form of a dictionary with `meta` and `data` keys. `meta` contains the detector's metadata while `data` is also a dictionary which contains the actual predictions stored in the following keys:\n\n* `is_drift`: 1 if the test-window (of the most recent `window_size` observations) has drifted from the reference data and 0 otherwise.\n\n* `time`: The number of observations that have been so far passed to the detector as test instances.\n\n* `ert`: The expected run-time the detector was configured to run at in the absence of drift.\n\n* `test_stat`: MMD^2 metric between the reference data and the test_window if `return_test_stat` equals *True*.\n\n* `threshold`: The value the test-statsitic is required to exceed for drift to be detected if `return_test_stat` equals *True*.\n\n\n```python\npreds = cd.predict(x_t, return_test_stat=True)\n```\n\nResetting the detector with the same reference data and thresholds but with a new and empty test-window is straight-forward:\n\n```python\ncd.reset()\n```",
"_____no_output_____"
],
[
"## Examples\n\n[Online Drift Detection on the Wine Quality Dataset](../../examples/cd_online_wine.nblink)\n\n[Online Drift Detection on the Camelyon medical imaging dataset](../../examples/cd_online_camelyon.nblink)",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7b071542c0f22e83f4635f05243baa56ca26eab | 10,582 | ipynb | Jupyter Notebook | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode | 3a6a770d5d0f4453b76cae0c4c9b642f7abed24c | [
"MIT"
] | 3 | 2021-05-26T19:07:32.000Z | 2021-06-25T03:42:18.000Z | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode | 3a6a770d5d0f4453b76cae0c4c9b642f7abed24c | [
"MIT"
] | null | null | null | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode | 3a6a770d5d0f4453b76cae0c4c9b642f7abed24c | [
"MIT"
] | null | null | null | 22.954447 | 125 | 0.393687 | [
[
[
"<h2>Quiz 1 : Sifat List</h2>\n\nJawab Pertanyaan di bawah ini :\n\nJenis data apa saja yang bisa ada di dalam List?",
"_____no_output_____"
],
[
" list, ada numerik, string, boolean, dan sebagainya",
"_____no_output_____"
],
[
"<h2>Quiz 2 : Akses List</h2>\n\nLengkapi kode untuk menghasilkan suatu output yang di harapkan",
"_____no_output_____"
]
],
[
[
"a = ['1', '13b', 'aa1', 1.32, 22.1, 2.34]\n# slicing list\nprint(a[1:5])",
"['13b', 'aa1', 1.32, 22.1]\n"
]
],
[
[
"Expected Output :\n\n[ '13b', 'aa1', 1.32, 22.1 ]",
"_____no_output_____"
],
[
"<h2>Quiz 3 : Nested List</h2>\n\nLengkapi kode untuk menghasilkan suatu output yang di harapkan",
"_____no_output_____"
]
],
[
[
"a = [1.32, 22.1, 2.34]\nb = ['1', '13b', 'aa1']\nc = [3, 40, 100]\n# combine list\nd = [a, c, b]\nprint(d)",
"[[1.32, 22.1, 2.34], [3, 40, 100], ['1', '13b', 'aa1']]\n"
]
],
[
[
"Expected Output :\n\n[ [1.32, 22.1, 2.34], [3, 40, 100], ['1', '13b', 'aa1'] ]",
"_____no_output_____"
],
[
"<h2>Quiz 4 : Akses Nested List</h2>\n\nLengkapi kode untuk menghasilkan suatu output yang di harapkan",
"_____no_output_____"
]
],
[
[
"a = [\n [5, 9, 8],\n [0, 0, 6]\n ]\n# subsetting list\nprint(a[1][1:3])",
"[0, 6]\n"
]
],
[
[
"Expected Output :\n\n\n[0, 6]",
"_____no_output_____"
],
[
"<h2>Quiz 5 : Built in Function List</h2>\n\nLengkapi kode untuk menghasilkan suatu output yang di harapkan",
"_____no_output_____"
]
],
[
[
"p = [0, 5, 2, 10, 4, 9]\n# ordered list\nprint(sorted(p, reverse=False))\n# get max value of list\nprint(max(p))",
"[0, 2, 4, 5, 9, 10]\n10\n"
]
],
[
[
"Expected Output :\n\n[0, 2, 4, 5, 9, 10]\n\n10",
"_____no_output_____"
],
[
"<h2>Quiz 6 : List Operation</h2>\n\nLengkapi kode untuk menghasilkan suatu output yang di harapkan",
"_____no_output_____"
]
],
[
[
"a = [1, 3, 5]\nb = [5, 1, 3]\n# combine list\nc = b + a\nprint(c)",
"[5, 1, 3, 1, 3, 5]\n"
]
],
[
[
"Expected Output :\n\n[5, 1, 3, 1, 3, 5]",
"_____no_output_____"
],
[
"<h2>Quiz 7 : List Manipulation</h2>\n\nLengkapi kode untuk menghasilkan suatu output yang di harapkan",
"_____no_output_____"
]
],
[
[
"a = [\n [5, 9, 8],\n [0, 0, 6]\n ]\n# change list value\na[0][2] = 10\n# change list value\na[1][0] = 11\nprint(a)",
"[[5, 9, 10], [11, 0, 6]]\n"
]
],
[
[
"Expected Output :\n\n[ [5, 9, 10], [11, 0, 6] ]",
"_____no_output_____"
],
[
"<h2>Quiz 8 : Delete Element List</h2>\n\nLengkapi kode untuk menghasilkan suatu output yang di harapkan",
"_____no_output_____"
]
],
[
[
"areas = [\"hallway\", 11.25, \"kitchen\", 18.0,\n \"chill zone\", 20.0, \"bedroom\", 10.75,\n \"bathroom\", 10.50, \"poolhouse\", 24.5,\n \"garage\", 15.45]\n\n# Hilangkan elemen yang bernilai \"bathroom\" dan 10.50 dalam satu statement code\ndel(areas[8], areas[8])\nprint(areas)",
"['hallway', 11.25, 'kitchen', 18.0, 'chill zone', 20.0, 'bedroom', 10.75, 'poolhouse', 24.5, 'garage', 15.45]\n"
]
],
[
[
"Expected Output :\n\n['hallway',\n 11.25,\n 'kitchen',\n 18.0,\n 'chill zone',\n 20.0,\n 'bedroom',\n 10.75,\n 'poolhouse',\n 24.5,\n 'garage',\n 15.45]\n\n",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b075383c2e170832fe5cc983d270d13d88b761 | 4,819 | ipynb | Jupyter Notebook | Spotify.ipynb | forkbabu/Spotify-Recommendation-Engine | 690d642a43c9a278b767fca7c24ccdb307eb45c2 | [
"MIT"
] | 2 | 2020-02-24T05:32:33.000Z | 2021-05-05T08:15:51.000Z | Spotify.ipynb | forkbabu/Spotify-Recommendation-Engine | 690d642a43c9a278b767fca7c24ccdb307eb45c2 | [
"MIT"
] | null | null | null | Spotify.ipynb | forkbabu/Spotify-Recommendation-Engine | 690d642a43c9a278b767fca7c24ccdb307eb45c2 | [
"MIT"
] | 1 | 2020-07-29T06:06:34.000Z | 2020-07-29T06:06:34.000Z | 24.712821 | 125 | 0.51629 | [
[
[
"%matplotlib notebook\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport pandas as pd\n\nimport sympy\nfrom sympy import Matrix, init_printing\n\nfrom scipy.sparse.linalg import svds,eigs\n\nimport sklearn\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics.pairwise import cosine_distances\nfrom sklearn.metrics import pairwise_distances\n\nfrom time import time\n\nimport surprise\nfrom surprise import SVD\nfrom surprise import Dataset\nfrom surprise.model_selection import cross_validate\n\ninit_printing()",
"_____no_output_____"
],
[
"data = pd.read_csv('top50.csv',encoding = \"ISO-8859-1\")\ndata.index = [data[\"Track.Name\"]]",
"_____no_output_____"
],
[
"\ndata = data[['Beats.Per.Minute',\n 'Energy', 'Danceability', 'Loudness..dB..', 'Liveness', 'Valence.',\n 'Length.', 'Acousticness..', 'Speechiness.', 'Popularity']]\n",
"_____no_output_____"
],
[
"def index_to_instance(df,index=None):\n if index:\n return XYZ(df)[index][1]\n else:\n return XYZ(df)\ndef XYZ(df):\n return sorted(list(zip(list(df.index.codes[0].data),list(df.index.levels[0].array))))\ndef value_to_index_map(array):\n array1 = zip(array,range(len(array)))\n return array1",
"_____no_output_____"
],
[
"index_to_instance(data,10)",
"_____no_output_____"
],
[
"class RecSysContentBased():\n def __init__(self):\n pass\n def fit(self,train):\n self.train_set = train\n df1 = cosine_similarity(train)\n self.similarity = df1\n self.distances = pairwise_distances(train,metric='euclidean')\n def evaluate(self,user):\n d = sorted(value_to_index_map(self.distances[user]))\n return list(index_to_instance(self.train_set,d[i][1]) for i in range(len(d)))\n def predict(self):\n pass\n def test(self,testset):\n pass\n ",
"_____no_output_____"
],
[
"model = RecSysContentBased()\n",
"_____no_output_____"
],
[
"model.fit(data)",
"_____no_output_____"
],
[
"print(\"Top 5 Songs closest to {0} are: \\n{1}\".format(index_to_instance(data,10),pd.Series(model.evaluate(10)[1:6])))",
"Top 5 Songs closest to One Thing Right are: \n0 Old Town Road - Remix\n1 Happier\n2 fuck, i'm lonely (with Anne-Marie) - from 13 ...\n3 boyfriend (with Social House)\n4 Takeaway\ndtype: object\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b08cb874f657e6e149b08724c0abaaf4eba673 | 22,333 | ipynb | Jupyter Notebook | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform | a815105a5ed84564c7eafbe01281473cebfb44e5 | [
"MIT"
] | null | null | null | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform | a815105a5ed84564c7eafbe01281473cebfb44e5 | [
"MIT"
] | 2 | 2022-02-25T05:03:13.000Z | 2022-03-09T13:56:56.000Z | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform | a815105a5ed84564c7eafbe01281473cebfb44e5 | [
"MIT"
] | null | null | null | 43.030829 | 531 | 0.574621 | [
[
[
"# Welcome to the walkthrough for the updated Python SDK for libsimba.py-platform\n\nTo use the Python SDK for SEP, there are two steps the user/developer takes. These two steps assume that you have already created a contract, and an app that uses that contract, on SEP.\n\n\n1. Instantiate a SimbaHintedContract object. Instantiating this object will automatically invoke that object's write_contract method. \n This method will generate a .py file that contains a class representation of our smart contract. Our \n smart contract's methods will be represented as class methods in this class. \n2. Instantiate an instance of your contract class. If your smart contract is named \"CarContract\", then you \n would instantiate, for example, cc = CarContract(). You would then call your smart contract's methods \n as methods of your cc instance. For example, if your smart contract has a method \n \"arrived_from_warehouse\", then you can invoke cc.arrived_from_warehouse(), with relevant parameters, \n of course. ",
"_____no_output_____"
],
[
"## First, we import SimbaHintedContract, define our app name, contract name, base api url, contract clas name (which take sthe name of our contract if not specified), and the path of our output file.\nThis output file will be the name of the file that we write our class-based contract object to. \nIn this example, we have already created a contract and app in SEP, both of which have the name \"TestSimbaHinted\". ",
"_____no_output_____"
]
],
[
[
"from libsimba.simba_hinted_contract import SimbaHintedContract\napp_name = \"TestSimbaHinted\"\ncontract_name = \"TestSimbaHinted\"\nbase_api_url = 'https://api.sep.dev.simbachain.com/'\noutput_file = \"test_simba_hinted.py\"\ncontract_class_name = \"TestSimbaHinted\"",
"_____no_output_____"
]
],
[
[
"## Next, we instantiate our SimbaHintedContract object:",
"_____no_output_____"
]
],
[
[
"sch = SimbaHintedContract(\n app_name, \n contract_name, \n contract_class_name=contract_class_name, \n base_api_url=base_api_url, \n output_file=output_file)",
"_____no_output_____"
]
],
[
[
"## Instantiating that object will write our class-based smart contract to \"test_simba_hinted.py\", since that is the name we specified for our output file\n\nIn this output, solidity structs from our smart contract are represented as subclasses (Addr, Person, AddressPerson). Also note that our contract methods are now represented as class methods (eg nowt, an_arr, etc.). One important detail to notice here is that if a method call does not accept files, then we are given the option to pass a query_method parameter. If query_method == True, then previous invocations of that method call will be queried. If query_method == False, then the method itself will actually be invoked.",
"_____no_output_____"
],
[
"## Here is our generated file:",
"_____no_output_____"
]
],
[
[
"from libsimba.simba import Simba\nfrom typing import List, Tuple, Dict, Any, Optional\nfrom libsimba.class_converter import ClassToDictConverter, convert_classes\nfrom libsimba.file_handler import open_files, close_files\n\nclass TestSimbaHinted:\n def __init__(self):\n self.app_name = \"TestSimbaHinted\"\n self.base_api_url = \"https://api.sep.dev.simbachain.com/\"\n self.contract_name = \"TestSimbaHinted\"\n self.simba = Simba(self.base_api_url)\n self.simba_contract = self.simba.get_contract(self.app_name, self.contract_name)\n \n class Addr(ClassToDictConverter):\n def __init__(self, street: str = '', number: int = 0, town: str = ''):\n self.street=street\n self.number=number\n self.town=town\n \n class Person(ClassToDictConverter):\n def __init__(self, name: str = '', age: int = 0, addr: \"TestSimbaHinted.Addr\" = None):\n self.name=name\n self.age=age\n self.addr=addr\n \n class AddressPerson(ClassToDictConverter):\n def __init__(self, name: str = '', age: int = 0, addrs: List[\"TestSimbaHinted.Addr\"] = []):\n self.name=name\n self.age=age\n self.addrs=addrs\n \n def get_bundle_file(self, bundle_hash, file_name, opts: Optional[dict] = None):\n return self.simba.get_bundle_file(self.app_name, self.contract_name, bundle_hash, file_name, opts)\n\n def get_transactions(self, opts: Optional[dict] = None):\n return self.simba_contract.get_transactions(opts)\n \n def validate_bundle_hash(self, bundle_hash: str, opts: Optional[dict] = None):\n return self.simba_contract.validate_bundle_hash(bundle_hash, opts)\n\n def get_transaction_statuses(self, txn_hashes: List[str] = None, opts: Optional[dict] = None):\n return self.simba_contract.get_transaction_statuses(txn_hashes, opts)\n\n def nowt(self, async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of nowt will be queried. Otherwise nowt will be invoked with inputs.\n \"\"\"\n inputs= {\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"nowt\", opts)\n else:\n return self.simba_contract.submit_method(\"nowt\", inputs, opts, async_method)\n\n def an_arr(self, first: List[int], async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of an_arr will be queried. Otherwise an_arr will be invoked with inputs.\n \"\"\"\n inputs= {\n 'first': first,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"an_arr\", opts)\n else:\n return self.simba_contract.submit_method(\"an_arr\", inputs, opts, async_method)\n\n def two_arrs(self, first: List[int], second: List[int], async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of two_arrs will be queried. Otherwise two_arrs will be invoked with inputs.\n \"\"\"\n inputs= {\n 'first': first,\n 'second': second,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"two_arrs\", opts)\n else:\n return self.simba_contract.submit_method(\"two_arrs\", inputs, opts, async_method)\n\n def address_arr(self, first: List[str], async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of address_arr will be queried. Otherwise address_arr will be invoked with inputs.\n \"\"\"\n inputs= {\n 'first': first,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"address_arr\", opts)\n else:\n return self.simba_contract.submit_method(\"address_arr\", inputs, opts, async_method)\n\n def nested_arr_0(self, first: List[List[int]], async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of nested_arr_0 will be queried. Otherwise nested_arr_0 will be invoked with inputs.\n \"\"\"\n inputs= {\n 'first': first,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"nested_arr_0\", opts)\n else:\n return self.simba_contract.submit_method(\"nested_arr_0\", inputs, opts, async_method)\n\n def nested_arr_1(self, first: List[List[int]], async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of nested_arr_1 will be queried. Otherwise nested_arr_1 will be invoked with inputs.\n \"\"\"\n inputs= {\n 'first': first,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"nested_arr_1\", opts)\n else:\n return self.simba_contract.submit_method(\"nested_arr_1\", inputs, opts, async_method)\n\n def nested_arr_2(self, first: List[List[int]], async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of nested_arr_2 will be queried. Otherwise nested_arr_2 will be invoked with inputs.\n \"\"\"\n inputs= {\n 'first': first,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"nested_arr_2\", opts)\n else:\n return self.simba_contract.submit_method(\"nested_arr_2\", inputs, opts, async_method)\n\n def nested_arr_3(self, first: List[List[int]], async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of nested_arr_3 will be queried. Otherwise nested_arr_3 will be invoked with inputs.\n \"\"\"\n inputs= {\n 'first': first,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"nested_arr_3\", opts)\n else:\n return self.simba_contract.submit_method(\"nested_arr_3\", inputs, opts, async_method)\n\n def nested_arr_4(self, first: List[List[int]], files: List[Tuple], async_method: Optional[bool] = False, opts: Optional[dict] = None):\n \"\"\"\n If async_method == True, then nested_arr_4 will be invoked as async, otherwise nested_arr_4 will be invoked as non async\n files parameter should be list with tuple elements of form (file_name, file_path) or (file_name, readable_file_like_object).\n see libsimba.file_handler for further details on what open_files expects as arguments\n \"\"\"\n inputs= {\n 'first': first,\n }\n convert_classes(inputs)\n files = open_files(files)\n\n if async_method:\n response = self.simba_contract.submit_contract_method_with_files_async(\"nested_arr_4\", inputs, files, opts)\n close_files(files)\n return response\n else:\n response = self.simba_contract.submit_contract_method_with_files(\"nested_arr_4\", inputs, files, opts)\n close_files(files)\n return response\n\n def structTest_1(self, people: List[\"TestSimbaHinted.Person\"], test_bool: bool, async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of structTest_1 will be queried. Otherwise structTest_1 will be invoked with inputs.\n \"\"\"\n inputs= {\n 'people': people,\n 'test_bool': test_bool,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"structTest_1\", opts)\n else:\n return self.simba_contract.submit_method(\"structTest_1\", inputs, opts, async_method)\n\n def structTest_2(self, person: \"TestSimbaHinted.Person\", test_bool: bool, async_method: Optional[bool] = False, opts: Optional[dict] = None, query_method: Optional[bool] = False):\n \"\"\"\n If query_method == True, then invocations of structTest_2 will be queried. Otherwise structTest_2 will be invoked with inputs.\n \"\"\"\n inputs= {\n 'person': person,\n 'test_bool': test_bool,\n }\n convert_classes(inputs)\n if query_method:\n return self.simba_contract.query_method(\"structTest_2\", opts)\n else:\n return self.simba_contract.submit_method(\"structTest_2\", inputs, opts, async_method)\n\n def structTest_3(self, person: \"TestSimbaHinted.AddressPerson\", files: List[Tuple], async_method: Optional[bool] = False, opts: Optional[dict] = None):\n \"\"\"\n If async_method == True, then structTest_3 will be invoked as async, otherwise structTest_3 will be invoked as non async\n files parameter should be list with tuple elements of form (file_name, file_path) or (file_name, readable_file_like_object).\n see libsimba.file_handler for further details on what open_files expects as arguments\n \"\"\"\n inputs= {\n 'person': person,\n }\n convert_classes(inputs)\n files = open_files(files)\n\n if async_method:\n response = self.simba_contract.submit_contract_method_with_files_async(\"structTest_3\", inputs, files, opts)\n close_files(files)\n return response\n else:\n response = self.simba_contract.submit_contract_method_with_files(\"structTest_3\", inputs, files, opts)\n close_files(files)\n return response\n\n def structTest_4(self, persons: List[\"TestSimbaHinted.AddressPerson\"], files: List[Tuple], async_method: Optional[bool] = False, opts: Optional[dict] = None):\n \"\"\"\n If async_method == True, then structTest_4 will be invoked as async, otherwise structTest_4 will be invoked as non async\n files parameter should be list with tuple elements of form (file_name, file_path) or (file_name, readable_file_like_object).\n see libsimba.file_handler for further details on what open_files expects as arguments\n \"\"\"\n inputs= {\n 'persons': persons,\n }\n convert_classes(inputs)\n files = open_files(files)\n\n if async_method:\n response = self.simba_contract.submit_contract_method_with_files_async(\"structTest_4\", inputs, files, opts)\n close_files(files)\n return response\n else:\n response = self.simba_contract.submit_contract_method_with_files(\"structTest_4\", inputs, files, opts)\n close_files(files)\n return response\n\n def structTest_5(self, person: \"TestSimbaHinted.Person\", files: List[Tuple], async_method: Optional[bool] = False, opts: Optional[dict] = None):\n \"\"\"\n If async_method == True, then structTest_5 will be invoked as async, otherwise structTest_5 will be invoked as non async\n files parameter should be list with tuple elements of form (file_name, file_path) or (file_name, readable_file_like_object).\n see libsimba.file_handler for further details on what open_files expects as arguments\n \"\"\"\n inputs= {\n 'person': person,\n }\n convert_classes(inputs)\n files = open_files(files)\n\n if async_method:\n response = self.simba_contract.submit_contract_method_with_files_async(\"structTest_5\", inputs, files, opts)\n close_files(files)\n return response\n else:\n response = self.simba_contract.submit_contract_method_with_files(\"structTest_5\", inputs, files, opts)\n close_files(files)\n return response",
"_____no_output_____"
]
],
[
[
"## Here we will instantiate an instance of our contract class. You could do that from a separate file, by importing your contract class, but since we're using a notebook here, we'll just instantiate an object in the same file:\n",
"_____no_output_____"
]
],
[
[
"tsh = TestSimbaHinted()",
"_____no_output_____"
]
],
[
[
"## Now we will call one of our smart contract's methods by invoking a method of our contract class object. We will call our method two_arrs, which simply takes two arrays as parameters.",
"_____no_output_____"
]
],
[
[
"arr1 = [2, 4, 20, 10, 3, 3]\narr2 = [1,3,5]\nr = tsh.two_arrs(arr1, arr2)",
"_____no_output_____"
]
],
[
[
"We can inspect the response from this submission to check it has succeeded:",
"_____no_output_____"
]
],
[
[
"assert (200 <= r.status_code <= 299)\nprint(r.json())",
"_____no_output_____"
]
],
[
[
"## Now let's invoke structTest_5, which is a method that accepts files, and also takes a nested struct as a parameter. \n\nFirst we need to assign our file path and file name, as well as specify the read_mode for our file. if read_mode is not specified here, then it defaults to 'r' (see file_handler.py for documentation on this).",
"_____no_output_____"
]
],
[
[
"file_name = 'test_file'\nfile_path = '../tests/data/file1.txt'\nfiles = [(file_name, file_path, 'r')]",
"_____no_output_____"
]
],
[
[
"Now we will need to instantiate Person and Addr objects. Person takes an Addr object as one of its initialization parameters.",
"_____no_output_____"
]
],
[
[
"name = \"Charlie\"\nage = 99\nstreet = \"rogers street\"\nnumber = 123\ntown = \"new york\"\naddr = TestSimbaHinted.Addr(street, number, town)\np = TestSimbaHinted.Person(name, age, addr)\n",
"_____no_output_____"
]
],
[
[
"Now we will invoke structTest_5 with parameters p, and files.",
"_____no_output_____"
]
],
[
[
"\nr = tsh.structTest_5(p, files)\nif 200 <= r.status_code <= 299:\n print(r.json())",
"_____no_output_____"
]
],
[
[
"\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"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b094c78e33236756e2f8bd82ac226f7915564f | 38,547 | ipynb | Jupyter Notebook | Movie-Recommendation.ipynb | Git-Sarang/Movie-Recommender | d11c39b8d5e5cd0bc4b2dda9d0094ef546816e23 | [
"MIT"
] | null | null | null | Movie-Recommendation.ipynb | Git-Sarang/Movie-Recommender | d11c39b8d5e5cd0bc4b2dda9d0094ef546816e23 | [
"MIT"
] | null | null | null | Movie-Recommendation.ipynb | Git-Sarang/Movie-Recommender | d11c39b8d5e5cd0bc4b2dda9d0094ef546816e23 | [
"MIT"
] | null | null | null | 19,273.5 | 38,546 | 0.576232 | [
[
[
"# **Movie Recommendation Model**\n",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"movies = pd.read_csv(\"/Users/sarang/Documents/Movie-Reccomendation/content/tmdb_5000_movies.csv\")\ncredits = pd.read_csv(\"/Users/sarang/Documents/Movie-Reccomendation/content/tmdb_5000_credits.csv\")",
"_____no_output_____"
],
[
"movies = movies.merge(credits,on='title')\nmovies = movies[['movie_id','title','overview','genres','keywords','cast','crew']]",
"_____no_output_____"
],
[
"movies.head(2)\n# movies.shape",
"_____no_output_____"
],
[
"credits.head()\ncredits.shape",
"_____no_output_____"
],
[
"#From a dict, it takes the value of the key named 'name' and adds it to a list\nimport ast\ndef convert(text):\n L = []\n for i in ast.literal_eval(text):\n L.append(i['name']) \n return L \nmovies.dropna(inplace=True)",
"_____no_output_____"
],
[
"movies['genres'] = movies['genres'].apply(convert)\nmovies.head()",
"_____no_output_____"
],
[
"movies['keywords'] = movies['keywords'].apply(convert)\nmovies.head(2)",
"_____no_output_____"
],
[
"movies['cast'] = movies['cast'].apply(convert)",
"_____no_output_____"
],
[
"# Only 3 member cast\nmovies['cast'] = movies['cast'].apply(lambda x: x[0:3])\nmovies.head(2)",
"_____no_output_____"
],
[
"def get_Director(text):\n L=[]\n for i in ast.literal_eval(text):\n if i['job'] == 'Director':\n L.append(i['name'])\n return L",
"_____no_output_____"
],
[
"movies['crew'] = movies['crew'].apply(get_Director)\nmovies.head(2)",
"_____no_output_____"
],
[
"#removes the space in the string in a list\ndef remove_space(text):\n L=[]\n for i in text:\n L.append(i.replace(\" \", \"\"))\n return L",
"_____no_output_____"
],
[
"movies['genres'] = movies['genres'].apply(remove_space)\nmovies['keywords'] = movies['keywords'].apply(remove_space)\nmovies['cast'] = movies['cast'].apply(remove_space)\nmovies['crew'] = movies['crew'].apply(remove_space)",
"_____no_output_____"
],
[
"movies.head(2)",
"_____no_output_____"
],
[
"#makes a list of words of the string overview\nmovies['overview'] = movies['overview'].apply(lambda x: x.split())",
"_____no_output_____"
],
[
"#makes a new col 'tag' concats all the parameters we created\nmovies['tag'] = movies['cast']+movies['crew']+movies['genres']+movies['overview']+movies['keywords']",
"_____no_output_____"
],
[
"#Creates new dataframe 'new'(softcopy of movies), where every col is dropped except id,title,tag\nnew = movies.drop(columns=['genres', 'overview', 'keywords', 'cast', 'crew'])\nnew.head(2)",
"_____no_output_____"
],
[
"new['tag'] = new['tag'].apply(lambda x: \" \".join(x))",
"_____no_output_____"
],
[
"new.head(2)",
"_____no_output_____"
]
],
[
[
"Machine Learning Section",
"_____no_output_____"
]
],
[
[
"from sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer(max_features=5000,stop_words='english')",
"_____no_output_____"
],
[
"vector = cv.fit_transform(new['tag']).toarray()",
"_____no_output_____"
],
[
"vector.shape",
"_____no_output_____"
],
[
"from sklearn.metrics.pairwise import cosine_similarity",
"_____no_output_____"
],
[
"similarity = cosine_similarity(vector)",
"_____no_output_____"
],
[
"type(similarity)",
"_____no_output_____"
],
[
"new[new['title']=='The Lego Movie'].index[0]",
"_____no_output_____"
],
[
"def recommend(movie):\n index = new[new['title'] == movie].index[0]\n distances = sorted(list(enumerate(similarity[index])),reverse=True,key = lambda x: x[1])\n for i in distances[1:6]:\n print(new.iloc[i[0]].title)",
"_____no_output_____"
],
[
"# Sample titles to try the recommend function\nnew['title'].sample(5)",
"_____no_output_____"
],
[
"recommend('Fury')",
"U-571\nThe Great Raid\nFort McCoy\nEnemy at the Gates\nRed Tails\n"
],
[
"import pickle",
"_____no_output_____"
],
[
"pickle.dump(new.to_dict(), open('movie_dict.pkl', 'wb'))\n",
"_____no_output_____"
],
[
"pickle.dump(similarity, open('similarity.pkl', 'wb'))",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b0ac9f943ef527950932e71f4c7c59b7b4a101 | 9,814 | ipynb | Jupyter Notebook | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog | 50022f35c7e49c6380714b696d67d473165dd88d | [
"Apache-2.0"
] | null | null | null | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog | 50022f35c7e49c6380714b696d67d473165dd88d | [
"Apache-2.0"
] | 1 | 2020-10-03T18:10:40.000Z | 2020-10-03T19:23:56.000Z | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog | 50022f35c7e49c6380714b696d67d473165dd88d | [
"Apache-2.0"
] | null | null | null | 23.422434 | 240 | 0.533014 | [
[
[
"# Hypothesis test power from scratch with Python",
"_____no_output_____"
],
[
"Calculating power of hypothesis tests.\n\nThe code is from the [Data Science from Scratch](https://www.oreilly.com/library/view/data-science-from/9781492041122/) book.\n",
"_____no_output_____"
],
[
"## Libraries and helper functions",
"_____no_output_____"
]
],
[
[
"from typing import Tuple\nimport math as m",
"_____no_output_____"
],
[
"def calc_normal_cdf(x: float, mu: float = 0, sigma: float = 1) -> float:\n return (1 + m.erf((x - mu) / m.sqrt(2) / sigma)) / 2\n\nnormal_probability_below = calc_normal_cdf",
"_____no_output_____"
],
[
"def normal_probability_between(lo: float, hi: float, mu: float = 0, sigma: float = 1) -> float:\n return normal_probability_below(hi, mu, sigma) - normal_probability_below(lo, mu, sigma)",
"_____no_output_____"
],
[
"def calc_normal_cdf(x: float, mu: float = 0, sigma: float = 1) -> float:\n return (1 + m.erf((x - mu) / m.sqrt(2) / sigma)) / 2",
"_____no_output_____"
],
[
"def calc_inverse_normal_cdf(p: float, mu:float = 0, sigma: float = 1, tolerance: float = 1E-5, show_steps=False) -> float:\n\n if p == 0: return -np.inf\n if p == 1: return np.inf\n\n # In case it is not a standard normal distribution, calculate the standard normal first and then rescale\n if mu != 0 or sigma != 1:\n return mu + sigma * calc_inverse_normal_cdf(p, tolerance=tolerance)\n\n low_z = -10\n hi_z = 10\n\n if show_steps: print(f\"{'':<19}\".join(['low_z', 'mid_z', 'hi_z']), \"\\n\")\n\n while hi_z - low_z > tolerance:\n mid_z = (low_z + hi_z) / 2\n mid_p = calc_normal_cdf(mid_z)\n\n if mid_p < p:\n low_z = mid_z\n else:\n hi_z = mid_z\n\n if show_steps: print(\"\\t\".join(map(to_string, [low_z, mid_z, hi_z])))\n\n return mid_z",
"_____no_output_____"
],
[
"def normal_upper_bound(probabilty: float, mu: float = 0, sigma: float = 1) -> float:\n return calc_inverse_normal_cdf(probabilty, mu, sigma)",
"_____no_output_____"
],
[
"def normal_lower_bound(probabilty: float, mu: float = 0, sigma: float = 1) -> float:\n return calc_inverse_normal_cdf(1 - probabilty, mu, sigma)",
"_____no_output_____"
],
[
"def normal_two_sided_bounds(probability: float, mu: float = 0, sigma: float = 1) -> float:\n if probability == 0: return 0, 0\n\n tail_probability = (1 - probability) / 2\n\n lower_bound = normal_upper_bound(tail_probability, mu, sigma)\n upper_bound = normal_lower_bound(tail_probability, mu, sigma)\n \n return lower_bound, upper_bound",
"_____no_output_____"
],
[
"def normal_approximation_to_binomial(n: int, p: float) -> Tuple[float, float]:\n mu = p * n\n sigma = m.sqrt(p * (1 - p) * n)\n\n return mu, sigma",
"_____no_output_____"
]
],
[
[
"## Type 1 Error and Tolerance",
"_____no_output_____"
],
[
"Let's make our null hypothesis ($H_0$) that the probability of head is 0.5",
"_____no_output_____"
]
],
[
[
"mu_0, sigma_0 = normal_approximation_to_binomial(1000, 0.5) \nmu_0, sigma_0",
"_____no_output_____"
]
],
[
[
"We define our tolerance at 5%. That is, we accept our model to produce 'type 1' errors (false positive) in 5% of the time. With the coin flipping example, we expect to receive 5% of the results to fall outsied of our defined interval.",
"_____no_output_____"
]
],
[
[
"lo, hi = normal_two_sided_bounds(0.95, mu_0, sigma_0)\nlo, hi",
"_____no_output_____"
]
],
[
[
"## Type 2 Error and Power",
"_____no_output_____"
],
[
"At type 2 error we consider false negatives, that is, those cases where we fail to reject our null hypothesis even though we should.",
"_____no_output_____"
],
[
"Let's assume that contra $H_0$ the actual probability is 0.55.",
"_____no_output_____"
]
],
[
[
"mu_1, sigma_1 = normal_approximation_to_binomial(1000, 0.55)\nmu_1, sigma_1",
"_____no_output_____"
]
],
[
[
"In this case we get our Type 2 probability as the overlapping of the real distribution and the 95% probability region of $H_0$. In this particular case, in 11% of the cases we will wrongly fail to reject our null hypothesis.",
"_____no_output_____"
]
],
[
[
"type_2_probability = normal_probability_between(lo, hi, mu_1, sigma_1)\ntype_2_probability",
"_____no_output_____"
]
],
[
[
"The power of the test is then the probability of rightly rejecting the $H_0$",
"_____no_output_____"
]
],
[
[
"power = 1 - type_2_probability\npower",
"_____no_output_____"
]
],
[
[
"Now, let's redefine our null hypothesis so that we expect the probability of head to be less than or equal to 0.5.\n\nIn this case we have a one-sided test.",
"_____no_output_____"
]
],
[
[
"hi = normal_upper_bound(0.95, mu_0, sigma_0)\nhi",
"_____no_output_____"
]
],
[
[
"Because this is a less strict hypothesis than our previus one, it has a smaller T2 probability and a greater power.",
"_____no_output_____"
]
],
[
[
"type_2_probability = normal_probability_below(hi, mu_1, sigma_1)\ntype_2_probability",
"_____no_output_____"
],
[
"power = 1 - type_2_probability\npower",
"_____no_output_____"
]
]
] | [
"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",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7b0afe21068b13da6b02eba647ed61ec0d61965 | 83,399 | ipynb | Jupyter Notebook | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials | 0e2aead9c2a7c92a6826b6b47970afbfa30fb1b2 | [
"MIT"
] | 1 | 2020-08-25T21:05:01.000Z | 2020-08-25T21:05:01.000Z | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials | 0e2aead9c2a7c92a6826b6b47970afbfa30fb1b2 | [
"MIT"
] | null | null | null | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials | 0e2aead9c2a7c92a6826b6b47970afbfa30fb1b2 | [
"MIT"
] | null | null | null | 149.460573 | 36,300 | 0.839866 | [
[
[
"# Carry signals\n\n#### by Gustavo Soares\n\nIn this notebook you will apply a few things you learned in our Python lecture [FinanceHub's Python lectures](https://github.com/Finance-Hub/FinanceHubMaterials/tree/master/Python%20Lectures):\n\n* You will use and manipulate different kinds of variables in Python such as text variables, booleans, date variables, floats, dictionaries, lists, list comprehensions, etc.;\n* We will also use `Pandas.DataFrame` objects and methods which are very useful in manipulating financial time series;\n* You will use if statements and loops, and;\n* You will use [FinanceHub's Bloomberg tools](https://github.com/Finance-Hub/FinanceHub/tree/master/bloomberg) for fetching data from a Bloomberg terminal. If you are using this notebook within BQNT, you may want to use BQL for getting the data.\n\n## Basic imports\n",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom bloomberg import BBG\nbbg = BBG() # because BBG is a class, we need to create an instance of the BBG class wihtin this notebook, here deonted by bbg",
"_____no_output_____"
]
],
[
[
"## Carry\n\nThe concept of carry arised in currency markets but it can be applied to any asset. Any security or derivative expected return can be decomposed into its “carry” – an ex-ante and model-free characteristic – and its expected price appreciation. So, \"carry\" can be understood as the expected return of a security or derivative if there is no change in underlying prices. That is, if \"nothing happens\", i.e., prices do not move and only time passes, that security or derivative will earn its \"carry\".\n\nThe concept of carry has been shown to be a good predictor or returns cross-sectionally (going long securities with high carry while at the same time going short securities with low carry) and in time series (going long a particular security when carry is positive or historically high and short when carry is negative or historically low). So, the concept of \"carry\" provides a unifying framework for return predictability and gives orgin to carry strategies across a host of different asset classes, including global equities, global bonds, commodities, US Treasuries, credit, and options. Carry strategies are commonly exposed to global recession, liquidity, and volatility risks, though none fully explain carry’s premium.\n\n[Koijen, Moskowitz, Pedersen, and Vrugt (2016)](https://ssrn.com/abstract=2298565) is a great reference for discussing cross-sectional carry strategies in several different markets. There are typically market-neutral carry strategies where we are always long some currencies, rates, commodities and indices and short some others. [Baz, Granger, Harvey, Le Roux, and Rattray (2015)](https://ssrn.com/abstract=2695101) discusses in detail the differences between cross-sectional strategies and time series strategies for three different factors, including carry. It is really important to understand the difference. [Baltas (2017)](https://doi.org/10.1016/B978-1-78548-201-4.50013-1) also looks at carry stratgies, both cross-sectional and time series, across different futures markets (commodities, equity indices and government bonds). He also discusses the benefits of constructing a multi-asset carry strategies.\n\nHere in this notebook, we just follow [Koijen, Moskowitz, Pedersen, and Vrugt (2016)](https://ssrn.com/abstract=2298565) and show how, using Bloomberg data, calculate carry metrics for different asset classes.\n\n\n### Carry in FX\n\nLet's start with the best known case, which is carry in currencies. For that, let's take the USDBRL and see how we can compute carry for that currency.\n\n#### Deposit rates\n\nThe “classic” definition of currency carry is the local deposit interest rate in the corresponding\ncountry. This definition captures an investment in a currency by literally putting cash into a country’s money market, which earns the interest rate if the exchange rate (the “price of the currency”) does not change. Typically, we would use the\nBRL 3M deposit rate (BCDRC BDSR Curncy on Bloomberg) which is the interest rate that a bank will charge for lending or pay for borrowing in BRL. For shorter investment horizons, we could pick shorter tenors such as 1M. However, in terms of predictability of future returns there should be little difference in using 1M, 3M or 6M deposit rates in your carry signal. As a matter of fact, now that many currencies have very small short term rates, many quantitative strategies have been using 2Y rates in their carry signals, even when the signal are meant to be predictive over relatively short investment horizons of 1M or 3M. So, in the case of 3M rates, we can define the annualized USDBRL carry as:\n\n$$\nCarry_{USDBRL}^{3M} = \\frac{1+r_{USD}}{1+r_{BRL}}-1\n$$\n\nwhere $r_{USD}$ is the 3M USD deposit rate and $r_{BRL}$ is the 3M BRL interest rate.\n\nNote that if we were calculating carry for BRLUSD, it would be a different number. This is important because some curruncies, like the BRL, are quoted as USDBRL and some currencies, like the EUR, are quoted as EURUSD. So, when trading FX, make sure your carry signal is calculated according to whethere you are trading XXXYYY or YYYXXX!\n\n#### Forwards\n\nRecall that by a no-arbitrage argument a currency 3M forward contract should be prices by:\n\n$$\nF_{USDBRL}^{3M} = S_{USDBRL} \\times \\Big(\\frac{1+r_{BRL}}{1+r_{USD}}\\Big)^{3/12}\n$$\n\nwhere $S_{USDBRL}$ is the spot USDBRL exchange rate. So, an alternative way of defining the 3M annualized carry in USDBRL is:\n\n\n$$\nCarry_{USDBRL}^{3M} = \\Big(\\frac{S_{USDBRL}}{F_{USDBRL}^{3M}}\\Big)^{12/3}-1\n$$\n\n\n#### Volatility adjusted carry\n\nThe forwards based definition of $Carry_{USDBRL}^{3M}$ above suggests that the expected return of buying a certain notional, $N$, of 3M forward contract at price $F_{USDBRL}$ expects to earn\n\n$$\nN \\times \\Big(\\big(1+Carry_{USDBRL}^{3M}\\big)^{3/12}-1\\Big)\n$$\n\nin profits if deposit rates $r_{USD}$ and $r_{BRL}$ and the spot exchange rate $S_{USDBRL}$ remains constant over the 3M period investment horizon. This is the right intuition for the concept of carry in FX.\n\nHowever, it is important to note that this trade, buying a 3M forward contract at price $F_{USDBRL}$ and unwinding it at maturity, does not really require the full notional, $N$ in capital. Let's call the actual required capital $X < N$, the \"margin amount\". The margin $X$ is the actual cash amount needed to operate unfunded derivatives contracts like FX forwards.\n\nAn investor typically allocates a fraction of $N$, sometimes as litle as 2% or 3% of $N$, as margin. Let's say $X = k \\times N$, then the carry return over the allocated cash capital $X$ is given by:\n\n$$\nk^{-1} \\times \\Big(\\big(1+Carry_{USDBRL}^{3M}\\big)^{3/12}-1\\Big)\n$$\n\nHence, by using a scaling factor $k$ one can modify the definition of carry to be consistent with the returns per unit of allocated capital. So, an asset with carry equal to 5% but that requires 2.5% margin has the same carry per allocated capital of an asset with carry equal to 10% but that requires 5% margin.\n\nFor time-series strategies, this scaling factor $k$ tends to be not very relevant because it is typically constant over time. However, for cross-sectional strategies, $k$ can vary from asset to asset making the comparison of their carry measures inapropriate as different assets may require different amounts of cash as margin. Asset from the same asset class will typically have very similar margin requirements unless the asset volatilities vary significantly in the cross section. Since, margin requirements, very roughly, vary with the underlying asset volatiltiy. It is common in quantitative cross-sectional carry strategies to adjust carry signals by the volatility of the underlying asset as in:\n\n$$\n\\sigma_{USDBRL}^{-1} \\times Carry_{USDBRL}^{3M}\n$$\n\nLet's see how these definitions can be computed in Python using Bloomberg data and [FinanceHub's Bloomberg tools](https://github.com/Finance-Hub/FinanceHub/tree/master/bloomberg):",
"_____no_output_____"
]
],
[
[
"ref_date = '2019-12-04'\ntickers = [\n 'BCDRC BDSR Curncy', # BRL 3M deposit rate\n 'USDRC BDSR Curncy', # USD 3M deposit rate\n 'USDBRL Curncy', # USDBRL spot exchange rate\n 'BCN+3M BGN Curncy', # USDBRL 3M forward contract\n 'USDBRLV3M BGN Curncy', # USDBRL 3M ATM implied volatility\n]\n\nbbg_data = bbg.fetch_series(securities=tickers,\n fields='PX_LAST', # This is the Bloomberg field that contains the spot exchange rates data\n startdate=ref_date,\n enddate=ref_date)\nbbg_data",
"_____no_output_____"
]
],
[
[
"Given the data above, let's calculate carry in both ways:",
"_____no_output_____"
]
],
[
[
"dr_carry = (1+bbg_data.iloc[-1,1]/100)/(1+bbg_data.iloc[-1,0]/100)-1\nprint('Deposit rate 3M ann. carry for USDBRL on %s is: %s'% (ref_date,dr_carry))\nfwd_carry = ((1+bbg_data.iloc[-1,2])/(1+bbg_data.iloc[-1,3]))**(12/3)-1\nprint('Forward contract 3M ann. carry for USDBRL on %s is: %s'% (ref_date,fwd_carry))\nvol_adj_carry = fwd_carry/(bbg_data.iloc[-1,-1]/100)\nprint('Vol-adjusted forward contract 3M ann. carry for USDBRL on %s is: %s'% (ref_date,vol_adj_carry))",
"Deposit rate 3M ann. carry for USDBRL on 2019-12-04 is: -0.016833325297719526\nForward contract 3M ann. carry for USDBRL on 2019-12-04 is: -0.013180395716221094\nVol-adjusted forward contract 3M ann. carry for USDBRL on 2019-12-04 is: -0.11723201739945827\n"
]
],
[
[
"### Carry in commodity futures\n\nCalculating carry for commodity futures, or for any futures contract follows pretty much the same lines as calculating carry for forward FX contract. Again, by a no-arbitrage argument any futures contract on an underlying $i$, maturing in $T$ years, should be priced by:\n\n$$\nF_{i}^{T} = S_{i} \\times \\big(1+Carry_{i}^{T}\\big)^{T}\n$$\n\nwhere $S_{i}$ is the spot price of the underlying. So, we can use the equation above as the definition of carry in futures. The problem is that in many commodity markets, there is not exactly a spot market like in FX. Hence, the standard practice is to use the front month future, i.e., the futures closest to maturity as the \"spot\" market and calculate carry as:\n\n$$\nCarry_{i}^{T-T_{0}} = \\Big(\\frac{F_{i}^{T_{0}}}{F_{i}^{T}}\\Big)^{1/(T-T_{0})}-1\n$$\n\nFor many commodities, prices move seasonally. For example, let's look at natural gas futures prices:",
"_____no_output_____"
]
],
[
[
"tickers = ['NG' + str(i) + ' Comdty' for i in range(1,13)]\n\nbbg_data = bbg.fetch_series(securities=tickers,\n fields='PX_LAST',\n startdate=ref_date,\n enddate=ref_date)\nbbg_data.columns = [int(x.replace('NG','').replace(' Comdty','')) for x in bbg_data.columns]\nbbg_data.sort_index(axis=1)\nplt.figure(figsize=(15,10))\nbbg_data.iloc[-1].sort_index().plot(title='Natural gas futures curve')\nplt.ylabel('$/MBTU')\nplt.xlabel('Months ahead')\nplt.show()",
"_____no_output_____"
]
],
[
[
"In order to avoid the definition of carry moving up and down seasonally, carry strategies in commodities often look at $T$ and $T_{0}$ exactly one year apart. However, this not always true. Some people may argue that you want carry to move up and down seasonally because the underlying spot markets do so.\n\n### Carry in rates\n\n#### Carry in zero coupon bonds\n\nWhen we have data on a zero-coupon rates curve, we can also apply the same carry definition as in FX forward contracts or commodity futures. Let's suppose we want to calculate carry on zero coupon bon with maturity $\\tau$ years ahead. Since we have a zero-coupon rates curve, we know the yield of this zero coupon bond, $y_{t}^{\\tau}$, on date $t$. Asuming without loss of generality that the bond pays 1 as principal, the spot price of this bond is then given by $P_{t}^{\\tau} = (1+y_{t}^{\\tau})^{-\\tau}$.\n\nSo, what is the expected return of this bond over a time period $h$ if there is no change in underlying prices, i.e., the zero-coupon rates curve remains the same? Well, after $h$ time periods have passed, this bond will now have maturity equal to $\\tau-h$ years and therefore, if the zero-coupon rates curve remains the same, it will have price: $P_{t+h}^{\\tau-h} = P_{t}^{\\tau-h} = (1+y_{t}^{\\tau-h})^{-\\tau+h}$. Hence, the annualized total return of buying a zero coupon bond of maturity $\\tau$ years and holding it for $h$ years is:\n\n$$\n\\Big(\\frac{P_{t+h}^{\\tau-h}}{P_{t}^{\\tau}}\\Big)^{1/h}-1= \\frac{(1+y_{t}^{\\tau})^{\\tau/h}}{(1+y_{t}^{\\tau-h})^{(\\tau-h)/h}}-1.\n$$\n\nThe chapter *A Framework for Analyzing Yield-curve trades* in [Fabozzi's book](https://www.amazon.com/Handbook-Fixed-Income-Securities-Eighth/dp/0071768467) will show that the expression on the right hand side of the equation above is in fact the $h$ years rate $\\tau-h$ years forward, i.e., the so-called $\\tau-h:h$ years forward rate, denoted here by $f_{t}^{\\tau-h:h}$. The $\\tau-h:h$ years forward rate is the non-arbitrage $h$ years rate implied by the current zero-coupon curve that is suppose to prevalent during the time period in between $\\tau-h$ and $\\tau$. Hence, the annualized total return of buying a zero coupon bond of maturity $\\tau$ years and holding it for $h$ years is $f_{t}^{\\tau-h:h}$.\n\nHowever, note that buying a zero coupon bond requires some actual cash. This cash which is required duing $h$ years needs to be remunerated at the $y_{t}^{h}$ rate. So, the actual carry of a zero-coupon bond, or any no-coupon paying derivative, with maturity $\\tau$ is:\n\n$$\nCarry_{\\tau}^{h} = \\frac{1+f_{t}^{\\tau-h:h}}{1+y_{t}^{h}}-1.\n$$\n\n#### Carry in coupon paying bonds\n\nWhen we do not have data on a zero-coupon rates curve, calculating carry is a bit different. We still know the bond, $y_{t}^{\\tau}$, on date $t$ and its price $P_{t}^{\\tau}$. After $h$ time periods have passed, this bond will now have maturity equal to $\\tau-h$ years and therefore, if the yield curve remains the same, it will have price: $P_{t+h}^{\\tau-h} = P_{t}^{\\tau-h}$ and yield equal to $y_{t}^{\\tau-h}$.\n\nUsing the arguemnts in the chapter *A Framework for Analyzing Yield-curve trades* in [Fabozzi's book](https://www.amazon.com/Handbook-Fixed-Income-Securities-Eighth/dp/0071768467) one can show that the annualized total return of buying a bond of maturity $\\tau$ years and holding it for $h$ years can be approximated by:\n\n$$\n\\Big(\\frac{P_{t+h}^{\\tau-h}}{P_{t}^{\\tau}}\\Big)^{1/h}-1 \\approx y_{t}^{\\tau} - \\frac{D_{t}^{\\tau-h}}{h} \\times (y_{t}^{\\tau-h}-y_{t}^{\\tau})\n$$\n\nwhere $D_{t}^{\\tau-h}$ is the modified duration of a bond with maturity $\\tau-h$.\n\nAgain, buying a bond requires some actual cash which needs to be remunerated at the $y_{t}^{h}$ rate. So, the actual carry of a a bond, or any similar derivative, with maturity $\\tau$ can be approximated by:\n\n$$\nCarry_{\\tau}^{h} \\approx \\underbrace{(y_{t}^{\\tau} - y_{t}^{h})}_\\text{slope} - \\underbrace{\\frac{D_{t}^{\\tau-h}}{h} \\times (y_{t}^{\\tau-h}-y_{t}^{\\tau})}_\\text{roll down}\n$$\n\nAs dicussed in [Koijen, Moskowitz, Pedersen, and Vrugt (2016)](https://ssrn.com/abstract=2298565) the equation above shows that the bond carry consists of two effects: (i) the bond’s yield spread to the risk-free rate, which is also called the **slope** of the term structure; plus (ii) the **roll down** which captures the price increase due to the fact that the bond rolls down the yield curve. The idea of the second component is that if the entire yield curve stays constanto, the bond \"rolls down\" the\nyield curve and it will now have yield $y_{t}^{\\tau-h}$, resulting in a price appreciation that can be measured by the change in yields times the modified duration.\n\nIn many case, the magnitude of the roll down component is small relative to the slope component. So, from time to time you will see carry strategies in rates defining carry simply as the slope component, i.e., $Carry_{\\tau}^{h} \\approx y_{t}^{\\tau} - y_{t}^{h}$. This approximation is sometimes called **cash carry** while the previous one is sometimes called **total carry**.\n\n\n#### Carry in interest rate swaps\n\nWe want to calculate the carry of holding a vanilla (fixed vs floating) interest rate swap in a particular currency. Here, we can actually use the same logic we used when calculating carry in FX using forward contracts. Let's denote the spot swap rate by $y^{\\tau}$. If there are $h:\\tau+h$ forward starting swaps available, they will trade at rate $y^{h:\\tau+h}$. The carry for holding the $\\tau$ years swap over $h$ periods should be equal to the expected return from holding a $h:\\tau+h$ forward starting swaps to its maturity at time ${\\tau}$.\n\nAgain using the arguements from the chapter *A Framework for Analyzing Yield-curve trades* in [Fabozzi's book](https://www.amazon.com/Handbook-Fixed-Income-Securities-Eighth/dp/0071768467) one can approximate the return of a $h:\\tau+h$ forward starting swaps by:\n\n$$\nCarry_{\\tau}^{h} \\approx D_{\\tau} \\times \\Delta y \\approx \\frac{D_{\\tau}}{h} \\times (y^{h:\\tau+h}-y_{t}^{\\tau})\n$$\n\n#### Carry across G10 IRS\n\nLet's see how all this looks in practice. Let's calcualte the 6M carry in 10Y rates across G10:",
"_____no_output_____"
]
],
[
[
"# get spot 10Y rates tickers\nspot_IRS = pd.Series({\n 'USD':'USSW10 Curncy',\n 'EUR':'EUSA10 Curncy',\n 'JPY':'JYSW10 Curncy',\n 'GBP':'BPSW10 Curncy',\n 'AUD':'ADSW10Q Curncy',\n 'CAD':'CDSW10 Curncy',\n 'SEK':'SKSW10 Curncy',\n 'CHF':'SFSW10 Curncy',\n 'NOK':'NKSW10 Curncy',\n 'NZD':'NDSWAP10 Curncy',\n})\n\n\nswap_rates = bbg.fetch_series(securities=list(spot_IRS.values),\n fields='PX_LAST',\n startdate=ref_date,\n enddate=ref_date)\nswap_rates.columns = [spot_IRS.index[list(spot_IRS.values).index(x)] for x in list(swap_rates.columns)]\n\n\n# 6M forward 10Y rates tickers\nfwd_6M_IRS = pd.Series({\n 'USD':'USFS0F10 Curncy',\n 'EUR':'EUSAF10 Curncy',\n 'JPY':'JYFS0F10 Curncy',\n 'GBP':'BPSW0F10 Curncy',\n 'AUD':'S0302FS 6M10Y BLC Curncy',\n 'CAD':'CDFS0F10 Curncy',\n 'SEK':'SKFS0F10 Curncy',\n 'CHF':'SFFS0F10 Curncy',\n 'NOK':'S0313FS 6M10Y BLC Curncy',\n 'NZD':'NDFS0F10 Curncy',\n})\n\nswap_6M_fwd_rates = bbg.fetch_series(securities=list(fwd_6M_IRS.values),\n fields='PX_LAST',\n startdate=ref_date,\n enddate=ref_date)\nswap_6M_fwd_rates.columns = [fwd_6M_IRS.index[list(fwd_6M_IRS.values).index(x)] for x in list(swap_6M_fwd_rates.columns)]\n\n\ndurations = bbg.fetch_contract_parameter(securities=list(spot_IRS.values), field='DUR_ADJ_BID')\ndurations.index = [spot_IRS.index[list(spot_IRS.values).index(x)] for x in list(durations.index)]\ndurations = durations.iloc[:,0]\n\n# calculate carry\ncarry = durations*(swap_6M_fwd_rates - swap_rates).iloc[0]/100\nplt.figure(figsize=(15,10))\ncarry.sort_values().plot(kind='bar', color='b',\n title='%s: 6M carry in 10Y rates' % ref_date)\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Carry in equity indices\n\nFor equities, we can also use the same arguemnt we used for FX forward contracts. The no-arbitrage price of a futures contract, $F_{t}$ depends on the current equity value $S_{t}$, the expected future dividend payment $D_{t+1}$ computed under the risk-neutral measure and the risk-free interest rate in the country of the equity index. So, $F_{t}=S_{t}(1+r_{f})-E^{Q}[D_{t+1}]$ and therefore:\n\n$$\nCarry_{eq} = \\frac{S_{t}}{F_{t}} -1 = \\Big(\\underbrace{ \\frac{E^{Q}[D_{t+1}]}{S_{t}}}_\\text{div yield}-r_{f}\\Big) \\frac{S_{t}}{F_{t}}\n$$\n\nIn practice, historical dividend yields can be quite different from $E^{Q}[D_{t+1}]/S_{t}$ so, calculating carry over $h$ periods in equity indices is simply:\n\n$$\nCarry_{eq}^{h} = \\Big(\\frac{S_{t}}{F_{t}}\\Big)^{1/h} -1\n$$\n\nLet's use S&P futures to illustrate:",
"_____no_output_____"
]
],
[
[
"front_month = bbg.fetch_contract_parameter(securities='SP1 Comdty', field='FUT_CUR_GEN_TICKER')\nexpiry = bbg.fetch_contract_parameter(securities=front_month.iloc[0,0] + ' Index', field='FUT_NOTICE_FIRST')\nh = (pd.to_datetime(expiry.iloc[0,0]) - pd.to_datetime('today')).days/365.25\n\nbbg_data = bbg.fetch_series(securities=['SP1 Comdty'] + ['SPX Index'],\n fields='PX_LAST',\n startdate=pd.to_datetime('today'),\n enddate=pd.to_datetime('today'))\ncarry = (bbg_data['SPX Index']/bbg_data['SP1 Comdty'])**(1/h)-1\nprint('On %s, the carry on the front month S&P future is: %s' % (carry.index[0].strftime('%d-%b-%y'),carry.iloc[0]))",
"On 28-Jan-20, the carry on the front month S&P future is: 0.0007568960130031055\n"
]
],
[
[
"### Carry in bond futures\n\nCalculating carry for bond futures is similar to calculating carry for any futures contract and it follows pretty much the same lines as calculating carry for forward FX contract. The tricky part about bond futures is that the underlying $i$ keeps changing. At any one point in time, the bond underlying a bond futures is called the *cheapest-to-deliver* (CTD) because it is the cheapest bond meeting the futures contract criteria that can be physically delivered to settle a futures contract at maturity. Associated to the CTD bond there is a conversion factor $k$ that makes the price of the bond (quoted in relation to 100 par bond) comparable with the bond futures price quoted on the screen. So, if you buy a bond via a bond future at price $F_{i}^{T}$ and the CTD bond has price $P_{i}$ at $T$, then you will profit: $F_{i}^{T} \\times k - P_{i}$. Hence, for 100 par bond, the annualized total returns on this strategy is given by:\n\n$$\nCarry_{i}^{T} = \\Big(1+\\frac{F_{i}^{T} \\times k - P_{i}}{100}\\Big)^{1/T}-1\n$$",
"_____no_output_____"
]
],
[
[
"front_month_ticker = bbg.fetch_contract_parameter(securities='TY1 Comdty', field='FUT_CUR_GEN_TICKER')\nfront_month_ticker = front_month_ticker.iloc[0,0] + ' Comdty'\nexpiry = bbg.fetch_contract_parameter(securities=front_month_ticker, field='LAST_TRADEABLE_DT')\nh = (pd.to_datetime(expiry.iloc[0,0])-pd.to_datetime('today')).days/365.25\nctd_cusip = bbg.fetch_contract_parameter(securities=front_month_ticker, field='FUT_CTD_CUSIP')\nctd_cusip = ctd_cusip.iloc[0,0] + ' Govt'\nconv_factor = bbg.fetch_contract_parameter(securities=front_month_ticker, field='FUT_CNVS_FACTOR')\nconv_factor = conv_factor.iloc[0,0]\n\nbbg_data = bbg.fetch_series(securities=[front_month_ticker,ctd_cusip],\n fields='PX_LAST',\n startdate=pd.to_datetime('today'),\n enddate=pd.to_datetime('today'))\n\nfut_price = bbg_data.iloc[0,0]*conv_factor\nbond_price = bbg_data.iloc[0,1]\ncarry = (1+(fut_price-bond_price)/100)**(1/h)-1\nprint('On %s, the carry on the front month 10Y UST future is: %s' % (pd.to_datetime('today').strftime('%d-%b-%y'),carry))",
"On 28-Jan-20, the carry on the front month 10Y UST future is: -0.001715206652355361\n"
]
],
[
[
"## Exercises\n\n#### Beginners\n\nTry to calculate carry for a few assets and create some code to run some regressions like on future returns on the carry metric or the chance in carry signal. Also, think about the case where the carry signal (or the chance in carry signal) is supposed to predict direction (so if the underlying is going up or down) and not predict the actual realized future returns.\n\n#### Intermediate\n\nCalculate a time series carry strategies as in [Baz, Granger, Harvey, Le Roux, and Rattray (2015)](https://www.cmegroup.com/education/files/dissecting-investment-strategies-in-the-cross-section-and-time-series.pdf) or in [Baltas (2017)](https://doi.org/10.1016/B978-1-78548-201-4.50013-1)\n\n\n#### Intermediate\n\nCreate a class to calculate carry for one asset class.\n\n#### Advanced\n\nCreate a class to calculate carry for all asset classes covered here in this notebook.\n\n#### Jedi Master\n\nCarry out the Advanced task above and make a contribution to [FinanceHub's signals class](https://github.com/Finance-Hub/FinanceHub/tree/master/signals).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b0b14dc87fc4befcf0754885b4fe9fdb2933d5 | 259,883 | ipynb | Jupyter Notebook | notebooks/ea_Interactive_controls.ipynb | lmcanavals/analytics_visualization | 48e5994a95889a565fa629125e2c87f5ad079ed0 | [
"CC0-1.0"
] | null | null | null | notebooks/ea_Interactive_controls.ipynb | lmcanavals/analytics_visualization | 48e5994a95889a565fa629125e2c87f5ad079ed0 | [
"CC0-1.0"
] | null | null | null | notebooks/ea_Interactive_controls.ipynb | lmcanavals/analytics_visualization | 48e5994a95889a565fa629125e2c87f5ad079ed0 | [
"CC0-1.0"
] | 5 | 2021-05-12T01:38:19.000Z | 2021-06-02T00:18:00.000Z | 62.910433 | 48,738 | 0.702847 | [
[
[
"<a href=\"https://colab.research.google.com/github/lmcanavals/analytics_visualization/blob/main/notebooks/ea_Interactive_controls.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\n\nfrom ipywidgets import interact, interactive, fixed, interact_manual\nimport ipywidgets as widgets",
"_____no_output_____"
],
[
"x = np.arange(1, 15)\nx",
"_____no_output_____"
],
[
"y = x * 5\ny",
"_____no_output_____"
],
[
"plt.plot(x, y)\nplt.axis([0, 16, -20, 100])\nplt.show()",
"_____no_output_____"
],
[
"def f(m):\n y = x * m\n plt.plot(x, y)\n plt.axis([0, 16, -20, 100])",
"_____no_output_____"
],
[
"f(5)",
"_____no_output_____"
],
[
"interact(f, m=1)",
"_____no_output_____"
],
[
"interact(f, m=(1, 7))",
"_____no_output_____"
],
[
"def f(m, b):\n y = x * m + b\n plt.plot(x, y)\n plt.axis([0, 16, -20, 100])",
"_____no_output_____"
],
[
"interact(f, m=(1, 7), b=(-10, 10))",
"_____no_output_____"
],
[
"def f(m, b, xmin, xmax, ymin, ymax):\n y = x * m + b\n plt.plot(x, y)\n plt.axis([xmin, xmax, ymin, ymax])",
"_____no_output_____"
],
[
"interact(f, m=(1, 7), b=(-10, 10),\n xmin=(-10, 10), xmax=(10, 20), ymin=(-30, 20), ymax=(10, 200))",
"_____no_output_____"
],
[
"def f(a, b):\n return a + b",
"_____no_output_____"
],
[
"interact(f, a=(1, 100), b=(1, 100))",
"_____no_output_____"
],
[
"interact(f, a=(1, 10, 0.5), b=(1, 10, 0.5))",
"_____no_output_____"
],
[
"interact(f, a=range(1, 10, 2), b=range(1, 10, 3))",
"_____no_output_____"
],
[
"data = {\n 'a': np.arange(1, 15),\n 'b': np.arange(1, 15) ** 2,\n 'c': np.arange(1, 15) + 2.5,\n 'd': np.arange(1, 15) ** .5,\n}",
"_____no_output_____"
],
[
"def f2(x, y):\n plt.scatter(data[x], data[y])",
"_____no_output_____"
],
[
"cols = ['a', 'b', 'c', 'd']\ninteract(f2, x=cols, y=cols)",
"_____no_output_____"
],
[
"def f3(val: bool):\n if val:\n return \"hola\"\n else:\n return \"chao\"",
"_____no_output_____"
],
[
"interact(f3, val=False)",
"_____no_output_____"
],
[
"#@title Example form fields\n#@markdown Forms support many types of fields.\n\nno_type_checking = '' #@param\nstring_type = '' #@param {type: \"string\"}\nslider_value = 131 #@param {type: \"slider\", min: 100, max: 200}\nnumber = 102 #@param {type: \"number\"}\ndate = '2010-11-05' #@param {type: \"date\"}\npick_me = \"monday\" #@param ['monday', 'tuesday', 'wednesday', 'thursday']\nselect_or_input = \"apples\" #@param [\"apples\", \"bananas\", \"oranges\"] {allow-input: true}\n#@markdown ---\n",
"_____no_output_____"
],
[
"from IPython.display import display, Javascript\nfrom google.colab.output import eval_js\nfrom base64 import b64decode\n\ndef take_photo(filename='photo.jpg', quality=0.8):\n js = Javascript('''\n async function takePhoto(quality) {\n const div = document.createElement('div');\n const capture = document.createElement('button');\n capture.textContent = 'Capture';\n div.appendChild(capture);\n\n const video = document.createElement('video');\n video.style.display = 'block';\n const stream = await navigator.mediaDevices.getUserMedia({video: true});\n\n document.body.appendChild(div);\n div.appendChild(video);\n video.srcObject = stream;\n await video.play();\n\n // Resize the output to fit the video element.\n google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);\n\n // Wait for Capture to be clicked.\n await new Promise((resolve) => capture.onclick = resolve);\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext('2d').drawImage(video, 0, 0);\n stream.getVideoTracks()[0].stop();\n div.remove();\n return canvas.toDataURL('image/jpeg', quality);\n }\n ''')\n display(js)\n data = eval_js('takePhoto({})'.format(quality))\n binary = b64decode(data.split(',')[1])\n with open(filename, 'wb') as f:\n f.write(binary)\n return filename",
"_____no_output_____"
],
[
"from IPython.display import Image\ntry:\n filename = take_photo()\n print('Saved to {}'.format(filename))\n \n # Show the image which was just taken.\n display(Image(filename))\nexcept Exception as err:\n # Errors will be thrown if the user does not have a webcam or if they do not\n # grant the page permission to access it.\n print(str(err))",
"_____no_output_____"
],
[
"import matplotlib.image as mpimg",
"_____no_output_____"
],
[
"img = mpimg.imread(\"photo.jpg\", format=\"jpeg\")\nplt.imshow(img)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b0b9db5c9d54d365c25d6b7e2595ea98f62791 | 23,377 | ipynb | Jupyter Notebook | 1_Basic_Python/additional_content/git_tutorial.ipynb | eo2cube/datacube_eagles | f0b1669a5010aef07b7b9f3155edc86dfb3e9cd2 | [
"MIT"
] | 1 | 2022-03-20T20:04:39.000Z | 2022-03-20T20:04:39.000Z | 1_Basic_Python/additional_content/git_tutorial.ipynb | eo2cube/datacube_eagles | f0b1669a5010aef07b7b9f3155edc86dfb3e9cd2 | [
"MIT"
] | null | null | null | 1_Basic_Python/additional_content/git_tutorial.ipynb | eo2cube/datacube_eagles | f0b1669a5010aef07b7b9f3155edc86dfb3e9cd2 | [
"MIT"
] | null | null | null | 27.796671 | 511 | 0.567951 | [
[
[
"<center>\n <img src=\"images/git.png\" width=100 padding = 0px/>\n <br>\n <span style=\"font-family:Papyrus; line-height= 0; font-size:2em;\"> An Introduction to Git and Github </span>\n<center>",
"_____no_output_____"
],
[
"# Basics",
"_____no_output_____"
],
[
"## Whats is git?\n\n- Git is a free software for distributed version management of files\n\n- Git was originally developed by Linus Torvald for source code management of the Linux kernel\n\n- It is by far the most widely used modern version control system in the world today\n\n- With its distributed architecture, Git is an example of a DVCS (Distributed Version Control System)\n\n",
"_____no_output_____"
],
[
"## What is versioning\n\nVersion control is a system that records changes to a file or set of files over time so that you can recall specific versions later. \n\nTypes\n \n - Local Version Control Systems\n - Centralized Version Control Systems\n - Distributed Version Control Systems\n ",
"_____no_output_____"
],
[
"<img src=\"images/dvcs.png\" width=400 padding = 0px/>",
"_____no_output_____"
],
[
"## Why using VCS?\n\n- Keep track of all files in a project\n- Record any changes to project files\n- Restore previous versions of files\n- Compare and analyze code\n- Merge code from different computers and different team members.\n\n<img src=\"images/gitworkflow.png\" width=500 padding = 0px/>",
"_____no_output_____"
],
[
"## Why git?\n \n - free and open software (GNU General Public License version 2.0)\n - small and fast\n - fast merging and branching\n - distributed repositories (decentralization)\n - Data security through content-hashes ",
"_____no_output_____"
],
[
"## How does it work\nI’m going to give you a lot of explanation here, but these are all the terminal commands that you really need to know to get started:\n\n```git clone```\n\n```git status```\n\n```git add```\n\n```git commit -m “ “```\n\n```git push```",
"_____no_output_____"
],
[
"<img src=\"images/git_level.png\" width=500 padding = 0px/>",
"_____no_output_____"
],
[
"## Configure your git environment\n\n`git config --global user.name \"exampleuser\"`\n\n`git config --global user.email \"[email protected]\"`\n\noptional: ```git config --global color.ui autoset``` \n\nCheck if git is configured\n\n`cat ~/.gitconfig`",
"_____no_output_____"
],
[
"## Git repository\n\nA repository is a collection of related items. In a repository or a repo are all files including their previous versions. This means that all changes made to a file are always available in the repository and it is possible to track who made which changes and when.\n\nBasically a git repository is a folder of items being tracked by Git. ",
"_____no_output_____"
],
[
"## Getting a Git Repository\n\nYou typically obtain a Git repository in one of two ways:\n\n 1. You can clone an existing Git repository from elsewhere, or\n\n 2. You can take a local directory that is currently not under version control, and turn it into a Git repository\n\n",
"_____no_output_____"
],
[
"## Clone a repository from Github\n\n<img style=\"float: right;\" width=270 src=\"images/git_clone.png\">\n\nGithub offers 4 different ways:\n 1. ZIP: Just click on the 'Download zip' button\n 2. Https: `git clone https://github.com/eo2cube/eo2cube-tools.git`\n 3. SSH: see below \n 4. GitHub CLI: ```gh https://github.com/eo2cube/eo2cube-tools.git clone```",
"_____no_output_____"
],
[
"### Via SSH\n\nCreate SSH key\n\n```ssh-keygen -t rsa -b 4096 -C \"[email protected]\"```\n\nFirst, make sure that ssh-agent is running with:\n\n```ssh-agent -s``` \n\nThen, add your private key to ssh-agent with:\n\n```ssh-add ~/.ssh/id_rsa```\n\nNext, you need to copy your public SSH key to the clipboard.\n\n```cat ~/.ssh/id_rsa.pub``` # Linux\n\n```clip < ~/.ssh/id_rsa.pub``` # Windows\n\nGo to your GitHub settings page and click the \"New SSH key\" button\n\n<img width=350 src=\"images/add-ssh.png\">\n",
"_____no_output_____"
],
[
"## Create own repository\n\nIf you want to create your own git repository you just have to create a new project folder and then initialize it as a Git repository. \n\nCreate folder with project name\n\n```mkdir project_name ```\n\nChange into folder\n\n```cd project_name```\n\nInitialize the git repository\n\n```git init ```",
"_____no_output_____"
],
[
"## Create example file\n\nNow that we've got a repository started let's add a file to it.\n\n```echo \"Hello World\" > test.html ```",
"_____no_output_____"
],
[
"## Check status\n\nNext we want to check the status of your repository. We have already added a new file, so git should already have tracked the change. In order to check the status of yout git project you can use following command:\n\n```git status```\n\n",
"_____no_output_____"
],
[
"## Staging\n\nYou use the git add command to add a change from the working directory to the staging environment. This tells git to include updates to a particular file in the next commit. However, git add has no significant effect on the repository: changes are not committed until you run git commit.\n\nStage one or multiple files\n\n```git add index.html ```\n\n```git add *.html ```\n\n```git add --all ```",
"_____no_output_____"
],
[
"### Git Commit\n\nWith the git commit command, you capture a snapshot of the project's currently deployed changes. Commits are snapshots or milestones in the timeline of your Git project. Commits are created using the ```git commit``` command, which captures the status of a project at that exact point in time, which are then committed to the local repository.\n\nCommit changes in stage to lokal repository\n\n```git commit -m \"My first commit\"```\n\nIf you want to stage and commit in one command you can also use\n\n```git commit -a -m \"some text\"```\n",
"_____no_output_____"
],
[
"<img src=\"images/commit.png\" width=500 padding = 0px/>",
"_____no_output_____"
],
[
"## Logs\n\nOnce a project history of commits is created, you can revisit and check each commit in the history. One of the best utilities for checking the history of a Git repository is the git log command.\n\n```git log```\n\n<img src=\"images/logs.png\" width=500 padding = 0px/>\n\nThis running log of commits contains the following four pieces of information:\n\n1. Commit Hash\n2. Commit Author\n3. Commit Date\n4. Commit Message\n\nIf you want more information about a single commit you can use\n\n```git show [commithash]```",
"_____no_output_____"
],
[
"# Github\n\nGitHub is a website that allows people everywhere to upload what they're working on with Git so that everyone can easily work together on the same project. GitHub which acts as the central repository for you and everyone else to share. You push your changes to it and pull down changes from others.\n\n<img src=\"images/github.jpeg\" width=200 padding = 0px/>",
"_____no_output_____"
],
[
"## Create a GitHub repository\n\n- Visit [github.com](github.com) and sign up for a free account\n\n- You want to sync your local version with one stored on GitHub.com. First you have to create a new remote repository on GitHub.com.\n\n- Go to [github.com](github.com), log in, and click the **'+'** in the top right and then click **'New repository'**\n\n- Give it a name that matches your local repository's name and a short description.",
"_____no_output_____"
],
[
"### Readmes, .gitignores and Licenses\n\nReadmes, .gitignores and Licenses are common files in many open source projects.\n\n- A **readme** describes the project. It explains what the project is, how to use it, and often times, how to contribute.\n\n- **.gitignore** is a list of files that shouldn't be tracked by Github (e.g. password list)\n\n- The **license** contains the license. The license lets others know how they can change and distribute the software. For more information on different licenses: choosealicense.com.",
"_____no_output_____"
],
[
"## Connect to local\n\nTo add a remote named 'origin' to your repository:\n\n```git remote add origin <GITHUBREPURL>```\n \nThe primary remote is typically named origin. Your local repository now knows where your remote repository, lives on GitHub's servers. \n\nYou can check out your remotes with following command\n\n```git remote -v```",
"_____no_output_____"
],
[
"## Push to remote\n\nNext you want to push everything we've done locally to your remote repository on GitHub. \n\n```git push origin main```\n\nGit has a branching system so that you can work on different parts of a project at different times. By default the first branch is named 'main'.",
"_____no_output_____"
],
[
"## Pull\n\nThe git pull command is used to download content from a remote repository and immediately update the local repository to match the content.\n\nIt is actually a combination of git fetch followed by git merge. The git pull command performs a git fetch that includes the local branch referenced by HEAD. Once the content has been downloaded, git pull starts a merge workflow. A new merge commit is created and HEAD is updated to point to the new commit.\n\n```git pull```\n\nor \n\n```git fetch <remote>``` \n\n```git merge origin/<current-branch>```",
"_____no_output_____"
],
[
"## Forks\n\nWhen you fork a repository, you're creating a copy of it on your GitHub account. Forks are used for creating your own version of a project or contributing back your changes to the original project.\n\nTo do this, click on the \"Fork\" button at the very top right of the GitHub repository web page.\n\n<img src=\"images/fork.png\" width=500 padding = 0px/>",
"_____no_output_____"
],
[
"## Branches\n\nBefore you start developing, it is advisable to create your own branch. We can use branches to isolate work when needed. This feature allows multiple people to work on one project. Git branches are effectively references to a snapshot of your changes. When you want to add a new feature or fix a bug, you create a new branch that contains your changes This way you can do your work while the main, commonly named 'master', branch stays stable. When the work is finished you merge it back to the master.\n\n<img src=\"images/gitworkflow.png\" width=500 padding = 0px/>",
"_____no_output_____"
],
[
"When you create a branch, Git copies everything from the current branch you're on and places it in the branch you've requested be made.\n\nList branches\n\n```git branch```\n\nCreate branch \n\n```git branch my-feature```\n\nIn order to switch into your branch and work you can use following:\n\n```git checkout <branch>```",
"_____no_output_____"
],
[
"## Merge branch to main\n\nIf we want our changes in the new branch to be merged in the main branch we can use the following commands\n\n```git branch```\n\n```git checkout main```\n\n```git merge feature-branch```",
"_____no_output_____"
],
[
"## Pull Requests\n\nOften when you make changes and improvements to a project you've forked, you'll want to send those changes to the maintainer of the original and request that they pull those changes into the original so that everyone can benefit from the updates—that's a pull request\n\n<img src=\"images/pull_request.png\" width=500 padding = 0px/>",
"_____no_output_____"
],
[
"# Advanced git",
"_____no_output_____"
],
[
"## View changes in files\n\nGit allows us to see the changes we've made in a file.\n\n```git diff <filename>```\n\n<img src=\"images/diff.png\" width=300 padding = 0px/>",
"_____no_output_____"
],
[
"## Edit a commit\n\nIf you want to change your last commit message (e.g. typo), you can use following command:\n\n```git commit --amend```\n\nIf have forgotten to add a file to your latest commit you can also use the git-amend command\n\n```git add new_file``` \n\n```git commit --amend```",
"_____no_output_____"
],
[
"## Clean up local commits \n\n--amend is nice, but it only allows you reword the latest commit. If you want to clean up your commits before pushing you can do this interactivly with rebase\n\n```git rebase --interactive ```",
"_____no_output_____"
],
[
"## Stash\n\nStashing code is kind of like a temporary save feature. It lets you save all your work, work on other files, and come back exactly where you left off. This is usefull for example if you have already changed some files and you don't want to lose your progress, but don't want these changes to appear in the commit history. \n\nStash your files\n\n```git stash```\n\nList your stashed files\n\n```git stash list```\n\nTo load your stash again\n\n```git stash apply```\n",
"_____no_output_____"
],
[
"## Ignore file\n\nYou can also tell git to ignore certain files, so we never accidentally commit the wrong file like passwords, to-dos, or entire database. Ignored files are tracked in a special file named ```.gitignore``` that is checked in at the root of your repository. There is no The .gitignore file must be edited and committed by hand when you have new files that you wish to ignore\n",
"_____no_output_____"
],
[
"## Undo commits\n\nRevert:\n\n- Creates a new commit from a specified commit by inverting it. Hence, adds a new commit history to the project, but it does not modify the existing one.\n\nReset:\n\n- Use this to return the entire working tree to the last committed state. \n\nThe git reset command has three options\n\n```--soft```: Tells Git to reset HEAD to another commit, so index and the working directory will not be altered in any way.\n\n```--mixed```: Just like the soft, this will reset HEAD to another commit. It will also reset the index to match it while working directory will not be touched. \n\n```--hard```: This resets everything - it resets HEAD back to another commit, resets the index to match it, and resets the working directory to match it as well.",
"_____no_output_____"
],
[
"<img src=\"images/reset_revert.png\" width=500 padding = 0px/>",
"_____no_output_____"
],
[
"Examples:\n\nIn case you want to revert your commit and still preserve your changes locally\n\n```git revert HEAD``` \n\nIn case you want to revert your commit and still preserve your changes locally\n\n```git reset --soft HEAD~1```\n\nIf you want to revert your commit and do not want to preserve your changes locally\n\n```git reset --hard HEAD~1```\n\nOr if you want to undo the latest to commits\n\n```git reset HEAD~2```",
"_____no_output_____"
],
[
"## Merge Conflicts\n\nWhen you try to merge/rebase code into other branches or other repos, and you and someone else has made a change on the same line, you'll get a conflict! \n\nIf this happens git will not allow us, to push the file\n\n<img src=\"images/conflict.png\" width=300 padding = 0px/>\n\nBut we can try to pull the from the repository. This will give us a message like this\n\n\n<img src=\"images/pull_conflict.png\" width=300 padding = 0px/>\n\nThis tells us that git will not merge the pulled changes into our local repository, because it doesn't know which change we want to keep",
"_____no_output_____"
],
[
"## How to solve this\n\nIf we want to solve this problem we can look at the problem with ```git diff <filename>```.Git already marks the conflict for us.\n\n\n<img src=\"images/diff_conflict.png\" width=300 padding = 0px/>\n\nNow we can edit the file and just delete the option we don't want to use and of course the markers by githb\n\n<img src=\"images/file_conflict.png\" width=500 padding = 0px/>\n\nAfter that we can just add and commit the conflict file again\n\n```git add <filename>```\n\n```git commit <filename> -m \"solved merge conflict\"```\n\nAnd push it\n\n```git push origin main```\n\n",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7b0c9e7a16ae6544d4a9d23f497844f0d6f8835 | 4,068 | ipynb | Jupyter Notebook | docs/notebooks/GasLeaks-NoSlider.ipynb | crose26/rosegeomap | 909fc4ecc26344c28dea078ed2bd8d59a5dd5079 | [
"MIT"
] | null | null | null | docs/notebooks/GasLeaks-NoSlider.ipynb | crose26/rosegeomap | 909fc4ecc26344c28dea078ed2bd8d59a5dd5079 | [
"MIT"
] | null | null | null | docs/notebooks/GasLeaks-NoSlider.ipynb | crose26/rosegeomap | 909fc4ecc26344c28dea078ed2bd8d59a5dd5079 | [
"MIT"
] | null | null | null | 38.742857 | 771 | 0.570059 | [
[
[
"def add_csv(csvfile):\n import pandas as pd\n import ipywidgets\n import rosegeomap\n from ipyleaflet import Marker\n \n GasLeaks = pd.read_csv(csvfile)\n GasLeaks = GasLeaks[['Date', 'Latitude', 'Longitude', 'Pipe Material']]\n GasLeaks_map = rosegeomap.Map(zoom=1)\n display(GasLeaks_map)\n \n # plot earthquake locations using widget\n def plot_GasLeaks(date):\n g = GasLeaks.loc[GasLeaks['Date'] == date]\n for (index, row) in g.iterrows():\n marker = Marker(location=[row.loc['Latitude'], row.loc['Longitude']])\n GasLeaks_map.add_layer(marker)\n print(GasLeaks.loc[GasLeaks['Date'] == date])\n \n plot_GasLeaks()",
"_____no_output_____"
],
[
"csvfile= \"GasLeaks_data.csv\"\nadd_csv(csvfile)",
"_____no_output_____"
],
[
"(5,10),(4,5),()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code"
]
] |
e7b0e257f245f683bb74a4722b5d597d070d381f | 702,529 | ipynb | Jupyter Notebook | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard | 1311eba613ce2f8feafe2cc6a2d8b0bf0c84a956 | [
"MIT"
] | null | null | null | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard | 1311eba613ce2f8feafe2cc6a2d8b0bf0c84a956 | [
"MIT"
] | null | null | null | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard | 1311eba613ce2f8feafe2cc6a2d8b0bf0c84a956 | [
"MIT"
] | 1 | 2020-07-29T03:14:19.000Z | 2020-07-29T03:14:19.000Z | 270.203462 | 60,268 | 0.893173 | [
[
[
"# Regression in Python\n\n***\nThis is a very quick run-through of some basic statistical concepts, adapted from [Lab 4 in Harvard's CS109](https://github.com/cs109/2015lab4) course. Please feel free to try the original lab if you're feeling ambitious :-) The CS109 git repository also has the solutions if you're stuck.\n\n* Linear Regression Models\n* Prediction using linear regression\n\nLinear regression is used to model and predict continuous outcomes with normal random errors. There are nearly an infinite number of different types of regression models and each regression model is typically defined by the distribution of the prediction errors (called \"residuals\") of the type of data. Logistic regression is used to model binary outcomes whereas Poisson regression is used to predict counts. In this exercise, we'll see some examples of linear regression as well as Train-test splits.\n\nThe packages we'll cover are: `statsmodels`, `seaborn`, and `scikit-learn`. While we don't explicitly teach `statsmodels` and `seaborn` in the Springboard workshop, those are great libraries to know.\n***",
"_____no_output_____"
],
[
"<img width=600 height=300 src=\"https://imgs.xkcd.com/comics/sustainable.png\"/>\n***",
"_____no_output_____"
]
],
[
[
"# special IPython command to prepare the notebook for matplotlib and other libraries\n%matplotlib inline \n\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport sklearn\nimport collections\n\nimport seaborn as sns\n\n# special matplotlib argument for improved plots\nfrom matplotlib import rcParams\nsns.set_style(\"whitegrid\")\nsns.set_context(\"poster\")\n",
"_____no_output_____"
]
],
[
[
"***\n# Part 1: Introduction to Linear Regression\n### Purpose of linear regression\n***\n<div class=\"span5 alert alert-info\">\n\n<p> Given a dataset containing predictor variables $X$ and outcome/response variable $Y$, linear regression can be used to: </p>\n<ul>\n <li> Build a <b>predictive model</b> to predict future values of $\\hat{Y}$, using new data $X^*$ where $Y$ is unknown.</li>\n <li> Model the <b>strength of the relationship</b> between each independent variable $X_i$ and $Y$</li>\n <ul>\n <li> Many times, only a subset of independent variables $X_i$ will have a linear relationship with $Y$</li>\n <li> Need to figure out which $X_i$ contributes most information to predict $Y$ </li>\n </ul>\n <li>It is in many cases, the first pass prediction algorithm for continuous outcomes. </li>\n</ul>\n</div>\n\n### A Brief Mathematical Recap\n***\n\n[Linear Regression](http://en.wikipedia.org/wiki/Linear_regression) is a method to model the relationship between a set of independent variables $X$ (also knowns as explanatory variables, features, predictors) and a dependent variable $Y$. This method assumes the relationship between each predictor $X$ is **linearly** related to the dependent variable $Y$. The most basic linear regression model contains one independent variable $X$, we'll call this the simple model. \n\n$$ Y = \\beta_0 + \\beta_1 X + \\epsilon$$\n\nwhere $\\epsilon$ is considered as an unobservable random variable that adds noise to the linear relationship. In linear regression, $\\epsilon$ is assumed to be normally distributed with a mean of 0. In other words, what this means is that on average, if we know $Y$, a roughly equal number of predictions $\\hat{Y}$ will be above $Y$ and others will be below $Y$. That is, on average, the error is zero. The residuals, $\\epsilon$ are also assumed to be \"i.i.d.\": independently and identically distributed. Independence means that the residuals are not correlated -- the residual from one prediction has no effect on the residual from another prediction. Correlated errors are common in time series analysis and spatial analyses.\n\n* $\\beta_0$ is the intercept of the linear model and represents the average of $Y$ when all independent variables $X$ are set to 0.\n\n* $\\beta_1$ is the slope of the line associated with the regression model and represents the average effect of a one-unit increase in $X$ on $Y$.\n\n* Back to the simple model. The model in linear regression is the *conditional mean* of $Y$ given the values in $X$ is expressed a linear function. \n\n$$ y = f(x) = E(Y | X = x)$$ \n\n\nhttp://www.learner.org/courses/againstallodds/about/glossary.html\n\n* The goal is to estimate the coefficients (e.g. $\\beta_0$ and $\\beta_1$). We represent the estimates of the coefficients with a \"hat\" on top of the letter. \n\n$$ \\hat{\\beta}_0, \\hat{\\beta}_1 $$\n\n* Once we estimate the coefficients $\\hat{\\beta}_0$ and $\\hat{\\beta}_1$, we can use these to predict new values of $Y$ given new data $X$.\n\n$$\\hat{y} = \\hat{\\beta}_0 + \\hat{\\beta}_1 x_1$$\n\n* Multiple linear regression is when you have more than one independent variable and the estimation involves matrices\n * $X_1$, $X_2$, $X_3$, $\\ldots$\n\n\n* How do you estimate the coefficients? \n * There are many ways to fit a linear regression model\n * The method called **least squares** is the most common methods\n * We will discuss least squares\n\n$$ Y = \\beta_0 + \\beta_1 X_1 + \\ldots + \\beta_p X_p + \\epsilon$$ \n \n### Estimating $\\hat\\beta$: Least squares\n***\n[Least squares](http://en.wikipedia.org/wiki/Least_squares) is a method that can estimate the coefficients of a linear model by minimizing the squared residuals: \n\n$$ \\mathscr{L} = \\sum_{i=1}^N \\epsilon_i = \\sum_{i=1}^N \\left( y_i - \\hat{y}_i \\right)^2 = \\sum_{i=1}^N \\left(y_i - \\left(\\beta_0 + \\beta_1 x_i\\right)\\right)^2 $$\n\nwhere $N$ is the number of observations and $\\epsilon$ represents a residual or error, ACTUAL - PREDICTED. \n\n#### Estimating the intercept $\\hat{\\beta_0}$ for the simple linear model\n\nWe want to minimize the squared residuals and solve for $\\hat{\\beta_0}$ so we take the partial derivative of $\\mathscr{L}$ with respect to $\\hat{\\beta_0}$ ",
"_____no_output_____"
],
[
"$\n\\begin{align}\n\\frac{\\partial \\mathscr{L}}{\\partial \\hat{\\beta_0}} &= \\frac{\\partial}{\\partial \\hat{\\beta_0}} \\sum_{i=1}^N \\epsilon^2 \\\\\n&= \\frac{\\partial}{\\partial \\hat{\\beta_0}} \\sum_{i=1}^N \\left( y_i - \\hat{y}_i \\right)^2 \\\\\n&= \\frac{\\partial}{\\partial \\hat{\\beta_0}} \\sum_{i=1}^N \\left( y_i - \\left( \\hat{\\beta}_0 + \\hat{\\beta}_1 x_i \\right) \\right)^2 \\\\\n&= -2 \\sum_{i=1}^N \\left( y_i - \\left( \\hat{\\beta}_0 + \\hat{\\beta}_1 x_i \\right) \\right) \\hspace{25mm} \\mbox{(by chain rule)} \\\\\n&= -2 \\sum_{i=1}^N y_i - \\hat{\\beta}_0 - \\hat{\\beta}_1 x_i \\\\\n&= -2 \\left[ \\left( \\sum_{i=1}^N y_i \\right) - n \\hat{\\beta_0} - \\hat{\\beta}_1 \\left( \\sum_{i=1}^N x_i\n\\right) \\right] \\\\\n& 2 \\left[ n \\hat{\\beta}_0 + \\hat{\\beta}_1 \\sum_{i=1}^N x_i - \\sum_{i=1}^N y_i \\right] = 0 \\hspace{20mm} \\mbox{(Set equal to 0 and solve for $\\hat{\\beta}_0$)} \\\\\n& n \\hat{\\beta}_0 + \\hat{\\beta}_1 \\sum_{i=1}^N x_i - \\sum{i=1}^N y_i = 0 \\\\\n& n \\hat{\\beta}_0 = \\sum_{i=1}^N y_i - \\hat{\\beta}_1 \\sum_{i=1}^N x_i \\\\\n& \\hat{\\beta}_0 = \\frac{\\sum_{i=1}^N y_i - \\hat{\\beta}_1 \\sum_{i=1}^N x_i}{n} \\\\\n& \\hat{\\beta}_0 = \\frac{\\sum_{i=1}^N y_i}{n} - \\hat{\\beta}_1 \\frac{\\sum_{i=1}^N x_i}{n} \\\\\n& \\boxed{\\hat{\\beta}_0 = \\bar{y} - \\hat{\\beta}_1 \\bar{x}}\n\\end{align}\n$",
"_____no_output_____"
],
[
"Using this new information, we can compute the estimate for $\\hat{\\beta}_1$ by taking the partial derivative of $\\mathscr{L}$ with respect to $\\hat{\\beta}_1$.",
"_____no_output_____"
],
[
"$\n\\begin{align}\n\\frac{\\partial \\mathscr{L}}{\\partial \\hat{\\beta_1}} &= \\frac{\\partial}{\\partial \\hat{\\beta_1}} \\sum_{i=1}^N \\epsilon^2 \\\\\n&= \\frac{\\partial}{\\partial \\hat{\\beta_1}} \\sum_{i=1}^N \\left( y_i - \\hat{y}_i \\right)^2 \\\\\n&= \\frac{\\partial}{\\partial \\hat{\\beta_1}} \\sum_{i=1}^N \\left( y_i - \\left( \\hat{\\beta}_0 + \\hat{\\beta}_1 x_i \\right) \\right)^2 \\\\\n&= 2 \\sum_{i=1}^N \\left( y_i - \\left( \\hat{\\beta}_0 + \\hat{\\beta}_1 x_i \\right) \\right) \\left( -x_i \\right) \\hspace{25mm}\\mbox{(by chain rule)} \\\\\n&= -2 \\sum_{i=1}^N x_i \\left( y_i - \\hat{\\beta}_0 - \\hat{\\beta}_1 x_i \\right) \\\\\n&= -2 \\sum_{i=1}^N x_i y_i - \\hat{\\beta}_0 x_i - \\hat{\\beta}_1 x_i^2 \\\\\n&= -2 \\sum_{i=1}^N x_i y_i - \\left( \\bar{y} - \\hat{\\beta}_1 \\bar{x} \\right) x_i - \\hat{\\beta}_1 x_i^2 \\\\\n&= -2 \\sum_{i=1}^N x_i y_i - \\bar{y}x_i + \\hat{\\beta}_1\\bar{x}x_i - \\hat{\\beta}_1 x_i^2 \\\\\n&= -2 \\left[ \\sum_{i=1}^N x_i y_i - \\bar{y} \\sum_{i=1}^N x_i + \\hat{\\beta}_1\\bar{x} - \\hat{\\beta}_1 x_i^2 \\right] \\\\\n&= -2 \\left[ \\hat{\\beta}_1 \\left\\{ \\bar{x} \\sum_{i=1}^N x_i - \\sum_{i=1}^N x_i^2 \\right\\} + \\left\\{ \\sum_{i=1}^N x_i y_i - \\bar{y} \\sum_{i=1}^N x_i \\right\\}\\right] \\\\\n& 2 \\left[ \\hat{\\beta}_1 \\left\\{ \\sum_{i=1}^N x_i^2 - \\bar{x} \\sum_{i=1}^N x_i \\right\\} + \\left\\{ \\bar{y} \\sum_{i=1}^N x_i - \\sum_{i=1}^N x_i y_i \\right\\} \\right] = 0 \\\\\n& \\hat{\\beta}_1 = \\frac{-\\left( \\bar{y} \\sum_{i=1}^N x_i - \\sum_{i=1}^N x_i y_i \\right)}{\\sum_{i=1}^N x_i^2 - \\bar{x}\\sum_{i=1}^N x_i} \\\\\n&= \\frac{\\sum_{i=1}^N x_i y_i - \\bar{y} \\sum_{i=1}^N x_i}{\\sum_{i=1}^N x_i^2 - \\bar{x} \\sum_{i=1}^N x_i} \\\\\n& \\boxed{\\hat{\\beta}_1 = \\frac{\\sum_{i=1}^N x_i y_i - \\bar{x}\\bar{y}n}{\\sum_{i=1}^N x_i^2 - n \\bar{x}^2}}\n\\end{align}\n$",
"_____no_output_____"
],
[
"The solution can be written in compact matrix notation as\n\n$$\\hat\\beta = (X^T X)^{-1}X^T Y$$ \n\nWe wanted to show you this in case you remember linear algebra, in order for this solution to exist we need $X^T X$ to be invertible. Of course this requires a few extra assumptions, $X$ must be full rank so that $X^T X$ is invertible, etc. Basically, $X^T X$ is full rank if all rows and columns are linearly independent. This has a loose relationship to variables and observations being independent respective. **This is important for us because this means that having redundant features in our regression models will lead to poorly fitting (and unstable) models.** We'll see an implementation of this in the extra linear regression example.",
"_____no_output_____"
],
[
"***\n# Part 2: Exploratory Data Analysis for Linear Relationships\n\nThe [Boston Housing data set](https://archive.ics.uci.edu/ml/datasets/Housing) contains information about the housing values in suburbs of Boston. This dataset was originally taken from the StatLib library which is maintained at Carnegie Mellon University and is now available on the UCI Machine Learning Repository. \n\n\n## Load the Boston Housing data set from `sklearn`\n***\n\nThis data set is available in the [sklearn](http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_boston.html#sklearn.datasets.load_boston) python module which is how we will access it today. ",
"_____no_output_____"
]
],
[
[
"from sklearn.datasets import load_boston\nimport pandas as pd\n\nboston = load_boston()",
"_____no_output_____"
],
[
"boston.keys()",
"_____no_output_____"
],
[
"boston.data.shape",
"_____no_output_____"
],
[
"# Print column names\nprint(boston.feature_names)",
"['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO'\n 'B' 'LSTAT']\n"
],
[
"# Print description of Boston housing data set\nprint(boston.DESCR)",
"Boston House Prices dataset\n===========================\n\nNotes\n------\nData Set Characteristics: \n\n :Number of Instances: 506 \n\n :Number of Attributes: 13 numeric/categorical predictive\n \n :Median Value (attribute 14) is usually the target\n\n :Attribute Information (in order):\n - CRIM per capita crime rate by town\n - ZN proportion of residential land zoned for lots over 25,000 sq.ft.\n - INDUS proportion of non-retail business acres per town\n - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n - NOX nitric oxides concentration (parts per 10 million)\n - RM average number of rooms per dwelling\n - AGE proportion of owner-occupied units built prior to 1940\n - DIS weighted distances to five Boston employment centres\n - RAD index of accessibility to radial highways\n - TAX full-value property-tax rate per $10,000\n - PTRATIO pupil-teacher ratio by town\n - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\n - LSTAT % lower status of the population\n - MEDV Median value of owner-occupied homes in $1000's\n\n :Missing Attribute Values: None\n\n :Creator: Harrison, D. and Rubinfeld, D.L.\n\nThis is a copy of UCI ML housing dataset.\nhttp://archive.ics.uci.edu/ml/datasets/Housing\n\n\nThis dataset was taken from the StatLib library which is maintained at Carnegie Mellon University.\n\nThe Boston house-price data of Harrison, D. and Rubinfeld, D.L. 'Hedonic\nprices and the demand for clean air', J. Environ. Economics & Management,\nvol.5, 81-102, 1978. Used in Belsley, Kuh & Welsch, 'Regression diagnostics\n...', Wiley, 1980. N.B. Various transformations are used in the table on\npages 244-261 of the latter.\n\nThe Boston house-price data has been used in many machine learning papers that address regression\nproblems. \n \n**References**\n\n - Belsley, Kuh & Welsch, 'Regression diagnostics: Identifying Influential Data and Sources of Collinearity', Wiley, 1980. 244-261.\n - Quinlan,R. (1993). Combining Instance-Based and Model-Based Learning. In Proceedings on the Tenth International Conference of Machine Learning, 236-243, University of Massachusetts, Amherst. Morgan Kaufmann.\n - many more! (see http://archive.ics.uci.edu/ml/datasets/Housing)\n\n"
]
],
[
[
"Now let's explore the data set itself. ",
"_____no_output_____"
]
],
[
[
"bos = pd.DataFrame(boston.data)\nbos.head()",
"_____no_output_____"
]
],
[
[
"There are no column names in the DataFrame. Let's add those. ",
"_____no_output_____"
]
],
[
[
"bos.columns = boston.feature_names\nbos.head()",
"_____no_output_____"
]
],
[
[
"Now we have a pandas DataFrame called `bos` containing all the data we want to use to predict Boston Housing prices. Let's create a variable called `PRICE` which will contain the prices. This information is contained in the `target` data. ",
"_____no_output_____"
]
],
[
[
"print(boston.target.shape)",
"(506,)\n"
],
[
"bos['PRICE'] = boston.target\nbos.head()",
"_____no_output_____"
]
],
[
[
"## EDA and Summary Statistics\n***\n\nLet's explore this data set. First we use `describe()` to get basic summary statistics for each of the columns. ",
"_____no_output_____"
]
],
[
[
"bos.describe()",
"_____no_output_____"
]
],
[
[
"### Scatterplots\n***\n\nLet's look at some scatter plots for three variables: 'CRIM' (per capita crime rate), 'RM' (number of rooms) and 'PTRATIO' (pupil-to-teacher ratio in schools). ",
"_____no_output_____"
]
],
[
[
"plt.scatter(bos.CRIM, bos.PRICE)\nplt.xlabel(\"Per capita crime rate by town (CRIM)\")\nplt.ylabel(\"Housing Price\")\nplt.title(\"Relationship between CRIM and Price\")",
"_____no_output_____"
],
[
"#Describe relationship\nsns.regplot(x=bos.CRIM, y=bos.PRICE, data=bos, fit_reg = True)\nstats.linregress(bos.CRIM,bos.PRICE)\nplt.xlabel(\"Per capita crime rate by town (CRIM)\")\nplt.ylabel(\"Housing Price\")\nplt.title(\"Relationship between CRIM and Price\")",
"_____no_output_____"
]
],
[
[
"The relationship between housing price and crime rate is negative. There are a few outliers, an unusual high crime rate for a same price and a higher crime rate at a high housing price.",
"_____no_output_____"
]
],
[
[
"#scatter plot between *RM* and *PRICE*\nsns.regplot(x=bos.RM, y=bos.PRICE, data=bos, fit_reg = True)\nstats.linregress(bos.RM,bos.PRICE)\nplt.xlabel(\"average number of rooms per dwelling\")\nplt.ylabel(\"Housing Price\")\nplt.title(\"Relationship between CRIM and Price\")",
"_____no_output_____"
],
[
"#Scatter plot between *PTRATIO* and *PRICE*\nsns.regplot(x=bos.PTRATIO, y=bos.PRICE, data=bos, fit_reg = True)\nstats.linregress(bos.PTRATIO,bos.PRICE)\nplt.xlabel(\"Pupil-Teacher ratio by town(PTratio)\")\nplt.ylabel(\"Housing Price\")\nplt.title(\"Relationship between PTRatio and Price\")",
"_____no_output_____"
],
[
"#Scatter plot between *B* and *PRICE*\nsns.regplot(x=bos.B, y=bos.PRICE, data=bos, fit_reg = True)\nstats.linregress(bos.B,bos.PRICE)\nplt.xlabel(\"1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\")\nplt.ylabel(\"Housing Price\")\nplt.title(\"Relationship between B and Price\")",
"_____no_output_____"
],
[
"#Scatter plot between *B* and *CRIM*\nsns.regplot(x=bos.B, y=bos.CRIM, data=bos, fit_reg = True)\nstats.linregress(bos.B,bos.CRIM)\nplt.xlabel(\"1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town\")\nplt.ylabel(\"Per capita crime rate by town (CRIM)\")\nplt.title(\"Relationship between B and CRIM\")",
"_____no_output_____"
]
],
[
[
"### Scatterplots using Seaborn\n***\n\n[Seaborn](https://stanford.edu/~mwaskom/software/seaborn/) is a cool Python plotting library built on top of matplotlib. It provides convenient syntax and shortcuts for many common types of plots, along with better-looking defaults.\n\nWe can also use [seaborn regplot](https://stanford.edu/~mwaskom/software/seaborn/tutorial/regression.html#functions-to-draw-linear-regression-models) for the scatterplot above. This provides automatic linear regression fits (useful for data exploration later on). Here's one example below.",
"_____no_output_____"
]
],
[
[
"sns.regplot(y=\"PRICE\", x=\"RM\", data=bos, fit_reg = True)\nplt.xlabel(\"average number of rooms per dwelling\")\nplt.ylabel(\"Housing Price\")",
"_____no_output_____"
]
],
[
[
"### Histograms\n***\n",
"_____no_output_____"
]
],
[
[
"plt.hist(np.log(bos.CRIM))\nplt.title(\"CRIM\")\nplt.xlabel(\"Crime rate per capita\")\nplt.ylabel(\"Frequencey\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"<p><b>Exercise:</b> Plot the histogram for *RM* and *PTRATIO* against each other, along with the two variables you picked in the previous section. We are looking for correlations in predictors here.</p>\n</div>",
"_____no_output_____"
]
],
[
[
"plt.hist(bos.CRIM)\nplt.title(\"CRIM\")\nplt.xlabel(\"Crime rate per capita\")\nplt.ylabel(\"Frequencey\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"The first histogram was created by taking the logarithm of the crime rate per capita. In comparison, the histogram above was created using the original data. Taking the log transforms the skewed data to approximately conform to normality. The transformation shows a bimodal type of distribution.",
"_____no_output_____"
]
],
[
[
"plt.hist(bos.RM)\nplt.hist(bos.PTRATIO)",
"_____no_output_____"
]
],
[
[
"## Part 3: Linear Regression with Boston Housing Data Example\n***\n\nHere, \n\n$Y$ = boston housing prices (called \"target\" data in python, and referred to as the dependent variable or response variable)\n\nand\n\n$X$ = all the other features (or independent variables, predictors or explanatory variables)\n\nwhich we will use to fit a linear regression model and predict Boston housing prices. We will use the least-squares method to estimate the coefficients. ",
"_____no_output_____"
],
[
"We'll use two ways of fitting a linear regression. We recommend the first but the second is also powerful in its features.",
"_____no_output_____"
],
[
"### Fitting Linear Regression using `statsmodels`\n***\n[Statsmodels](http://statsmodels.sourceforge.net/) is a great Python library for a lot of basic and inferential statistics. It also provides basic regression functions using an R-like syntax, so it's commonly used by statisticians. While we don't cover statsmodels officially in the Data Science Intensive workshop, it's a good library to have in your toolbox. Here's a quick example of what you could do with it. The version of least-squares we will use in statsmodels is called *ordinary least-squares (OLS)*. There are many other versions of least-squares such as [partial least squares (PLS)](https://en.wikipedia.org/wiki/Partial_least_squares_regression) and [weighted least squares (WLS)](https://en.wikipedia.org/wiki/Iteratively_reweighted_least_squares).",
"_____no_output_____"
]
],
[
[
"# Import regression modules\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import ols",
"_____no_output_____"
],
[
"# statsmodels works nicely with pandas dataframes\n# The thing inside the \"quotes\" is called a formula, a bit on that below\nm = ols('PRICE ~ RM',bos).fit()\nprint(m.summary())",
" OLS Regression Results \n==============================================================================\nDep. Variable: PRICE R-squared: 0.484\nModel: OLS Adj. R-squared: 0.483\nMethod: Least Squares F-statistic: 471.8\nDate: Mon, 26 Feb 2018 Prob (F-statistic): 2.49e-74\nTime: 21:18:29 Log-Likelihood: -1673.1\nNo. Observations: 506 AIC: 3350.\nDf Residuals: 504 BIC: 3359.\nDf Model: 1 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nIntercept -34.6706 2.650 -13.084 0.000 -39.877 -29.465\nRM 9.1021 0.419 21.722 0.000 8.279 9.925\n==============================================================================\nOmnibus: 102.585 Durbin-Watson: 0.684\nProb(Omnibus): 0.000 Jarque-Bera (JB): 612.449\nSkew: 0.726 Prob(JB): 1.02e-133\nKurtosis: 8.190 Cond. No. 58.4\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
]
],
[
[
"#### Interpreting coefficients\n\nThere is a ton of information in this output. But we'll concentrate on the coefficient table (middle table). We can interpret the `RM` coefficient (9.1021) by first noticing that the p-value (under `P>|t|`) is so small, basically zero. This means that the number of rooms, `RM`, is a statisticall significant predictor of `PRICE`. The regression coefficient for `RM` of 9.1021 means that *on average, each additional room is associated with an increase of $\\$9,100$ in house price net of the other variables*. The confidence interval gives us a range of plausible values for this average change, about ($\\$8,279, \\$9,925$), definitely not chump change. \n\nIn general, the $\\hat{\\beta_i}, i > 0$ can be interpreted as the following: \"A one unit increase in $x_i$ is associated with, on average, a $\\hat{\\beta_i}$ increase/decrease in $y$ net of all other variables.\"\n\nOn the other hand, the interpretation for the intercept, $\\hat{\\beta}_0$ is the average of $y$ given that all of the independent variables $x_i$ are 0.",
"_____no_output_____"
],
[
"#### `statsmodels` formulas\n***\nThis formula notation will seem familiar to `R` users, but will take some getting used to for people coming from other languages or are new to statistics.\n\nThe formula gives instruction for a general structure for a regression call. For `statsmodels` (`ols` or `logit`) calls you need to have a Pandas dataframe with column names that you will add to your formula. In the below example you need a pandas data frame that includes the columns named (`Outcome`, `X1`,`X2`, ...), but you don't need to build a new dataframe for every regression. Use the same dataframe with all these things in it. The structure is very simple:\n\n`Outcome ~ X1`\n\nBut of course we want to to be able to handle more complex models, for example multiple regression is doone like this:\n\n`Outcome ~ X1 + X2 + X3`\n\nIn general, a formula for an OLS multiple linear regression is\n\n`Y ~ X1 + X2 + ... + Xp`\n\nThis is the very basic structure but it should be enough to get you through the homework. Things can get much more complex. You can force statsmodels to treat variables as categorical with the `C()` function, call numpy functions to transform data such as `np.log` for extremely-skewed data, or fit a model without an intercept by including `- 1` in the formula. For a quick run-down of further uses see the `statsmodels` [help page](http://statsmodels.sourceforge.net/devel/example_formulas.html).\n",
"_____no_output_____"
],
[
"Let's see how our model actually fit our data. We can see below that there is a ceiling effect, we should probably look into that. Also, for large values of $Y$ we get underpredictions, most predictions are below the 45-degree gridlines. ",
"_____no_output_____"
]
],
[
[
"sns.regplot(bos.PRICE, m.fittedvalues)\nstats.linregress(bos.PRICE, m.fittedvalues)\nplt.ylabel(\"Predicted Values\")\nplt.xlabel(\"Actual Values\")\nplt.title(\"Comparing Predicted Values to the Actual Values\")",
"_____no_output_____"
]
],
[
[
"The majority of the predicted value match the actual values. However, the outliers that were incorrectly predicted range from 10 to 40 prices.",
"_____no_output_____"
],
[
"### Fitting Linear Regression using `sklearn`\n",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LinearRegression\nX = bos.drop('PRICE', axis = 1)\nlm = LinearRegression()\nlm",
"_____no_output_____"
]
],
[
[
"#### What can you do with a LinearRegression object? \n***\nCheck out the scikit-learn [docs here](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html). We have listed the main functions here. Most machine learning models in scikit-learn follow this same API of fitting a model with `fit`, making predictions with `predict` and the appropriate scoring function `score` for each model.",
"_____no_output_____"
],
[
"Main functions | Description\n--- | --- \n`lm.fit()` | Fit a linear model\n`lm.predit()` | Predict Y using the linear model with estimated coefficients\n`lm.score()` | Returns the coefficient of determination (R^2). *A measure of how well observed outcomes are replicated by the model, as the proportion of total variation of outcomes explained by the model*",
"_____no_output_____"
],
[
"#### What output can you get?",
"_____no_output_____"
]
],
[
[
"lm.predict",
"_____no_output_____"
]
],
[
[
"Output | Description\n--- | --- \n`lm.coef_` | Estimated coefficients\n`lm.intercept_` | Estimated intercept ",
"_____no_output_____"
],
[
"### Fit a linear model\n***\n\nThe `lm.fit()` function estimates the coefficients the linear regression using least squares. ",
"_____no_output_____"
]
],
[
[
"# Use all 13 predictors to fit linear regression model\nlm.fit(X, bos.PRICE)",
"_____no_output_____"
],
[
"lm.fit_intercept = True\nlm.fit(X, bos.PRICE)",
"_____no_output_____"
]
],
[
[
"Determining whether an intercept is important or not requires looking at t-test.",
"_____no_output_____"
],
[
"### Estimated intercept and coefficients\n\nLet's look at the estimated coefficients from the linear model using `1m.intercept_` and `lm.coef_`. \n\nAfter we have fit our linear regression model using the least squares method, we want to see what are the estimates of our coefficients $\\beta_0$, $\\beta_1$, ..., $\\beta_{13}$: \n\n$$ \\hat{\\beta}_0, \\hat{\\beta}_1, \\ldots, \\hat{\\beta}_{13} $$\n\n",
"_____no_output_____"
]
],
[
[
"print('Estimated intercept coefficient: {}'.format(lm.intercept_))",
"Estimated intercept coefficient: 36.4911032804\n"
],
[
"print('Number of coefficients: {}'.format(len(lm.coef_)))",
"Number of coefficients: 13\n"
],
[
"pd.DataFrame({'features': X.columns, 'estimatedCoefficients': lm.coef_})[['features', 'estimatedCoefficients']]",
"_____no_output_____"
]
],
[
[
"### Predict Prices \n\nWe can calculate the predicted prices ($\\hat{Y}_i$) using `lm.predict`. \n\n$$ \\hat{Y}_i = \\hat{\\beta}_0 + \\hat{\\beta}_1 X_1 + \\ldots \\hat{\\beta}_{13} X_{13} $$",
"_____no_output_____"
]
],
[
[
"# first five predicted prices\nlm.predict(X)[0:5]",
"_____no_output_____"
],
[
"#Plot a histogram of all the predicted prices.\nplt.hist(lm.predict(X))\nplt.xlabel('Predict Values')\nplt.ylabel('Frequency')\nplt.show()\nprint('Predicted Average:', lm.predict(X).mean())\nprint('Predicted Variance:', np.var(lm.predict(X)))",
"_____no_output_____"
],
[
"print(collections.Counter(lm.predict(X)))",
"Counter({20.016555805800373: 1, 24.579467855461104: 1, 6.1208572825177399: 1, 24.918604575058957: 1, 27.205513409100657: 1, 28.881081062840845: 1, 13.326355212505575: 1, 22.980248019722755: 1, 13.056778235262961: 1, 27.291321497180803: 1, 25.21974252317181: 1, 14.057495497818017: 1, 21.11758503846913: 1, 19.769753351683004: 1, 29.039383786299716: 1, 28.513863519852702: 1, 21.282593718054557: 1, 6.1682741718053826: 1, 15.803085862626411: 1, 18.132775466922684: 1, 19.284554664110924: 1, 37.206621854559664: 1, 8.7884166608377861: 1, 14.291725830814794: 1, 23.771455228784788: 1, 24.888261312979616: 1, 28.608140549203092: 1, 12.008156585670637: 1, 40.842746034391595: 1, 23.684205692273778: 1, 23.532617285111716: 1, 9.5500784360195432: 1, 21.920244141312487: 1, 12.711014724341922: 1, 22.426149366012311: 1, 20.789308603516787: 1, 23.470522031748501: 1, 19.287903175342642: 1, 13.424279334502852: 1, 12.648537775395038: 1, 18.123422937863818: 1, 27.54088053583444: 1, 23.370684025029767: 1, 30.76057665877844: 1, 19.764391373816146: 1, 16.931124190048394: 1, 21.744905948636486: 1, 19.400797373503703: 1, 15.838348605720196: 1, 25.824160348559502: 1, 11.862313638504002: 1, 6.1390311373342357: 1, 32.114599121212208: 1, 43.185827223985271: 1, 22.146334672503855: 1, 24.044795191529321: 1, 30.570231695892442: 1, 27.100344940154358: 1, 27.942882319321324: 1, 32.397697035308148: 1, 25.550022009836567: 1, 21.083988102337926: 1, 5.6227121261473378: 1, 19.108255341625078: 1, 6.568436621110763: 1, 1.6934740632762058: 1, 29.142032828539044: 1, 30.092762280212391: 1, 8.0593646728977468: 1, 20.460812057608013: 1, 13.812708138458884: 1, 27.121273537288662: 1, 15.760057721319896: 1, 17.614063837139618: 1, 35.831780677554754: 1, 19.592929315285883: 1, 18.666454961626609: 1, 22.303448784678675: 1, 34.991297014289664: 1, 24.730382184304858: 1, 33.266352214417488: 1, 34.214853851252144: 1, 22.872556052759681: 1, 28.427353758986733: 1, 15.23453780461406: 1, 25.483373227522804: 1, 25.593862148819788: 1, 15.877596722215984: 1, 13.803683172472056: 1, 9.892374899007752: 1, 20.563421113030856: 1, 20.749349494014687: 1, 24.513006167069832: 1, 35.474941222679938: 1, 25.896856635363925: 1, 20.528356890806549: 1, 24.291875938829477: 1, 22.692388797722458: 1, 24.765676829884917: 1, 24.206037924094982: 1, 15.677081383419591: 1, 13.76275950700154: 1, 20.332022386479188: 1, 28.943083504363589: 1, 25.618353591221094: 1, 23.004339941026885: 1, 9.8906435147410434: 1, 17.17173660967401: 1, 25.029860603819667: 1, 20.873099453841171: 1, 10.828258169064863: 1, 22.47833185904442: 1, 13.061155281235095: 1, 16.329935748551563: 1, 15.939266017124371: 1, 29.748023621860327: 1, 37.479460986087382: 1, 27.402412087403349: 1, 35.780623783019578: 1, 20.064010335656572: 1, 18.036140221184468: 1, 19.413062879641359: 1, 14.205974507458524: 1, 18.995826599304493: 1, 12.145030927836398: 1, 21.868206028382716: 1, 24.077964818139115: 1, 39.317688078150049: 1, 22.944389532173993: 1, 25.0420153377977: 1, 17.290350654406005: 1, 34.611634007876411: 1, 36.130463425610991: 1, 19.555359306744055: 1, 14.569332345986194: 1, 27.216743972440199: 1, 19.835114119776282: 1, 36.781113881110443: 1, 29.074883888737691: 1, 12.84121048922233: 1, 17.27585680619741: 1, 16.546570630556278: 1, 20.558846351967048: 1, 20.618088678728821: 1, 17.208565708265709: 1, 31.358262156677878: 1, 16.881943908810012: 1, 21.59311196681513: 1, 11.542904504797409: 1, 21.08526738877956: 1, 27.6293424672876: 1, 13.247715772050142: 1, 23.977090541408074: 1, 16.482385430651568: 1, 26.038072460603683: 1, 17.734659141740067: 1, 23.811349869393169: 1, 14.225735677136303: 1, 14.698636070512972: 1, 13.137074572061792: 1, 30.328745231141781: 1, 8.0789997118164578: 1, 28.406999367149012: 1, 34.402287854722751: 1, 20.079851835550539: 1, 21.699319690388879: 1, 11.516965391483982: 1, 18.734249061398614: 1, 32.7173216415243: 1, 22.395350659520098: 1, 26.656474326219794: 1, 23.111232035368793: 1, 33.184927550594452: 1, 11.811162629210919: 1, 14.489492108907541: 1, 20.163951545938033: 1, 20.543437687269204: 1, 27.792918891627764: 1, 20.225932822470313: 1, 16.937156030867953: 1, 11.498556118529699: 1, 17.008724184982121: 1, 16.39091111582006: 1, 25.570720702133897: 1, 24.484783211694577: 1, 40.566155330112835: 1, 37.070626228172678: 1, 21.297207409460377: 1, 16.170674106084416: 1, -4.2830093419227282: 1, 20.427365203822383: 1, 23.593884388430183: 1, 6.4493515374455903: 1, 23.98798089829862: 1, 18.509068577851441: 1, 22.169270725823207: 1, 30.773251834040657: 1, 19.283795700376842: 1, 8.7836673082013945: 1, 28.945647798489485: 1, 26.884290235032964: 1, 20.03651959033834: 1, 13.379164499389628: 1, 25.061521247735648: 1, 35.312602620231722: 1, 41.85122271435705: 1, 18.546155801288123: 1, 23.744466705655309: 1, 19.6322459666426: 1, 17.854352952874265: 1, 20.160757095719585: 1, 23.682096563325238: 1, 17.876188371344391: 1, 14.782782612414145: 1, 30.101515000419056: 1, 17.213072033211681: 1, 40.832562017308412: 1, 18.059004122013349: 1, 28.249136468610413: 1, 20.467642350514009: 1, 22.554129191715599: 1, 18.052710131504629: 1, 14.278823185819423: 1, 19.300001744405222: 1, 20.224443861052237: 1, 17.2102267126598: 1, 32.718976554595024: 1, 15.536971480578618: 1, 36.481214265332888: 1, 16.987166294490294: 1, 22.647913455859527: 1, 17.061522433502965: 1, 17.515032307219457: 1, 44.673399227723493: 1, 20.424674174499909: 1, 22.711730202679853: 1, 16.909674898646674: 1, 20.125752670765461: 1, 19.654230661967159: 1, 8.2560956143728532: 1, 10.875415771467434: 1, 22.139739585180955: 1, 14.43123608183565: 1, 29.114806789155175: 1, 24.118789410417421: 1, 14.339134098152293: 1, 20.528899934974454: 1, 20.544723324706553: 1, 28.3580244351033: 1, 13.690971317486827: 1, 17.810989286112488: 1, 24.858787464295755: 1, 35.8813171888672: 1, 24.052108797043786: 1, 28.647598612745782: 1, 18.25461066314157: 1, 19.544418776556896: 1, 25.534073324284961: 1, 18.920593743308082: 1, 25.203491743535544: 1, 13.599037440531987: 1, 22.474320058504006: 1, 6.8835107716412693: 1, 14.612648388438203: 1, 23.976212484959802: 1, 23.495438565830355: 1, 16.363007643810128: 1, 25.259400479378876: 1, 31.561333848230955: 1, 34.720964871911214: 1, 33.110171106911409: 1, 26.12983843827044: 1, 31.436906344555339: 1, 25.266580174646226: 1, 30.723512254688082: 1, 19.198915098601539: 1, 19.339517250225757: 1, 31.833741807948591: 1, 34.332965412040132: 1, 23.082446076714184: 1, 20.311571167258137: 1, 15.180260696352811: 1, 19.449052902198119: 1, 18.115168596058243: 1, 22.434537595949678: 1, 25.311373002269697: 1, 9.1017619808971979: 1, 11.106011606045492: 1, 34.705586469871754: 1, 34.516118183202778: 1, 29.086680032038675: 1, 22.549440982623885: 1, 39.807164584701781: 1, 32.415136248715953: 1, 20.610354427959116: 1, 33.889928992023556: 1, 25.377154499326267: 1, 11.44806825264137: 1, 3.2764648500878835: 1, 33.42696242130291: 1, 22.451106388588823: 1, 28.46348890875295: 1, 22.977435459782569: 1, 26.002597244200196: 1, 19.985637151316457: 1, 23.970767582161066: 1, 31.908526989887321: 1, 13.565111010595306: 1, 20.317503138035008: 1, 11.887040974379911: 1, 7.3931905331245744: 1, 37.583625456745793: 1, 32.920402211821475: 1, 16.319980484720041: 1, 43.294593573606079: 1, 30.677715217992773: 1, 27.04501726466092: 1, 19.54518511915704: 1, 19.534755802207012: 1, 27.045185236731314: 1, 27.658535207873282: 1, 23.817554688220298: 1, 18.573929513966849: 1, 22.218922095981625: 1, 40.340386359594042: 1, 30.291698927486937: 1, 17.261677290418149: 1, 24.562756115913803: 1, 37.157372670446996: 1, 35.558434848776422: 1, 20.627300965903888: 1, 33.286157230769824: 1, 30.997258045067746: 1, 13.396952134661468: 1, 32.707254359868699: 1, 21.286046038760908: 1, 14.01017243751923: 1, 33.436029793736161: 1, 25.566945288004277: 1, 16.592740301905518: 1, 17.288762403965016: 1, 18.376279327299695: 1, 22.378697978109194: 1, 22.049153962887814: 1, 21.248937352891922: 1, 38.043681635397974: 1, 32.140865078413889: 1, 15.462588290847609: 1, 22.721242884695428: 1, 30.365575842322563: 1, 27.369161757978077: 1, 28.625067051607523: 1, 23.340795837350534: 1, 21.774580356022899: 1, 21.325720195248131: 1, 19.862059038309706: 1, 8.222605922226407: 1, 24.297094799792397: 1, 25.509115704536214: 1, 18.938284432588645: 1, 18.53971968322001: 1, 35.450482572931634: 1, 30.832258860274809: 1, 15.829348906953921: 1, 22.199469491659976: 1, 28.429991681043855: 1, 8.5096392934435769: 1, 8.7240710758660072: 1, 18.47647772924558: 1, 27.359946418781107: 1, 18.300170132803014: 1, 18.520119872223162: 1, 21.17636040865575: 1, 32.647871629195066: 1, 14.798480672912543: 1, 3.6582516843329387: 1, 28.020713197806202: 1, 12.520404544698021: 1, 26.526526910072072: 1, 24.917090968077069: 1, 17.424682231873529: 1, 22.348702685916464: 1, 26.607490258270381: 1, 34.808657287701884: 1, 35.611419508333064: 1, 37.162963742818697: 1, 29.937629752573621: 1, 18.455242173551316: 1, 31.71297468902938: 1, 20.647453492995709: 1, 37.510513813076258: 1, 22.101509452341993: 1, 32.798767944026359: 1, 22.948235189431628: 1, 31.220223118380339: 1, 25.119487412280257: 1, 19.028038742211436: 1, 27.415978251895027: 1, 27.706101248913772: 1, 19.361451043855649: 1, 25.174614840987843: 1, 15.937809442911938: 1, 15.783276086571043: 1, 33.203569486762618: 1, 24.871430486144344: 1, 23.378625212899834: 1, 30.353593229776781: 1, 26.526200662204861: 1, 42.028796113611662: 1, 26.403268342127753: 1, 40.982363804045995: 1, 30.641397236824538: 1, 22.914941565514496: 1, 17.669755765537875: 1, 0.78021126495091409: 1, 38.79684808008799: 1, 18.508813814469164: 1, 22.485704543081344: 1, 14.592412069108985: 1, 21.324670996233976: 1, 21.589708537230582: 1, 19.203874824234337: 1, 26.997347160395787: 1, 22.359979920343335: 1, 22.741068242208819: 1, 21.55349196293875: 1, 18.407816357002481: 1, 3.9834397409417974: 1, 18.594317013030309: 1, 16.880480350077622: 1, 14.322995468737204: 1, 20.715464323550499: 1, 15.359891319499809: 1, 24.785861303958793: 1, 17.872035375138992: 1, 20.219722221957625: 1, 25.710994243503137: 1, 23.284854418807338: 1, 26.911052257384704: 1, 19.987666674728288: 1, 31.595547296019749: 1, 30.008212692345236: 1, 36.11110647123742: 1, 18.227153592609348: 1, 24.946041023954024: 1, 17.185726113907577: 1, 14.067503009748378: 1, 20.793781392182357: 1, 17.945110515916717: 1, 29.291897044113256: 1, 34.843117423072734: 1, 24.668163741964811: 1, 25.400669556459047: 1, 20.164417730515087: 1, 13.32952716005682: 1, 14.596626012435898: 1, 34.442116907399488: 1, 35.112695149881588: 1, 24.436871393646449: 1, 17.000393790016275: 1, 13.007522506879617: 1, 20.30017588452554: 1, 24.798756844669331: 1, 12.992827069447628: 1, 4.8300317049741359: 1, 21.264325488889462: 1, 32.251154678501763: 1, 24.611928505082293: 1, 20.835980961589293: 1, 32.66639270599881: 1, 19.770009770971445: 1, 16.097654269545558: 1, 19.454023398540691: 1, 28.545950040077276: 1, 31.234464806545105: 1, 27.767927334870329: 1, 21.435363501684684: 1, 22.34216285209294: 1, 22.66091019343374: 1, 9.7096551228127197: 1, 20.095205962294845: 1, 16.837424005324412: 1, 20.905348512348645: 1, 29.692549506093194: 1, 24.253065877079258: 1, 25.273367717625565: 1, 38.366056319129953: 1, 13.696517442811192: 1, 25.206465719601177: 1, 20.774405543958043: 1, 16.447829342880716: 1, 21.429854558746563: 1, 15.241798355477922: 1, 30.765685457217799: 1, 23.694541450427597: 1, 31.1481700256581: 1, 28.570648131570032: 1, 33.800048069322997: 1, 17.671045654954298: 1, 18.91981483098342: 1, 13.008415122981955: 1, 21.502837953394291: 1, 23.361060946047896: 1, 22.165939190847418: 1, 32.923293800156834: 1, 16.333000084069784: 1})\n"
],
[
"plt.scatter(bos.PRICE,lm.predict(X))\nplt.xlabel('Original PRICE')\nplt.ylabel('Predicted Price using all 13 variables')",
"_____no_output_____"
]
],
[
[
"The histogram is approximately a normal distribution. The center is 22.5328063241 and the variance is 62.5217769385, suggesting that outliers do exist; the plot above shows the outliers.",
"_____no_output_____"
],
[
"### Evaluating the Model: Sum-of-Squares\n\nThe partitioning of the sum-of-squares shows the variance in the predictions explained by the model and the variance that is attributed to error.\n\n$$TSS = ESS + RSS$$\n\n#### Residual Sum-of-Squares (aka $RSS$)\n\nThe residual sum-of-squares is one of the basic ways of quantifying how much error exists in the fitted model. We will revisit this in a bit.\n\n$$ RSS = \\sum_{i=1}^N r_i^2 = \\sum_{i=1}^N \\left(y_i - \\left(\\beta_0 + \\beta_1 x_i\\right)\\right)^2 $$",
"_____no_output_____"
]
],
[
[
"print(np.sum((bos.PRICE - lm.predict(X)) ** 2))",
"11080.2762841\n"
]
],
[
[
"#### Explained Sum-of-Squares (aka $ESS$)\n\nThe explained sum-of-squares measures the variance explained by the regression model.\n\n$$ESS = \\sum_{i=1}^N \\left( \\hat{y}_i - \\bar{y} \\right)^2 = \\sum_{i=1}^N \\left( \\left( \\hat{\\beta}_0 + \\hat{\\beta}_1 x_i \\right) - \\bar{y} \\right)^2$$",
"_____no_output_____"
]
],
[
[
"print(np.sum(lm.predict(X) - np.mean(bos.PRICE)) ** 2)",
"8.69056631064e-23\n"
]
],
[
[
"### Evaluating the Model: The Coefficient of Determination ($R^2$)\n\nThe coefficient of determination, $R^2$, tells us the percentage of the variance in the response variable $Y$ that can be explained by the linear regression model.\n\n$$ R^2 = \\frac{ESS}{TSS} $$\n\nThe $R^2$ value is one of the most common metrics that people use in describing the quality of a model, but it is important to note that *$R^2$ increases artificially as a side-effect of increasing the number of independent variables.* While $R^2$ is reported in almost all statistical packages, another metric called the *adjusted $R^2$* is also provided as it takes into account the number of variables in the model, and can sometimes even be used for non-linear regression models!\n\n$$R_{adj}^2 = 1 - \\left( 1 - R^2 \\right) \\frac{N - 1}{N - K - 1} = R^2 - \\left( 1 - R^2 \\right) \\frac{K}{N - K - 1} = 1 - \\frac{\\frac{RSS}{DF_R}}{\\frac{TSS}{DF_T}}$$\n\nwhere $N$ is the number of observations, $K$ is the number of variables, $DF_R = N - K - 1$ is the degrees of freedom associated with the residual error and $DF_T = N - 1$ is the degrees of the freedom of the total error.",
"_____no_output_____"
],
[
"### Evaluating the Model: Mean Squared Error and the $F$-Statistic\n***\nThe mean squared errors are just the *averages* of the sum-of-squares errors over their respective degrees of freedom.\n\n$$MSE = \\frac{ESS}{K}$$\n$$MSR = \\frac{RSS}{N-K-1}$$\n\n**Remember: ** Notation may vary across resources particularly the use of *R* and *E* in *RSS/ESS* and *MSR/MSE*. In some resources, E = explained and R = residual. In other resources, E = error and R = regression (explained). **This is a very important distinction that requires looking at the formula to determine which naming scheme is being used.**\n\nGiven the MSR and MSE, we can now determine whether or not the entire model we just fit is even statistically significant. We use an $F$-test for this. The null hypothesis is that all of the $\\beta$ coefficients are zero, that is, none of them have any effect on $Y$. The alternative is that *at least one* $\\beta$ coefficient is nonzero, but it doesn't tell us which one in a multiple regression:\n\n$$H_0: \\beta_i = 0, \\mbox{for all $i$} \\\\\nH_A: \\beta_i > 0, \\mbox{for some $i$}$$ \n\n$$F = \\frac{MSR}{MSE} = \\left( \\frac{R^2}{1 - R^2} \\right) \\left( \\frac{N - K - 1}{K} \\right)$$\n \nOnce we compute the $F$-statistic, we can use the $F$-distribution with $N-K$ and $K-1$ degrees of degrees of freedom to get a p-value.\n\n**Warning!** The $F$-statistic mentioned in this section is NOT the same as the F1-measure or F1-value discused in Unit 7.",
"_____no_output_____"
]
],
[
[
"lm = LinearRegression()\nlm.fit(X[['CRIM','RM','PTRATIO']],bos.PRICE)\nmseCRP = np.mean((bos.PRICE - lm.predict(X[['CRIM','RM','PTRATIO']])) ** 2)\nmsy = np.mean((bos.PRICE - np.mean(bos.PRICE)) ** 2)\nRsquareCRP = 1 - mseCRP/msy\nprint(mseCRP, RsquareCRP)",
"(34.32379656468118, 0.5934141551136983)\n"
],
[
"plt.scatter(bos.PRICE, lm.predict(X[['CRIM','RM','PTRATIO']]))\nplt.xlabel('original PRICE')\nplt.ylabel('predicted price using CRIM, RM and PTRATIO')",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(\n X, bos.PRICE, test_size=0.33, random_state = 5)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(Y_train.shape)\nprint(Y_test.shape)",
"(339, 13)\n(167, 13)\n(339,)\n(167,)\n"
],
[
"lm = LinearRegression()\nlm.fit(X=X_train, y = Y_train)\nplt.scatter(Y_test,lm.predict(X=X_test))\nplt.xlabel('Original PRICE on test set')\nplt.ylabel('Predicted price on test set using all 13 variables')",
"_____no_output_____"
],
[
"from sklearn.metrics import mean_squared_error\nmse_test = mean_squared_error(Y_test,lm.predict(X_test))\nmse_train = mean_squared_error(Y_train,lm.predict(X_train))\nprint('Mean square error for train set:',mse_train,'Mean square error for test set:', mse_test)",
"('Mean square error for train set:', 19.546758473534663, 'Mean square error for test set:', 28.54136727561901)\n"
],
[
"Rsquare_train = 1 - mse_train/np.mean((Y_train - np.mean(Y_train))**2)\nRsquare_test = 1 - mse_test/np.mean((Y_test - np.mean(Y_test))**2)\nprint('Rsquare for train set:', Rsquare_train, 'Rsquare for test set:', Rsquare_test)",
"('Rsquare for train set:', 0.75513327417799969, 'Rsquare for test set:', 0.69553880055063377)\n"
],
[
"plt.scatter(lm.predict(X_train), lm.predict(X_train) - Y_train, c='b', s=50, alpha=0.8)\nplt.scatter(lm.predict(X_test), lm.predict(X_test) - Y_test, c='r',s=50)\nplt.hlines(y = 0, xmin=0, xmax = 50)\nplt.title('Residual Plot using training (blue) and test (red) data')\nplt.ylabel('Residuals')",
"_____no_output_____"
]
],
[
[
"## Part 4: Comparing Models",
"_____no_output_____"
],
[
"During modeling, there will be times when we want to compare models to see which one is more predictive or fits the data better. There are many ways to compare models, but we will focus on two.",
"_____no_output_____"
],
[
"### The $F$-Statistic Revisited\n\nThe $F$-statistic can also be used to compare two *nested* models, that is, two models trained on the same dataset where one of the models contains a *subset* of the variables of the other model. The *full* model contains $K$ variables and the *reduced* model contains a subset of these $K$ variables. This allows us to add additional variables to a base model and then test if adding the variables helped the model fit.\n\n$$F = \\frac{\\left( \\frac{RSS_{reduced} - RSS_{full}}{DF_{reduced} - DF_{full}} \\right)}{\\left( \\frac{RSS_{full}}{DF_{full}} \\right)}$$\n\nwhere $DF_x = N - K_x - 1$ where $K_x$ is the number of variables in model $x$.",
"_____no_output_____"
],
[
"### Akaike Information Criterion (AIC)\n\nAnother statistic for comparing two models is AIC, which is based on the likelihood function and takes into account the number of variables in the model.\n\n$$AIC = 2 K - 2 \\log_e{L}$$\n\nwhere $L$ is the likelihood of the model. AIC is meaningless in the absolute sense, and is only meaningful when compared to AIC values from other models. Lower values of AIC indicate better fitting models.\n\n`statsmodels` provides the AIC in its output.",
"_____no_output_____"
]
],
[
[
"# ols - ordinary least squares\nimport statsmodels.api as sm\nfrom statsmodels.api import OLS\nm = sm.OLS(bos.PRICE, bos.RM).fit()\nprint(m.summary())",
" OLS Regression Results \n==============================================================================\nDep. Variable: PRICE R-squared: 0.901\nModel: OLS Adj. R-squared: 0.901\nMethod: Least Squares F-statistic: 4615.\nDate: Mon, 26 Feb 2018 Prob (F-statistic): 3.74e-256\nTime: 21:18:33 Log-Likelihood: -1747.1\nNo. Observations: 506 AIC: 3496.\nDf Residuals: 505 BIC: 3500.\nDf Model: 1 \nCovariance Type: nonrobust \n==============================================================================\n coef std err t P>|t| [0.025 0.975]\n------------------------------------------------------------------------------\nRM 3.6534 0.054 67.930 0.000 3.548 3.759\n==============================================================================\nOmnibus: 83.295 Durbin-Watson: 0.493\nProb(Omnibus): 0.000 Jarque-Bera (JB): 152.507\nSkew: 0.955 Prob(JB): 7.65e-34\nKurtosis: 4.894 Cond. No. 1.00\n==============================================================================\n\nWarnings:\n[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n"
]
],
[
[
"\n## Part 5: Evaluating the Model via Model Assumptions and Other Issues\n***\nLinear regression makes several assumptions. It is always best to check that these assumptions are valid after fitting a linear regression model.\n\n<div class=\"span5 alert alert-danger\">\n<ul>\n <li>**Linearity**. The dependent variable $Y$ is a linear combination of the regression coefficients and the independent variables $X$. This can be verified with a scatterplot of each $X$ vs. $Y$ and plotting correlations among $X$. Nonlinearity can sometimes be resolved by [transforming](https://onlinecourses.science.psu.edu/stat501/node/318) one or more independent variables, the dependent variable, or both. In other cases, a [generalized linear model](https://en.wikipedia.org/wiki/Generalized_linear_model) or a [nonlinear model](https://en.wikipedia.org/wiki/Nonlinear_regression) may be warranted.</li>\n <li>**Constant standard deviation**. The SD of the dependent variable $Y$ should be constant for different values of X. We can check this by plotting each $X$ against $Y$ and verifying that there is no \"funnel\" shape showing data points fanning out as $X$ increases or decreases. Some techniques for dealing with non-constant variance include weighted least squares (WLS), [robust standard errors](https://en.wikipedia.org/wiki/Heteroscedasticity-consistent_standard_errors), or variance stabilizing transformations.\n </li>\n <li> **Normal distribution for errors**. The $\\epsilon$ term we discussed at the beginning are assumed to be normally distributed. This can be verified with a fitted values vs. residuals plot and verifying that there is no pattern, and with a quantile plot.\n $$ \\epsilon_i \\sim N(0, \\sigma^2)$$\nSometimes the distributions of responses $Y$ may not be normally distributed at any given value of $X$. e.g. skewed positively or negatively. </li>\n<li> **Independent errors**. The observations are assumed to be obtained independently.\n <ul>\n <li>e.g. Observations across time may be correlated\n </ul>\n</li>\n</ul> \n\n</div>\n\nThere are some other issues that are important investigate with linear regression models.\n\n<div class=\"span5 alert alert-danger\">\n<ul>\n <li>**Correlated Predictors:** Care should be taken to make sure that the independent variables in a regression model are not too highly correlated. Correlated predictors typically do not majorly affect prediction, but do inflate standard errors of coefficients making interpretation unreliable. Common solutions are dropping the least important variables involved in the correlations, using regularlization, or, when many predictors are highly correlated, considering a dimension reduction technique such as principal component analysis (PCA).\n <li>**Influential Points:** Data points that have undue influence on the regression model. These points can be high leverage points or outliers. Such points are typically removed and the regression model rerun.\n</ul>\n</div>\n",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.linear_model import LinearRegression\nlm = LinearRegression()\nRsquared = cross_val_score(estimator =lm, X=bos.iloc[:,:-1], y = bos.PRICE,cv=5)\nprint('Rsquared:', Rsquared)",
"('Rsquared:', array([ 0.63861069, 0.71334432, 0.58645134, 0.07842495, -0.26312455]))\n"
]
],
[
[
"Interesting. I got a R^2 that is negative, meaning that this model fits worse than a horizontal line. ",
"_____no_output_____"
]
],
[
[
"np.mean(Rsquares) ",
"_____no_output_____"
],
[
"from sklearn.model_selection import KFold\nY=bos.PRICE\nkf=KFold(n_splits=4)\nfor train, test in kf.split(X):\n X_train, X_test= X.iloc[train], X.iloc[test]\nfor train, test in kf.split(Y):\n Y_train, Y_test = Y.iloc[train], Y.iloc[test]\nlm.fit(X_train, Y_train)\nlm.predict(X_test)\nprint('Testing Set MSE:', np.mean((Y_test - lm.predict(X_test))**2),'Training Set MSE :', np.mean((Y_train - lm.predict(X_train))**2))",
"('Testing Set MSE:', 61.59301573238758, 'Training Set MSE :', 21.198414282847672)\n"
]
],
[
[
"This is a mini-project to practice the skills I learned. ",
"_____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"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e7b0e67c29f1bcd6a285e6f55409cfe7605c6fc6 | 11,954 | ipynb | Jupyter Notebook | 03_getting_started_with_iris.ipynb | ArkoMukherjee25/Machine-Learning | aa5e6d2d6258cb2cedaa2eb5cecdd1a414c29a8e | [
"MIT"
] | 1 | 2019-01-21T10:20:35.000Z | 2019-01-21T10:20:35.000Z | 03_getting_started_with_iris.ipynb | ArkoMukherjee25/Machine-Learning | aa5e6d2d6258cb2cedaa2eb5cecdd1a414c29a8e | [
"MIT"
] | null | null | null | 03_getting_started_with_iris.ipynb | ArkoMukherjee25/Machine-Learning | aa5e6d2d6258cb2cedaa2eb5cecdd1a414c29a8e | [
"MIT"
] | 1 | 2019-01-21T10:01:19.000Z | 2019-01-21T10:01:19.000Z | 25.652361 | 125 | 0.435754 | [
[
[
"# Getting started in scikit-learn with the famous iris dataset ",
"_____no_output_____"
],
[
"## Objectives\n\n- What is the famous iris dataset, and how does it relate to machine learning?\n- How do we load the iris dataset into scikit-learn?\n- How do we describe a dataset using machine learning terminology?\n- What are scikit-learn's four key requirements for working with data?",
"_____no_output_____"
],
[
"## Introducing the iris dataset",
"_____no_output_____"
],
[
"- 50 samples of 3 different species of iris (150 samples total)\n- Measurements: sepal length, sepal width, petal length, petal width",
"_____no_output_____"
]
],
[
[
"from IPython.display import IFrame\nIFrame('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', width=300, height=200)",
"_____no_output_____"
]
],
[
[
"## Machine learning on the iris dataset\n\n- Framed as a **supervised learning** problem: Predict the species of an iris using the measurements\n- Famous dataset for machine learning because prediction is **easy**",
"_____no_output_____"
],
[
"## Loading the iris dataset into scikit-learn",
"_____no_output_____"
]
],
[
[
"# import load_iris function from datasets module\nfrom sklearn.datasets import load_iris",
"_____no_output_____"
],
[
"# save \"bunch\" object containing iris dataset and its attributes\niris = load_iris()\ntype(iris)",
"_____no_output_____"
],
[
"# print the iris data\nprint(iris.data)",
"[[5.1 3.5 1.4 0.2]\n [4.9 3. 1.4 0.2]\n [4.7 3.2 1.3 0.2]\n [4.6 3.1 1.5 0.2]\n [5. 3.6 1.4 0.2]\n [5.4 3.9 1.7 0.4]\n [4.6 3.4 1.4 0.3]\n [5. 3.4 1.5 0.2]\n [4.4 2.9 1.4 0.2]\n [4.9 3.1 1.5 0.1]\n [5.4 3.7 1.5 0.2]\n [4.8 3.4 1.6 0.2]\n [4.8 3. 1.4 0.1]\n [4.3 3. 1.1 0.1]\n [5.8 4. 1.2 0.2]\n [5.7 4.4 1.5 0.4]\n [5.4 3.9 1.3 0.4]\n [5.1 3.5 1.4 0.3]\n [5.7 3.8 1.7 0.3]\n [5.1 3.8 1.5 0.3]\n [5.4 3.4 1.7 0.2]\n [5.1 3.7 1.5 0.4]\n [4.6 3.6 1. 0.2]\n [5.1 3.3 1.7 0.5]\n [4.8 3.4 1.9 0.2]\n [5. 3. 1.6 0.2]\n [5. 3.4 1.6 0.4]\n [5.2 3.5 1.5 0.2]\n [5.2 3.4 1.4 0.2]\n [4.7 3.2 1.6 0.2]\n [4.8 3.1 1.6 0.2]\n [5.4 3.4 1.5 0.4]\n [5.2 4.1 1.5 0.1]\n [5.5 4.2 1.4 0.2]\n [4.9 3.1 1.5 0.1]\n [5. 3.2 1.2 0.2]\n [5.5 3.5 1.3 0.2]\n [4.9 3.1 1.5 0.1]\n [4.4 3. 1.3 0.2]\n [5.1 3.4 1.5 0.2]\n [5. 3.5 1.3 0.3]\n [4.5 2.3 1.3 0.3]\n [4.4 3.2 1.3 0.2]\n [5. 3.5 1.6 0.6]\n [5.1 3.8 1.9 0.4]\n [4.8 3. 1.4 0.3]\n [5.1 3.8 1.6 0.2]\n [4.6 3.2 1.4 0.2]\n [5.3 3.7 1.5 0.2]\n [5. 3.3 1.4 0.2]\n [7. 3.2 4.7 1.4]\n [6.4 3.2 4.5 1.5]\n [6.9 3.1 4.9 1.5]\n [5.5 2.3 4. 1.3]\n [6.5 2.8 4.6 1.5]\n [5.7 2.8 4.5 1.3]\n [6.3 3.3 4.7 1.6]\n [4.9 2.4 3.3 1. ]\n [6.6 2.9 4.6 1.3]\n [5.2 2.7 3.9 1.4]\n [5. 2. 3.5 1. ]\n [5.9 3. 4.2 1.5]\n [6. 2.2 4. 1. ]\n [6.1 2.9 4.7 1.4]\n [5.6 2.9 3.6 1.3]\n [6.7 3.1 4.4 1.4]\n [5.6 3. 4.5 1.5]\n [5.8 2.7 4.1 1. ]\n [6.2 2.2 4.5 1.5]\n [5.6 2.5 3.9 1.1]\n [5.9 3.2 4.8 1.8]\n [6.1 2.8 4. 1.3]\n [6.3 2.5 4.9 1.5]\n [6.1 2.8 4.7 1.2]\n [6.4 2.9 4.3 1.3]\n [6.6 3. 4.4 1.4]\n [6.8 2.8 4.8 1.4]\n [6.7 3. 5. 1.7]\n [6. 2.9 4.5 1.5]\n [5.7 2.6 3.5 1. ]\n [5.5 2.4 3.8 1.1]\n [5.5 2.4 3.7 1. ]\n [5.8 2.7 3.9 1.2]\n [6. 2.7 5.1 1.6]\n [5.4 3. 4.5 1.5]\n [6. 3.4 4.5 1.6]\n [6.7 3.1 4.7 1.5]\n [6.3 2.3 4.4 1.3]\n [5.6 3. 4.1 1.3]\n [5.5 2.5 4. 1.3]\n [5.5 2.6 4.4 1.2]\n [6.1 3. 4.6 1.4]\n [5.8 2.6 4. 1.2]\n [5. 2.3 3.3 1. ]\n [5.6 2.7 4.2 1.3]\n [5.7 3. 4.2 1.2]\n [5.7 2.9 4.2 1.3]\n [6.2 2.9 4.3 1.3]\n [5.1 2.5 3. 1.1]\n [5.7 2.8 4.1 1.3]\n [6.3 3.3 6. 2.5]\n [5.8 2.7 5.1 1.9]\n [7.1 3. 5.9 2.1]\n [6.3 2.9 5.6 1.8]\n [6.5 3. 5.8 2.2]\n [7.6 3. 6.6 2.1]\n [4.9 2.5 4.5 1.7]\n [7.3 2.9 6.3 1.8]\n [6.7 2.5 5.8 1.8]\n [7.2 3.6 6.1 2.5]\n [6.5 3.2 5.1 2. ]\n [6.4 2.7 5.3 1.9]\n [6.8 3. 5.5 2.1]\n [5.7 2.5 5. 2. ]\n [5.8 2.8 5.1 2.4]\n [6.4 3.2 5.3 2.3]\n [6.5 3. 5.5 1.8]\n [7.7 3.8 6.7 2.2]\n [7.7 2.6 6.9 2.3]\n [6. 2.2 5. 1.5]\n [6.9 3.2 5.7 2.3]\n [5.6 2.8 4.9 2. ]\n [7.7 2.8 6.7 2. ]\n [6.3 2.7 4.9 1.8]\n [6.7 3.3 5.7 2.1]\n [7.2 3.2 6. 1.8]\n [6.2 2.8 4.8 1.8]\n [6.1 3. 4.9 1.8]\n [6.4 2.8 5.6 2.1]\n [7.2 3. 5.8 1.6]\n [7.4 2.8 6.1 1.9]\n [7.9 3.8 6.4 2. ]\n [6.4 2.8 5.6 2.2]\n [6.3 2.8 5.1 1.5]\n [6.1 2.6 5.6 1.4]\n [7.7 3. 6.1 2.3]\n [6.3 3.4 5.6 2.4]\n [6.4 3.1 5.5 1.8]\n [6. 3. 4.8 1.8]\n [6.9 3.1 5.4 2.1]\n [6.7 3.1 5.6 2.4]\n [6.9 3.1 5.1 2.3]\n [5.8 2.7 5.1 1.9]\n [6.8 3.2 5.9 2.3]\n [6.7 3.3 5.7 2.5]\n [6.7 3. 5.2 2.3]\n [6.3 2.5 5. 1.9]\n [6.5 3. 5.2 2. ]\n [6.2 3.4 5.4 2.3]\n [5.9 3. 5.1 1.8]]\n"
]
],
[
[
"## Machine learning terminology\n\n- Each row is an **observation** (also known as: sample, example, instance, record)\n- Each column is a **feature** (also known as: predictor, attribute, independent variable, input, regressor, covariate)",
"_____no_output_____"
]
],
[
[
"# print the names of the four features\nprint(iris.feature_names)",
"['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']\n"
],
[
"# print integers representing the species of each observation\nprint(iris.target)",
"[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2\n 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2\n 2 2]\n"
],
[
"# print the encoding scheme for species: 0 = setosa, 1 = versicolor, 2 = virginica\nprint(iris.target_names)",
"['setosa' 'versicolor' 'virginica']\n"
]
],
[
[
"- Each value we are predicting is the **response** (also known as: target, outcome, label, dependent variable)\n- **Classification** is supervised learning in which the response is categorical\n- **Regression** is supervised learning in which the response is ordered and continuous",
"_____no_output_____"
],
[
"## Requirements for working with data in scikit-learn\n\n1. Features and response are **separate objects**\n2. Features and response should be **numeric**\n3. Features and response should be **NumPy arrays**\n4. Features and response should have **specific shapes**",
"_____no_output_____"
]
],
[
[
"# check the types of the features and response\nprint(type(iris.data))\nprint(type(iris.target))",
"<class 'numpy.ndarray'>\n<class 'numpy.ndarray'>\n"
],
[
"# check the shape of the features (first dimension = number of observations, second dimensions = number of features)\nprint(iris.data.shape)",
"(150, 4)\n"
],
[
"# check the shape of the response (single dimension matching the number of observations)\nprint(iris.target.shape)",
"(150,)\n"
],
[
"# store feature matrix in \"X\"\nX = iris.data\n\n# store response vector in \"y\"\ny = iris.target",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7b0ec301d587783ef0b6ed4fd5e2ac10c207562 | 43,189 | ipynb | Jupyter Notebook | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python | 72a6107475d23dd0f3f63c244a985e2e80f2076e | [
"MIT"
] | null | null | null | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python | 72a6107475d23dd0f3f63c244a985e2e80f2076e | [
"MIT"
] | null | null | null | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python | 72a6107475d23dd0f3f63c244a985e2e80f2076e | [
"MIT"
] | null | null | null | 55.799742 | 10,080 | 0.79041 | [
[
[
"<h1 align=center><font size = 5>PYTHON OBJECTS AND CLASSES</font></h1>",
"_____no_output_____"
],
[
"# Welcome!\n\nObjects in programming are like objects in real life. Like life, there are different classes of objects. In this notebook, we will create two classes called Circle and Rectangle. By the end of this notebook, you will have a better idea about :\n\n-what a class is\n\n-what an attribute is\n\n-what a method is\n\nDon’t worry if you don’t get it the first time, as much of the terminology is confusing. Don’t forget to do the practice tests in the notebook.\n",
"_____no_output_____"
],
[
"### Introduction \n\n#### Creating a Class \n The first part of creating a class is giving it a name: In this notebook, we will create two classes, Circle and Rectangle. We need to determine all the data that make up that class, and we call that an attribute. Think about this step as creating a blue print that we will use to create objects. In figure 1 we see two classes, circle and rectangle. Each has their attributes, they are variables. The class circle has the attribute radius and colour, while the rectangle has the attribute height and width. Let’s use the visual examples of these shapes before we get to the code, as this will help you get accustomed to the vocabulary.\n\n\n",
"_____no_output_____"
],
[
" <a ><img src = \"O1.png\" width = 500, align = \"center\"></a>\n <h4 align=center>\n",
"_____no_output_____"
],
[
"#### Figure 1: Classes circle and rectangle, and each has their own attributes. The class circle has the attribute radius and colour, the rectangle has the attribute height and width. \n",
"_____no_output_____"
],
[
"#### Instances of a Class: Objects and Attributes",
"_____no_output_____"
],
[
"An instance of an object is the realisation of a class, and in figure 2 we see three instances of the class circle. We give each object a name: red circle, yellow circle and green circle. Each object has different attributes, so let's focus on the attribute of colour for each object.",
"_____no_output_____"
],
[
" <a ><img src = \"o2.png\" width = 500, align = \"center\"></a>\n <h4 align=center>\n Figure 2: Three instances of the class circle or three objects of type circle. \n\n\n",
"_____no_output_____"
],
[
" The colour attribute for the red circle is the colour red, for the green circle object the colour attribute is green, and for the yellow circle the colour attribute is yellow. \n",
"_____no_output_____"
],
[
"#### Methods \n\nMethods give you a way to change or interact with the object; they are functions that interact with objects. For example, let’s say we would like to increase the radius by a specified amount of a circle. We can create a method called **add_radius(r)** that increases the radius by **r**. This is shown in figure 3, where after applying the method to the \"orange circle object\", the radius of the object increases accordingly. The “dot” notation means to apply the method to the object, which is essentially applying a function to the information in the object.",
"_____no_output_____"
],
[
"# Creating a Class",
"_____no_output_____"
],
[
"Now we are going to create a class circle, but first, we are going to import a library to draw the objects: ",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\n%matplotlib inline \n",
"_____no_output_____"
]
],
[
[
" The first step in creating your own class is to use the **class** keyword, then the name of the class. In this course the class parent will always be object: \n",
"_____no_output_____"
],
[
"The next step is a special method called a constructor **__init__**, which is used to initialize the object. The input are data attributes. The term **self** contains all the attributes in the set. For example the **self.color** gives the value of the attribute colour and **self.radius** will give you the radius of the object. We also have the method **add_radius()** with the parameter **r**, the method adds the value of **r** to the attribute radius. To access the radius we use the sintax **self.radius**. \n\n",
"_____no_output_____"
],
[
"The actual object is shown below. We include the method drawCircle to display the image of a circle. We set the default radius to 3 and the default colour to blue:",
"_____no_output_____"
]
],
[
[
"class Circle(object):\n \n def __init__(self,radius=3,color='blue'):\n \n self.radius=radius\n self.color=color \n \n def add_radius(self,r):\n \n self.radius=self.radius+r\n return(self.radius)\n def drawCircle(self):\n \n plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))\n plt.axis('scaled')\n plt.show() ",
"_____no_output_____"
]
],
[
[
"### Creating an instance of a class Circle",
"_____no_output_____"
],
[
" Let’s create the object **RedCircle** of type Circle to do the following:",
"_____no_output_____"
]
],
[
[
"RedCircle=Circle(10,'red')",
"_____no_output_____"
]
],
[
[
"We can use the **dir** command to get a list of the object's methods. Many of them are default Python methods.",
"_____no_output_____"
]
],
[
[
"dir(RedCircle)",
"_____no_output_____"
]
],
[
[
"We can look at the data attributes of the object: ",
"_____no_output_____"
]
],
[
[
"RedCircle.radius",
"_____no_output_____"
],
[
"RedCircle.color",
"_____no_output_____"
]
],
[
[
" We can change the object's data attributes: ",
"_____no_output_____"
]
],
[
[
"RedCircle.radius=1",
"_____no_output_____"
],
[
"RedCircle.radius",
"_____no_output_____"
]
],
[
[
" We can draw the object by using the method **drawCircle()**:",
"_____no_output_____"
]
],
[
[
"RedCircle.drawCircle()",
"_____no_output_____"
]
],
[
[
"We can increase the radius of the circle by applying the method **add_radius()**. Let increases the radius by 2 and then by 5: ",
"_____no_output_____"
]
],
[
[
"print('Radius of object:',RedCircle.radius)\nRedCircle.add_radius(2)\nprint('Radius of object of after applying the method add_radius(2):',RedCircle.radius)\nRedCircle.add_radius(5)\nprint('Radius of object of after applying the method add_radius(5):',RedCircle.radius)",
"Radius of object: 1\nRadius of object of after applying the method add_radius(2): 3\nRadius of object of after applying the method add_radius(5): 8\n"
]
],
[
[
" Let’s create a blue circle. As the default colour is blue, all we have to do is specify what the radius is:",
"_____no_output_____"
]
],
[
[
"BlueCircle=Circle(radius=100)",
"_____no_output_____"
]
],
[
[
" As before we can access the attributes of the instance of the class by using the dot notation:",
"_____no_output_____"
]
],
[
[
"BlueCircle.radius",
"_____no_output_____"
],
[
"BlueCircle.color",
"_____no_output_____"
]
],
[
[
" We can draw the object by using the method **drawCircle()**:",
"_____no_output_____"
]
],
[
[
"BlueCircle.drawCircle()",
"_____no_output_____"
]
],
[
[
" Compare the x and y axis of the figure to the figure for **RedCircle**; they are different.",
"_____no_output_____"
],
[
"### The Rectangle Class \n\nLet's create a class rectangle with the attributes of height, width and colour. We will only add the method to draw the rectangle object:\n",
"_____no_output_____"
]
],
[
[
"class Rectangle(object):\n \n def __init__(self,width=2,height =3,color='r'):\n self.height=height \n self.width=width\n self.color=color\n \n def drawRectangle(self):\n import matplotlib.pyplot as plt\n plt.gca().add_patch(plt.Rectangle((0, 0),self.width, self.height ,fc=self.color))\n plt.axis('scaled')\n plt.show()",
"_____no_output_____"
]
],
[
[
" Let’s create the object **SkinnyBlueRectangle** of type Rectangle. Its width will be 2 and height will be 3, and the colour will be blue:\n",
"_____no_output_____"
]
],
[
[
"SkinnyBlueRectangle= Rectangle(2,10,'blue')",
"_____no_output_____"
]
],
[
[
" As before we can access the attributes of the instance of the class by using the dot notation:",
"_____no_output_____"
]
],
[
[
"SkinnyBlueRectangle.height ",
"_____no_output_____"
],
[
"SkinnyBlueRectangle.width",
"_____no_output_____"
],
[
"SkinnyBlueRectangle.color",
"_____no_output_____"
]
],
[
[
" We can draw the object:",
"_____no_output_____"
]
],
[
[
"SkinnyBlueRectangle.drawRectangle()",
"_____no_output_____"
]
],
[
[
"Let’s create the object “FatYellowRectangle” of type Rectangle :",
"_____no_output_____"
]
],
[
[
"FatYellowRectangle = Rectangle(20,5,'yellow')",
"_____no_output_____"
]
],
[
[
" We can access the attributes of the instance of the class by using the dot notation:",
"_____no_output_____"
]
],
[
[
"FatYellowRectangle.height ",
"_____no_output_____"
],
[
"FatYellowRectangle.width",
"_____no_output_____"
],
[
"FatYellowRectangle.color",
"_____no_output_____"
]
],
[
[
" We can draw the object:",
"_____no_output_____"
]
],
[
[
"FatYellowRectangle.drawRectangle()",
"_____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",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b114438a25ebec0c6dcfcd73afe553e5265d4d | 601,205 | ipynb | Jupyter Notebook | nb/base_gan.ipynb | raxman0721/kaggle-dog_gan | 6089cb419537c95acda24c74ab41df91bb897777 | [
"MIT"
] | null | null | null | nb/base_gan.ipynb | raxman0721/kaggle-dog_gan | 6089cb419537c95acda24c74ab41df91bb897777 | [
"MIT"
] | null | null | null | nb/base_gan.ipynb | raxman0721/kaggle-dog_gan | 6089cb419537c95acda24c74ab41df91bb897777 | [
"MIT"
] | null | null | null | 259.812014 | 152,648 | 0.874277 | [
[
[
"# Pytorch Rals-C-SAGAN\n* Ra - Relativistic Average;\n* Ls - Least Squares;\n* C - Conditional;\n* SA - Self-Attention;\n* DCGAN - Deep Convolutional Generative Adversarial Network\n\n<br>\nReferences:\n* https://www.kaggle.com/speedwagon/ralsgan-dogs\n* https://www.kaggle.com/cdeotte/dog-breed-cgan\n* https://github.com/eriklindernoren/PyTorch-GAN/blob/master/implementations/cgan/cgan.py\n* https://github.com/voletiv/self-attention-GAN-pytorch/blob/master/sagan_models.py",
"_____no_output_____"
]
],
[
[
"loss_calculation = 'hinge'\n# loss_calculation = 'rals'\nbatch_size = 32\ncrop_dog = True #犬のアノテーションを使用するかどうか\nnoisy_label = True #ラベルスムージング的な\nR_uni = (0.70, 0.95) #ラベルスムージングするときのrealの範囲\nF_uni = (0.05, 0.15) #ラベルスムージングするときのfakeの範囲\nGcbn = False # generatorにConditionalBatchNorm2dを使うかどうか\nGlrelu = True # generatorにLeakyLeLUを使うかどうか\nflip_p = 0.5 # RandomHorizontalFlipの割合\nn_epochs = 301\nuse_pixelnorm = True\n\n# optimizerゾーン\nG_opt = 'adaboundw'\n# G_opt = 'adam'\nG_lr = 0.0002\nG_betas = (0.5, 0.99) #ada系のみ\nG_final_lr=0.5 # adaboundのみ\nG_weight_decay=5e-4 # adaboundのみ\nG_eta_min = 0.00001 # コサインアニーリングのパラメタ\n\nD_opt = 'adaboundw'\n# D_opt = 'adam'\n# D_opt = 'SGD'\nD_lr = 0.00005\nD_betas = (0.1, 0.99) #ada系のみ\nD_final_lr=0.1 # adaboundのみ\nD_weight_decay=0 #adaboundのみ\nD_eta_min = 0.00005",
"_____no_output_____"
],
[
"import os\nimport PIL\nimport torchvision\nimport torchvision.datasets as dset\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nimport xml.etree.ElementTree as ET\nimport numpy as np\n\nimport imgaug as ia\nimport imgaug.augmenters as iaa\n\nimport matplotlib.pyplot as plt\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.optim as optim\nfrom torch.nn.init import xavier_uniform_\n\n\nimport time\nimport torch\nimport torch.nn as nn\n\nimport torch.nn.parallel\nimport torch.optim as optim\nfrom torch.nn.utils import spectral_norm\nimport torch.utils.data\nimport torchvision\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\nimport matplotlib.image as mpimg\n\nimport torch.nn.functional as F\nfrom torch.nn import Parameter\n\n\nimport numpy as np\nimport os\nimport gzip, pickle\nimport tensorflow as tf\nfrom scipy import linalg\nimport pathlib\nimport urllib\nimport warnings\nfrom tqdm import tqdm\nfrom PIL import Image\nimport zipfile\n\nfrom tqdm import tqdm_notebook as tqdm\n\n\nkernel_start_time = time.perf_counter()",
"_____no_output_____"
]
],
[
[
"# Helper Blocks",
"_____no_output_____"
]
],
[
[
"import math\nimport torch\nfrom torch.optim import Optimizer\n\n\nclass AdaBound(Optimizer):\n \"\"\"Implements AdaBound algorithm.\n It has been proposed in `Adaptive Gradient Methods with Dynamic Bound of Learning Rate`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): Adam learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n final_lr (float, optional): final (SGD) learning rate (default: 0.1)\n gamma (float, optional): convergence speed of the bound functions (default: 1e-3)\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsbound (boolean, optional): whether to use the AMSBound variant of this algorithm\n .. Adaptive Gradient Methods with Dynamic Bound of Learning Rate:\n https://openreview.net/forum?id=Bkg3g2R9FX\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), final_lr=0.1, gamma=1e-3,\n eps=1e-8, weight_decay=0, amsbound=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n if not 0.0 <= final_lr:\n raise ValueError(\"Invalid final learning rate: {}\".format(final_lr))\n if not 0.0 <= gamma < 1.0:\n raise ValueError(\"Invalid gamma parameter: {}\".format(gamma))\n defaults = dict(lr=lr, betas=betas, final_lr=final_lr, gamma=gamma, eps=eps,\n weight_decay=weight_decay, amsbound=amsbound)\n super(AdaBound, self).__init__(params, defaults)\n\n self.base_lrs = list(map(lambda group: group['lr'], self.param_groups))\n\n def __setstate__(self, state):\n super(AdaBound, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsbound', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group, base_lr in zip(self.param_groups, self.base_lrs):\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError(\n 'Adam does not support sparse gradients, please consider SparseAdam instead')\n amsbound = group['amsbound']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsbound:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsbound:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n grad = grad.add(group['weight_decay'], p.data)\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsbound:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n\n # Applies bounds on actual learning rate\n # lr_scheduler cannot affect final_lr, this is a workaround to apply lr decay\n final_lr = group['final_lr'] * group['lr'] / base_lr\n lower_bound = final_lr * (1 - 1 / (group['gamma'] * state['step'] + 1))\n upper_bound = final_lr * (1 + 1 / (group['gamma'] * state['step']))\n step_size = torch.full_like(denom, step_size)\n step_size.div_(denom).clamp_(lower_bound, upper_bound).mul_(exp_avg)\n\n p.data.add_(-step_size)\n\n return loss\n\nclass AdaBoundW(Optimizer):\n \"\"\"Implements AdaBound algorithm with Decoupled Weight Decay (arxiv.org/abs/1711.05101)\n It has been proposed in `Adaptive Gradient Methods with Dynamic Bound of Learning Rate`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): Adam learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n final_lr (float, optional): final (SGD) learning rate (default: 0.1)\n gamma (float, optional): convergence speed of the bound functions (default: 1e-3)\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsbound (boolean, optional): whether to use the AMSBound variant of this algorithm\n .. Adaptive Gradient Methods with Dynamic Bound of Learning Rate:\n https://openreview.net/forum?id=Bkg3g2R9FX\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), final_lr=0.1, gamma=1e-3,\n eps=1e-8, weight_decay=0, amsbound=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n if not 0.0 <= final_lr:\n raise ValueError(\"Invalid final learning rate: {}\".format(final_lr))\n if not 0.0 <= gamma < 1.0:\n raise ValueError(\"Invalid gamma parameter: {}\".format(gamma))\n defaults = dict(lr=lr, betas=betas, final_lr=final_lr, gamma=gamma, eps=eps,\n weight_decay=weight_decay, amsbound=amsbound)\n super(AdaBoundW, self).__init__(params, defaults)\n\n self.base_lrs = list(map(lambda group: group['lr'], self.param_groups))\n\n def __setstate__(self, state):\n super(AdaBoundW, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsbound', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group, base_lr in zip(self.param_groups, self.base_lrs):\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError(\n 'Adam does not support sparse gradients, please consider SparseAdam instead')\n amsbound = group['amsbound']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsbound:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsbound:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsbound:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n\n # Applies bounds on actual learning rate\n # lr_scheduler cannot affect final_lr, this is a workaround to apply lr decay\n final_lr = group['final_lr'] * group['lr'] / base_lr\n lower_bound = final_lr * (1 - 1 / (group['gamma'] * state['step'] + 1))\n upper_bound = final_lr * (1 + 1 / (group['gamma'] * state['step']))\n step_size = torch.full_like(denom, step_size)\n step_size.div_(denom).clamp_(lower_bound, upper_bound).mul_(exp_avg)\n\n if group['weight_decay'] != 0:\n decayed_weights = torch.mul(p.data, group['weight_decay'])\n p.data.add_(-step_size)\n p.data.sub_(decayed_weights)\n else:\n p.data.add_(-step_size)\n\n return loss",
"_____no_output_____"
],
[
"# スペクトラルノルム使ったコンボそう\ndef snconv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True):\n return spectral_norm(nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,\n stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias))\n# スペクトラルノルム使った全結合層\ndef snlinear(in_features, out_features):\n return spectral_norm(nn.Linear(in_features=in_features, out_features=out_features))\n\n#スペクトラルノルム使ったエンべ層\ndef sn_embedding(num_embeddings, embedding_dim):\n return spectral_norm(nn.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim))\n\n#パイトーチ本のアテンションクラス\nclass Self_Attention_book(nn.Module):\n \"\"\" Self-AttentionのLayer\"\"\"\n\n def __init__(self, in_dim):\n super(Self_Attention_book, self).__init__()\n\n # 1×1の畳み込み層によるpointwise convolutionを用意\n self.query_conv = nn.Conv2d(\n in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)\n self.key_conv = nn.Conv2d(\n in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)\n self.value_conv = nn.Conv2d(\n in_channels=in_dim, out_channels=in_dim, kernel_size=1)\n\n # Attention Map作成時の規格化のソフトマックス\n self.softmax = nn.Softmax(dim=-2)\n\n # 元の入力xとSelf-Attention Mapであるoを足し算するときの係数\n # output = x +gamma*o\n # 最初はgamma=0で、学習させていく\n self.gamma = nn.Parameter(torch.zeros(1))\n\n def forward(self, x):\n\n # 入力変数\n X = x\n\n # 畳み込みをしてから、サイズを変形する。 B,C',W,H→B,C',N へ\n proj_query = self.query_conv(X).view(\n X.shape[0], -1, X.shape[2]*X.shape[3]) # サイズ:B,C',N\n proj_query = proj_query.permute(0, 2, 1) # 転置操作\n proj_key = self.key_conv(X).view(\n X.shape[0], -1, X.shape[2]*X.shape[3]) # サイズ:B,C',N\n\n # かけ算\n S = torch.bmm(proj_query, proj_key) # bmmはバッチごとの行列かけ算です\n\n # 規格化\n attention_map_T = self.softmax(S) # 行i方向の和を1にするソフトマックス関数\n attention_map = attention_map_T.permute(0, 2, 1) # 転置をとる\n\n # Self-Attention Mapを計算する\n proj_value = self.value_conv(X).view(\n X.shape[0], -1, X.shape[2]*X.shape[3]) # サイズ:B,C,N\n o = torch.bmm(proj_value, attention_map.permute(\n 0, 2, 1)) # Attention Mapは転置してかけ算\n\n # Self-Attention MapであるoのテンソルサイズをXにそろえて、出力にする\n o = o.view(X.shape[0], X.shape[1], X.shape[2], X.shape[3])\n out = x+self.gamma*o\n\n return out\n\n#カーネルのアテンションクラス\nclass Self_Attn(nn.Module):\n \"\"\" Self attention Layer\"\"\"\n def __init__(self, in_channels):\n super(Self_Attn, self).__init__()\n self.in_channels = in_channels\n self.snconv1x1_theta = snconv2d(in_channels=in_channels, out_channels=in_channels//8, kernel_size=1, stride=1, padding=0)\n self.snconv1x1_phi = snconv2d(in_channels=in_channels, out_channels=in_channels//8, kernel_size=1, stride=1, padding=0)\n self.snconv1x1_g = snconv2d(in_channels=in_channels, out_channels=in_channels//2, kernel_size=1, stride=1, padding=0)\n self.snconv1x1_attn = snconv2d(in_channels=in_channels//2, out_channels=in_channels, kernel_size=1, stride=1, padding=0)\n self.maxpool = nn.MaxPool2d(2, stride=2, padding=0)\n self.softmax = nn.Softmax(dim=-1)\n self.sigma = nn.Parameter(torch.zeros(1))\n\n def forward(self, x):\n _, ch, h, w = x.size()\n # Theta path\n theta = self.snconv1x1_theta(x)\n theta = theta.view(-1, ch//8, h*w)\n # Phi path\n phi = self.snconv1x1_phi(x)\n phi = self.maxpool(phi)\n phi = phi.view(-1, ch//8, h*w//4)\n # Attn map\n attn = torch.bmm(theta.permute(0, 2, 1), phi)\n attn = self.softmax(attn)\n # g path\n g = self.snconv1x1_g(x)\n g = self.maxpool(g)\n g = g.view(-1, ch//2, h*w//4)\n # Attn_g\n attn_g = torch.bmm(g, attn.permute(0, 2, 1))\n attn_g = attn_g.view(-1, ch//2, h, w)\n attn_g = self.snconv1x1_attn(attn_g)\n # Out\n out = x + self.sigma * attn_g\n return out\n\n \nclass ConditionalBatchNorm2d(nn.Module):\n def __init__(self, num_features, num_classes):\n super().__init__()\n self.num_features = num_features\n self.bn = nn.BatchNorm2d(num_features)\n self.embed = nn.Embedding(num_classes, num_features * 2)\n self.embed.weight.data[:, :num_features].fill_(1.) # Initialize scale to 1\n self.embed.weight.data[:, num_features:].zero_() # Initialize bias at 0\n\n def forward(self, inputs):\n x, y = inputs\n \n out = self.bn(x)\n gamma, beta = self.embed(y).chunk(2, 1)\n out = gamma.view(-1, self.num_features, 1, 1) * out + beta.view(-1, self.num_features, 1, 1)\n return out",
"_____no_output_____"
]
],
[
[
"# Generator and Discriminator",
"_____no_output_____"
]
],
[
[
"class UpConvBlock(nn.Module):\n \"\"\"\n n_cl クラス数(120),\n k_s=カーネルサイズ(4), \n stride=stride(2), \n padding=padding(0), \n bias=バイアス入れるかどうか(False),\n dropout_p=dropout_p(0.0), \n use_cbn=Conditional Batch Normalization使うかどうか(True)\n Lrelu=LeakyReLU使うかどうか(True)(FalseはReLU)\n slope=Lreluのslope(0.05)\n \"\"\"\n def __init__(self, n_input, n_output, n_cl, k_s=4, stride=2, padding=0, \n bias=False, dropout_p=0.0, use_cbn=True, Lrelu=True, slope=0.05):\n super(UpConvBlock, self).__init__()\n self.use_cbn = use_cbn\n self.dropout_p=dropout_p\n self.upconv = spectral_norm(nn.ConvTranspose2d(n_input, n_output, kernel_size=k_s, stride=stride, padding=padding, bias=bias))\n if use_cbn:\n self.cond_bn = ConditionalBatchNorm2d(n_output, n_cl)\n else: \n self.bn = nn.BatchNorm2d(n_output)\n if Lrelu:\n self.activ = nn.LeakyReLU(slope, inplace=True)\n else:\n self.activ = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout2d(p=dropout_p)\n \n def forward(self, inputs):\n x0, labels = inputs\n \n x = self.upconv(x0)\n if self.use_cbn: \n x = self.activ(self.cond_bn((x, labels)))\n else: \n x = self.activ(self.bn(x))\n if self.dropout_p > 0.0: \n x = self.dropout(x)\n return x\n\n\nclass Generator(nn.Module):\n def __init__(self, nz=128, num_classes=120, channels=3, nfilt=64,use_cbn=True, Lrelu=True):\n super(Generator, self).__init__()\n self.nz = nz\n self.num_classes = num_classes\n self.channels = channels\n \n self.label_emb = nn.Embedding(num_classes, nz)\n self.upconv1 = UpConvBlock(2*nz, nfilt*16, num_classes, k_s=4, stride=1, padding=0, dropout_p=0.15,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv2 = UpConvBlock(nfilt*16, nfilt*8, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.10,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv3 = UpConvBlock(nfilt*8, nfilt*4, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.05,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv4 = UpConvBlock(nfilt*4, nfilt*2, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.05,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv5 = UpConvBlock(nfilt*2, nfilt, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.05,use_cbn=use_cbn,Lrelu=Lrelu)\n self.self_attn = Self_Attention_book(nfilt)\n self.upconv6 = UpConvBlock(nfilt, 3, num_classes, k_s=3, stride=1, padding=1)\n self.out_conv = spectral_norm(nn.Conv2d(3, 3, 3, 1, 1, bias=False))\n\n self.out_activ = nn.Tanh()\n \n def forward(self, inputs):\n z, labels = inputs\n \n enc = self.label_emb(labels).view((-1, self.nz, 1, 1))\n enc = F.normalize(enc, p=2, dim=1)\n x = torch.cat((z, enc), 1)\n \n x = self.upconv1((x, labels))\n x = self.upconv2((x, labels))\n x = self.upconv3((x, labels))\n x = self.upconv4((x, labels))\n x = self.upconv5((x, labels))\n x = self.self_attn(x)\n x = self.upconv6((x, labels))\n x = self.out_conv(x)\n img = self.out_activ(x) \n return img\n \n \nclass Discriminator(nn.Module):\n def __init__(self, num_classes=120, channels=3, nfilt=64):\n super(Discriminator, self).__init__()\n self.channels = channels\n self.num_classes = num_classes\n\n def down_convlayer(n_input, n_output, k_s=4, stride=2, padding=0, dropout_p=0.0):\n block = [spectral_norm(nn.Conv2d(n_input, n_output, kernel_size=k_s, stride=stride, padding=padding, bias=False)),\n nn.BatchNorm2d(n_output),\n nn.LeakyReLU(0.2, inplace=True),\n ]\n if dropout_p > 0.0: block.append(nn.Dropout(p=dropout_p))\n return block\n \n self.label_emb = nn.Embedding(num_classes, 64*64)\n self.model = nn.Sequential(\n *down_convlayer(self.channels + 1, nfilt, 4, 2, 1),\n Self_Attn(nfilt),\n \n *down_convlayer(nfilt, nfilt*2, 4, 2, 1, dropout_p=0.20),\n *down_convlayer(nfilt*2, nfilt*4, 4, 2, 1, dropout_p=0.5),\n *down_convlayer(nfilt*4, nfilt*8, 4, 2, 1, dropout_p=0.35),\n \n spectral_norm(nn.Conv2d(nfilt*8, 1, 4, 1, 0, bias=False)),\n )\n\n def forward(self, inputs):\n imgs, labels = inputs\n\n enc = self.label_emb(labels).view((-1, 1, 64, 64))\n enc = F.normalize(enc, p=2, dim=1)\n x = torch.cat((imgs, enc), 1) # 4 input feature maps(3rgb + 1label)\n \n out = self.model(x)\n return out.view(-1)\n\n \ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02) \n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constrideant_(m.bias.data, 0)",
"_____no_output_____"
],
[
"# ----------------------------------------------------------------------------\n# Pixelwise feature vector normalization.\n# reference: https://github.com/tkarras/progressive_growing_of_gans/blob/master/networks.py#L120\n# ----------------------------------------------------------------------------\nclass PixelwiseNorm(nn.Module):\n def __init__(self):\n super(PixelwiseNorm, self).__init__()\n\n def forward(self, x, alpha=1e-8):\n \"\"\"\n forward pass of the module\n :param x: input activations volume\n :param alpha: small number for numerical stability\n :return: y => pixel normalized activations\n \"\"\"\n y = x.pow(2.).mean(dim=1, keepdim=True).add(alpha).sqrt() # [N1HW]\n y = x / y # normalize the input x volume\n return y\n\nclass Generator_pix(nn.Module):\n def __init__(self, nz=128, num_classes=120, channels=3, nfilt=64,use_cbn=True, Lrelu=True):\n super(Generator, self).__init__()\n self.nz = nz\n self.num_classes = num_classes\n self.channels = channels\n \n self.label_emb = nn.Embedding(num_classes, nz)\n self.upconv1 = UpConvBlock(2*nz, nfilt*16, num_classes, k_s=4, stride=1, padding=0, dropout_p=0.15,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv2 = UpConvBlock(nfilt*16, nfilt*8, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.10,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv3 = UpConvBlock(nfilt*8, nfilt*4, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.05,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv4 = UpConvBlock(nfilt*4, nfilt*2, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.05,use_cbn=use_cbn,Lrelu=Lrelu)\n self.upconv5 = UpConvBlock(nfilt*2, nfilt, num_classes, k_s=4, stride=2, padding=1, dropout_p=0.05,use_cbn=use_cbn,Lrelu=Lrelu)\n self.self_attn = Self_Attention_book(nfilt)\n self.upconv6 = UpConvBlock(nfilt, 3, num_classes, k_s=3, stride=1, padding=1)\n self.out_conv = spectral_norm(nn.Conv2d(3, 3, 3, 1, 1, bias=False))\n self.pixnorm = PixelwiseNorm()\n\n self.out_activ = nn.Tanh()\n \n def forward(self, inputs):\n z, labels = inputs\n \n enc = self.label_emb(labels).view((-1, self.nz, 1, 1))\n enc = F.normalize(enc, p=2, dim=1)\n x = torch.cat((z, enc), 1)\n \n x = self.upconv1((x, labels))\n x = self.upconv2((x, labels))\n x = self.pixnorm(x)\n x = self.upconv3((x, labels))\n x = self.pixnorm(x) \n x = self.upconv4((x, labels))\n x = self.pixnorm(x) \n x = self.upconv5((x, labels))\n x = self.self_attn(x)\n x = self.upconv6((x, labels))\n x = self.out_conv(x)\n img = self.out_activ(x) \n return img\n \n \nclass Discriminator_pix(nn.Module):\n def __init__(self, num_classes=120, channels=3, nfilt=64):\n super(Discriminator, self).__init__()\n self.channels = channels\n self.num_classes = num_classes \n\n def down_convlayer(n_input, n_output, k_s=4, stride=2, padding=0, dropout_p=0.0, use_pixnorm=True):\n block = [spectral_norm(nn.Conv2d(n_input, n_output, kernel_size=k_s, stride=stride, padding=padding, bias=False)),\n nn.BatchNorm2d(n_output),\n nn.LeakyReLU(0.2, inplace=True),\n ]\n if dropout_p > 0.0: block.append(nn.Dropout(p=dropout_p))\n if use_pixnorm: block.append(PixelwiseNorm())\n return block\n \n self.label_emb = nn.Embedding(num_classes, 64*64)\n self.model = nn.Sequential(\n *down_convlayer(self.channels + 1, nfilt, 4, 2, 1,use_pixnorm=False),\n Self_Attn(nfilt),\n \n *down_convlayer(nfilt, nfilt*2, 4, 2, 1, dropout_p=0.20),\n *down_convlayer(nfilt*2, nfilt*4, 4, 2, 1, dropout_p=0.5),\n *down_convlayer(nfilt*4, nfilt*8, 4, 2, 1, dropout_p=0.35,use_pixnorm=False),\n \n spectral_norm(nn.Conv2d(nfilt*8, 1, 4, 1, 0, bias=False)),\n )\n\n def forward(self, inputs):\n imgs, labels = inputs\n\n enc = self.label_emb(labels).view((-1, 1, 64, 64))\n enc = F.normalize(enc, p=2, dim=1)\n x = torch.cat((imgs, enc), 1) # 4 input feature maps(3rgb + 1label)\n \n out = self.model(x)\n return out.view(-1)",
"_____no_output_____"
]
],
[
[
"# Data loader",
"_____no_output_____"
]
],
[
[
"class DataGenerator(Dataset):\n def __init__(self, directory, transform=None, n_samples=np.inf, crop_dogs=True):\n self.directory = directory\n self.transform = transform\n self.n_samples = n_samples \n self.samples, self.labels = self.load_dogs_data(directory, crop_dogs)\n\n def load_dogs_data(self, directory, crop_dogs):\n required_transforms = torchvision.transforms.Compose([\n torchvision.transforms.Resize(64),\n torchvision.transforms.CenterCrop(64),\n ])\n\n imgs = []\n labels = []\n paths = []\n for root, _, fnames in sorted(os.walk(directory)):\n for fname in sorted(fnames)[:min(self.n_samples, 999999999999999)]:\n path = os.path.join(root, fname)\n paths.append(path)\n\n for path in paths:\n # Load image\n try: img = dset.folder.default_loader(path)\n except: continue\n \n # Get bounding boxes\n annotation_basename = os.path.splitext(os.path.basename(path))[0]\n annotation_dirname = next(\n dirname for dirname in os.listdir('../input/annotation/Annotation/') if\n dirname.startswith(annotation_basename.split('_')[0]))\n \n if crop_dogs:\n tree = ET.parse(os.path.join('../input/annotation/Annotation/',\n annotation_dirname, annotation_basename))\n root = tree.getroot()\n objects = root.findall('object')\n for o in objects:\n bndbox = o.find('bndbox')\n xmin = int(bndbox.find('xmin').text)\n ymin = int(bndbox.find('ymin').text)\n xmax = int(bndbox.find('xmax').text)\n ymax = int(bndbox.find('ymax').text)\n object_img = required_transforms(img.crop((xmin, ymin, xmax, ymax)))\n imgs.append(object_img)\n labels.append(annotation_dirname.split('-')[1].lower())\n\n else:\n object_img = required_transforms(img)\n imgs.append(object_img)\n labels.append(annotation_dirname.split('-')[1].lower())\n \n return imgs, labels\n \n \n def __getitem__(self, index):\n sample = self.samples[index]\n label = self.labels[index]\n \n if self.transform is not None: \n sample = self.transform(sample)\n return np.asarray(sample), label\n\n \n def __len__(self):\n return len(self.samples)",
"_____no_output_____"
]
],
[
[
"## Training Parameters",
"_____no_output_____"
]
],
[
[
"database = '../input/all-dogs/all-dogs/'\ncrop_dogs = crop_dog\nn_samples = np.inf\nBATCH_SIZE = batch_size\n\nepochs = n_epochs\n\nuse_soft_noisy_labels=noisy_label #ラベルスムージングするかどうか\nloss_calc = loss_calculation\n\nnz = 128\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ntransform = transforms.Compose([transforms.RandomHorizontalFlip(p=flip_p),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrain_data = DataGenerator(database, transform=transform, n_samples=n_samples, crop_dogs=crop_dogs)\n\ndecoded_dog_labels = {i:breed for i, breed in enumerate(sorted(set(train_data.labels)))}\nencoded_dog_labels = {breed:i for i, breed in enumerate(sorted(set(train_data.labels)))}\ntrain_data.labels = [encoded_dog_labels[l] for l in train_data.labels] # encode dog labels in the data generator\n\n\ntrain_loader = torch.utils.data.DataLoader(train_data, shuffle=True,\n batch_size=BATCH_SIZE, num_workers=4)\n\n\nprint(\"Dog breeds loaded: \", len(encoded_dog_labels))\nprint(\"Data samples loaded:\", len(train_data))",
"Dog breeds loaded: 120\nData samples loaded: 22125\n"
],
[
"if use_pixelnorm:\n netG = Generator_pix(nz, num_classes=len(encoded_dog_labels), nfilt=64,use_cbn=Gcbn, Lrelu=Glrelu).to(device)\n netD = Discriminator_pix(num_classes=len(encoded_dog_labels), nfilt=64).to(device)\nelse:\n netG = Generator(nz, num_classes=len(encoded_dog_labels), nfilt=64,use_cbn=Gcbn, Lrelu=Glrelu).to(device)\n netD = Discriminator(num_classes=len(encoded_dog_labels), nfilt=64).to(device)\nweights_init(netG)\nweights_init(netD)\nprint(\"Generator parameters: \", sum(p.numel() for p in netG.parameters() if p.requires_grad))\nprint(\"Discriminator parameters:\", sum(p.numel() for p in netD.parameters() if p.requires_grad))\n\nif G_opt == 'adaboundw':\n optimizerG = AdaBoundW(netG.parameters(), lr=G_lr, betas=G_betas,final_lr=G_final_lr,weight_decay=G_weight_decay)\nelif G_opt == 'adam':\n optimizerG = optim.Adam(netG.parameters(), lr=G_lr, betas=G_betas)\n \nif D_opt == 'adaboundw':\n optimizerD = AdaBoundW(netD.parameters(), lr=D_lr, betas=D_betas,final_lr=D_final_lr,weight_decay=D_weight_decay)\nelif D_opt == 'adam':\n optimizerD = optim.Adam(netD.parameters(), lr=D_lr, betas=D_betas)\nelif D_opt == 'SGD':\n optimizerD = optim.SGD(netD.parameters(), lr=D_lr)\n\n \nlr_schedulerG = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizerG, T_0=epochs//20, eta_min=G_eta_min)\nlr_schedulerD = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizerD, T_0=epochs//20, eta_min=D_eta_min)",
"Generator parameters: 15362488\nDiscriminator parameters: 3263473\n"
],
[
"def mse(imageA, imageB):\n err = np.sum((imageA.astype(\"float\") - imageB.astype(\"float\")) ** 2)\n err /= float(imageA.shape[0] * imageA.shape[1])\n return err\n\ndef show_generated_img(n_images=5, nz=128):\n sample = []\n for _ in range(n_images):\n noise = torch.randn(1, nz, 1, 1, device=device)\n dog_label = torch.randint(0, len(encoded_dog_labels), (1, ), device=device)\n gen_image = netG((noise, dog_label)).to(\"cpu\").clone().detach().squeeze(0)\n gen_image = gen_image.numpy().transpose(1, 2, 0)\n sample.append(gen_image)\n \n figure, axes = plt.subplots(1, len(sample), figsize=(64, 64))\n for index, axis in enumerate(axes):\n axis.axis('off')\n image_array = (sample[index] + 1.) / 2.\n axis.imshow(image_array)\n plt.show()\n\n \ndef analyse_generated_by_class(n_images=5):\n good_breeds = []\n for l in range(len(decoded_dog_labels)):\n sample = []\n for _ in range(n_images):\n noise = torch.randn(1, nz, 1, 1, device=device)\n dog_label = torch.full((1,) , l, device=device, dtype=torch.long)\n gen_image = netG((noise, dog_label)).to(\"cpu\").clone().detach().squeeze(0)\n gen_image = gen_image.numpy().transpose(1, 2, 0)\n sample.append(gen_image)\n \n d = np.round(np.sum([mse(sample[k], sample[k+1]) for k in range(len(sample)-1)])/n_images, 1)\n if d < 1.0: continue # had mode colapse(discard)\n \n print(f\"Generated breed({d}): \", decoded_dog_labels[l])\n figure, axes = plt.subplots(1, len(sample), figsize=(64, 64))\n for index, axis in enumerate(axes):\n axis.axis('off')\n image_array = (sample[index] + 1.) / 2.\n axis.imshow(image_array)\n plt.show()\n \n good_breeds.append(l)\n return good_breeds\n\n\ndef create_submit(good_breeds):\n print(\"Creating submit\")\n os.makedirs('../output_images', exist_ok=True)\n im_batch_size = 32\n n_images = 10000\n \n all_dog_labels = np.random.choice(good_breeds, size=n_images, replace=True)\n for i_batch in range(0, n_images, im_batch_size):\n noise = torch.randn(im_batch_size, nz, 1, 1, device=device)\n dog_labels = torch.from_numpy(all_dog_labels[i_batch: (i_batch+im_batch_size)]).to(device)\n gen_images = netG((noise, dog_labels))\n gen_images = (gen_images.to(\"cpu\").clone().detach() + 1) / 2\n for ii, img in enumerate(gen_images):\n save_image(gen_images[ii, :, :, :], os.path.join('../output_images', f'image_{i_batch + ii:05d}.png'))\n \n import shutil\n shutil.make_archive('images', 'zip', '../output_images')",
"_____no_output_____"
]
],
[
[
"## Training loop",
"_____no_output_____"
]
],
[
[
"d_loss_log = []\ng_loss_log = []\ndout_real_log = []\ndout_fake_log = []\ndout_fake_log2 = []\n\niter_n = len(train_loader) - 1 #最後の余ったバッチは計算されないから-1\n\nfor epoch in range(epochs):\n \n epoch_g_loss = 0.0 # epochの損失和\n epoch_d_loss = 0.0 # epochの損失和\n epoch_dout_real = 0.0\n epoch_dout_fake = 0.0\n epoch_dout_fake2 = 0.0\n\n epoch_time = time.perf_counter()\n if time.perf_counter() - kernel_start_time > 31000:\n print(\"Time limit reached! Stopping kernel!\"); break\n\n for ii, (real_images, dog_labels) in tqdm(enumerate(train_loader),total=len(train_loader)):\n if real_images.shape[0]!= BATCH_SIZE: continue\n \n # ラベルにノイズを入れる。そして時々fakeとrealを入れ替える。\n if use_soft_noisy_labels:\n real_labels = torch.squeeze(torch.empty((BATCH_SIZE, 1), device=device).uniform_(*R_uni))\n fake_labels = torch.squeeze(torch.empty((BATCH_SIZE, 1), device=device).uniform_(*F_uni))\n for p in np.random.choice(BATCH_SIZE, size=np.random.randint((BATCH_SIZE//8)), replace=False):\n real_labels[p], fake_labels[p] = fake_labels[p], real_labels[p] # swap labels\n else:\n real_labels = torch.full((BATCH_SIZE, 1), 1.0, device=device)\n fake_labels = torch.full((BATCH_SIZE, 1), 0.0, device=device)\n \n ############################\n # (1) Update D network\n ###########################\n netD.zero_grad()\n\n dog_labels = torch.tensor(dog_labels, device=device)\n real_images = real_images.to(device)\n noise = torch.randn(BATCH_SIZE, nz, 1, 1, device=device)\n \n outputR = netD((real_images, dog_labels))\n fake_images = netG((noise, dog_labels))\n\n outputF = netD((fake_images.detach(), dog_labels))\n if loss_calc == 'rals':\n errD = (torch.mean((outputR - torch.mean(outputF) - real_labels) ** 2) + \n torch.mean((outputF - torch.mean(outputR) + real_labels) ** 2))/2\n elif loss_calc == 'hinge':\n d_loss_real = torch.nn.ReLU()(1 - outputR).mean()\n # 誤差 outputRがreal_labels以上で誤差0になる。outputR>1で、\n # real_labels - outputRが負の場合ReLUで0にする \n d_loss_fake = torch.nn.ReLU()(1 + outputF).mean()\n # 誤差 outputFがreal_labels以下で誤差0になる。outputF>1で、\n # real_labels - outputFが負の場合ReLUで0にする\n errD = (d_loss_real / 3) + (d_loss_fake / 2) # fakeのlossを強めに流す→fakeに敏感なD→何でもfakeにしがち→Gのlossが流れやすい。→Gに厳しい\n\n errD.backward(retain_graph=True)\n optimizerD.step()\n\n ############################\n # (2) Update G network\n ###########################\n netG.zero_grad()\n \n outputF2 = netD((fake_images, dog_labels))\n if loss_calc == 'rals':\n errG = (torch.mean((outputR - torch.mean(outputF2) + real_labels) ** 2) +\n torch.mean((outputF2 - torch.mean(outputR) - real_labels) ** 2))/2\n elif loss_calc == 'hinge':\n errG = - outputF2.mean()\n \n errG.backward()\n optimizerG.step()\n \n lr_schedulerG.step(epoch)\n lr_schedulerD.step(epoch)\n \n # --------------------\n # 3. 記録\n # --------------------\n epoch_d_loss += errD.item()\n epoch_g_loss += errG.item()\n epoch_dout_real += outputR.mean().item()\n epoch_dout_fake += outputF.mean().item()\n epoch_dout_fake2 += outputF2.mean().item()\n \n d_loss_log.append(epoch_d_loss/iter_n)\n g_loss_log.append(epoch_g_loss/iter_n)\n dout_real_log.append(epoch_dout_real/iter_n)\n dout_fake_log.append(epoch_dout_fake/iter_n)\n dout_fake_log2.append(epoch_dout_fake2/iter_n)\n\n print('loss=%s 1epochの中での平均値 \\n %.2fs [%d/%d] Loss_D: %.4f Loss_G: %.4f outputR: %.4f outputF: %.4f / %.4f' % (loss_calc,\n time.perf_counter()-epoch_time, epoch+1, epochs, d_loss_log[-1], g_loss_log[-1],dout_real_log[-1], dout_fake_log[-1],dout_fake_log2[-1] ))\n print('最後のバッチのloss等 \\n %.2fs [%d/%d] Loss_D: %.4f Loss_G: %.4f outputR: %.4f outputF: %.4f / %.4f' % (\n time.perf_counter()-epoch_time, epoch+1, epochs, errD.item(), errG.item(),outputR.mean().item(), outputF.mean().item(),outputF2.mean().item() ))\n\n if epoch % 10 == 0:\n show_generated_img(6)\n \n",
"_____no_output_____"
]
],
[
[
"## Visualise generated results by label and submit",
"_____no_output_____"
]
],
[
[
"good_breeds = analyse_generated_by_class(6)\ncreate_submit(good_breeds)",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\nplt.figure()\nplt.title(\"Learning Curve\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"loss\")\n\n# Traing score と Test score をプロット\nplt.plot(d_loss_log, color=\"r\", label=\"d_loss\")\nplt.plot(g_loss_log, color=\"g\", label=\"g_loss\")\n\nplt.legend(loc=\"best\")\n\nplt.show()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n\nplt.figure()\nplt.title(\"Learning Curve\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"loss\")\n\n# Traing score と Test score をプロット\nplt.plot(dout_real_log, color=\"r\", label=\"dout_r\")\nplt.plot(dout_fake_log, color=\"g\", label=\"dout_f\")\n\nplt.legend(loc=\"best\")\n\nplt.show()",
"_____no_output_____"
]
]
] | [
"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"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7b122df60fb8dff75a2043a997c016a943aa7c6 | 864,230 | ipynb | Jupyter Notebook | Part 3. Data Analysis.ipynb | jamesgsw/Exploring-Data-and-Analytics-Job-Market-Outlook-in-Singapore-2020 | c7fe4aa972d9b82ae2da0dea054c93f7b9e4f827 | [
"MIT"
] | null | null | null | Part 3. Data Analysis.ipynb | jamesgsw/Exploring-Data-and-Analytics-Job-Market-Outlook-in-Singapore-2020 | c7fe4aa972d9b82ae2da0dea054c93f7b9e4f827 | [
"MIT"
] | null | null | null | Part 3. Data Analysis.ipynb | jamesgsw/Exploring-Data-and-Analytics-Job-Market-Outlook-in-Singapore-2020 | c7fe4aa972d9b82ae2da0dea054c93f7b9e4f827 | [
"MIT"
] | null | null | null | 331.503644 | 489,204 | 0.906653 | [
[
[
"# Data Analysis for Data Analyst Job Landscape 2020",
"_____no_output_____"
],
[
"## Goal\nThere were 2 main motivations for me to do this project,\n* (1) Understand the current job market for data centric jobs\n* (2) Find out the what employers are looking for in data centric jobs",
"_____no_output_____"
],
[
"## Background\nThe project data analysis occurs in the 3rd section: Exploratory Analysis where I explore various themes that I wanted to understand to fufil my 2 goals that I listed above. I used data visualization to explore the various themes, for ease of understanding and giving me an easy snapshot of the job landscape at this current moment.\n<br> The data was pulled from Glassdoor on 22nd May 2020.",
"_____no_output_____"
],
[
"## Methodology\n* [1. Packages](#point_1)\n* [2. Reading Datasets](#point_2)\n* [3. Exploratory Analysis](#point_3)\n * [3.1 One Important Caveat](#point_3_1)\n * [3.2 Average Base Pay Comparison Across Job Titles](#point_3_2)\n * [3.3 Number of Jobs listed on Glassdoor](#point_3_3)\n * [3.4 Technical Skills](#point_3_4)\n * [3.5 Academic Skills](#point_3_5)\n * [3.6 Education Level](#point_3_6)\n * [3.7 Job demand by Ownership](#point_3_7)\n * [3.8 Job demand by Industry](#point_3_8)\n * [3.9 Rating Distribution](#point_3_9)\n* [4. Word Cloud](#point_4)",
"_____no_output_____"
],
[
"## Click button to show/hide code",
"_____no_output_____"
]
],
[
[
"from IPython.display import HTML\n\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide();\n } else {\n $('div.input').show();\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>''')",
"_____no_output_____"
]
],
[
[
"<a id = \"point_1\"> </a>\n## 1. Packages\nThere are various data analysis packages within Python that I'll be using for my anaysis",
"_____no_output_____"
]
],
[
[
"\"\"\"Data Science Packages\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import norm\nfrom pandas import DataFrame\n\n\"\"\"Data Visualisation Packages\"\"\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom matplotlib import pyplot\nfrom matplotlib.pyplot import figure\nimport squarify\n\n\"\"\"World Cloud\"\"\"\nimport nltk\nfrom wordcloud import WordCloud, ImageColorGenerator, STOPWORDS\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize",
"_____no_output_____"
]
],
[
[
"<a id = \"point_2\"></a>\n## 2. Reading Datasets\nAfter performing the Data Cleaning in Part 2, I'm using my clean dataset in this data analysis portion.",
"_____no_output_____"
]
],
[
[
"print(\"---------------------- Job Dataset --------------------------\")",
"---------------------- Job Dataset --------------------------\n"
],
[
"df = pd.read_excel(\n '/Users/james/Documents/GitHub/Exploring-the-Big-Data-and-Analytics-Job-Market-in-Singapore-2020/Job Titles CSV Files/Job_dataset.xlsx')\ndf.head()",
"_____no_output_____"
],
[
"# Lisiting all the columns that are in the csv file\ndf.columns",
"_____no_output_____"
],
[
"print(\"---------------------- Salary Dataset --------------------------\")",
"---------------------- Salary Dataset --------------------------\n"
],
[
"salary_df = pd.read_excel(\n '/Users/james/Documents/GitHub/Exploring-the-Big-Data-and-Analytics-Job-Market-in-Singapore-2020/Job Titles CSV Files/Salary by title.xlsx')\nsalary_df",
"_____no_output_____"
]
],
[
[
"<a id = \"point_3\"></a>\n## 3. Exploratory Analysis",
"_____no_output_____"
],
[
"<a id = \"point_3_1\"></a>\n### 3.1 One Important Caveat",
"_____no_output_____"
],
[
"An Important Caveat I would like to make which I believe is important to address before I begin my Exploratory Analysis is how representative the salary statistics I gathered is. As I have outputted in Section 2, it can be seen that the number of respondents for the Glassdoor Singapore Data related jobs is the extremely small sample size that is available. Therefore, it's important to note that this results is an indication and estimated for us to have a better understanding of the current salaries in this industry but should not be taken as the **yardstick**.\n\n<br> Looking at other resources available, I have found that Glassdoor was my choice website to obtain my data despite the limitations due to its unbiasness which I deemed as an important element of this project.",
"_____no_output_____"
],
[
"<a id = \"point_3_2\"></a>\n### 3.2 Average Base Pay Comparison Across Job Titles\nWe want to compare the average base pay for the different job titles. And within the job titles, if there's any deviations in salary for the level of seniority. ",
"_____no_output_____"
]
],
[
[
"sns.set(style=\"whitegrid\")\n\nfig = sns.catplot(x=\"Job Title\", y=\"Average Base Pay\", hue=\"Position Level\", data=salary_df,\n kind=\"bar\", palette=\"muted\", aspect=8/3)\nfig.despine(left=True)\nfig.set_ylabels(\"Average Base Pay\")\nfig.set(title=\"Pay Comparison for Various Job Titles\")\nfig.savefig(\"Average Base Pay Comparison Across Job Titles.png\")",
"_____no_output_____"
]
],
[
[
"**Findings:** The salary plot allows us to see that the best paid position is as a Quantitative Analyst, followed closely by the Senior Data Scientist and Senior Technology Consultant.\n<br> For fresh graduates, the expected pay for the Data Scientist/Engineer/Analyst role is **S\\\\$ 50666 /year or S\\\\$ 4222 /month**.",
"_____no_output_____"
],
[
"<a id = \"point_3_3\"></a>\n### 3.3 Number of Jobs listed on Glassdoor\nWe want to compare across the different job titles how many avaialbe positions are there listed on Glassdoor.",
"_____no_output_____"
]
],
[
[
"df_jobs_available = df['Job Title'].value_counts().rename_axis(\n 'Job Title').reset_index(name='Number of Jobs')",
"_____no_output_____"
],
[
"sns.set(style=\"whitegrid\")\nsns_plot = sns.barplot(x=\"Job Title\", y=\"Number of Jobs\", data=df_jobs_available).set_title(\n 'Number of Jobs listed on Glassdoor')\nsns.set(rc={'figure.figsize': (16, 8)})\nsns_plot.figure.savefig(\"Number of Jobs listed on Glassdoor.png\")",
"_____no_output_____"
],
[
"total_jobs = df_jobs_available[\"Number of Jobs\"].sum()\nprint(\"The total number of job listings found on Glassdoor is \" + str(total_jobs))\nprint(\"\\n\")",
"The total number of job listings found on Glassdoor is 2049\n\n\n"
],
[
"df_jobs_available[\"Relative Frequency, %\"] = round((df_jobs_available[\"Number of Jobs\"]/total_jobs)*100, 2)\ndf_jobs_available",
"_____no_output_____"
]
],
[
[
"**Findings:** We found that the Data Scientist job title has the most number of jobs available by a large margin with 925 jobs. Followed by Data Analyst and Data Engineer with 477 and 440 jobs postings respectively.\n<br> Surprisingly, there were more managerial positions for the Data Driven jobs compared to machine learning engineer. ",
"_____no_output_____"
],
[
"<a id = \"point_3_4\"></a>\n### 3.4 Technical Skills\nThe technology industry is heavily dependent on the proficiency of the technical skill sets. Therefore, I searched through the Job Description and pulled out the technical skills requested by companies.\n<br> Methodology: I searched through the job description and pull the top 8 most mentioned technical skillset. There are 2 representations which are (1) Dataframe and (2) Histogram.",
"_____no_output_____"
]
],
[
[
"# Creating dictionary counting the number of times a particular technical skill is called\ntechnical_skills = ['AWS', 'Excel', 'Python',\n 'R', 'Spark', 'Hadoop', 'Scala', 'SQL']\nadict = {}\nfor every_skill in technical_skills:\n that_sum = df[every_skill].sum()\n adict[every_skill] = that_sum\n\nprint(adict)",
"{'AWS': 328, 'Excel': 763, 'Python': 1351, 'R': 159, 'Spark': 629, 'Hadoop': 531, 'Scala': 509, 'SQL': 1193}\n"
],
[
"# Representing these numbers with a dataframe\ndf_technical_skill = DataFrame(list(adict.items()), columns=[\n 'Technical Skills', 'Frequency'])\ndf_technical_skill[\"Relative Frequency, %\"] = round((df_technical_skill[\"Frequency\"]/total_jobs)*100, 2)\ndf_technical_skill",
"_____no_output_____"
],
[
"# Creating barplot representing the values in the dataframe\nsns.set(style=\"whitegrid\")\nsns_plot = sns.barplot(x=\"Technical Skills\", y=\"Frequency\", data=df_technical_skill).set_title(\n 'Technical Skills requested for Job')\nsns.set(rc={'figure.figsize': (16, 8)})\nsns_plot.figure.savefig(\"Technical Skills requested for Job.png\")",
"_____no_output_____"
]
],
[
[
"**Findings:** As I expected Python was the most requested skillset that employer wanted prospective hires to have, it's closely followed by SQL. Big data platforms such as Apache Spark and Hadoop alongside Scala are relatively high in demand as well.\n<br> I was very surprise to see that R was not highly requested in the technology industry but I postulate that R is used greater in academic circles.",
"_____no_output_____"
],
[
"<a id = \"point_3_5\"></a>\n### 3.5 Academic Skills\nOn top of the technical skills that are required for the technology jobs, there's an importance of academic skills with the heavy use of mathematical concepts in this industry. I'll search through the job description and find the academic skillset that companies are looking forwards.",
"_____no_output_____"
]
],
[
[
"# Creating dictionary counting the number of times a particular academic skill is called\nacademic_skills = ['Calculus', 'Database Management',\n 'Machine Learning', 'Statistics', 'DevOps']\nadict1 = {}\nfor every_skill in academic_skills:\n that_sum = df[every_skill].sum()\n adict1[every_skill] = that_sum",
"_____no_output_____"
],
[
"# Representing these numbers with a dataframe\ndf_academic_skill = DataFrame(list(adict1.items()), columns=[\n 'Academic Skills', 'Frequency'])\ndf_academic_skill[\"Relative Frequency, %\"] = round((df_academic_skill[\"Frequency\"]/total_jobs)*100, 2)\ndf_academic_skill",
"_____no_output_____"
],
[
"# Creating barplot representing the values in the dataframe\nsns.set(style=\"whitegrid\")\nsns_plot = sns.barplot(x=\"Academic Skills\", y=\"Frequency\", data=df_academic_skill).set_title(\n 'Academic Skills requested for Job')\nsns.set(rc={'figure.figsize': (16, 8)})\nsns_plot.figure.savefig(\"Academic Skills requested for Job.png\")",
"_____no_output_____"
]
],
[
[
"**Findings:** Unsurprinsingly, the top academic skill set looked for by employers is Machine Learning with predictive analysis. However other academic skills sets such as DevOps, Statistics and Database Management is actually rarely mention, and Calculus was not mention at all. \n<br> I postulate that many employers believe that these skills should be instilled into them during their academic training. Therefore, in the next sub-section, I'll investigate the education level that employers expect.",
"_____no_output_____"
],
[
"<a id = \"point_3_6\"></a>\n### 3.6 Education Level\nEducation is a big part of our lives, and I would want to know what education levels are they looking for.",
"_____no_output_____"
]
],
[
[
"df.columns",
"_____no_output_____"
],
[
"df.rename({\"Bachelors Degreee\" : \"Bachelors Degree\"}, axis=1)",
"_____no_output_____"
],
[
"# Creating dictionary counting the number of times a particular Education Level is called\neducation_level = ['Bachelors Degreee', 'Masters','PhD', 'No Education Specified']\nadict2 = {}\nfor every_level in education_level:\n that_sum = df[every_level].sum()\n adict2[every_level] = that_sum\nadict2",
"_____no_output_____"
],
[
"df_education_level = DataFrame(list(adict2.items()), columns=[\n 'Education Level', 'Frequency'])\ndf_education_level[\"Relative Frequency, %\"] = round((df_education_level[\"Frequency\"]/total_jobs)*100, 2)\ndf_education_level",
"_____no_output_____"
],
[
"# Creating barplot representing the values in the dataframe\nsns.set(style=\"whitegrid\")\nsns_plot = sns.barplot(x=\"Education Level\", y=\"Frequency\", data=df_education_level).set_title(\n 'Education Level requested for Job')\nsns.set(rc={'figure.figsize': (16, 8)})\nsns_plot.figure.savefig(\"Minimum Education Level required.png\")",
"_____no_output_____"
]
],
[
[
"**Findings:** I found that most jobs posting for data-driven jobs look for hires with Bachelors Degree. However, it can be noted that there's a sizeable numbers of employers looking for masters and PhD level of qualification. There's a sizeable portion of employers who do not specify university level of qualification either as they do not require a university qualification or they omitted the education level in the Job Description.",
"_____no_output_____"
],
[
"<a id = \"point_3_7\"></a>\n### 3.7 Job demand by Ownership\nData related jobs are on the rise, but I want to investigate where this demand for jobs are at. \n<br> Methodology: To represent the job demand by Ownership, I'll use the Treemap graph to visualize the results.",
"_____no_output_____"
]
],
[
[
"# We drop the rows with null values and count the number of jobs by type of ownership\ndf_ownership = df[df['Type of ownership'] != '-1']\ndf_ownership = df_ownership['Type of ownership'].value_counts(\n).rename_axis('Ownership').reset_index(name='Number of Jobs')",
"_____no_output_____"
],
[
"# Specific number of jobs by the different ownership\ndf_ownership[\"Relative Frequency, %\"] = round((df_ownership[\"Number of Jobs\"]/total_jobs)*100, 2)\ndf_ownership",
"_____no_output_____"
],
[
"# Creating the Tree Map Visualisation\nsquarify.plot(sizes=df_ownership['Number of Jobs'],\n label=df_ownership['Ownership'], alpha=.8)\nplt.show()\nplt.savefig('Job demand by Ownership.png')",
"_____no_output_____"
]
],
[
[
"**Findings:** We found that by ownership, the biggest hire of data driven jobs is the private sector. Followed by public companies and government firms. This is not surprising that private and public company are the biggest players, as they are profit driven and would want to capitalise on new technology and skill set that can help to streamline their operations.",
"_____no_output_____"
],
[
"<a id = \"point_3_8\"></a>\n### 3.8 Job demand by Industry\nData related jobs are on the rise, but I want to investigate where this demand for jobs are at. \n<br> Methodology: To represent the job demand by industry, I'll use the Treemap graph to visualize the results.",
"_____no_output_____"
]
],
[
[
"# We drop the rows with null values and count the number of jobs by industry\ndf_industry = df[df['Industry'] != '-1']\ndf_industry = df_industry['Industry'].value_counts().rename_axis(\n 'Industry').reset_index(name='Number of Jobs')",
"_____no_output_____"
],
[
"# Specific number of jobs by the different industry\ndf_industry[\"Relative Frequency, %\"] = round((df_industry[\"Number of Jobs\"]/total_jobs)*100, 2)\ndf_industry",
"_____no_output_____"
],
[
"# Creating the Tree Map Visualisation\nsquarify.plot(sizes=df_industry['Number of Jobs'],\n label=df_industry['Industry'], alpha=.8)\nplt.show()\nplt.savefig('Job demand by Industry.png')",
"_____no_output_____"
]
],
[
[
"**Findings:** I was surprised to find that Government Agencies was the largest employer of the data driven jobs. The second largest employer by Industry is unsurprisingly is the Internet(Technology) Industry.\n<br> Other surprising results was the Banking and Asset Management Industry.",
"_____no_output_____"
],
[
"<a id = \"point_3_9\"></a>\n### 3.9 Rating Distribution\nWe want to investigate the distribution of company rating across in this technology industry.",
"_____no_output_____"
]
],
[
[
"# Removing null value for ratings\ndf_rating = df[df['Rating'] != -1]",
"_____no_output_____"
],
[
"sns.set(style=\"whitegrid\")\nn, bins, patches = plt.hist(x=df_rating['Rating'], bins='auto',\n alpha=0.7, rwidth=0.85)\nplt.xlabel('Company Ratings')\nplt.ylabel('Frequency')\nplt.title('Distribution of Company Ratings')\n\n# Set a clean upper y-axis limit.\nmaxfreq = n.max()\nplt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)\nplt.savefig('Rating Distribution.png')",
"_____no_output_____"
]
],
[
[
"**Findings:** We find that the average company rating in the technology sector is around 3.75/5.",
"_____no_output_____"
],
[
"<a id ='point_4'></a>\n## Word Cloud in Job Description\nWe want to visualise what are the words that are most frequently repeated in the job description, we use a word cloud algorithm to represent the results below.",
"_____no_output_____"
]
],
[
[
"nltk.download('stopwords')\nnltk.download('punkt')\n\nwords = \" \".join(df['Job Description'])\n\n\ndef punctuation_stop(text):\n \"\"\"remove punctuation and stop words\"\"\"\n filtered = []\n stop_words = set(stopwords.words('english'))\n word_tokens = word_tokenize(text)\n for w in word_tokens:\n if w not in stop_words and w.isalpha():\n filtered.append(w.lower())\n return filtered\n\n\nwords_filtered = punctuation_stop(words)\ntext = \" \".join([ele for ele in words_filtered])\nwc = WordCloud(background_color=\"white\", random_state=1,\n stopwords=STOPWORDS, max_words=2000, width=800, height=1500)\nwc.generate(text)\nplt.figure(figsize=[10, 10])\nplt.imshow(wc, interpolation=\"bilinear\")\nplt.axis('off')\nplt.show()\nwc.to_file('Job Description Word Cloud.png')",
"[nltk_data] Downloading package stopwords to /Users/james/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n[nltk_data] Downloading package punkt to /Users/james/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n"
]
],
[
[
"**Findings:** In the job description, we find that the knowledge in machine learning is the most popular skill that is requested by employers. Other notable skills are data mining, predicitve modeling, data pipline, natural language processing and big 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"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b12fbdedb63ace99edddcd1f1f052bdb1cf016 | 8,118 | ipynb | Jupyter Notebook | aoc-2016/22/22.ipynb | bsamseth/advent-of-code-2018 | bdd3969e61fac3f1543c20983260aa9fda912e99 | [
"MIT"
] | 1 | 2021-01-03T17:09:13.000Z | 2021-01-03T17:09:13.000Z | aoc-2016/22/22.ipynb | bsamseth/advent-of-code-2018 | bdd3969e61fac3f1543c20983260aa9fda912e99 | [
"MIT"
] | 3 | 2021-06-01T23:09:26.000Z | 2022-03-12T01:08:40.000Z | aoc-2016/22/22.ipynb | bsamseth/advent-of-code-2018 | bdd3969e61fac3f1543c20983260aa9fda912e99 | [
"MIT"
] | null | null | null | 26.102894 | 276 | 0.479552 | [
[
[
"with open('test_input.txt', 'r') as f:\n lines = f.read().strip().split('\\n')[2:]\nlines[:3] # Showing the type of input",
"_____no_output_____"
],
[
"import re\nfrom collections import namedtuple\nfrom itertools import permutations\n\nNode = namedtuple('Node', ['coord', 'size', 'used', 'avail'])\nnodes = []\nfor line in lines:\n name, size, used, avail, *rest = line.split()\n \n coord = tuple(int(i) for i in re.search('x(\\d+)-y(\\d+)', name).groups())\n size, used, avail = [int(i[:-1]) for i in (size, used, avail)]\n nodes.append(Node(coord, size, used, avail))\n\npairs = [(A, B) for A, B in permutations(nodes, r=2) if 0 < A.used <= B.avail]\n\nprint('Number of viable pairs:', len(pairs))",
"Number of viable pairs: 7\n"
],
[
"pairs",
"_____no_output_____"
],
[
"nodes",
"_____no_output_____"
]
],
[
[
"## Part 2",
"_____no_output_____"
]
],
[
[
"def dist(A, B):\n \"\"\"Taxi-driver distance\"\"\"\n return abs(B[0] - A[0]) + abs(B[1] - A[1])\n\ndef move_hole(hole, G, node_grid):\n Gx, Gy = G.coord\n target = (Gx-1, Gy)\n \n while hole.coord != target:\n \n if hole.coord[0] >= Gx and hole.coord[1] > Gy:\n hole = node_grid[hole.coord[0]-1][hole.coord[1]]\n elif hole.coord[1] > Gy and hole.coord[0] < Gx:\n hole = node_grid[hole.coord[0]][hole.coord[1]-1]\n elif hole.coord[0]\n\n \n\nG, *_ = [node for node in nodes if node.coord == (maxx, 0)]\nT = nodes[0]\n\nmaxx, maxy = nodes[-1].coord\nnode_grid =[nodes[i*(maxy+1):i*(maxy+1)+ maxy+1] for i in range(maxx+1)]\n\nsteps = 0\nwhile G.coord != T.coord:\n holes = [B for A, B in permutations(nodes, r=2) if A == G and 0 < A.used <= B.avail]\n closest_hole = next(sorted(holes, key=lambda A: dist(A.coord, (G.coord[0]-1, G.coord[1]))))\n move_hole(closest_hole, G, nodes)",
"_____no_output_____"
],
[
"G, T",
"_____no_output_____"
],
[
"holes",
"_____no_output_____"
],
[
"node_grid",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7b134d6ef438ad10e13aecf3edfa5d23b65a87e | 8,182 | ipynb | Jupyter Notebook | 06-2021-05-28/notebooks/06-01_Reporting_using_jupyterbook.ipynb | eotp/python-FU-class | f0a7518b3e3204a77e8855bef91afeaabb0d52ac | [
"MIT"
] | null | null | null | 06-2021-05-28/notebooks/06-01_Reporting_using_jupyterbook.ipynb | eotp/python-FU-class | f0a7518b3e3204a77e8855bef91afeaabb0d52ac | [
"MIT"
] | null | null | null | 06-2021-05-28/notebooks/06-01_Reporting_using_jupyterbook.ipynb | eotp/python-FU-class | f0a7518b3e3204a77e8855bef91afeaabb0d52ac | [
"MIT"
] | 1 | 2020-12-04T15:37:28.000Z | 2020-12-04T15:37:28.000Z | 30.416357 | 178 | 0.608409 | [
[
[
"# Reporting using Jupyter Book",
"_____no_output_____"
],
[
"[Jupyter Book](https://jupyterbook.org/intro.html) is an open source project for building beautiful, publication-quality books and documents from computational material.\n\nIn our case it will help us to export our Jupyter Notebooks into nice to look at HTML files.",
"_____no_output_____"
],
[
"## Installation\n- **If you're running this notebook from the environment of todays lesson `jupyter-book` should already be installed.**\n\n- To install it with conda use the following command to install it from the `conda-forge` channel\n\n```bash\nconda install -c conda-forge jupyter-book\n```",
"_____no_output_____"
],
[
"## Initialize a template",
"_____no_output_____"
],
[
"- Jupyter Book relies on certain files (mostly for configuration). In order to create them, use the `jupyter-book create <template_path>` command.\n\n- To keep things tidy lets use the `reports` directory.\n\n> Hint: We can execute terminal commands directly inside our jupyter notebook by starting the line with `!`",
"_____no_output_____"
]
],
[
[
"!jupyter-book create ../reports/jupyterbook",
"_____no_output_____"
]
],
[
[
"- Before we take a look at the generated files, lets copy over the jupyter notebooks we want to include in our HTML report\n\n## Task:\n- Copy `06-00_Processing_of_Tabular_Data.ipynb` and `06-00_Temperature_anomalies.ipynb` into `../reports/jupyterbook`\n\n> Hint: you don't have to leave the Jupyter Universe to do that. Just open the explorer on the left (the folder icon) and use right-click -> copy.",
"_____no_output_____"
]
],
[
[
"# alternatively use this snippet to copy the desired files\n!cp 06-00_Processing_of_Tabular_Data.ipynb 06-00_Temperature_anomalies.ipynb ../reports/jupyterbook/",
"_____no_output_____"
]
],
[
[
"- Now let us take a look at the files",
"_____no_output_____"
],
[
"## File inspection\n### We need to change the content of two files for everything to run smoothly",
"_____no_output_____"
],
[
"### _config.yml\n\n- Stores configuration parameters such as the Title, Author and execution behaviour\n\n- You can change `title` and `author` to whatever you like\n- The **only parameter we need to change is set `execute_notebooks` to `\"off\"`**\n - This ensures `jupyter-book` doesn't rerun our notebooks but takes them as they are (with the current outputs)\n- The remaining fields can be removed\n\nSample file:\n\n```yml\n# _config.yml\n# Book settings\n# Learn more at https://jupyterbook.org/customize/config.html\n\ntitle: Your Title\nauthor: Your Name\nlogo: logo.png\n\n# Force re-execution of notebooks on each build.\n# See https://jupyterbook.org/content/execute.html\nexecute:\n execute_notebooks: 'off'\n```",
"_____no_output_____"
],
[
"### _toc.yml\n\n- Table of Content file\n\n- Specifies which files to render into HTML\n\n- Make sure you see the jupyter notebook files `06-00_Processing_of_Tabular_Data.ipynb` and `06-00_Temperature_anomalies.ipynb` in `reports/jupyterbook`\n\n- Include both of these files in the Table of Contents\n\nSample file:\n\n```yml\n# Table of content\n# Learn more at https://jupyterbook.org/customize/toc.html\n#\n- file: 06-00_Processing_of_Tabular_Data.ipynb\n- file: 06-00_Temperature_anomalies.ipynb\n```",
"_____no_output_____"
],
[
"### Remaining files:\n\n- `logo.png` will be displayed inside the HTML\n- All remaining files are for demonstration purposes only and serve no use for us (you can savely remove them)",
"_____no_output_____"
],
[
"## Generate HTML files\n\n- In order to generate the html files use `jupyter-book build <template_path>`",
"_____no_output_____"
]
],
[
[
"!jupyter-book build ../reports/jupyterbook",
"_____no_output_____"
]
],
[
[
"# Safety Net\n\n- Make sure you specify the `_toc.yml` and `_config.yml` files as specified above\n- If it should still fail for you, try running this:",
"_____no_output_____"
]
],
[
[
"!rm -rf ../reports/jupyterbook\n!jupyter-book create ../reports/jupyterbook\n!cp 06-00_Processing_of_Tabular_Data.ipynb 06-00_Temperature_anomalies.ipynb ../reports/jupyterbook/\n!cp ../src/_solutions/_toc.yml ../src/_solutions/_config.yml ../reports/jupyterbook/\n!jupyter-book build ../reports/jupyterbook",
"_____no_output_____"
]
],
[
[
"## Open the HTML files\n\n- Check the last lines of the `jupyter-book build` output\n\n- All HTML files are in the folder: `../reports/jupyterbook/_build/html`\n- Open `../reports/jupyterbook/_build/html/index.html` in your Browser or copy the link generated by `jupyter-book` into your Browser to view your notebooks!",
"_____no_output_____"
],
[
"## Further Reading:\n- [JupyterBook Website](https://jupyterbook.org/intro.html)\n- [JupyterBook Tutorial by Pablo Caceres](https://github.com/pabloinsente/jupyter-book-tutorial)\n - This goes pretty in-depth, you can skip most of the stuff mentioned there (like publishing the HTMLs to GitHub Pages)\n - Still very well balanced tutorial (more in-depth than we go, but not too complex)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
e7b15bdb7a15542d7854760b7ed0edf16961c986 | 413,976 | ipynb | Jupyter Notebook | pl/tabnet.ipynb | ronaldokun/isic2019 | 26d436f7ecd9efbce8834dd01aae02c2a8ad85f6 | [
"MIT"
] | null | null | null | pl/tabnet.ipynb | ronaldokun/isic2019 | 26d436f7ecd9efbce8834dd01aae02c2a8ad85f6 | [
"MIT"
] | null | null | null | pl/tabnet.ipynb | ronaldokun/isic2019 | 26d436f7ecd9efbce8834dd01aae02c2a8ad85f6 | [
"MIT"
] | null | null | null | 256.808933 | 69,628 | 0.90678 | [
[
[
"# Update Log\n\nv14 : Added some new features , now local CV has climed to 0.87 just with Meta-Features and can climb even more , this is the first notebook exploring high end score with just the metafeatures.\n\nI have also removed the embedding layer because the model performs better without it\n\nv15 : Inference added",
"_____no_output_____"
],
[
"# About this competition\n\nHello everyone , In this competition , we are asked to classify whether a person has beningn or a melignant melanoma based on the images of skin lesions taken from various parts of the body over different period of times . We have been also given some metadata information to improve results. Given this let's see what we know so far\n\n# What we know so far?\n\nWe know the data is highly imbalanced with almost 98 percent of images being beningn .The discussion forum is filled with threads expressing kernels about the mystery images (image clusters that are present in test set but not in train set). This notebook does not include any EDA and discussions regarding what has already been discovered and explained thoroughly but for all those who are just getting started with this competition , I am adding all the necessary and important kernels and discussions to get up to speed quickly :-\n\n* [EDA kernel by Andrada](https://www.kaggle.com/andradaolteanu/siim-melanoma-competition-eda-augmentations)\n* [Exceptional Kernel giving all the insights about this competition by Laura](https://www.kaggle.com/allunia/don-t-turn-into-a-smoothie-after-the-shake-up)\n* [Code used to merge external Data and Data Splitting by Alex](https://www.kaggle.com/shonenkov/merge-external-data)\n* [Best Public TensorFlow Pipeline with explanantion of best CV strategy by chris deotte](https://www.kaggle.com/cdeotte/triple-stratified-kfold-with-tfrecords)\n* [Mystery Images Discussion Thread by Chris Deotte](https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/168028)\n\nNow that you know what the competition is about the underlying difficulties and solutions which people have adapted so far let's understand what this notebook is all about\n\n# About this Notebook\n\nWe have been given two types of data , one is the images of skin lesions of patients , other is the tabular meta data . Now there are three ways of combining these two information together :-\n\n* Build a CNN image model and find a way to input the tabular data into the CNN image model\n* Build a Tabular data model and find a way to extract image embeddings or image features and input into the Tabular data model\n* Build 2 separate models for images and metadata and ensemble\n\n**We have tried all three and the third option works the best and gives significant amount of boost. Now another question comes to find what models can we use for modelling with tabular data , this notebook tries to answer this question only**\n\n<font color='orange'>What if I say you can use a neural network architecture based on attention and transformers especially designed for tabular data,that too with your own custom loss, custom lr and all the techniques that you might be applying with your image model , one such architecture which can give very could results IMO is Google's Tabnet. </font>\n\nPeople have already applied Tabnet for this competition using Pytorch-Tabnet implementation by Sebastien ([@optimo](https://www.kaggle.com/optimo)) . The Implementation can be found [here](https://github.com/dreamquark-ai/tabnet). However this implementations comes with following limitations : \n* We cannot use custom losses, custom LR schedulers\n* We cannot use custom samplers which we found to have improved results considerably\n* We are provided with a scikit-learn type interface which makes it really easy to use tabnet but at the same time takes away the benifits of it being a deep learning model\n\n**This Notebook also tries to address and solve these limitations**\n\n# How this Notebook solves the Limitations\n\nHere in this notebook I show how to use Tabnet as a custom Model instead of the scikit-learn type interface provided by Pytorch-Tabnet , thanks to Sebastien and his active responses on the github repo . I show how anyone can use Tabnet just like a torchvision or any torch-hub model for any downstream task . I have tried to write a code in such a way that anyone can use this code and apply it to their tasks by just changing the dataset and dataloader. Here are the components that any deep learning models need :-\n* Dataset + DataLoader\n* Model\n* Criterion/Loss\n* Training Loop\n* Evaluation Loop\n* Engine for uniting all of them together\n\n# Things used Specific to this competition\n\n* For Data I am using the dataset and folds provided by [@alex](https://www.kaggle.com/shonenkov) [here](https://www.kaggle.com/shonenkov/melanoma-merged-external-data-512x512-jpeg) which has been generated using the notebook [here](https://www.kaggle.com/shonenkov/merge-external-data)\n* Embeddings for Categorical Variables\n* Soft Margin Focal Loss , because it has seemed to work the best as of now , you can play around with that \n* Balance Sampler for balancing classes in each batch\n* A Plotting fucntion adapted from chris Deotte's Training kernel\n* ReduceOn Pleateau Lr Scheduler \n\n**I hope you all like my efforts and find this kernel useful** ",
"_____no_output_____"
],
[
"<font color='red'> Before diving into code , if you want to understand how tabnet works , you can watch the following talk given\nby Sebastien",
"_____no_output_____"
]
],
[
[
"from IPython.display import IFrame, YouTubeVideo\nYouTubeVideo('ysBaZO8YmX8',width=600, height=400)",
"_____no_output_____"
]
],
[
[
"If you want to do it the scikit learn way here is a [notebook](https://www.kaggle.com/tanulsingh077/achieving-sota-results-with-tabnet) where I explain how to that",
"_____no_output_____"
]
],
[
[
"#Installing Pytorch-Tabnet\n#!pip install pytorch-tabnet",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nimport random\nimport os\nimport seaborn as sns\nfrom tqdm.autonotebook import tqdm\nfrom fastprogress import master_bar, progress_bar\ntqdm.pandas()\nfrom scipy.stats import skew \nimport pickle\nimport glob\n\n#Visuals\nimport matplotlib.pyplot as plt\n\n#torch\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset,DataLoader\nfrom catalyst.data.sampler import BalanceClassSampler\n\n#CV2\nimport cv2\n\n#Importing Tabnet\nfrom pytorch_tabnet.tab_network import TabNet\n\n#error\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import roc_auc_score",
"/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/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:6: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n \n"
]
],
[
[
"# Utils\n\nSince we are writing our custom model , we need early stopping which is present in Pytorch-Tabnet's implementation as a built-in.\nThe following Early-Stopping Implementation can monitor both minimization and maximization of quantities",
"_____no_output_____"
]
],
[
[
"class EarlyStopping:\n def __init__(self, patience=7, mode=\"max\", delta=0.001,verbose=True):\n self.patience = patience\n self.counter = 0\n self.mode = mode\n self.best_score = None\n self.early_stop = False\n self.delta = delta\n self.verbose = verbose\n if self.mode == \"min\":\n self.val_score = np.Inf\n else:\n self.val_score = -np.Inf\n\n def __call__(self, epoch_score, model, model_path):\n\n if self.mode == \"min\":\n score = -1.0 * epoch_score\n else:\n score = np.copy(epoch_score)\n\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(epoch_score, model, model_path)\n elif score < self.best_score + self.delta:\n self.counter += 1\n if self.verbose:\n print('EarlyStopping counter: {} out of {}'.format(self.counter, self.patience))\n \n if self.counter >= self.patience:\n self.early_stop = True\n else:\n self.best_score = score\n self.save_checkpoint(epoch_score, model, model_path)\n self.counter = 0\n\n def save_checkpoint(self, epoch_score, model, model_path):\n if epoch_score not in [-np.inf, np.inf, -np.nan, np.nan]:\n if self.verbose:\n print('Validation score improved ({} --> {}). Saving model!'.format(self.val_score, epoch_score))\n torch.save(model.state_dict(), model_path)\n self.val_score = epoch_score",
"_____no_output_____"
]
],
[
[
"# Configuration\n\nWe define all the configuration needed elsewhere in the notebook here",
"_____no_output_____"
]
],
[
[
"BATCH_SIZE = 1024 \nEPOCHS = 150\nLR = 0.02\nseed = 2020 # seed for reproducible results\npatience = 50\ndevice = torch.device('cuda')\nFOLDS = 5",
"_____no_output_____"
]
],
[
[
"# Seed",
"_____no_output_____"
]
],
[
[
"def seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = False\n torch.backends.cudnn.benchmark = True ",
"_____no_output_____"
],
[
"seed_everything(seed)",
"_____no_output_____"
]
],
[
[
"# Data Preparation and Feature Engineering\n\nHere we input the data and prepare it for inputting to the model",
"_____no_output_____"
]
],
[
[
"# Defining Categorical variables and their Indexes, embedding dimensions , number of classes each have\ndf =pd.read_csv('/data/full/folds_13062020.csv')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"# df = pd.concat([df, pd.get_dummies(df.source)], axis=1)\n\n# df = pd.concat([df, pd.get_dummies(df.anatom_site_general_challenge)], axis=1)\n\n# df.head()\n\n# df['age_approx'] = (df.age_approx - df.age_approx.min()) / df.age_approx.max()\n\n# df.head()\n\n# df = pd.concat([df, pd.get_dummies(df.sex)], axis=1)\n\n# df.drop('unknown', axis=1, inplace=True)\n\n# df.head()\n\n# features = df.iloc[:, -11:].columns.tolist() + ['age_approx']",
"_____no_output_____"
],
[
"features = ['sex', 'age_approx', 'anatom_site_general_challenge'] \ncat = ['sex', 'anatom_site_general_challenge']\ntarget = 'target'\n\ncategorical_columns = []\n\nfor col in cat: \n print(col, df[col].nunique()) \n l_enc = LabelEncoder()\n df[col] = l_enc.fit_transform(df[col].values)\n\n #SAVING LABEL _ ENC\n output = open(f'/out/{col}_encoder.pkl', 'wb')\n pickle.dump(l_enc, output)\n output.close()\n\n categorical_columns.append(col)",
"sex 3\nanatom_site_general_challenge 8\n"
],
[
"class MelanomaDataset(Dataset):\n def __init__(self,features,target):\n self.features = features\n self.target = target\n \n def __len__(self):\n return len(self.features)\n \n def __getitem__(self,idx):\n return{\n 'features': torch.tensor(self.features[idx],dtype=torch.float),\n 'target': self.one_hot(2, self.target[idx])\n }\n \n def get_targets(self):\n return list(self.target)\n \n @staticmethod\n def one_hot(size, target):\n tensor = torch.zeros(size, dtype=torch.float32)\n tensor[target] = 1.\n return tensor",
"_____no_output_____"
]
],
[
[
"# Model\n\nHere we built our Custom Tabnet model",
"_____no_output_____"
]
],
[
[
"class CustomTabnet(nn.Module):\n def __init__(self, input_dim, output_dim,n_d=8, n_a=8,n_steps=3, gamma=1.3,\n cat_idxs=[], cat_dims=[], cat_emb_dim=1,n_independent=2, n_shared=2,\n momentum=0.02,mask_type=\"sparsemax\"):\n \n super(CustomTabnet, self).__init__()\n self.tabnet = TabNet(input_dim=input_dim,output_dim=output_dim, n_d=n_d, n_a=n_a,n_steps=n_steps, gamma=gamma,\n cat_idxs=cat_idxs, cat_dims=cat_dims, cat_emb_dim=cat_emb_dim,n_independent=n_independent,\n n_shared=n_shared, momentum=momentum,mask_type=\"sparsemax\")\n \n \n def forward(self, x):\n return self.tabnet(x)",
"_____no_output_____"
]
],
[
[
"# Loss\n\nDefining SoftMarginFocal Loss which is to be used as a criterion",
"_____no_output_____"
]
],
[
[
"class SoftMarginFocalLoss(nn.Module):\n def __init__(self, margin=0.2, gamma=2):\n super(SoftMarginFocalLoss, self).__init__()\n self.gamma = gamma\n self.margin = margin\n \n self.weight_pos = 2\n self.weight_neg = 1\n \n def forward(self, inputs, targets):\n em = np.exp(self.margin)\n \n log_pos = -F.logsigmoid(inputs)\n log_neg = -F.logsigmoid(-inputs)\n \n log_prob = targets*log_pos + (1-targets)*log_neg\n prob = torch.exp(-log_prob)\n margin = torch.log(em + (1-em)*prob)\n \n weight = targets*self.weight_pos + (1-targets)*self.weight_neg\n loss = self.margin + weight * (1 - prob) ** self.gamma * log_prob\n \n loss = loss.mean()\n \n return loss",
"_____no_output_____"
]
],
[
[
"# Training\n\nOur Custom Training loop",
"_____no_output_____"
]
],
[
[
"def train_fn(dataloader,model,criterion,optimizer,device,scheduler,epoch):\n model.train()\n \n train_targets=[]\n train_outputs=[]\n \n for bi,d in enumerate(dataloader):\n features = d['features']\n target = d['target']\n \n features = features.to(device, dtype=torch.float)\n target = target.to(device, dtype=torch.float)\n \n optimizer.zero_grad()\n \n output,_ = model(features)\n \n loss = criterion(output,target)\n loss.backward()\n optimizer.step()\n \n if scheduler is not None:\n scheduler.step()\n \n output = 1 - F.softmax(output,dim=-1).cpu().detach().numpy()[:,0] \n \n train_targets.extend(target.cpu().detach().numpy().argmax(axis=1).astype(int).tolist())\n train_outputs.extend(output)\n \n \n return loss.item(),train_outputs,train_targets",
"_____no_output_____"
]
],
[
[
"# Evaluation\n\nCustom Evaluation loop",
"_____no_output_____"
]
],
[
[
"def eval_fn(data_loader,model,criterion,device):\n \n fin_targets=[]\n fin_outputs=[]\n \n model.eval()\n with torch.no_grad():\n \n for bi, d in enumerate(data_loader):\n features = d[\"features\"]\n target = d[\"target\"]\n\n features = features.to(device, dtype=torch.float)\n target = target.to(device, dtype=torch.float)\n outputs,_ = model(features) \n loss_eval = criterion(outputs,target) \n outputs = 1 - F.softmax(outputs,dim=-1).cpu().detach().numpy()[:,0] \n fin_targets.extend(target.cpu().detach().numpy().argmax(axis=1).astype(int).tolist())\n fin_outputs.extend(outputs)\n \n return loss_eval.item(),fin_outputs,fin_targets",
"_____no_output_____"
]
],
[
[
"# Plotter\n\nFunction for plotting the losses and auc_scores for each fold ",
"_____no_output_____"
]
],
[
[
"def print_history(fold,history,num_epochs=EPOCHS):\n plt.figure(figsize=(15,5))\n \n plt.plot(\n np.arange(num_epochs),\n history['train_history_auc'],\n '-o',\n label='Train AUC',\n color='#ff7f0e'\n )\n \n plt.plot(\n np.arange(num_epochs),\n history['val_history_auc'],\n '-o',\n label='Val AUC',\n color='#1f77b4'\n )\n \n x = np.argmax(history['val_history_auc'])\n y = np.max(history['val_history_auc'])\n \n xdist = plt.xlim()[1] - plt.xlim()[0]\n ydist = plt.ylim()[1] - plt.ylim()[0]\n \n plt.scatter(x, y, s=200, color='#1f77b4')\n \n plt.text(\n x-0.03*xdist,\n y-0.13*ydist,\n 'max auc\\n%.2f'%y,\n size=14\n )\n \n plt.ylabel('AUC', size=14)\n plt.xlabel('Epoch', size=14)\n \n plt.legend(loc=2)\n \n plt2 = plt.gca().twinx()\n \n plt2.plot(\n np.arange(num_epochs),\n history['train_history_loss'],\n '-o',\n label='Train Loss',\n color='#2ca02c'\n )\n \n plt2.plot(\n np.arange(num_epochs),\n history['val_history_loss'],\n '-o',\n label='Val Loss',\n color='#d62728'\n )\n \n x = np.argmin(history['val_history_loss'])\n y = np.min(history['val_history_loss'])\n \n ydist = plt.ylim()[1] - plt.ylim()[0]\n \n plt.scatter(x, y, s=200, color='#d62728')\n \n plt.text(\n x-0.03*xdist, \n y+0.05*ydist, \n 'min loss', \n size=14\n )\n \n plt.ylabel('Loss', size=14)\n \n plt.title(f'FOLD {fold + 1}',size=18)\n \n plt.legend(loc=3)\n plt.show() ",
"_____no_output_____"
]
],
[
[
"# Engine\n\nEngine where we unite everything",
"_____no_output_____"
]
],
[
[
"def run(fold):\n \n df_train = df[df.fold != fold]\n df_valid = df[df.fold == fold]\n \n # Defining DataSet\n train_dataset = MelanomaDataset(\n df_train[features].values,\n df_train[target].values\n )\n \n \n valid_dataset = MelanomaDataset(\n df_valid[features].values,\n df_valid[target].values\n )\n \n # Defining DataLoader with BalanceClass Sampler\n train_loader = DataLoader(\n train_dataset,\n sampler=BalanceClassSampler(\n labels=train_dataset.get_targets(), \n mode=\"downsampling\",\n ),\n batch_size=BATCH_SIZE,\n pin_memory=True,\n drop_last=True,\n num_workers=4\n )\n \n \n valid_loader = torch.utils.data.DataLoader(\n valid_dataset,\n batch_size=BATCH_SIZE,\n num_workers=4,\n shuffle=False,\n pin_memory=True,\n drop_last=False,\n )\n \n # Defining Device\n device = torch.device(\"cuda\")\n \n # Defining Model for specific fold\n model = CustomTabnet(input_dim = len(features), \n output_dim = 2,\n n_d=32, \n n_a=32,\n n_steps=4, \n gamma=1.6,\n cat_emb_dim=2,\n n_independent=2,\n n_shared=2,\n momentum=0.02,\n mask_type=\"sparsemax\")\n \n model.to(device)\n \n #DEfining criterion\n criterion = SoftMarginFocalLoss()\n criterion.to(device)\n \n # Defining Optimizer with weight decay to params other than bias and layer norms\n param_optimizer = list(model.named_parameters())\n no_decay = [\"bias\", \"LayerNorm.bias\", \"LayerNorm.weight\"]\n optimizer_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.001},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0},\n ] \n \n optimizer = torch.optim.AdamW(optimizer_parameters, lr=LR)\n \n # Defining LR SCheduler\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max',\n factor=0.5, patience=10, verbose=True, \n threshold=0.0001, threshold_mode='rel',\n cooldown=0, min_lr=0, eps=1e-08)\n #DEfining Early Stopping Object\n es = EarlyStopping(patience=patience,verbose=False)\n \n # History dictionary to store everything\n history = {\n 'train_history_loss': [],\n 'train_history_auc': [],\n 'val_history_loss': [],\n 'val_history_auc': [],\n }\n \n # THE ENGINE LOOP \n mb = progress_bar(range(EPOCHS), total=EPOCHS)\n for epoch in mb:\n train_loss,train_out,train_targets = train_fn(train_loader, model,criterion, optimizer, device,scheduler=None,epoch=epoch)\n \n val_loss,outputs, targets = eval_fn(valid_loader, model, criterion,device)\n \n train_auc = roc_auc_score(train_targets, train_out)\n auc_score = roc_auc_score(targets, outputs)\n \n scheduler.step(auc_score)\n \n #mb.set_postfix(Train_Loss=train_loss,Train_AUC_SCORE = train_auc,Valid_Loss = val_loss,Valid_AUC_SCORE = auc_score)\n mb.comment = f'train Loss: {train_loss:.4f}, valid_loss: {val_loss:.4f}, auc_score: {auc_score:.4f}'\n history['train_history_loss'].append(train_loss)\n history['train_history_auc'].append(train_auc)\n history['val_history_loss'].append(val_loss)\n history['val_history_auc'].append(auc_score)\n\n es(val_loss,model,f'model_{fold}.pth')\n \n if es.early_stop:\n print('Maximum Patience {} Reached , Early Stopping'.format(patience))\n break \n \n print_history(fold,history,num_epochs=epoch+1)",
"_____no_output_____"
],
[
"run(fold=0)",
"_____no_output_____"
],
[
"run(fold=1)",
"_____no_output_____"
],
[
"run(fold=2)",
"_____no_output_____"
],
[
"run(fold=3)",
"_____no_output_____"
],
[
"run(fold=4)",
"_____no_output_____"
]
],
[
[
"# Inference",
"_____no_output_____"
]
],
[
[
"df_test =pd.read_csv('/data/full/test.csv')\ndf_test['anatom_site_general_challenge'].fillna('unknown',inplace=True)\ndf_test['target'] = 0",
"_____no_output_____"
],
[
"# df_test.head()\n\n# df_test['age_approx'] = (df_test.age_approx - df_test.age_approx.min()) / df_test.age_approx.max()\n# df_test = pd.concat([df_test, pd.get_dummies(df_test.sex), pd.get_dummies(df_test.anatom_site_general_challenge)], axis=1)\n\n# df_test['ISIC19'] = 0\n# df_test['ISIC20'] = 1\n\n# df_test['target'] = 0\n\n# df_test['lateral torso'] = 0",
"_____no_output_____"
],
[
"features = ['sex', 'age_approx', 'anatom_site_general_challenge'] \ncat = ['sex', 'anatom_site_general_challenge']\ntarget = 'target'\n\ncategorical_columns = [] \n\nfor col in cat:\n print(col, df_test[col].nunique())\n pkl_file = open(f'/out/{col}_encoder.pkl', 'rb')\n l_enc = pickle.load(pkl_file) \n df_test[col] = l_enc.transform(df_test[col].values)\n pkl_file.close()",
"sex 2\nanatom_site_general_challenge 7\n"
],
[
"def load_model():\n \n models = []\n paths = glob.glob('/out/model_*')\n \n for path in tqdm(paths,total=len(paths)):\n \n model = CustomTabnet(input_dim = len(features), \n output_dim = 2,\n n_d=32, \n n_a=32,\n n_steps=4, \n gamma=1.6,\n cat_emb_dim=2,\n n_independent=2,\n n_shared=2,\n momentum=0.02,\n mask_type=\"sparsemax\")\n \n model.to(device)\n loader = torch.load(path)\n model.load_state_dict(loader)\n \n models.append(model)\n \n return models",
"_____no_output_____"
],
[
"models = load_model()",
"_____no_output_____"
],
[
"def make_prediction(data_loader):\n predictions = np.zeros((len(df_test),FOLDS))\n for i,model in enumerate(models):\n \n fin_outputs=[]\n \n model.eval()\n with torch.no_grad():\n \n for bi, d in enumerate(data_loader):\n features = d[\"features\"]\n target = d[\"target\"]\n\n features = features.to(device, dtype=torch.float)\n\n outputs,_ = model(features)\n\n outputs = 1 - F.softmax(outputs,dim=-1).cpu().detach().numpy()[:,0] \n \n fin_outputs.extend(outputs)\n \n predictions[:,i] = fin_outputs\n \n return predictions",
"_____no_output_____"
],
[
"test_dataset = MelanomaDataset(\n df_test[features].values,\n df_test[target].values\n )\n\ntest_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=BATCH_SIZE,\n num_workers=4,\n shuffle=False,\n pin_memory=True,\n drop_last=False,\n )",
"_____no_output_____"
],
[
"pred = make_prediction(test_loader)",
"_____no_output_____"
]
],
[
[
"# Writing Submission File",
"_____no_output_____"
]
],
[
[
"pred = pred.mean(axis=-1)\npred",
"_____no_output_____"
],
[
"pred.min()",
"_____no_output_____"
],
[
"ss = pd.read_csv('/data/full/sample_submission.csv')",
"_____no_output_____"
],
[
"ss['target'] = pred",
"_____no_output_____"
],
[
"#ss.to_csv('/out/tabnet_submission.csv',index=False)\nss.head()",
"_____no_output_____"
],
[
"#!kaggle competitions submit -c siim-isic-melanoma-classification -f submission.csv -m \"Tabnet One Hot\"",
"_____no_output_____"
]
],
[
[
"# Thank you all for reading my Notebook",
"_____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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7b169a521e80c2d42e550e023f1939901ff5910 | 9,414 | ipynb | Jupyter Notebook | Archive/basic_rnn.ipynb | PlanetExp/rcnn | c0f26c18c17334d7185a83b60c68eaf4357246bf | [
"Apache-2.0"
] | null | null | null | Archive/basic_rnn.ipynb | PlanetExp/rcnn | c0f26c18c17334d7185a83b60c68eaf4357246bf | [
"Apache-2.0"
] | null | null | null | Archive/basic_rnn.ipynb | PlanetExp/rcnn | c0f26c18c17334d7185a83b60c68eaf4357246bf | [
"Apache-2.0"
] | null | null | null | 30.865574 | 99 | 0.534417 | [
[
[
"import tensorflow as tf\nimport numpy as np\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"# Hyperparameters\nnum_steps = 5\nbatch_size = 32\nnum_classes = 2\nstate_size = 4\nlearning_rate = 0.1",
"_____no_output_____"
],
[
"def gen_data(size=1000000):\n X = np.array(np.random.choice(2, size=(size,)))\n Y = []\n for i in range(size):\n threshold = .5\n if X[i-3] == 1: # 3 steps back\n threshold += .5\n if X[i-8] == 1: # 8 steps back\n threshold -= .25\n if np.random.rand() > threshold:\n Y.append(0)\n else:\n Y.append(1)\n return X, np.array(Y)\n\ndef gen_batch(raw_data, batch_size, num_steps):\n raw_x, raw_y = raw_data\n data_length = len(raw_x)\n \n # partition raw data into batches and stack them vertically in a data matrix\n batch_partition_length = data_length // batch_size\n data_x = np.zeros([batch_size, batch_partition_length], dtype=np.int32)\n data_y = np.zeros([batch_size, batch_partition_length], dtype=np.int32)\n for i in range(batch_size):\n data_x[i] = raw_x[batch_partition_length * i:batch_partition_length * (i + 1)]\n data_y[i] = raw_y[batch_partition_length * i:batch_partition_length * (i + 1)]\n # further divide batch partitions into num_steps for truncated backprop\n epoch_size = batch_partition_length // num_steps\n \n for i in range(epoch_size):\n x = data_x[:, i * num_steps:(i + 1) * num_steps]\n y = data_y[:, i * num_steps:(i + 1) * num_steps]\n yield (x, y)\n\ndef gen_epochs(n, num_steps):\n for i in range(n):\n yield gen_batch(gen_data(), batch_size, num_steps)",
"_____no_output_____"
],
[
"'''\nPlaceholders\n'''\n\nx = tf.placeholder(tf.int32, [batch_size, num_steps], name='input_placeholder')\ny = tf.placeholder(tf.int32, [batch_size, num_steps], name='labels_placeholder')\ninit_state = tf.zeros([batch_size, state_size])\n\n'''\nRNN Inputs\n'''\n\n# Turn our x placeholder into a list of one-hot tensors:\n# rnn_inputs is a list of num_steps tensors with shape [batch_size, num_classes]\nx_one_hot = tf.one_hot(x, num_classes)\nrnn_inputs = tf.unpack(x_one_hot, axis=1)",
"_____no_output_____"
],
[
"\"\"\"\nDefinition of rnn_cell\n\nThis is very similar to the __call__ method on Tensorflow's BasicRNNCell. See:\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn_cell.py\n\"\"\"\nwith tf.variable_scope('rnn_cell'):\n W = tf.get_variable('W', [num_classes + state_size, state_size])\n b = tf.get_variable('b', [state_size], initializer=tf.constant_initializer(0.0))\n\ndef rnn_cell(rnn_input, state):\n with tf.variable_scope('rnn_cell', reuse=True):\n W = tf.get_variable('W', [num_classes + state_size, state_size])\n b = tf.get_variable('b', [state_size], initializer=tf.constant_initializer(0.0))\n return tf.tanh(tf.matmul(tf.concat(1, [rnn_input, state]), W) + b)",
"_____no_output_____"
],
[
"\"\"\"\nAdding rnn_cells to graph\n\nThis is a simplified version of the \"rnn\" function from Tensorflow's api. See:\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn.py\n\"\"\"\nstate = init_state\nrnn_outputs = []\nfor rnn_input in rnn_inputs:\n state = rnn_cell(rnn_input, state)\n rnn_outputs.append(state)\nfinal_state = rnn_outputs[-1]",
"_____no_output_____"
],
[
"\"\"\"\nPredictions, loss, training step\n\nLosses and total_loss are simlar to the \"sequence_loss_by_example\" and \"sequence_loss\"\nfunctions, respectively, from Tensorflow's api. See:\nhttps://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/seq2seq.py\n\"\"\"\n\n#logits and predictions\nwith tf.variable_scope('softmax'):\n W = tf.get_variable('W', [state_size, num_classes])\n b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(0.0))\nlogits = [tf.matmul(rnn_output, W) + b for rnn_output in rnn_outputs]\npredictions = [tf.nn.softmax(logit) for logit in logits]\n\n# Turn our y placeholder into a list labels\ny_as_list = [tf.squeeze(i, squeeze_dims=[1]) for i in tf.split(1, num_steps, y)]\n\n#losses and train_step\nlosses = [tf.nn.sparse_softmax_cross_entropy_with_logits(logit,label) for \\\n logit, label in zip(logits, y_as_list)]\ntotal_loss = tf.reduce_mean(losses)\ntrain_step = tf.train.AdagradOptimizer(learning_rate).minimize(total_loss)",
"_____no_output_____"
],
[
"'''\nFunction to train the network\n'''\n\ndef train_network(num_epochs, num_steps, state_size=4, verbose=True):\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n training_losses = []\n for idx, epoch in enumerate(gen_epochs(num_epochs, num_steps)):\n training_loss = 0\n training_state = np.zeros((batch_size, state_size))\n if verbose:\n print(\"\\nEPOCH\", idx)\n for step, (X, Y) in enumerate(epoch):\n tr_losses, training_loss_, training_state, _ = \\\n sess.run([losses,\n total_loss,\n final_state,\n train_step],\n feed_dict={x:X, y:Y, init_state:training_state})\n training_loss += training_loss_\n if step % 100 == 0 and step > 0:\n if verbose:\n print(\"Average loss at step\", step,\n \"for last 250 steps:\", training_loss / 100)\n training_losses.append(training_loss / 100)\n training_loss = 0\n\n return training_losses",
"_____no_output_____"
],
[
"# training_losses = train_network(1, num_steps)\n# plt.plot(training_losses)\n\n# Print all variables\ng = tf.get_default_graph()\nvars = g.get_collection('variables')\nfor v in vars:\n print(v.name)\n\n# Get single tensor\ncell_weights = g.get_tensor_by_name('rnn_cell/W:0')\nprint(cell_weights.name)",
"rnn_cell/W:0\nrnn_cell/b:0\nsoftmax/W:0\nsoftmax/b:0\nrnn_cell/W/Adagrad:0\nrnn_cell/b/Adagrad:0\nsoftmax/W/Adagrad:0\nsoftmax/b/Adagrad:0\nrnn_cell/W:0\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b17e2e14d3d092f8113cd6e2d801cab816238b | 2,707 | ipynb | Jupyter Notebook | python/10daysOfStatistics/Day_5_Poisson_Distribution_II .ipynb | muatik/interactive-coding-challenges | 05c00cceffdb42f1f9f9829b20ba2c552c46a83b | [
"MIT"
] | 26 | 2016-02-10T05:43:25.000Z | 2022-01-10T17:44:23.000Z | python/10daysOfStatistics/Day_5_Poisson_Distribution_II .ipynb | muatik/interactive-coding-challenges | 05c00cceffdb42f1f9f9829b20ba2c552c46a83b | [
"MIT"
] | null | null | null | python/10daysOfStatistics/Day_5_Poisson_Distribution_II .ipynb | muatik/interactive-coding-challenges | 05c00cceffdb42f1f9f9829b20ba2c552c46a83b | [
"MIT"
] | 16 | 2016-02-10T05:43:58.000Z | 2021-03-16T18:41:07.000Z | 29.107527 | 225 | 0.581825 | [
[
[
"## Day 5: Poisson Distribution II \nhttps://www.hackerrank.com/challenges/s10-poisson-distribution-2\n\n### Objective \nIn this challenge, we go further with Poisson distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.\n\n### Task \nThe manager of a industrial plant is planning to buy a machine of either type or type . For each day’s operation:\n\n- The number of repairs, , that machine needs is a Poisson random variable with mean . The daily cost of operating is .\n- The number of repairs, , that machine needs is a Poisson random variable with mean . The daily cost of operating is .\nAssume that the repairs take a negligible amount of time and the machines are maintained nightly to ensure that they operate like new at the start of each day. Find and print the expected daily cost for each machine.\n\n### Input Format\n\nA single line comprised of space-separated values denoting the respective means for and :\n\n```\n0.88 1.55\n```\nIf you do not wish to read this information from stdin, you can hard-code it into your program.\n\n### Output Format\n\nThere are two lines of output. Your answers must be rounded to a scale of decimal places (i.e., format):\n\nOn the first line, print the expected daily cost of machine .\nOn the second line, print the expected daily cost of machine .\n",
"_____no_output_____"
]
],
[
[
"a_m, b_m = [float(i) for i in input().split(\" \")]\n\nprint(round(160 + 40 * (a_m + a_m ** 2), 3))\nprint(round(128 + 40 * (b_m + b_m ** 2), 3))",
"0.88 1.55\n226.176\n286.1\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code"
]
] |
e7b18dd5dc2c6c6623e163135e9094fb23e74c00 | 35,581 | ipynb | Jupyter Notebook | Course1 - Build Basic Generative Adversarial Networks (GANs)/Week4/C1W4A_Build_a_Conditional_GAN_Original.ipynb | RamzanShahidkhan/Generative-Adversarial-Networks-Specialization | bb4479a2c67b4fad8b241827479123346ef15504 | [
"MIT"
] | null | null | null | Course1 - Build Basic Generative Adversarial Networks (GANs)/Week4/C1W4A_Build_a_Conditional_GAN_Original.ipynb | RamzanShahidkhan/Generative-Adversarial-Networks-Specialization | bb4479a2c67b4fad8b241827479123346ef15504 | [
"MIT"
] | null | null | null | Course1 - Build Basic Generative Adversarial Networks (GANs)/Week4/C1W4A_Build_a_Conditional_GAN_Original.ipynb | RamzanShahidkhan/Generative-Adversarial-Networks-Specialization | bb4479a2c67b4fad8b241827479123346ef15504 | [
"MIT"
] | null | null | null | 39.755307 | 496 | 0.579663 | [
[
[
"# Build a Conditional GAN",
"_____no_output_____"
],
[
"### Goals\nIn this notebook, you're going to make a conditional GAN in order to generate hand-written images of digits, conditioned on the digit to be generated (the class vector). This will let you choose what digit you want to generate.\n\nYou'll then do some exploration of the generated images to visualize what the noise and class vectors mean. \n\n### Learning Objectives\n1. Learn the technical difference between a conditional and unconditional GAN.\n2. Understand the distinction between the class and noise vector in a conditional GAN.\n\n",
"_____no_output_____"
],
[
"## Getting Started\n\nFor this assignment, you will be using the MNIST dataset again, but there's nothing stopping you from applying this generator code to produce images of animals conditioned on the species or pictures of faces conditioned on facial characteristics.\n\nNote that this assignment requires no changes to the architectures of the generator or discriminator, only changes to the data passed to both. The generator will no longer take `z_dim` as an argument, but `input_dim` instead, since you need to pass in both the noise and class vectors. In addition to good variable naming, this also means that you can use the generator and discriminator code you have previously written with different parameters.\n\nYou will begin by importing the necessary libraries and building the generator and discriminator.",
"_____no_output_____"
],
[
"#### Packages and Visualization",
"_____no_output_____"
]
],
[
[
"import torch\nfrom torch import nn\nfrom tqdm.auto import tqdm\nfrom torchvision import transforms\nfrom torchvision.datasets import MNIST\nfrom torchvision.utils import make_grid\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt\ntorch.manual_seed(0) # Set for our testing purposes, please do not change!\n\ndef show_tensor_images(image_tensor, num_images=25, size=(1, 28, 28), nrow=5, show=True):\n '''\n Function for visualizing images: Given a tensor of images, number of images, and\n size per image, plots and prints the images in an uniform grid.\n '''\n image_tensor = (image_tensor + 1) / 2\n image_unflat = image_tensor.detach().cpu()\n image_grid = make_grid(image_unflat[:num_images], nrow=nrow)\n plt.imshow(image_grid.permute(1, 2, 0).squeeze())\n if show:\n plt.show()",
"_____no_output_____"
]
],
[
[
"#### Generator and Noise",
"_____no_output_____"
]
],
[
[
"class Generator(nn.Module):\n '''\n Generator Class\n Values:\n input_dim: the dimension of the input vector, a scalar\n im_chan: the number of channels in the images, fitted for the dataset used, a scalar\n (MNIST is black-and-white, so 1 channel is your default)\n hidden_dim: the inner dimension, a scalar\n '''\n def __init__(self, input_dim=10, im_chan=1, hidden_dim=64):\n super(Generator, self).__init__()\n self.input_dim = input_dim\n # Build the neural network\n self.gen = nn.Sequential(\n self.make_gen_block(input_dim, hidden_dim * 4),\n self.make_gen_block(hidden_dim * 4, hidden_dim * 2, kernel_size=4, stride=1),\n self.make_gen_block(hidden_dim * 2, hidden_dim),\n self.make_gen_block(hidden_dim, im_chan, kernel_size=4, final_layer=True),\n )\n\n def make_gen_block(self, input_channels, output_channels, kernel_size=3, stride=2, final_layer=False):\n '''\n Function to return a sequence of operations corresponding to a generator block of DCGAN;\n a transposed convolution, a batchnorm (except in the final layer), and an activation.\n Parameters:\n input_channels: how many channels the input feature representation has\n output_channels: how many channels the output feature representation should have\n kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size)\n stride: the stride of the convolution\n final_layer: a boolean, true if it is the final layer and false otherwise \n (affects activation and batchnorm)\n '''\n if not final_layer:\n return nn.Sequential(\n nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),\n nn.BatchNorm2d(output_channels),\n nn.ReLU(inplace=True),\n )\n else:\n return nn.Sequential(\n nn.ConvTranspose2d(input_channels, output_channels, kernel_size, stride),\n nn.Tanh(),\n )\n\n def forward(self, noise):\n '''\n Function for completing a forward pass of the generator: Given a noise tensor, \n returns generated images.\n Parameters:\n noise: a noise tensor with dimensions (n_samples, input_dim)\n '''\n x = noise.view(len(noise), self.input_dim, 1, 1)\n return self.gen(x)\n\ndef get_noise(n_samples, input_dim, device='cpu'):\n '''\n Function for creating noise vectors: Given the dimensions (n_samples, input_dim)\n creates a tensor of that shape filled with random numbers from the normal distribution.\n Parameters:\n n_samples: the number of samples to generate, a scalar\n input_dim: the dimension of the input vector, a scalar\n device: the device type\n '''\n return torch.randn(n_samples, input_dim, device=device)",
"_____no_output_____"
]
],
[
[
"#### Discriminator",
"_____no_output_____"
]
],
[
[
"class Discriminator(nn.Module):\n '''\n Discriminator Class\n Values:\n im_chan: the number of channels in the images, fitted for the dataset used, a scalar\n (MNIST is black-and-white, so 1 channel is your default)\n hidden_dim: the inner dimension, a scalar\n '''\n def __init__(self, im_chan=1, hidden_dim=64):\n super(Discriminator, self).__init__()\n self.disc = nn.Sequential(\n self.make_disc_block(im_chan, hidden_dim),\n self.make_disc_block(hidden_dim, hidden_dim * 2),\n self.make_disc_block(hidden_dim * 2, 1, final_layer=True),\n )\n\n def make_disc_block(self, input_channels, output_channels, kernel_size=4, stride=2, final_layer=False):\n '''\n Function to return a sequence of operations corresponding to a discriminator block of the DCGAN; \n a convolution, a batchnorm (except in the final layer), and an activation (except in the final layer).\n Parameters:\n input_channels: how many channels the input feature representation has\n output_channels: how many channels the output feature representation should have\n kernel_size: the size of each convolutional filter, equivalent to (kernel_size, kernel_size)\n stride: the stride of the convolution\n final_layer: a boolean, true if it is the final layer and false otherwise \n (affects activation and batchnorm)\n '''\n if not final_layer:\n return nn.Sequential(\n nn.Conv2d(input_channels, output_channels, kernel_size, stride),\n nn.BatchNorm2d(output_channels),\n nn.LeakyReLU(0.2, inplace=True),\n )\n else:\n return nn.Sequential(\n nn.Conv2d(input_channels, output_channels, kernel_size, stride),\n )\n\n def forward(self, image):\n '''\n Function for completing a forward pass of the discriminator: Given an image tensor, \n returns a 1-dimension tensor representing fake/real.\n Parameters:\n image: a flattened image tensor with dimension (im_chan)\n '''\n disc_pred = self.disc(image)\n return disc_pred.view(len(disc_pred), -1)",
"_____no_output_____"
]
],
[
[
"## Class Input\n\nIn conditional GANs, the input vector for the generator will also need to include the class information. The class is represented using a one-hot encoded vector where its length is the number of classes and each index represents a class. The vector is all 0's and a 1 on the chosen class. Given the labels of multiple images (e.g. from a batch) and number of classes, please create one-hot vectors for each label. There is a class within the PyTorch functional library that can help you.\n\n<details>\n\n<summary>\n<font size=\"3\" color=\"green\">\n<b>Optional hints for <code><font size=\"4\">get_one_hot_labels</font></code></b>\n</font>\n</summary>\n\n1. This code can be done in one line.\n2. The documentation for [F.one_hot](https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.one_hot) may be helpful.\n\n</details>\n",
"_____no_output_____"
]
],
[
[
"# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: get_one_hot_labels\n\nimport torch.nn.functional as F\ndef get_one_hot_labels(labels, n_classes):\n '''\n Function for creating one-hot vectors for the labels, returns a tensor of shape (?, num_classes).\n Parameters:\n labels: tensor of labels from the dataloader, size (?)\n n_classes: the total number of classes in the dataset, an integer scalar\n '''\n #### START CODE HERE ####\n return None\n #### END CODE HERE ####",
"_____no_output_____"
],
[
"assert (\n get_one_hot_labels(\n labels=torch.Tensor([[0, 2, 1]]).long(),\n n_classes=3\n ).tolist() == \n [[\n [1, 0, 0], \n [0, 0, 1], \n [0, 1, 0]\n ]]\n)\nprint(\"Success!\")",
"_____no_output_____"
]
],
[
[
"Next, you need to be able to concatenate the one-hot class vector to the noise vector before giving it to the generator. You will also need to do this when adding the class channels to the discriminator.\n\nTo do this, you will need to write a function that combines two vectors. Remember that you need to ensure that the vectors are the same type: floats. Again, you can look to the PyTorch library for help.\n<details>\n<summary>\n<font size=\"3\" color=\"green\">\n<b>Optional hints for <code><font size=\"4\">combine_vectors</font></code></b>\n</font>\n</summary>\n\n1. This code can also be written in one line.\n2. The documentation for [torch.cat](https://pytorch.org/docs/master/generated/torch.cat.html) may be helpful.\n3. Specifically, you might want to look at what the `dim` argument of `torch.cat` does.\n\n</details>\n",
"_____no_output_____"
]
],
[
[
"# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: combine_vectors\ndef combine_vectors(x, y):\n '''\n Function for combining two vectors with shapes (n_samples, ?) and (n_samples, ?).\n Parameters:\n x: (n_samples, ?) the first vector. \n In this assignment, this will be the noise vector of shape (n_samples, z_dim), \n but you shouldn't need to know the second dimension's size.\n y: (n_samples, ?) the second vector.\n Once again, in this assignment this will be the one-hot class vector \n with the shape (n_samples, n_classes), but you shouldn't assume this in your code.\n '''\n # Note: Make sure this function outputs a float no matter what inputs it receives\n #### START CODE HERE ####\n combined = None\n #### END CODE HERE ####\n return combined",
"_____no_output_____"
],
[
"combined = combine_vectors(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[5, 6], [7, 8]]));\n# Check exact order of elements\nassert torch.all(combined == torch.tensor([[1, 2, 5, 6], [3, 4, 7, 8]]))\n# Tests that items are of float type\nassert (type(combined[0][0].item()) == float)\n# Check shapes\ncombined = combine_vectors(torch.randn(1, 4, 5), torch.randn(1, 8, 5));\nassert tuple(combined.shape) == (1, 12, 5)\nassert tuple(combine_vectors(torch.randn(1, 10, 12).long(), torch.randn(1, 20, 12).long()).shape) == (1, 30, 12)\nprint(\"Success!\")",
"_____no_output_____"
]
],
[
[
"## Training\nNow you can start to put it all together!\nFirst, you will define some new parameters:\n\n* mnist_shape: the number of pixels in each MNIST image, which has dimensions 28 x 28 and one channel (because it's black-and-white) so 1 x 28 x 28\n* n_classes: the number of classes in MNIST (10, since there are the digits from 0 to 9)",
"_____no_output_____"
]
],
[
[
"mnist_shape = (1, 28, 28)\nn_classes = 10",
"_____no_output_____"
]
],
[
[
"And you also include the same parameters from previous assignments:\n\n * criterion: the loss function\n * n_epochs: the number of times you iterate through the entire dataset when training\n * z_dim: the dimension of the noise vector\n * display_step: how often to display/visualize the images\n * batch_size: the number of images per forward/backward pass\n * lr: the learning rate\n * device: the device type\n",
"_____no_output_____"
]
],
[
[
"criterion = nn.BCEWithLogitsLoss()\nn_epochs = 200\nz_dim = 64\ndisplay_step = 500\nbatch_size = 128\nlr = 0.0002\ndevice = 'cuda'\n\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,)),\n])\n\ndataloader = DataLoader(\n MNIST('.', download=False, transform=transform),\n batch_size=batch_size,\n shuffle=True)",
"_____no_output_____"
]
],
[
[
"Then, you can initialize your generator, discriminator, and optimizers. To do this, you will need to update the input dimensions for both models. For the generator, you will need to calculate the size of the input vector; recall that for conditional GANs, the generator's input is the noise vector concatenated with the class vector. For the discriminator, you need to add a channel for every class.",
"_____no_output_____"
]
],
[
[
"# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED FUNCTION: get_input_dimensions\ndef get_input_dimensions(z_dim, mnist_shape, n_classes):\n '''\n Function for getting the size of the conditional input dimensions \n from z_dim, the image shape, and number of classes.\n Parameters:\n z_dim: the dimension of the noise vector, a scalar\n mnist_shape: the shape of each MNIST image as (C, W, H), which is (1, 28, 28)\n n_classes: the total number of classes in the dataset, an integer scalar\n (10 for MNIST)\n Returns: \n generator_input_dim: the input dimensionality of the conditional generator, \n which takes the noise and class vectors\n discriminator_im_chan: the number of input channels to the discriminator\n (e.g. C x 28 x 28 for MNIST)\n '''\n #### START CODE HERE ####\n generator_input_dim = None\n discriminator_im_chan = None\n #### END CODE HERE ####\n return generator_input_dim, discriminator_im_chan",
"_____no_output_____"
],
[
"def test_input_dims():\n gen_dim, disc_dim = get_input_dimensions(23, (12, 23, 52), 9)\n assert gen_dim == 32\n assert disc_dim == 21\ntest_input_dims()\nprint(\"Success!\")",
"_____no_output_____"
],
[
"generator_input_dim, discriminator_im_chan = get_input_dimensions(z_dim, mnist_shape, n_classes)\n\ngen = Generator(input_dim=generator_input_dim).to(device)\ngen_opt = torch.optim.Adam(gen.parameters(), lr=lr)\ndisc = Discriminator(im_chan=discriminator_im_chan).to(device)\ndisc_opt = torch.optim.Adam(disc.parameters(), lr=lr)\n\ndef weights_init(m):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n torch.nn.init.normal_(m.weight, 0.0, 0.02)\n if isinstance(m, nn.BatchNorm2d):\n torch.nn.init.normal_(m.weight, 0.0, 0.02)\n torch.nn.init.constant_(m.bias, 0)\ngen = gen.apply(weights_init)\ndisc = disc.apply(weights_init)",
"_____no_output_____"
]
],
[
[
"Now to train, you would like both your generator and your discriminator to know what class of image should be generated. There are a few locations where you will need to implement code.\n\nFor example, if you're generating a picture of the number \"1\", you would need to:\n \n1. Tell that to the generator, so that it knows it should be generating a \"1\"\n2. Tell that to the discriminator, so that it knows it should be looking at a \"1\". If the discriminator is told it should be looking at a 1 but sees something that's clearly an 8, it can guess that it's probably fake\n\nThere are no explicit unit tests here -- if this block of code runs and you don't change any of the other variables, then you've done it correctly!",
"_____no_output_____"
]
],
[
[
"# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)\n# GRADED CELL\ncur_step = 0\ngenerator_losses = []\ndiscriminator_losses = []\n\n#UNIT TEST NOTE: Initializations needed for grading\nnoise_and_labels = False\nfake = False\n\nfake_image_and_labels = False\nreal_image_and_labels = False\ndisc_fake_pred = False\ndisc_real_pred = False\n\nfor epoch in range(n_epochs):\n # Dataloader returns the batches and the labels\n for real, labels in tqdm(dataloader):\n cur_batch_size = len(real)\n # Flatten the batch of real images from the dataset\n real = real.to(device)\n\n one_hot_labels = get_one_hot_labels(labels.to(device), n_classes)\n image_one_hot_labels = one_hot_labels[:, :, None, None]\n image_one_hot_labels = image_one_hot_labels.repeat(1, 1, mnist_shape[1], mnist_shape[2])\n\n ### Update discriminator ###\n # Zero out the discriminator gradients\n disc_opt.zero_grad()\n # Get noise corresponding to the current batch_size \n fake_noise = get_noise(cur_batch_size, z_dim, device=device)\n \n # Now you can get the images from the generator\n # Steps: 1) Combine the noise vectors and the one-hot labels for the generator\n # 2) Generate the conditioned fake images\n \n #### START CODE HERE ####\n noise_and_labels = None\n fake = None\n #### END CODE HERE ####\n \n # Make sure that enough images were generated\n assert len(fake) == len(real)\n # Check that correct tensors were combined\n assert tuple(noise_and_labels.shape) == (cur_batch_size, fake_noise.shape[1] + one_hot_labels.shape[1])\n # It comes from the correct generator\n assert tuple(fake.shape) == (len(real), 1, 28, 28)\n\n # Now you can get the predictions from the discriminator\n # Steps: 1) Create the input for the discriminator\n # a) Combine the fake images with image_one_hot_labels, \n # remember to detach the generator (.detach()) so you do not backpropagate through it\n # b) Combine the real images with image_one_hot_labels\n # 2) Get the discriminator's prediction on the fakes as disc_fake_pred\n # 3) Get the discriminator's prediction on the reals as disc_real_pred\n \n #### START CODE HERE ####\n fake_image_and_labels = None\n real_image_and_labels = None\n disc_fake_pred = None\n disc_real_pred = None\n #### END CODE HERE ####\n \n # Make sure shapes are correct \n assert tuple(fake_image_and_labels.shape) == (len(real), fake.detach().shape[1] + image_one_hot_labels.shape[1], 28 ,28)\n assert tuple(real_image_and_labels.shape) == (len(real), real.shape[1] + image_one_hot_labels.shape[1], 28 ,28)\n # Make sure that enough predictions were made\n assert len(disc_real_pred) == len(real)\n # Make sure that the inputs are different\n assert torch.any(fake_image_and_labels != real_image_and_labels)\n # Shapes must match\n assert tuple(fake_image_and_labels.shape) == tuple(real_image_and_labels.shape)\n assert tuple(disc_fake_pred.shape) == tuple(disc_real_pred.shape)\n \n \n disc_fake_loss = criterion(disc_fake_pred, torch.zeros_like(disc_fake_pred))\n disc_real_loss = criterion(disc_real_pred, torch.ones_like(disc_real_pred))\n disc_loss = (disc_fake_loss + disc_real_loss) / 2\n disc_loss.backward(retain_graph=True)\n disc_opt.step() \n\n # Keep track of the average discriminator loss\n discriminator_losses += [disc_loss.item()]\n\n ### Update generator ###\n # Zero out the generator gradients\n gen_opt.zero_grad()\n\n fake_image_and_labels = combine_vectors(fake, image_one_hot_labels)\n # This will error if you didn't concatenate your labels to your image correctly\n disc_fake_pred = disc(fake_image_and_labels)\n gen_loss = criterion(disc_fake_pred, torch.ones_like(disc_fake_pred))\n gen_loss.backward()\n gen_opt.step()\n\n # Keep track of the generator losses\n generator_losses += [gen_loss.item()]\n #\n\n if cur_step % display_step == 0 and cur_step > 0:\n gen_mean = sum(generator_losses[-display_step:]) / display_step\n disc_mean = sum(discriminator_losses[-display_step:]) / display_step\n print(f\"Step {cur_step}: Generator loss: {gen_mean}, discriminator loss: {disc_mean}\")\n show_tensor_images(fake)\n show_tensor_images(real)\n step_bins = 20\n x_axis = sorted([i * step_bins for i in range(len(generator_losses) // step_bins)] * step_bins)\n num_examples = (len(generator_losses) // step_bins) * step_bins\n plt.plot(\n range(num_examples // step_bins), \n torch.Tensor(generator_losses[:num_examples]).view(-1, step_bins).mean(1),\n label=\"Generator Loss\"\n )\n plt.plot(\n range(num_examples // step_bins), \n torch.Tensor(discriminator_losses[:num_examples]).view(-1, step_bins).mean(1),\n label=\"Discriminator Loss\"\n )\n plt.legend()\n plt.show()\n elif cur_step == 0:\n print(\"Congratulations! If you've gotten here, it's working. Please let this train until you're happy with how the generated numbers look, and then go on to the exploration!\")\n cur_step += 1",
"_____no_output_____"
]
],
[
[
"## Exploration\nYou can do a bit of exploration now!",
"_____no_output_____"
]
],
[
[
"# Before you explore, you should put the generator\n# in eval mode, both in general and so that batch norm\n# doesn't cause you issues and is using its eval statistics\ngen = gen.eval()",
"_____no_output_____"
]
],
[
[
"#### Changing the Class Vector\nYou can generate some numbers with your new model! You can add interpolation as well to make it more interesting.\n\nSo starting from a image, you will produce intermediate images that look more and more like the ending image until you get to the final image. Your're basically morphing one image into another. You can choose what these two images will be using your conditional GAN.",
"_____no_output_____"
]
],
[
[
"import math\n\n### Change me! ###\nn_interpolation = 9 # Choose the interpolation: how many intermediate images you want + 2 (for the start and end image)\ninterpolation_noise = get_noise(1, z_dim, device=device).repeat(n_interpolation, 1)\n\ndef interpolate_class(first_number, second_number):\n first_label = get_one_hot_labels(torch.Tensor([first_number]).long(), n_classes)\n second_label = get_one_hot_labels(torch.Tensor([second_number]).long(), n_classes)\n\n # Calculate the interpolation vector between the two labels\n percent_second_label = torch.linspace(0, 1, n_interpolation)[:, None]\n interpolation_labels = first_label * (1 - percent_second_label) + second_label * percent_second_label\n\n # Combine the noise and the labels\n noise_and_labels = combine_vectors(interpolation_noise, interpolation_labels.to(device))\n fake = gen(noise_and_labels)\n show_tensor_images(fake, num_images=n_interpolation, nrow=int(math.sqrt(n_interpolation)), show=False)\n\n### Change me! ###\nstart_plot_number = 1 # Choose the start digit\n### Change me! ###\nend_plot_number = 5 # Choose the end digit\n\nplt.figure(figsize=(8, 8))\ninterpolate_class(start_plot_number, end_plot_number)\n_ = plt.axis('off')\n\n### Uncomment the following lines of code if you would like to visualize a set of pairwise class \n### interpolations for a collection of different numbers, all in a single grid of interpolations.\n### You'll also see another visualization like this in the next code block!\n# plot_numbers = [2, 3, 4, 5, 7]\n# n_numbers = len(plot_numbers)\n# plt.figure(figsize=(8, 8))\n# for i, first_plot_number in enumerate(plot_numbers):\n# for j, second_plot_number in enumerate(plot_numbers):\n# plt.subplot(n_numbers, n_numbers, i * n_numbers + j + 1)\n# interpolate_class(first_plot_number, second_plot_number)\n# plt.axis('off')\n# plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0.1, wspace=0)\n# plt.show()\n# plt.close()",
"_____no_output_____"
]
],
[
[
"#### Changing the Noise Vector\nNow, what happens if you hold the class constant, but instead you change the noise vector? You can also interpolate the noise vector and generate an image at each step.",
"_____no_output_____"
]
],
[
[
"n_interpolation = 9 # How many intermediate images you want + 2 (for the start and end image)\n\n# This time you're interpolating between the noise instead of the labels\ninterpolation_label = get_one_hot_labels(torch.Tensor([5]).long(), n_classes).repeat(n_interpolation, 1).float()\n\ndef interpolate_noise(first_noise, second_noise):\n # This time you're interpolating between the noise instead of the labels\n percent_first_noise = torch.linspace(0, 1, n_interpolation)[:, None].to(device)\n interpolation_noise = first_noise * percent_first_noise + second_noise * (1 - percent_first_noise)\n\n # Combine the noise and the labels again\n noise_and_labels = combine_vectors(interpolation_noise, interpolation_label.to(device))\n fake = gen(noise_and_labels)\n show_tensor_images(fake, num_images=n_interpolation, nrow=int(math.sqrt(n_interpolation)), show=False)\n\n# Generate noise vectors to interpolate between\n### Change me! ###\nn_noise = 5 # Choose the number of noise examples in the grid\nplot_noises = [get_noise(1, z_dim, device=device) for i in range(n_noise)]\nplt.figure(figsize=(8, 8))\nfor i, first_plot_noise in enumerate(plot_noises):\n for j, second_plot_noise in enumerate(plot_noises):\n plt.subplot(n_noise, n_noise, i * n_noise + j + 1)\n interpolate_noise(first_plot_noise, second_plot_noise)\n plt.axis('off')\nplt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0.1, wspace=0)\nplt.show()\nplt.close()",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b18e58744dbb78e9da4588e4e298181b3d9c4d | 276,968 | ipynb | Jupyter Notebook | examples/tabula_example.ipynb | shailp52/tabula-py | 74215e08edf6877ea8cd67bdf84c9a381f4999a0 | [
"MIT"
] | null | null | null | examples/tabula_example.ipynb | shailp52/tabula-py | 74215e08edf6877ea8cd67bdf84c9a381f4999a0 | [
"MIT"
] | null | null | null | examples/tabula_example.ipynb | shailp52/tabula-py | 74215e08edf6877ea8cd67bdf84c9a381f4999a0 | [
"MIT"
] | null | null | null | 47.556319 | 36,272 | 0.329164 | [
[
[
"<a href=\"https://colab.research.google.com/github/chezou/tabula-py/blob/master/examples/tabula_example.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# tabula-py example notebook\n\ntabula-py is a tool for convert PDF tables to pandas DataFrame. tabula-py is a wrapper of [tabula-java](https://github.com/tabulapdf/tabula-java), which requires java on your machine. tabula-py also enales you to convert PDF tables into CSV/TSV files.\n\ntabula-py's PDF extraction accuracy is same as tabula-java or [tabula app](https://tabula.technology/); GUI tool of tabula, so if you want to know the performance of tabula-py, I highly recommend you to try tabula app.\n\ntabula-py is good for:\n- automation with Python script\n- advanced analytics after converting pandas DataFrame\n- casual analytics with Jupyter notebook or Google Colabolatory\n",
"_____no_output_____"
],
[
"## Check Java environment and install tabula-py\n\ntabula-py requires java environment so let's check the java environment on your machine.",
"_____no_output_____"
]
],
[
[
"!java -version",
"openjdk version \"11.0.3\" 2019-04-16\nOpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.04.1)\nOpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu218.04.1, mixed mode, sharing)\nopenjdk version \"11.0.3\" 2019-04-16\nOpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.04.1)\nOpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu218.04.1, mixed mode, sharing)\n"
]
],
[
[
"After confirming the java environment, install tabula-py by using pip.",
"_____no_output_____"
]
],
[
[
"# To be more precisely, it's better to use `{sys.executable} -m pip install tabula-py`\n!pip install -q tabula-py",
"\u001b[K |████████████████████████████████| 10.4MB 4.2MB/s \n\u001b[?25h"
]
],
[
[
"Before trying tabula-py, check your environment via tabula-py `environment_info()` function, which shows Python version, Java version, and your OS environment.",
"_____no_output_____"
]
],
[
[
"import tabula\n\ntabula.environment_info()",
"Python version:\n 3.6.8 (default, Jan 14 2019, 11:02:34) \n[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]\nJava version:\n openjdk version \"11.0.3\" 2019-04-16\nOpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.04.1)\nOpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu218.04.1, mixed mode, sharing)\ntabula-py version: 1.4.0\nplatform: Linux-4.14.79+-x86_64-with-Ubuntu-18.04-bionic\nuname:\n uname_result(system='Linux', node='b5c4edf3fd8a', release='4.14.79+', version='#1 SMP Wed Dec 19 21:19:13 PST 2018', machine='x86_64', processor='x86_64')\nlinux_distribution: ('Ubuntu', '18.04', 'bionic')\nmac_ver: ('', ('', '', ''), '')\n \n"
]
],
[
[
"## Read a PDF with `read_pdf()` function\n\nLet's read a PDF from GitHub. tabula-py can load a PDF or file like object on both local or internet by using `read_pdf()` function.",
"_____no_output_____"
]
],
[
[
"pdf_path = \"https://github.com/chezou/tabula-py/raw/master/tests/resources/data.pdf\"\n\ntabula.read_pdf(pdf_path, stream=True)",
"_____no_output_____"
]
],
[
[
"## Options for `read_pdf()`\n\nNote that `read_pdf()` function reads only page 1 by default. For more details, use `?read_pdf` and `?tabula.wrapper.build_options`.",
"_____no_output_____"
]
],
[
[
"help(tabula.read_pdf)",
"Help on function read_pdf in module tabula.wrapper:\n\nread_pdf(input_path, output_format='dataframe', encoding='utf-8', java_options=None, pandas_options=None, multiple_tables=False, **kwargs)\n Read tables in PDF.\n \n Args:\n input_path (file like obj):\n File like object of tareget PDF file.\n output_format (str, optional):\n Output format of this function (dataframe or json)\n encoding (str, optional):\n Encoding type for pandas. Default is 'utf-8'\n java_options (list, optional):\n Set java options like `-Xmx256m`.\n pandas_options (dict, optional):\n Set pandas options like {'header': None}.\n multiple_tables (bool, optional):\n It enables to handle multiple tables within a page.\n Note: If `multiple_tables` option is enabled, tabula-py uses not\n :func:`pd.read_csv()`, but `pd.DataFrame()`. Make sure to pass appropriate\n `pandas_options`.\n kwargs (dict):\n Dictionary of option for tabula-java. Details are shown in\n :func:`build_options()`\n \n Returns:\n Extracted pandas DataFrame or list.\n\n"
],
[
"help(tabula.wrapper.build_options)",
"Help on function build_options in module tabula.wrapper:\n\nbuild_options(kwargs=None)\n Build options for tabula-java\n \n Args:\n options (str, optional):\n Raw option string for tabula-java.\n pages (str, int, :obj:`list` of :obj:`int`, optional):\n An optional values specifying pages to extract from. It allows\n `str`,`int`, :obj:`list` of :obj:`int`.\n Example: '1-2,3', 'all' or [1,2]\n guess (bool, optional):\n Guess the portion of the page to analyze per page. Default `True`\n If you use \"area\" option, this option becomes `False`.\n \n Note that as of tabula-java 1.0.3, guess option becomes independent from\n lattice and stream option, you can use guess and lattice/stream option\n at the same time.\n area (:obj:`list` of :obj:`float` or\n :obj:`list` of :obj:`list` of :obj:`float`, optional):\n Portion of the page to analyze(top,left,bottom,right).\n Example; [269.875,12.75,790.5,561] or\n [[12.1,20.5,30.1,50.2], [1.0,3.2,10.5,40.2]].\n Default is entire page.\n relative_area (bool, optional):\n If all area values are between 0-100 (inclusive) and preceded by '%',\n input will be taken as % of actual height or width of the page.\n Default False.\n lattice (bool, optional):\n Force PDF to be extracted using lattice-mode extraction\n (if there are ruling lines separating each cell, as in a PDF of an\n Excel spreadsheet)\n stream (bool, optional):\n Force PDF to be extracted using stream-mode extraction\n (if there are no ruling lines separating each cell, as in a PDF of an\n Excel spreadsheet)\n password (str, optional):\n Password to decrypt document. Default is empty\n silent (bool, optional):\n Suppress all stderr output.\n columns (list, optional):\n X coordinates of column boundaries.\n Example: [10.1, 20.2, 30.3]\n format (str, optional):\n Format for output file or extracted object. (CSV, TSV, JSON)\n batch (str, optional):\n Convert all .pdfs in the provided directory. This argument should be\n directory.\n output_path (str, optional):\n Output file path. File format of it is depends on `format`.\n Same as `--outfile` option of tabula-java.\n \n Returns:\n `obj`:list: Built list of options\n\n"
]
],
[
[
"Let's set `pages` option. Here is the extraction result of page 3:",
"_____no_output_____"
]
],
[
[
"# set pages option\ntabula.read_pdf(pdf_path, pages=3, stream=True)",
"_____no_output_____"
],
[
"# pass pages as string\ntabula.read_pdf(pdf_path, pages=\"1-2,3\", stream=True)",
"_____no_output_____"
]
],
[
[
"You can set `pages=\"all\"` for extration all pages. If you hit OOM error with Java, you should set appropriate `-Xmx` option for `java_options`.",
"_____no_output_____"
]
],
[
[
"# extract all pages\ntabula.read_pdf(pdf_path, pages=\"all\", stream=True)",
"_____no_output_____"
]
],
[
[
"## Read multiple tables with `multiple_tables` option\n\ntabula-py assumes single tabule for an output by default, because of the limitation of pandas. To avoid this issue, you can set `multiple_tables` option. By using this option, `read_pdf` function returns list of DataFrames.",
"_____no_output_____"
]
],
[
[
"# extract multiple from all pages\nmulti_tables = tabula.read_pdf(pdf_path, pages=\"all\", multiple_tables=True)\nprint(multi_tables[0].head())\nprint(multi_tables[1].head())",
" 0 1 2 3 4 5 6 7 8 9\n0 mpg cyl disp hp drat wt qsec vs am gear\n1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4\n2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4\n3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4\n4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3\n 0 1 2 3 4\n0 Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n1 5.1 3.5 1.4 0.2 setosa\n2 4.9 3.0 1.4 0.2 setosa\n3 4.7 3.2 1.3 0.2 setosa\n4 4.6 3.1 1.5 0.2 setosa\n"
]
],
[
[
"## Read partial area of PDF\n\nIf you want to set a certain part of page, you can use `area` option.",
"_____no_output_____"
]
],
[
[
"# set area option\ntabula.read_pdf(pdf_path, area=(126,149,212,462), pages=2)",
"_____no_output_____"
]
],
[
[
"## Extract to JSON, TSV, or CSV\n\ntabula-py has capability to convert not only DataFrame but also JSON, TSV, or CSV. You can set output format with `output_format` option.",
"_____no_output_____"
]
],
[
[
"# read pdf as JSON\ntabula.read_pdf(pdf_path, output_format=\"json\")",
"_____no_output_____"
]
],
[
[
"## Convert PDF tables into CSV, TSV, or JSON files\n\nYou can convert files directly rather creating Python objects with `convert_into()` function.",
"_____no_output_____"
]
],
[
[
"# You can convert from pdf into JSON, CSV, TSV\n\ntabula.convert_into(pdf_path, \"test.json\", output_format=\"json\")\n!cat test.json",
"[{\"extraction_method\":\"lattice\",\"top\":125.17005,\"left\":247.14917,\"width\":292.90167236328125,\"height\":395.14886474609375,\"right\":540.05084,\"bottom\":520.3189,\"data\":[[{\"top\":125.17005,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.186347961425781,\"text\":\"mpg\"},{\"top\":125.17005,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.186347961425781,\"text\":\"cyl\"},{\"top\":125.17005,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.186347961425781,\"text\":\"disp\"},{\"top\":125.17005,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.186347961425781,\"text\":\"hp\"},{\"top\":125.17005,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.186347961425781,\"text\":\"drat\"},{\"top\":125.17005,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.186347961425781,\"text\":\"wt\"},{\"top\":125.17005,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.186347961425781,\"text\":\"qsec\"},{\"top\":125.17005,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.186347961425781,\"text\":\"vs\"},{\"top\":125.17005,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.186347961425781,\"text\":\"am\"},{\"top\":125.17005,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.186347961425781,\"text\":\"gear\"}],[{\"top\":137.3564,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.352630615234375,\"text\":\"21.0\"},{\"top\":137.3564,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.352630615234375,\"text\":\"6\"},{\"top\":137.3564,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.352630615234375,\"text\":\"160.0\"},{\"top\":137.3564,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.352630615234375,\"text\":\"110\"},{\"top\":137.3564,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.352630615234375,\"text\":\"3.90\"},{\"top\":137.3564,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.352630615234375,\"text\":\"2.620\"},{\"top\":137.3564,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.352630615234375,\"text\":\"16.46\"},{\"top\":137.3564,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.352630615234375,\"text\":\"0\"},{\"top\":137.3564,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.352630615234375,\"text\":\"1\"},{\"top\":137.3564,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.352630615234375,\"text\":\"4\"}],[{\"top\":149.70903,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35186767578125,\"text\":\"21.0\"},{\"top\":149.70903,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35186767578125,\"text\":\"6\"},{\"top\":149.70903,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35186767578125,\"text\":\"160.0\"},{\"top\":149.70903,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35186767578125,\"text\":\"110\"},{\"top\":149.70903,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35186767578125,\"text\":\"3.90\"},{\"top\":149.70903,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35186767578125,\"text\":\"2.875\"},{\"top\":149.70903,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35186767578125,\"text\":\"17.02\"},{\"top\":149.70903,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35186767578125,\"text\":\"0\"},{\"top\":149.70903,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35186767578125,\"text\":\"1\"},{\"top\":149.70903,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35186767578125,\"text\":\"4\"}],[{\"top\":162.0609,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35662841796875,\"text\":\"22.8\"},{\"top\":162.0609,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35662841796875,\"text\":\"4\"},{\"top\":162.0609,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35662841796875,\"text\":\"108.0\"},{\"top\":162.0609,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35662841796875,\"text\":\"93\"},{\"top\":162.0609,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35662841796875,\"text\":\"3.85\"},{\"top\":162.0609,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35662841796875,\"text\":\"2.320\"},{\"top\":162.0609,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35662841796875,\"text\":\"18.61\"},{\"top\":162.0609,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35662841796875,\"text\":\"1\"},{\"top\":162.0609,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35662841796875,\"text\":\"1\"},{\"top\":162.0609,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35662841796875,\"text\":\"4\"}],[{\"top\":174.41753,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.352005004882812,\"text\":\"21.4\"},{\"top\":174.41753,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.352005004882812,\"text\":\"6\"},{\"top\":174.41753,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.352005004882812,\"text\":\"258.0\"},{\"top\":174.41753,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.352005004882812,\"text\":\"110\"},{\"top\":174.41753,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.352005004882812,\"text\":\"3.08\"},{\"top\":174.41753,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.352005004882812,\"text\":\"3.215\"},{\"top\":174.41753,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.352005004882812,\"text\":\"19.44\"},{\"top\":174.41753,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.352005004882812,\"text\":\"1\"},{\"top\":174.41753,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.352005004882812,\"text\":\"0\"},{\"top\":174.41753,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.352005004882812,\"text\":\"3\"}],[{\"top\":186.76953,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351882934570312,\"text\":\"18.7\"},{\"top\":186.76953,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351882934570312,\"text\":\"8\"},{\"top\":186.76953,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351882934570312,\"text\":\"360.0\"},{\"top\":186.76953,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351882934570312,\"text\":\"175\"},{\"top\":186.76953,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351882934570312,\"text\":\"3.15\"},{\"top\":186.76953,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351882934570312,\"text\":\"3.440\"},{\"top\":186.76953,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351882934570312,\"text\":\"17.02\"},{\"top\":186.76953,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351882934570312,\"text\":\"0\"},{\"top\":186.76953,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351882934570312,\"text\":\"0\"},{\"top\":186.76953,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351882934570312,\"text\":\"3\"}],[{\"top\":199.12141,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.356597900390625,\"text\":\"18.1\"},{\"top\":199.12141,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.356597900390625,\"text\":\"6\"},{\"top\":199.12141,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.356597900390625,\"text\":\"225.0\"},{\"top\":199.12141,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.356597900390625,\"text\":\"105\"},{\"top\":199.12141,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.356597900390625,\"text\":\"2.76\"},{\"top\":199.12141,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.356597900390625,\"text\":\"3.460\"},{\"top\":199.12141,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.356597900390625,\"text\":\"20.22\"},{\"top\":199.12141,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.356597900390625,\"text\":\"1\"},{\"top\":199.12141,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.356597900390625,\"text\":\"0\"},{\"top\":199.12141,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.356597900390625,\"text\":\"3\"}],[{\"top\":211.47801,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351959228515625,\"text\":\"14.3\"},{\"top\":211.47801,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351959228515625,\"text\":\"8\"},{\"top\":211.47801,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351959228515625,\"text\":\"360.0\"},{\"top\":211.47801,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351959228515625,\"text\":\"245\"},{\"top\":211.47801,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351959228515625,\"text\":\"3.21\"},{\"top\":211.47801,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351959228515625,\"text\":\"3.570\"},{\"top\":211.47801,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351959228515625,\"text\":\"15.84\"},{\"top\":211.47801,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351959228515625,\"text\":\"0\"},{\"top\":211.47801,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351959228515625,\"text\":\"0\"},{\"top\":211.47801,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351959228515625,\"text\":\"3\"}],[{\"top\":223.82997,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351806640625,\"text\":\"24.4\"},{\"top\":223.82997,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351806640625,\"text\":\"4\"},{\"top\":223.82997,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351806640625,\"text\":\"146.7\"},{\"top\":223.82997,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351806640625,\"text\":\"62\"},{\"top\":223.82997,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351806640625,\"text\":\"3.69\"},{\"top\":223.82997,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351806640625,\"text\":\"3.190\"},{\"top\":223.82997,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351806640625,\"text\":\"20.00\"},{\"top\":223.82997,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351806640625,\"text\":\"1\"},{\"top\":223.82997,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351806640625,\"text\":\"0\"},{\"top\":223.82997,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351806640625,\"text\":\"4\"}],[{\"top\":236.18178,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.356719970703125,\"text\":\"22.8\"},{\"top\":236.18178,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.356719970703125,\"text\":\"4\"},{\"top\":236.18178,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.356719970703125,\"text\":\"140.8\"},{\"top\":236.18178,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.356719970703125,\"text\":\"95\"},{\"top\":236.18178,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.356719970703125,\"text\":\"3.92\"},{\"top\":236.18178,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.356719970703125,\"text\":\"3.150\"},{\"top\":236.18178,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.356719970703125,\"text\":\"22.90\"},{\"top\":236.18178,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.356719970703125,\"text\":\"1\"},{\"top\":236.18178,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.356719970703125,\"text\":\"0\"},{\"top\":236.18178,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.356719970703125,\"text\":\"4\"}],[{\"top\":248.5385,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351882934570312,\"text\":\"19.2\"},{\"top\":248.5385,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351882934570312,\"text\":\"6\"},{\"top\":248.5385,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351882934570312,\"text\":\"167.6\"},{\"top\":248.5385,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351882934570312,\"text\":\"123\"},{\"top\":248.5385,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351882934570312,\"text\":\"3.92\"},{\"top\":248.5385,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351882934570312,\"text\":\"3.440\"},{\"top\":248.5385,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351882934570312,\"text\":\"18.30\"},{\"top\":248.5385,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351882934570312,\"text\":\"1\"},{\"top\":248.5385,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351882934570312,\"text\":\"0\"},{\"top\":248.5385,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351882934570312,\"text\":\"4\"}],[{\"top\":260.89038,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.3564453125,\"text\":\"17.8\"},{\"top\":260.89038,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.3564453125,\"text\":\"6\"},{\"top\":260.89038,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.3564453125,\"text\":\"167.6\"},{\"top\":260.89038,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.3564453125,\"text\":\"123\"},{\"top\":260.89038,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.3564453125,\"text\":\"3.92\"},{\"top\":260.89038,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.3564453125,\"text\":\"3.440\"},{\"top\":260.89038,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.3564453125,\"text\":\"18.90\"},{\"top\":260.89038,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.3564453125,\"text\":\"1\"},{\"top\":260.89038,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.3564453125,\"text\":\"0\"},{\"top\":260.89038,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.3564453125,\"text\":\"4\"}],[{\"top\":273.24683,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.352142333984375,\"text\":\"16.4\"},{\"top\":273.24683,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.352142333984375,\"text\":\"8\"},{\"top\":273.24683,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.352142333984375,\"text\":\"275.8\"},{\"top\":273.24683,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.352142333984375,\"text\":\"180\"},{\"top\":273.24683,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.352142333984375,\"text\":\"3.07\"},{\"top\":273.24683,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.352142333984375,\"text\":\"4.070\"},{\"top\":273.24683,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.352142333984375,\"text\":\"17.40\"},{\"top\":273.24683,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.352142333984375,\"text\":\"0\"},{\"top\":273.24683,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.352142333984375,\"text\":\"0\"},{\"top\":273.24683,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.352142333984375,\"text\":\"3\"}],[{\"top\":285.59897,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35186767578125,\"text\":\"17.3\"},{\"top\":285.59897,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35186767578125,\"text\":\"8\"},{\"top\":285.59897,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35186767578125,\"text\":\"275.8\"},{\"top\":285.59897,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35186767578125,\"text\":\"180\"},{\"top\":285.59897,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35186767578125,\"text\":\"3.07\"},{\"top\":285.59897,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35186767578125,\"text\":\"3.730\"},{\"top\":285.59897,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35186767578125,\"text\":\"17.60\"},{\"top\":285.59897,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35186767578125,\"text\":\"0\"},{\"top\":285.59897,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35186767578125,\"text\":\"0\"},{\"top\":285.59897,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35186767578125,\"text\":\"3\"}],[{\"top\":297.95084,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.357086181640625,\"text\":\"15.2\"},{\"top\":297.95084,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.357086181640625,\"text\":\"8\"},{\"top\":297.95084,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.357086181640625,\"text\":\"275.8\"},{\"top\":297.95084,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.357086181640625,\"text\":\"180\"},{\"top\":297.95084,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.357086181640625,\"text\":\"3.07\"},{\"top\":297.95084,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.357086181640625,\"text\":\"3.780\"},{\"top\":297.95084,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.357086181640625,\"text\":\"18.00\"},{\"top\":297.95084,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.357086181640625,\"text\":\"0\"},{\"top\":297.95084,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.357086181640625,\"text\":\"0\"},{\"top\":297.95084,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.357086181640625,\"text\":\"3\"}],[{\"top\":310.30792,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.3515625,\"text\":\"10.4\"},{\"top\":310.30792,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.3515625,\"text\":\"8\"},{\"top\":310.30792,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.3515625,\"text\":\"472.0\"},{\"top\":310.30792,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.3515625,\"text\":\"205\"},{\"top\":310.30792,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.3515625,\"text\":\"2.93\"},{\"top\":310.30792,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.3515625,\"text\":\"5.250\"},{\"top\":310.30792,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.3515625,\"text\":\"17.98\"},{\"top\":310.30792,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.3515625,\"text\":\"0\"},{\"top\":310.30792,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.3515625,\"text\":\"0\"},{\"top\":310.30792,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.3515625,\"text\":\"3\"}],[{\"top\":322.6595,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35186767578125,\"text\":\"10.4\"},{\"top\":322.6595,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35186767578125,\"text\":\"8\"},{\"top\":322.6595,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35186767578125,\"text\":\"460.0\"},{\"top\":322.6595,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35186767578125,\"text\":\"215\"},{\"top\":322.6595,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35186767578125,\"text\":\"3.00\"},{\"top\":322.6595,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35186767578125,\"text\":\"5.424\"},{\"top\":322.6595,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35186767578125,\"text\":\"17.82\"},{\"top\":322.6595,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35186767578125,\"text\":\"0\"},{\"top\":322.6595,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35186767578125,\"text\":\"0\"},{\"top\":322.6595,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35186767578125,\"text\":\"3\"}],[{\"top\":335.01135,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.357086181640625,\"text\":\"14.7\"},{\"top\":335.01135,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.357086181640625,\"text\":\"8\"},{\"top\":335.01135,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.357086181640625,\"text\":\"440.0\"},{\"top\":335.01135,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.357086181640625,\"text\":\"230\"},{\"top\":335.01135,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.357086181640625,\"text\":\"3.23\"},{\"top\":335.01135,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.357086181640625,\"text\":\"5.345\"},{\"top\":335.01135,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.357086181640625,\"text\":\"17.42\"},{\"top\":335.01135,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.357086181640625,\"text\":\"0\"},{\"top\":335.01135,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.357086181640625,\"text\":\"0\"},{\"top\":335.01135,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.357086181640625,\"text\":\"3\"}],[{\"top\":347.36844,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351531982421875,\"text\":\"32.4\"},{\"top\":347.36844,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351531982421875,\"text\":\"4\"},{\"top\":347.36844,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351531982421875,\"text\":\"78.7\"},{\"top\":347.36844,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351531982421875,\"text\":\"66\"},{\"top\":347.36844,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351531982421875,\"text\":\"4.08\"},{\"top\":347.36844,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351531982421875,\"text\":\"2.200\"},{\"top\":347.36844,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351531982421875,\"text\":\"19.47\"},{\"top\":347.36844,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351531982421875,\"text\":\"1\"},{\"top\":347.36844,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351531982421875,\"text\":\"1\"},{\"top\":347.36844,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351531982421875,\"text\":\"4\"}],[{\"top\":359.71997,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.3570556640625,\"text\":\"30.4\"},{\"top\":359.71997,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.3570556640625,\"text\":\"4\"},{\"top\":359.71997,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.3570556640625,\"text\":\"75.7\"},{\"top\":359.71997,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.3570556640625,\"text\":\"52\"},{\"top\":359.71997,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.3570556640625,\"text\":\"4.93\"},{\"top\":359.71997,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.3570556640625,\"text\":\"1.615\"},{\"top\":359.71997,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.3570556640625,\"text\":\"18.52\"},{\"top\":359.71997,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.3570556640625,\"text\":\"1\"},{\"top\":359.71997,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.3570556640625,\"text\":\"1\"},{\"top\":359.71997,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.3570556640625,\"text\":\"4\"}],[{\"top\":372.07703,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351959228515625,\"text\":\"33.9\"},{\"top\":372.07703,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351959228515625,\"text\":\"4\"},{\"top\":372.07703,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351959228515625,\"text\":\"71.1\"},{\"top\":372.07703,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351959228515625,\"text\":\"65\"},{\"top\":372.07703,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351959228515625,\"text\":\"4.22\"},{\"top\":372.07703,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351959228515625,\"text\":\"1.835\"},{\"top\":372.07703,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351959228515625,\"text\":\"19.90\"},{\"top\":372.07703,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351959228515625,\"text\":\"1\"},{\"top\":372.07703,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351959228515625,\"text\":\"1\"},{\"top\":372.07703,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351959228515625,\"text\":\"4\"}],[{\"top\":384.429,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351531982421875,\"text\":\"21.5\"},{\"top\":384.429,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351531982421875,\"text\":\"4\"},{\"top\":384.429,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351531982421875,\"text\":\"120.1\"},{\"top\":384.429,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351531982421875,\"text\":\"97\"},{\"top\":384.429,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351531982421875,\"text\":\"3.70\"},{\"top\":384.429,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351531982421875,\"text\":\"2.465\"},{\"top\":384.429,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351531982421875,\"text\":\"20.01\"},{\"top\":384.429,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351531982421875,\"text\":\"1\"},{\"top\":384.429,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351531982421875,\"text\":\"0\"},{\"top\":384.429,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351531982421875,\"text\":\"3\"}],[{\"top\":396.78052,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.357025146484375,\"text\":\"15.5\"},{\"top\":396.78052,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.357025146484375,\"text\":\"8\"},{\"top\":396.78052,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.357025146484375,\"text\":\"318.0\"},{\"top\":396.78052,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.357025146484375,\"text\":\"150\"},{\"top\":396.78052,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.357025146484375,\"text\":\"2.76\"},{\"top\":396.78052,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.357025146484375,\"text\":\"3.520\"},{\"top\":396.78052,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.357025146484375,\"text\":\"16.87\"},{\"top\":396.78052,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.357025146484375,\"text\":\"0\"},{\"top\":396.78052,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.357025146484375,\"text\":\"0\"},{\"top\":396.78052,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.357025146484375,\"text\":\"3\"}],[{\"top\":409.13754,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35205078125,\"text\":\"15.2\"},{\"top\":409.13754,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35205078125,\"text\":\"8\"},{\"top\":409.13754,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35205078125,\"text\":\"304.0\"},{\"top\":409.13754,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35205078125,\"text\":\"150\"},{\"top\":409.13754,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35205078125,\"text\":\"3.15\"},{\"top\":409.13754,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35205078125,\"text\":\"3.435\"},{\"top\":409.13754,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35205078125,\"text\":\"17.30\"},{\"top\":409.13754,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35205078125,\"text\":\"0\"},{\"top\":409.13754,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35205078125,\"text\":\"0\"},{\"top\":409.13754,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35205078125,\"text\":\"3\"}],[{\"top\":421.4896,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351348876953125,\"text\":\"13.3\"},{\"top\":421.4896,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351348876953125,\"text\":\"8\"},{\"top\":421.4896,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351348876953125,\"text\":\"350.0\"},{\"top\":421.4896,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351348876953125,\"text\":\"245\"},{\"top\":421.4896,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351348876953125,\"text\":\"3.73\"},{\"top\":421.4896,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351348876953125,\"text\":\"3.840\"},{\"top\":421.4896,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351348876953125,\"text\":\"15.41\"},{\"top\":421.4896,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351348876953125,\"text\":\"0\"},{\"top\":421.4896,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351348876953125,\"text\":\"0\"},{\"top\":421.4896,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351348876953125,\"text\":\"3\"}],[{\"top\":433.84094,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.357208251953125,\"text\":\"19.2\"},{\"top\":433.84094,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.357208251953125,\"text\":\"8\"},{\"top\":433.84094,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.357208251953125,\"text\":\"400.0\"},{\"top\":433.84094,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.357208251953125,\"text\":\"175\"},{\"top\":433.84094,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.357208251953125,\"text\":\"3.08\"},{\"top\":433.84094,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.357208251953125,\"text\":\"3.845\"},{\"top\":433.84094,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.357208251953125,\"text\":\"17.05\"},{\"top\":433.84094,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.357208251953125,\"text\":\"0\"},{\"top\":433.84094,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.357208251953125,\"text\":\"0\"},{\"top\":433.84094,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.357208251953125,\"text\":\"3\"}],[{\"top\":446.19815,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35186767578125,\"text\":\"27.3\"},{\"top\":446.19815,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35186767578125,\"text\":\"4\"},{\"top\":446.19815,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35186767578125,\"text\":\"79.0\"},{\"top\":446.19815,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35186767578125,\"text\":\"66\"},{\"top\":446.19815,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35186767578125,\"text\":\"4.08\"},{\"top\":446.19815,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35186767578125,\"text\":\"1.935\"},{\"top\":446.19815,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35186767578125,\"text\":\"18.90\"},{\"top\":446.19815,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35186767578125,\"text\":\"1\"},{\"top\":446.19815,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35186767578125,\"text\":\"1\"},{\"top\":446.19815,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35186767578125,\"text\":\"4\"}],[{\"top\":458.55002,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35150146484375,\"text\":\"26.0\"},{\"top\":458.55002,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35150146484375,\"text\":\"4\"},{\"top\":458.55002,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35150146484375,\"text\":\"120.3\"},{\"top\":458.55002,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35150146484375,\"text\":\"91\"},{\"top\":458.55002,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35150146484375,\"text\":\"4.43\"},{\"top\":458.55002,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35150146484375,\"text\":\"2.140\"},{\"top\":458.55002,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35150146484375,\"text\":\"16.70\"},{\"top\":458.55002,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35150146484375,\"text\":\"0\"},{\"top\":458.55002,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35150146484375,\"text\":\"1\"},{\"top\":458.55002,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35150146484375,\"text\":\"5\"}],[{\"top\":470.90152,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.357025146484375,\"text\":\"30.4\"},{\"top\":470.90152,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.357025146484375,\"text\":\"4\"},{\"top\":470.90152,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.357025146484375,\"text\":\"95.1\"},{\"top\":470.90152,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.357025146484375,\"text\":\"113\"},{\"top\":470.90152,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.357025146484375,\"text\":\"3.77\"},{\"top\":470.90152,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.357025146484375,\"text\":\"1.513\"},{\"top\":470.90152,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.357025146484375,\"text\":\"16.90\"},{\"top\":470.90152,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.357025146484375,\"text\":\"1\"},{\"top\":470.90152,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.357025146484375,\"text\":\"1\"},{\"top\":470.90152,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.357025146484375,\"text\":\"5\"}],[{\"top\":483.25854,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.351776123046875,\"text\":\"15.8\"},{\"top\":483.25854,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.351776123046875,\"text\":\"8\"},{\"top\":483.25854,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.351776123046875,\"text\":\"351.0\"},{\"top\":483.25854,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.351776123046875,\"text\":\"264\"},{\"top\":483.25854,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.351776123046875,\"text\":\"4.22\"},{\"top\":483.25854,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.351776123046875,\"text\":\"3.170\"},{\"top\":483.25854,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.351776123046875,\"text\":\"14.50\"},{\"top\":483.25854,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.351776123046875,\"text\":\"0\"},{\"top\":483.25854,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.351776123046875,\"text\":\"1\"},{\"top\":483.25854,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.351776123046875,\"text\":\"5\"}],[{\"top\":495.61032,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.356109619140625,\"text\":\"19.7\"},{\"top\":495.61032,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.356109619140625,\"text\":\"6\"},{\"top\":495.61032,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.356109619140625,\"text\":\"145.0\"},{\"top\":495.61032,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.356109619140625,\"text\":\"175\"},{\"top\":495.61032,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.356109619140625,\"text\":\"3.62\"},{\"top\":495.61032,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.356109619140625,\"text\":\"2.770\"},{\"top\":495.61032,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.356109619140625,\"text\":\"15.50\"},{\"top\":495.61032,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.356109619140625,\"text\":\"0\"},{\"top\":495.61032,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.356109619140625,\"text\":\"1\"},{\"top\":495.61032,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.356109619140625,\"text\":\"5\"}],[{\"top\":507.96643,\"left\":247.14917,\"width\":30.773834228515625,\"height\":12.35247802734375,\"text\":\"15.0\"},{\"top\":507.96643,\"left\":277.923,\"width\":24.407867431640625,\"height\":12.35247802734375,\"text\":\"8\"},{\"top\":507.96643,\"left\":302.33087,\"width\":34.6478271484375,\"height\":12.35247802734375,\"text\":\"301.0\"},{\"top\":507.96643,\"left\":336.9787,\"width\":26.899566650390625,\"height\":12.35247802734375,\"text\":\"335\"},{\"top\":507.96643,\"left\":363.87827,\"width\":30.24810791015625,\"height\":12.35247802734375,\"text\":\"3.54\"},{\"top\":507.96643,\"left\":394.12637,\"width\":34.64752197265625,\"height\":12.35247802734375,\"text\":\"3.570\"},{\"top\":507.96643,\"left\":428.7739,\"width\":34.64801025390625,\"height\":12.35247802734375,\"text\":\"14.60\"},{\"top\":507.96643,\"left\":463.4219,\"width\":21.1429443359375,\"height\":12.35247802734375,\"text\":\"0\"},{\"top\":507.96643,\"left\":484.56485,\"width\":25.238006591796875,\"height\":12.35247802734375,\"text\":\"1\"},{\"top\":507.96643,\"left\":509.80286,\"width\":30.24798583984375,\"height\":12.35247802734375,\"text\":\"5\"}]]}]"
],
[
"tabula.convert_into(pdf_path, \"test.tsv\", output_format=\"tsv\")\n!cat test.tsv",
"mpg\tcyl\tdisp\thp\tdrat\twt\tqsec\tvs\tam\tgear\r\n21.0\t6\t160.0\t110\t3.90\t2.620\t16.46\t0\t1\t4\r\n21.0\t6\t160.0\t110\t3.90\t2.875\t17.02\t0\t1\t4\r\n22.8\t4\t108.0\t93\t3.85\t2.320\t18.61\t1\t1\t4\r\n21.4\t6\t258.0\t110\t3.08\t3.215\t19.44\t1\t0\t3\r\n18.7\t8\t360.0\t175\t3.15\t3.440\t17.02\t0\t0\t3\r\n18.1\t6\t225.0\t105\t2.76\t3.460\t20.22\t1\t0\t3\r\n14.3\t8\t360.0\t245\t3.21\t3.570\t15.84\t0\t0\t3\r\n24.4\t4\t146.7\t62\t3.69\t3.190\t20.00\t1\t0\t4\r\n22.8\t4\t140.8\t95\t3.92\t3.150\t22.90\t1\t0\t4\r\n19.2\t6\t167.6\t123\t3.92\t3.440\t18.30\t1\t0\t4\r\n17.8\t6\t167.6\t123\t3.92\t3.440\t18.90\t1\t0\t4\r\n16.4\t8\t275.8\t180\t3.07\t4.070\t17.40\t0\t0\t3\r\n17.3\t8\t275.8\t180\t3.07\t3.730\t17.60\t0\t0\t3\r\n15.2\t8\t275.8\t180\t3.07\t3.780\t18.00\t0\t0\t3\r\n10.4\t8\t472.0\t205\t2.93\t5.250\t17.98\t0\t0\t3\r\n10.4\t8\t460.0\t215\t3.00\t5.424\t17.82\t0\t0\t3\r\n14.7\t8\t440.0\t230\t3.23\t5.345\t17.42\t0\t0\t3\r\n32.4\t4\t78.7\t66\t4.08\t2.200\t19.47\t1\t1\t4\r\n30.4\t4\t75.7\t52\t4.93\t1.615\t18.52\t1\t1\t4\r\n33.9\t4\t71.1\t65\t4.22\t1.835\t19.90\t1\t1\t4\r\n21.5\t4\t120.1\t97\t3.70\t2.465\t20.01\t1\t0\t3\r\n15.5\t8\t318.0\t150\t2.76\t3.520\t16.87\t0\t0\t3\r\n15.2\t8\t304.0\t150\t3.15\t3.435\t17.30\t0\t0\t3\r\n13.3\t8\t350.0\t245\t3.73\t3.840\t15.41\t0\t0\t3\r\n19.2\t8\t400.0\t175\t3.08\t3.845\t17.05\t0\t0\t3\r\n27.3\t4\t79.0\t66\t4.08\t1.935\t18.90\t1\t1\t4\r\n26.0\t4\t120.3\t91\t4.43\t2.140\t16.70\t0\t1\t5\r\n30.4\t4\t95.1\t113\t3.77\t1.513\t16.90\t1\t1\t5\r\n15.8\t8\t351.0\t264\t4.22\t3.170\t14.50\t0\t1\t5\r\n19.7\t6\t145.0\t175\t3.62\t2.770\t15.50\t0\t1\t5\r\n15.0\t8\t301.0\t335\t3.54\t3.570\t14.60\t0\t1\t5\r\n"
],
[
"tabula.convert_into(pdf_path, \"test.csv\", output_format=\"csv\", stream=True)\n!cat test.csv",
"\"\",mpg,cyl,disp,hp,drat,wt,qsec,vs,am,gear,carb\r\nMazda RX4,21.0,6,160.0,110,3.90,2.620,16.46,0,1,4,4\r\nMazda RX4 Wag,21.0,6,160.0,110,3.90,2.875,17.02,0,1,4,4\r\nDatsun 710,22.8,4,108.0,93,3.85,2.320,18.61,1,1,4,1\r\nHornet 4 Drive,21.4,6,258.0,110,3.08,3.215,19.44,1,0,3,1\r\nHornet Sportabout,18.7,8,360.0,175,3.15,3.440,17.02,0,0,3,2\r\nValiant,18.1,6,225.0,105,2.76,3.460,20.22,1,0,3,1\r\nDuster 360,14.3,8,360.0,245,3.21,3.570,15.84,0,0,3,4\r\nMerc 240D,24.4,4,146.7,62,3.69,3.190,20.00,1,0,4,2\r\nMerc 230,22.8,4,140.8,95,3.92,3.150,22.90,1,0,4,2\r\nMerc 280,19.2,6,167.6,123,3.92,3.440,18.30,1,0,4,4\r\nMerc 280C,17.8,6,167.6,123,3.92,3.440,18.90,1,0,4,4\r\nMerc 450SE,16.4,8,275.8,180,3.07,4.070,17.40,0,0,3,3\r\nMerc 450SL,17.3,8,275.8,180,3.07,3.730,17.60,0,0,3,3\r\nMerc 450SLC,15.2,8,275.8,180,3.07,3.780,18.00,0,0,3,3\r\nCadillac Fleetwood,10.4,8,472.0,205,2.93,5.250,17.98,0,0,3,4\r\nLincoln Continental,10.4,8,460.0,215,3.00,5.424,17.82,0,0,3,4\r\nChrysler Imperial,14.7,8,440.0,230,3.23,5.345,17.42,0,0,3,4\r\nFiat 128,32.4,4,78.7,66,4.08,2.200,19.47,1,1,4,1\r\nHonda Civic,30.4,4,75.7,52,4.93,1.615,18.52,1,1,4,2\r\nToyota Corolla,33.9,4,71.1,65,4.22,1.835,19.90,1,1,4,1\r\nToyota Corona,21.5,4,120.1,97,3.70,2.465,20.01,1,0,3,1\r\nDodge Challenger,15.5,8,318.0,150,2.76,3.520,16.87,0,0,3,2\r\nAMC Javelin,15.2,8,304.0,150,3.15,3.435,17.30,0,0,3,2\r\nCamaro Z28,13.3,8,350.0,245,3.73,3.840,15.41,0,0,3,4\r\nPontiac Firebird,19.2,8,400.0,175,3.08,3.845,17.05,0,0,3,2\r\nFiat X1-9,27.3,4,79.0,66,4.08,1.935,18.90,1,1,4,1\r\nPorsche 914-2,26.0,4,120.3,91,4.43,2.140,16.70,0,1,5,2\r\nLotus Europa,30.4,4,95.1,113,3.77,1.513,16.90,1,1,5,2\r\nFord Pantera L,15.8,8,351.0,264,4.22,3.170,14.50,0,1,5,4\r\nFerrari Dino,19.7,6,145.0,175,3.62,2.770,15.50,0,1,5,6\r\nMaserati Bora,15.0,8,301.0,335,3.54,3.570,14.60,0,1,5,8\r\nVolvo 142E,21.4,4,121.0,109,4.11,2.780,18.60,1,1,4,2\r\n"
]
],
[
[
"## Use lattice mode for more accurate extraction for spreadsheet style tables\n\nIf your tables have lines separating cells, you can use `lattice` option. By default, tabula-py sets `guess=True`, which is the same behavior for default of tabula app. If your tables don't have separation lines, you can try `stream` option.\n\nAs it mentioned, try tabula app before struglling with tabula-py option. Or, [PDFplumber](https://github.com/jsvine/pdfplumber) can be an alternative since it has different extraction strategy.",
"_____no_output_____"
]
],
[
[
"tabula.read_pdf(pdf_path, pages=\"1\", lattice=True)",
"_____no_output_____"
]
],
[
[
"## Use tabula app template\n\ntabula-py can handle tabula app template, which has area options set by GUI app to reuse.",
"_____no_output_____"
]
],
[
[
"!wget -q \"https://github.com/chezou/tabula-py/raw/master/tests/resources/data.tabula-template.json\"\n\ntabula.read_pdf_with_template(pdf_path, \"data.tabula-template.json\")",
"_____no_output_____"
]
],
[
[
"If you have any question, ask on [StackOverflow](https://stackoverflow.com/search?q=tabula-py).",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b19d0b93f7a09d00e0f3ec2d9a88c2d24726b0 | 137,443 | ipynb | Jupyter Notebook | ClointFusion_Labs.ipynb | JAY-007-TRIVEDI/ClointFusion | 7abd18608dcbd0d5722a1432e095671c52678cd5 | [
"BSD-4-Clause"
] | 1 | 2021-06-16T18:37:02.000Z | 2021-06-16T18:37:02.000Z | ClointFusion_Labs.ipynb | JAY-007-TRIVEDI/ClointFusion | 7abd18608dcbd0d5722a1432e095671c52678cd5 | [
"BSD-4-Clause"
] | null | null | null | ClointFusion_Labs.ipynb | JAY-007-TRIVEDI/ClointFusion | 7abd18608dcbd0d5722a1432e095671c52678cd5 | [
"BSD-4-Clause"
] | null | null | null | 68.379602 | 67,351 | 0.750828 | [
[
[
"\n\n# **Welcome to ClointFusion, Made in India with ❤️ (Version 0.1.37)**",
"_____no_output_____"
],
[
"ClointFusion's Jupyter Notebook\n\n* ClointFusion offers you Python based RPA platform for your Automation needs. \n\n* You now have access to more than 130 easy to use functions, which could be used in GUI and non GUI mode as well. If you prefer GUI mode, you could run your BOTs in Fully Automatic Mode or Interactive (Semi-Automatic) Mode.\n\n* You may use this platform to explore and experiment with these functions and contribute by giving a star on GitHub / writing blog article on ClointFusion / feedback / report any issues / help us in bug fixes / feature enhancement / add documentation / many more ways as you please.. \n\n\nFor more details, on how to contribute, please visit ClointFusion GitHub repository at : https://github.com/ClointFusion/ClointFusion\n",
"_____no_output_____"
],
[
"# **Start here by importing** *ClointFusion*\n\n",
"_____no_output_____"
],
[
"On executing below cell, if you are able to see **Welcome to ClointFusion, Made in India with ❤️** & 2 prompt messages, then you are all set.. Kudos ! \n\n(Depending on your internet speed, you might see a slight delay in getting this welcome message, as all required Python packages are to be downloaded & installed)\n\n\n",
"_____no_output_____"
]
],
[
[
"import ClointFusion as cf",
"_____no_output_____"
]
],
[
[
"NOTE: We recommend that you execute (press ▶️) for each function, block-by-block, as-it-is, before adjusting parameters/inputs. Once you've verified that the function is working, you are welcome to play with it, learn from manipulating inputs/parameters and even contribute in a way of bug fixing or enhancing with new features. Please read the CONTRIBUTING.md file in GitHub.\n\nAs a reminder, this ClointFusion Jupyter Notebook is not for sharing; please refer to the **Copyright** directly below and **Code License Agreement** in the last cell of this notebook.\n\n*Team ClointFusion*,\n\n<hr>\n\n***Copyright:*** *The contents of this Jupyter Notebook, unless otherwise indicated, are Copyright of 2020 ClointFusion, https://cloint.com, released under BSD-4 License* ",
"_____no_output_____"
],
[
"# **Test drive a *ClointFusion* function now !**\n\n",
"_____no_output_____"
],
[
"Tip: While executing any of the below cells, there are chances that, Google Colab session may get crashed. In that case, please run above import cell once again & click on Reconnect, and you can continue with your exploration...",
"_____no_output_____"
]
],
[
[
"print(\"Hi {} ! Welcome to ClointFusion {}\".format(cf.gui_get_any_input_from_user('your Name'),cf.show_emoji()))",
"_____no_output_____"
]
],
[
[
"Note : Executing *import ClointFusion as cf* in any Python file, would create a set of folders in C:\\ClointFusion. The sub folders created are Batch_File, Config_Files, Error_Screenshots, Images, Logs, Output and StatusLogExcel. All these 7 folders would be placed in a parent folder, which has name that begins with My_Bot_Folder_Name. Here, Folder_Name has same name, as the one where you are importing ClointFusion as cf !\n\nTip : Most of ClointFusion's functions work in Dual mode i.e if you pass the required arguments, ClointFusion works silently, else ClointFusion would popup a GUI, asking you for required inputs and here if semi_automatic_mode is ENABLED, your previous inputs would be used to run the function, else if semi_automatic_mode is DISABLED, GUI would be shown with previously used inputs & you could modify them.\n\nYou have 2 functions turn ON/OFF the semi-automatic mode #Working internally, to be made public\n\ncf.ON_semi_automatic_mode()\ncf.OFF_semi_automatic_mode()",
"_____no_output_____"
],
[
"# **GUI Based Functions**\n\nWe have 6 functions which take different inputs from users.",
"_____no_output_____"
]
],
[
[
"cf.OFF_semi_automatic_mode()\n\noutlook_url = 'https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=13&ct=1622187509&rver=7.0.6737.0&wp=MBI_SSL&wreply=https%3a%2f%2foutlook.live.com%2fowa%2f0%2f%3fstate%3d1%26redirectTo%3daHR0cHM6Ly9vdXRsb29rLmxpdmUuY29tL21haWwvMC9pbmJveC8%26nlp%3d1%26RpsCsrfState%3da1418c6a-2688-64b6-5738-67971d0c6e02&id=292841&aadredir=1&CBCXT=out&lw=1&fl=dob%2cflname%2cwld&cobrandid=90015'\n\ncf.window_show_desktop()\n\n\nresponse = cf.gui_get_consent_from_user(msgForUser=\"Want to start Mailing\")\n\nif response == 'Yes':\n # cf.gui_get_dropdownlist_values_from_user()\n mail_client = cf.gui_get_dropdownlist_values_from_user(msgForUser='Select the email Client',\n dropdown_list=['Outlook', 'Yahoo'], multi_select=False)\n\n if mail_client == ['Outlook']:\n cf.browser_navigate_h(outlook_url)\n\n # cf.gui_get_any_input_from_user()\n username = cf.gui_get_any_input_from_user('Enter Username')\n cf.key_write_enter(username)\n password = cf.gui_get_any_input_from_user('Enter Password', password=True)\n cf.key_write_enter(password)\n\n close = cf.gui_get_consent_from_user(msgForUser=\"Want to Close Mail\")\n if close == 'Yes':\n cf.browser_quit_h()\n",
"_____no_output_____"
],
[
"file = cf.gui_get_any_file_from_user()\nprint(file)",
"_____no_output_____"
],
[
"excel_file = cf.gui_get_excel_sheet_header_from_user()\nprint(excel_file)",
"_____no_output_____"
],
[
"folder = cf.gui_get_folder_path_from_user()\nprint(folder)",
"_____no_output_____"
]
],
[
[
"# **Excel Based Functions**",
"_____no_output_____"
]
],
[
[
"import os\n\nWORKSPACE_DIR = r\"C:\\Users\\Hp\\Desktop\\Excel_Operations\"\nEXCEL_FILES_DIR = os.path.join(WORKSPACE_DIR,'Excel_Files')\ntest_xlsx_path = os.path.join(EXCEL_FILES_DIR,'Test','Test.xlsx')\nnew_test_xlsx_path = os.path.join(EXCEL_FILES_DIR,'Test','New_Test.xlsx')",
"_____no_output_____"
]
],
[
[
"# Excel Operations | ClointFusion\n\n- 20+ Excel Operations\n\n| Function Name | Accepted Parameters | Description |\n| :--- | :--- | :--- |\n|excel_create_excel_file_in_given_folder()| fullpathToTheFodler='',excelFileName='',sheet_name='' |Creates a new excel file in the given folder|\n| excel_create_file() | fullPathToTheFile='',fileName='',sheet_name='' | Creates a new excel file in the provided folder |\n| excel_get_all_sheet_names() | excelFilePath=\"\" | Gives you all names of the sheets in the given excel sheet |\n| excel_get_all_header_columns() | excel_path=\"\",sheet_name=\"Sheet1\",header=0 | Returns all the column names of the excel file |\n| excel_if_value_exists() | excel_path=\"\",sheet_name='Sheet1',header=0,usecols=\"\",value=\"\" | Check if a given value exists in given excel. Return True/False |\n| excel_copy_paste_range_from_to_sheet() | excel_path=\"\", sheet_name='Sheet1', startCol=0, startRow=0, endCol=0, endRow=0, copiedData=\"\" | Pastes the copied data in the specific range of the given excel sheet |\n| excel_get_row_column_count() | excel_path=\"\", sheet_name=\"Sheet1\", header=0 | Gets the row and coloumn count of the provided excel sheet |\n| excel_copy_range_from_sheet() | excel_path=\"\", sheet_name='Sheet1', startCol=0, startRow=0, endCol=0, endRow=0 | Copies the specific range from the provided excel sheet and returns copied data as a list |\n| excel_split_by_column() | excel_path=\"\",sheet_name='Sheet1',header=0,columnName=\"\" | Splits the excel file by Column Name |\n| excel_split_the_file_on_row_count() | excel_path=\"\", sheet_name = 'Sheet1', rowSplitLimit=\"\", outputFolderPath=\"\", outputTemplateFileName =\"Split\" | Splits the excel file as per given row limit |\n| excel_merge_all_files() | input_folder_path=\"\",output_folder_path=\"\" | Merges all the excel files in the given folder |\n| excel_drop_columns() | excel_path=\"\", sheet_name='Sheet1', header=0, columnsToBeDropped = \"\" | Drops the desired column from the given excel file |\n| excel_sort_columns() | excel_path=\"\",sheet_name='Sheet1', header=0, firstColumnToBeSorted=None, secondColumnToBeSorted=None,thirdColumnToBeSorted=None, firstColumnSortType=True, secondColumnSortType=True, thirdColumnSortType=True | A function which takes excel full path to excel and column names on which sort is to be performed |\n| excel_clear_sheet() | excel_path=\"\",sheet_name=\"Sheet1\", header=0 | Clears the contents of given excel files keeping header row intact |\n| excel_set_single_cell() | excel_path='',sheet_name='',header=0,columnName='',cellNumber=0,setText='' | Writes the given text to the desired column/cell number for the given excel file |\n| excel_get_single_cell() | excel_path=\"\",sheet_name=\"Sheet1\",header=0, columnName=\"\",cellNumber=0 | Gets the text from the desired column/cell number of the given excel file |\n| excel_remove_duplicates() | excel_path=\"\",sheet_name=\"Sheet1\", header=0, columnName=\"\", saveResultsInSameExcel=True, which_one_to_keep=\"first\" | Drops the duplicates from the desired Column of the given excel file |\n| excel_vlook_up() | filepath_1=\"\", sheet_name_1 = 'Sheet1', header_1 = 0,filepath_2=\"\", sheet_name_2 = 'Sheet1', header_2 = 0, Output_path=\"\", OutputExcelFileName=\"\", match_column_name=\"\",how='left' | Performs excel_vlook_up on the given excel files for the desired columns. Possible values for how are \"inner\",\"left\", \"right\", \"outer\" |\n| excel_describe_data() | excel_path=\"\",sheet_name='Sheet1',header=0 | Describe statistical data for the given excel |\n| excel_change_corrupt_xls_to_xlsx() | xls_file ='',xlsx_file = '', xls_sheet_name='' | Repair corrupt excel file |\n",
"_____no_output_____"
],
[
"## Create a new excel file",
"_____no_output_____"
]
],
[
[
"# Creates a new excel file New_Test.xlsx in Test folder\ncf.excel_create_file(fullPathToTheFile=os.path.join(EXCEL_FILES_DIR,'Test'),fileName='New_Test',sheet_name='Sheet1')",
"_____no_output_____"
],
[
"# Creating a new excel file Test.xlsx\ncf.excel_create_excel_file_in_given_folder(fullPathToTheFolder=os.path.dirname(test_xlsx_path),excelFileName='Test.xlsx',sheet_name='Sheet1')",
"_____no_output_____"
]
],
[
[
"## Add some data into it with Excel set single Cell",
"_____no_output_____"
]
],
[
[
"# Adding some data into the Test.xlsx file\n'''\nOutput: \n\n|Name | Age |\n|-----|-----|\n|A | 5 |\n|B | 4 |\n|C | 3 |\n|D | 2 |\n|E | 1 |\n'''\n\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Name',cellNumber=0,setText='A')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Name',cellNumber=1,setText='B')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Name',cellNumber=2,setText='C')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Name',cellNumber=3,setText='D')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Name',cellNumber=4,setText='E')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Name',cellNumber=5,setText='F')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Name',cellNumber=6,setText='F')\n\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Age',cellNumber=0,setText='5')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Age',cellNumber=1,setText='4')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Age',cellNumber=2,setText='3')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Age',cellNumber=3,setText='2')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Age',cellNumber=4,setText='1')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Age',cellNumber=5,setText='6')\ncf.excel_set_single_cell(excel_path=test_xlsx_path,columnName='Age',cellNumber=6,setText='6')",
"_____no_output_____"
]
],
[
[
"## Get All sheet names",
"_____no_output_____"
]
],
[
[
"# Get all the sheet names of Test.xlsx\ncf.excel_get_all_sheet_names(excelFilePath=test_xlsx_path)",
"_____no_output_____"
]
],
[
[
"## Get all Header Columns",
"_____no_output_____"
]
],
[
[
"cf.excel_get_all_header_columns(excel_path=test_xlsx_path,sheet_name='Sheet1')",
"_____no_output_____"
]
],
[
[
"## Get Row Column Count",
"_____no_output_____"
]
],
[
[
"cf.excel_get_row_column_count(excel_path=test_xlsx_path,sheet_name='Sheet1')",
"_____no_output_____"
]
],
[
[
"## Excel Split by ColumnName",
"_____no_output_____"
]
],
[
[
"# Splitting the column into different excel files according to the columnName\n\ncf.excel_split_by_column(excel_path=test_xlsx_path, columnName='Age')",
"_____no_output_____"
]
],
[
[
"## Excel Split by row count",
"_____no_output_____"
]
],
[
[
"# Divide the excel file based on the row count\ncf.excel_split_the_file_on_row_count(excel_path=test_xlsx_path, rowSplitLimit=3, outputFolderPath=EXCEL_FILES_DIR)",
"_____no_output_____"
]
],
[
[
"## Excel Merge Files",
"_____no_output_____"
]
],
[
[
"merge_folder = os.path.join(EXCEL_FILES_DIR,'Test')\ncf.excel_merge_all_files(input_folder_path=EXCEL_FILES_DIR, output_folder_path=merge_folder)",
"_____no_output_____"
]
],
[
[
"## Excel sort Columns",
"_____no_output_____"
]
],
[
[
"cf.excel_sort_columns(excel_path=test_xlsx_path, firstColumnToBeSorted='Name', secondColumnToBeSorted='Age')",
"_____no_output_____"
]
],
[
[
"## Excel Drop Columns",
"_____no_output_____"
]
],
[
[
"split_excel_file1 = os.path.join(EXCEL_FILES_DIR, \"Split-1.xlsx\")\nsplit_excel_file2 = os.path.join(EXCEL_FILES_DIR, \"Split-2.xlsx\")\ncf.excel_drop_columns(excel_path=split_excel_file1, sheet_name='Sheet1', columnsToBeDropped='Age')",
"_____no_output_____"
]
],
[
[
"## Excel Clear Sheet",
"_____no_output_____"
]
],
[
[
"cf.excel_clear_sheet(excel_path=split_excel_file2, sheet_name='Sheet1')",
"_____no_output_____"
]
],
[
[
"## Excel Get Single Cell",
"_____no_output_____"
]
],
[
[
"cf.excel_get_single_cell(excel_path=test_xlsx_path, columnName='Name', cellNumber=0)",
"_____no_output_____"
]
],
[
[
"## Excel Remove Duplicates",
"_____no_output_____"
]
],
[
[
"cf.excel_remove_duplicates(excel_path=test_xlsx_path, columnName='Name')",
"_____no_output_____"
]
],
[
[
"## Excel vlook-up",
"_____no_output_____"
]
],
[
[
"cf.excel_vlook_up(filepath_1=split_excel_file1, filepath_2=test_xlsx_path, match_column_name='Name')",
"_____no_output_____"
]
],
[
[
"## Excel Describe Data",
"_____no_output_____"
]
],
[
[
"cf.excel_describe_data(excel_path=test_xlsx_path,sheet_name='Sheet1')",
"_____no_output_____"
]
],
[
[
"## Excel Check if data exists",
"_____no_output_____"
]
],
[
[
"cf.excel_if_value_exists(excel_path=test_xlsx_path, usecols=['Name'], value='A')",
"_____no_output_____"
]
],
[
[
"## Excel Copy Range from Sheet",
"_____no_output_____"
]
],
[
[
"copied_data = cf.excel_copy_range_from_sheet(excel_path=test_xlsx_path, startCol=1, startRow=1, endRow=5, endCol=2)",
"_____no_output_____"
]
],
[
[
"## Excel Copy Paste Range From To",
"_____no_output_____"
]
],
[
[
"cf.excel_copy_paste_range_from_to_sheet(excel_path=new_test_xlsx_path, startCol=1, startRow=1, endRow=5, endCol=2, copiedData=copied_data)",
"_____no_output_____"
]
],
[
[
"Tip: In any case, if **ClointFusion-Labs**, stops responding, then just refresh this page and go to Connect and click **CONNECT** (no need to run jupyter commands again) and execute **import ClointFusion as cf** block again. Now, you can resume with your functions.",
"_____no_output_____"
],
[
"# **Mouse Operations**",
"_____no_output_____"
]
],
[
[
"# Moves the cursor to the given X Y Co-ordinates.\ncf.mouse_move(1766,8)",
"_____no_output_____"
],
[
"# Clicks at the given X Y Co-ordinates on the screen using ingle / double / tripple click(s).\n# Optionally copies selected data to clipboard (works for double / triple clicks).\ncf.mouse_click(x=1100, y=777, left_or_right=\"left\", no_of_clicks=1)",
"_____no_output_____"
],
[
"# Searches the given image on the screen and returns its center of X Y co-ordinates.\nchrome = cf.mouse_search_snip_return_coordinates_x_y(r\"C:\\Users\\Avinash Chodavarapu\\Desktop\\Demo\\chrome.png\", wait=200)\nprint(chrome)",
"_____no_output_____"
]
],
[
[
"# **Simple Bot**",
"_____no_output_____"
]
],
[
[
"path = r\"C:\\Users\\Avinash Chodavarapu\\Desktop\\Demo\\avinash.xlsx\"\n\nrow, column = cf.excel_get_row_column_count(excel_path=path)\nfor i in range(row-1):\n unit_price = cf.excel_get_single_cell(excel_path=path,columnName=\"Unit price\",cellNumber=i)\n quantity = cf.excel_get_single_cell(excel_path=path,columnName=\"Quantity\",cellNumber=i)\n tax = cf.excel_get_single_cell(excel_path=path,columnName=\"Tax\",cellNumber=1)\n final = (unit_price * quantity) + tax\n cf.excel_set_single_cell(excel_path = path,columnName=\"Total\",cellNumber=i,setText=final)\n\n\ncf.excel_sort_columns(excel_path=path,firstColumnToBeSorted=\"Total\")",
"_____no_output_____"
]
],
[
[
"# **Window Operations**\n\nWe have 5 functions to control a Window Application.",
"_____no_output_____"
]
],
[
[
"# Use this function, when you want to minimize all open windows and see the desktop.\n# This function doesnot have GUI mode and does not take any parameters.\n\ncf.window_show_desktop()",
"_____no_output_____"
],
[
"# Lets see all window operations via a small application.\n# This application opens a notepad (automatically maximises), then minimizes, then again activate & maximise and finally close\n\n#NON GUI Mode\n# for i in range(1,3):\n\ncf.launch_any_exe_bat_application(\"notepad\") \ncf.window_minimize_windows(\"notepad\")\ncf.window_activate_and_maximize_windows(\"notepad\")\ncf.window_close_windows(\"notepad\")\n\n#GUI Mode\n# cf.launch_any_exe_bat_application() \n# cf.window_minimize_windows()\n# cf.window_activate_and_maximize_windows()\n# cf.window_close_windows()",
"_____no_output_____"
]
],
[
[
"# **Windows Objects - The High Level Automation**",
"_____no_output_____"
]
],
[
[
"# Open Calculator\napp, main_dlg = cf.win_obj_open_app(title=\"Calculator\", program_path_with_name=\"C:\\Windows\\System32\\calc.exe\")\n# Print all objects\ncf.win_obj_get_all_objects(main_dlg)\n\n# Open Standard Calc\ncf.win_obj_mouse_click(main_dlg, auto_id=\"TogglePaneButton\", control_type=\"button\")\ncf.win_obj_mouse_click(main_dlg, title=\"Standard Calculator\", auto_id=\"Standard\", control_type=\"list item\")",
"_____no_output_____"
],
[
"print(\"Finding Square of 5 ...\")\n# Click on 5 Num\ncf.win_obj_mouse_click(main_dlg, auto_id=\"num5Button\", control_type=\"button\")\n# Click on Square\ncf.win_obj_mouse_click(main_dlg, auto_id=\"xpower2Button\", control_type=\"button\")\n# Get Text\nans = cf.win_obj_get_text(main_dlg, auto_id=\"CalculatorResults\", control_type=\"text\")\nprint(\"Answer: 5^2 = \"+ans.split(\" \")[-1])",
"_____no_output_____"
],
[
"# 5+5-10+2/3*9\ncf.win_obj_key_press(main_dlg=main_dlg, write='5{+}5{-}10{+}2{/}3{*}9{=}', auto_id='CalculatorResults', control_type=\"Text\")\n# Get the Answer\nread = cf.win_obj_get_text(main_dlg=main_dlg, auto_id='CalculatorResults')\nprint(read)",
"_____no_output_____"
]
],
[
[
"# **Folder Operations**",
"_____no_output_____"
]
],
[
[
"# Here you may pass any folder path separated by \\. This folder structure would be created, when you run this function.\n\n#NON GUI Mode\ncf.folder_create('C:\\Test\\Test12')\n\n#GUI Mode\n# cf.folder_create()\n\n# Notice, 2 ways of using the functions ! This feature is true for almost all functions of ClointFusion.",
"_____no_output_____"
],
[
"# Use this function to create an empty text file in the chosen folder\n\n# GUI Mode, without passing parameters\n# cf.folder_create_text_file()\n\n# NON GUI Mode\ncf.folder_create_text_file(r\"C:\\Test\",\"My Text File\")",
"_____no_output_____"
],
[
"# Use this function to get all the files of the given folder as a list.\n# Note the different ways of using it.\n\n# With GUI mode, default extenstion is 'all'\n# all_files_list = cf.folder_get_all_filenames_as_list()\n# print(all_files_list)\n\n# NON GUI, default extenstion is 'all'\nfiles_list = cf.folder_get_all_filenames_as_list(\"C:\\Test\")\nprint(files_list)\n\n# NON GUI, extenstion set to 'xlsx'\nexcel_files_list = cf.folder_get_all_filenames_as_list(\"C:\\Test\",extension='txt')\nprint(excel_files_list)",
"_____no_output_____"
],
[
"# Use this function to delete all the files of given folder.\n# Be carewful, as it wont prompt, before performing delete.\n\n# This function can be used in different ways as shown in above example\n\ncf.folder_delete_all_files(\"C:\\Test\",file_extension_without_dot='txt')",
"_____no_output_____"
],
[
"# Use this function to rename any file by just passing file path\n# If you pass ext as False than it will take extension of the file and if True than it will take extension of new file name.\n\n# GUI\n# cf.file_rename()\n\n# Non GUI\ncf.file_rename(old_file_path=r\"C:\\Test\\My Text File\", new_file_name=\"My New Text File\", ext=False)",
"_____no_output_____"
]
],
[
[
"## **Keyboard functions**",
"_____no_output_____"
],
[
"Lets understand Keyboard functions by buidling a small application.\n\nHere, we shall launch a Notepad, type something, close & exit the notepad.. All using keyboard functions.",
"_____no_output_____"
]
],
[
[
"# Demonstrating keyboard functions.\n\n# Launch notepad \ncf.launch_any_exe_bat_application(\"notepad\")\n\n# Enter specified text into newly opened notepad\ncf.key_write_enter(write_to_window=\"notepad\",text_to_write=\"ClointFusion is Awesome\")\ncf.key_hit_enter(write_to_window=\"notepad\")\n\n# Exit notepad\ncf.key_press(write_to_window=\"notepad\",key_1=\"alt\", key_2=\"f4\", key_3=\"n\")\n",
"_____no_output_____"
]
],
[
[
"## **String operations (GUI mode)**",
"_____no_output_____"
]
],
[
[
"\n# GUI mode\ncf.OFF_semi_automatic_mode()\ncf.string_extract_only_numbers()\ncf.string_extract_only_alphabets()\ncf.string_remove_special_characters()",
"_____no_output_____"
]
],
[
[
"### **String operations (Non-GUI mode)**",
"_____no_output_____"
]
],
[
[
"# Function to extract numbers from a given string\nnum = cf.string_extract_only_numbers(inputString=\"C1l2o3i4n5t6F7u8i9o0n\")\nprint(\"Returned value:\",num)\nprint(type(num))",
"_____no_output_____"
],
[
"# Function to extract letters from a given string\nprint(cf.string_extract_only_alphabets(inputString=\"C1l2o#%^int&*Fus12i5on\"))",
"_____no_output_____"
],
[
"# Function to remove all special characters (Example - '!','@','%')\nprint(cf.string_remove_special_characters(inputStr=\"C!@loin#$tFu*(sion\"))",
"_____no_output_____"
]
],
[
[
"# **Screenscraping functions**",
"_____no_output_____"
]
],
[
[
"# Clears previously found text (crtl+f highlight)\n\ncf.screen_clear_search(delay=0.5) ",
"_____no_output_____"
],
[
"# Copy pastes all the available text on the launched website to notepad and saves it in 'notepad-contents.txt'\n\ncf.browser_activate(url=\"https://en.wikipedia.org/wiki/Robotic_process_automation\")\ncf.scrape_save_contents_to_notepad(folderPathToSaveTheNotepad=\"E:/ClointFusion Demo/RPA\")\n",
"_____no_output_____"
],
[
"# Gets the focus on the screen by searching given text using crtl+f and performs copy/paste of all data. Useful in Citrix applications\n# This is useful in Citrix applicat^%#ions\n\ncf.scrape_get_contents_by_search_copy_paste(\"ClointFusion\")",
"_____no_output_____"
]
],
[
[
"## **Demo BOT**",
"_____no_output_____"
]
],
[
[
"# Launch website\ncf.window_show_desktop()\ncf.browser_activate('https://en.wikipedia.org/wiki/Robotic_process_automation')\n\n# # Method 1 - Use screen scraping functions to copy all available data to notepad\n# cf.message_counter_down_timer(strMsg=\"Calling ClointFusion Screen Scraping function in: \")\n# cf.scrape_save_contents_to_notepad(folderPathToSaveTheNotepad=\"E:/ClointFusion Demo/Bot Demo\")\n\n# Method 2 - Use keyboard shortcuts\ncf.message_counter_down_timer(strMsg=\"Using keyboard shortcuts for selecting and copying content...\")\n\n# Select all text and copy to clipboard\ncf.key_press(write_to_window=\"Chrome\",key_1=\"ctrl\", key_2=\"a\")\ncf.key_press(write_to_window=\"Chrome\",key_1=\"ctrl\", key_2=\"c\")\n\n# Open a new Word document and paste copied data\ncf.launch_any_exe_bat_application(pathOfExeFile=\"Winword\")\ncf.key_hit_enter(write_to_window=\"Word\")\ncf.message_counter_down_timer(strMsg=\"Pasting copied data to Word...\")\ncf.key_press(write_to_window=\"Word\", key_1=\"ctrl\", key_2=\"v\")\n\n# Open Save-As dialog box and enter filename\ncf.key_press(key_1=\"F12\")\ncf.time.sleep(5)\ncf.key_write_enter(text_to_write=\"RPA - info\")\ncf.time.sleep(3)",
"_____no_output_____"
]
],
[
[
"# **Browser Automation using Helium**",
"_____no_output_____"
]
],
[
[
"# Use this function to launch a browser and navigate to given url\n\n'''\nfunction : cf.browser_activate(\n url=\"\", \n files_download_path='', \n dummy_browser=True,\n open_in_background=False, \n incognito=False,\n clear_previous_instances=False, \n profile=\"Default\"\n )\n\nparam desc:\n url (str, optional): Website you want to visit. \n\n files_download_path (str, optional): Path to \n which the files need to be downloaded.\n \n dummy_browser (bool, optional): If it is false \n Default profile is opened.\n \n incognito (bool, optional): Opens the browser in \n incognito mode. \n \n clear_previous_instances (bool, optional): If true \n all the opened chrome instances are closed. \n\n profile (str, optional): By default it opens the \n 'Default' profile. \n Eg : Profile 1, Profile 2\n'''\n\n\ncf.browser_activate(url=\"https://github.com/\")",
"_____no_output_____"
],
[
"# Use this function to Write a String on the user visible element on the page\n\n'''\nfunction : \n \n browser_write_h(Value='', User_Visible_Text_Element='')\n\nparam Desc:\n \n Value:\n The value to enter into the Visible element area.\n User_Visible_Text_Element:\n Label of element where the stored Value needs to be entered.\n'''\n\ncf.browser_write_h(\"ClointFusion\",User_Visible_Text_Element=\"Search GitHub\")",
"_____no_output_____"
],
[
"# Use this function to enter Special KEYS using Browser Selenium API\n\n'''\nfunction: cf.browser_key_press_h(key_1=\"\", key_2=\"\")\n\nparam desc:\n key_1 (str): Keys you want to simulate or string you want to press \n Eg: \"tab\" or \"ClointFusion\".\n key_2 (str, optional): Key you want to simulate with combination to key_1. \n Eg: \"shift\" or \"escape\".\n\n'''\n\ncf.browser_key_press_h('ENTER')",
"_____no_output_____"
],
[
"# Use this function to perform Mouse Left Click on the user visible element on the page\n\n'''\nfunction: browser_mouse_click_h(\n User_Visible_Text_Element='',\n element='',\n double_click=False,\n right_click=False\n )\n\n'''\n\ncf.browser_mouse_click_h(\"ClointFusion/ClointFusion\",element='d')",
"_____no_output_____"
],
[
"# Use this function to navigate to specified URL\n\n'''\nfunction: \n\n browser_navigate_h(url='')\n\nparam desc:\n\n url: \n Url of the website\n'''\n\n\n# GUI Mode\n# cf.browser_navigate_h()\n\n# Non GUI Mode\ncf.browser_navigate_h(url='https://github.com/clointfusion/clointfusion')",
"_____no_output_____"
],
[
"# Use this function to refresh the page\n\n'''\nfunction:\n \n browser_refresh_page_h()\n\n'''\n\ncf.browser_refresh_page_h()",
"_____no_output_____"
],
[
"# Use this function to perform left doubleclick on the user visible element on the page\n\ncf.browser_mouse_click_h(User_Visible_Text_Element='What is ClointFusion ?',element='d',double_click=True)",
"_____no_output_____"
],
[
"# Use this function to locate element by xpath\n\n'''\nfunction: \n\n browser_locate_element_h(selector=\"\", get_text=False, multiple_elements=False)\n\nparam desc:\n selector (str, optional):\n Give Xpath or CSS selector. Defaults to \"\".\n get_text (bool, optional):\n Give the text of the element. Defaults to False.\n multiple_elements (bool, optional): \n True if you want to get all the similar elements with matching selector as list. Defaults to False.\n\n'''\n\ntxt = cf.browser_locate_element_h(\"//h2[text()='About']/following-sibling::p\",get_text=True)\nprint(txt)",
"_____no_output_____"
],
[
"#use this function to wait unil a specific text or element loads on the screen\n\n'''\nfunction: \n\n browser_wait_until_h(text=\"\",element=\"t\")\n\n'''\n\ncf.browser_mouse_click_h(\"Insights\",element='d')\n\ncf.browser_wait_until_h(\"Contributors\")\n\ncf.browser_mouse_click_h('Contributors',element='d')",
"_____no_output_____"
],
[
"# Use this function to close the browser\n\ncf.browser_quit_h()",
"_____no_output_____"
]
],
[
[
"# **Miscellaneous Functions**",
"_____no_output_____"
]
],
[
[
"# Use this function to launch an excel. Just click browse and point to Excel File.\n# Note that, once the selected application is opened, it maximises automatically.\n \ncf.launch_any_exe_bat_application()",
"_____no_output_____"
],
[
"cf.schedule_create_task_windows()",
"_____no_output_____"
],
[
"cf.schedule_delete_task_windows()",
"_____no_output_____"
],
[
"# Use this function in any of your print statements, to make your messages impressive to your Audience.\nprint(cf.show_emoji('yum'))\nprint(cf.show_emoji('heart_eyes'))\n# You may please refer emoji cheat_sheet here: https://www.webfx.com/tools/emoji-cheat-sheet",
"_____no_output_____"
],
[
"# Use this function to Pause program.\nprint(\"Program is Paused for 5 seconds..\")\ncf.pause_program(\"5\")\nprint(\"Program is Resumed.\")",
"_____no_output_____"
],
[
"# Use this function to print colorful statements in random color order\ncf.print_with_magic_color(strMsg=\"Welcome to RPA tool ClointFusion\", magic=True)",
"_____no_output_____"
]
],
[
[
"# **BSD-4 License**\nCopyright (c) 2020, Cloint India Pvt Ltd. All rights reserved.\n\n",
"_____no_output_____"
],
[
"\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n3. All advertising materials mentioning features or use of this software\n must display the following acknowledgement:\n This product includes software developed by the Cloint India Pvt Ltd.\n4. Neither the name of the Cloint India Pvt Ltd. nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY\nEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE \nUSE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
e7b19e0cdd659f71f2e81719b952094a5d4febc0 | 93,776 | ipynb | Jupyter Notebook | jupyter/3.logistic_regression/.ipynb_checkpoints/paddle_logistic-checkpoint.ipynb | BaiduOSS/PaddleTutorial | d71136c105b78b57c5df1fe98e19e2fd8ee65045 | [
"Apache-2.0"
] | 33 | 2018-03-18T08:56:11.000Z | 2022-01-06T14:43:54.000Z | jupyter/3.logistic_regression/.ipynb_checkpoints/paddle_logistic-checkpoint.ipynb | CaesarXI/DeepLearningAndPaddleTutorial | d71136c105b78b57c5df1fe98e19e2fd8ee65045 | [
"Apache-2.0"
] | 5 | 2017-12-06T12:40:59.000Z | 2019-07-05T08:47:48.000Z | jupyter/3.logistic_regression/.ipynb_checkpoints/paddle_logistic-checkpoint.ipynb | CaesarXI/DeepLearningAndPaddleTutorial | d71136c105b78b57c5df1fe98e19e2fd8ee65045 | [
"Apache-2.0"
] | 43 | 2017-12-06T12:51:16.000Z | 2022-01-06T14:44:00.000Z | 91.310613 | 26,824 | 0.835747 | [
[
[
"# Paddlepaddle实现逻辑回归 - 识别猫\n\n欢迎大家来到这个有趣的实验!在这个实验中,大家将学使用PaddlePaddle实现Logistic回归模型来解决识别猫的问题,一步步跟随内容完成训练,加深对逻辑回归理论内容的理解并串联各个知识点,收获对神经网络和深度学习概念的整体把握。 \n\n** 你将学会 **\n\n- 预处理图片数据\n\n- 利用PaddlePaddle框架实现Logistic回归模型:\n\n在开始实验之前,让我们简单介绍一下图片处理的相关知识:\n\n** 图片处理 **\n\n由于识别猫问题涉及到图片处理指示,这里对计算机如何保存图片做一个简单的介绍。在计算机中,图片被存储为三个独立的矩阵,分别对应图3-6中的红、绿、蓝三个颜色通道,如果图片是64*64像素的,就会有三个64*64大小的矩阵,要把这些像素值放进一个特征向量中,需要定义一个特征向量X,将三个颜色通道中的所有像素值都列出来。如果图片是64*64大小的,那么特征向量X的总纬度就是64*64*3,也就是12288维。这样一个12288维矩阵就是Logistic回归模型的一个训练数据。\n\n<img src=\"images/image_to_vector.png\" style=\"width:550px;height:300px;\">\n\n现在,让我们正式进入实验吧!\n\n## 1 - 引用库\n\n首先,载入几个需要用到的库,它们分别是:\n\n- numpy:一个python的基本库,用于科学计算\n- matplotlib.pyplot:用于生成图,在验证模型准确率和展示成本变化趋势时会使用到\n- h5py:用于处理hdf5文件数据\n- PIL和scipy:用于最后使用自己的图片验证训练模型\n- lr_utils:定义了load_datase()方法用于载入数据\n- paddle.v2:PaddlePaddle深度学习框架",
"_____no_output_____"
]
],
[
[
"import sys\nimport numpy as np\n\nimport lr_utils\nimport matplotlib.pyplot as plt\n\nimport paddle.v2 as paddle\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"## 2 - 数据预处理\n\n这里简单介绍数据集及其结构。数据集以hdf5文件的形式存储,包含了如下内容:\n\n- 训练数据集:包含了m_train个图片的数据集,数据的标签(Label)分为cat(y=1)和non-cat(y=0)两类。\n- 测试数据集:包含了m_test个图片的数据集,数据的标签(Label)同上。\n\n单个图片数据的存储形式为(num_x, num_x, 3),其中num_x表示图片的长或宽(数据集图片的长和宽相同),数字3表示图片的三通道(RGB)。\n在代码中使用一行代码来读取数据,读者暂不需要了解数据的读取过程,只需调用load_dataset()方法,并存储五个返回值,以便后续的使用。\n \n需要注意的是,添加“_orig”后缀表示该数据为原始数据,因为之后还需要对数据进行进一步处理。未添加“_orig”的数据则表示之后不对该数据作进一步处理。",
"_____no_output_____"
]
],
[
[
"train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = lr_utils.load_dataset()",
"_____no_output_____"
],
[
"# 图片示例\nindex = 23\nplt.imshow(train_set_x_orig[index])\nprint (\"y = \" + str(train_set_y[:, index]) + \", it's a '\" + classes[np.squeeze(train_set_y[:, index])].decode(\"utf-8\") + \"' picture.\")",
"y = [0], it's a 'non-cat' picture.\n"
]
],
[
[
"获取数据后的下一步工作是获得数据的相关信息,如训练样本个数m_train、测试样本个数m_test和图片的长度或宽度num_x,使用numpy.array.shape来获取数据的相关信息。\n",
"_____no_output_____"
],
[
"** 练习: ** 查看样本信息:\n - m_train (训练样本数)\n - m_test (测试样本数)\n - num_px (图片长或宽)\n`train_set_x_orig` 是一个(m_train, num_px, num_px, 3)形状的numpy数组。举个例子,你可以使用`train_set_x_orig.shape[0]`来获得 `m_train`。",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (≈ 3 lines of code)\nm_train = train_set_x_orig.shape[0]\nm_test = test_set_x_orig.shape[0]\nnum_px = test_set_x_orig.shape[1]\n### END CODE HERE ###\n\nprint (\"训练样本数: m_train = \" + str(m_train))\nprint (\"测试样本数: m_test = \" + str(m_test))\nprint (\"图片高度/宽度: num_px = \" + str(num_px))\nprint (\"图片大小: (\" + str(num_px) + \", \" + str(num_px) + \", 3)\")\nprint (\"train_set_x shape: \" + str(train_set_x_orig.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x shape: \" + str(test_set_x_orig.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))",
"训练样本数: m_train = 209\n测试样本数: m_test = 50\n图片高度/宽度: num_px = 64\n图片大小: (64, 64, 3)\ntrain_set_x shape: (209, 64, 64, 3)\ntrain_set_y shape: (1, 209)\ntest_set_x shape: (50, 64, 64, 3)\ntest_set_y shape: (1, 50)\n"
]
],
[
[
"**期望输出:**: \n<table style=\"width:15%\">\n <tr>\n <td>**m_train**</td>\n <td> 209 </td> \n </tr>\n \n <tr>\n <td>**m_test**</td>\n <td> 50 </td> \n </tr>\n \n <tr>\n <td>**num_px**</td>\n <td> 64 </td> \n </tr>\n \n</table>\n\n",
"_____no_output_____"
],
[
"接下来需要对数据作进一步处理,为了便于训练,你可以忽略图片的结构信息,将包含图像长、宽和通道数信息的三维数组压缩成一维数组,图片数据的形状将由(64, 64, 3)转化为(64 * 64 * 3, 1)。\n\n** 练习:** \n\n将数据形状由(64, 64, 3)转化为(64 * 64 * 3, 1)。\n\n** 技巧:**\n\n我们可以使用一个小技巧来将(a,b,c,d)形状的矩阵转化为(b$*$c$*$d, a)形状的矩阵: \n\n```python\nX_flatten = X.reshape(X.shape[0], -1)\n```\n",
"_____no_output_____"
]
],
[
[
"# 转换数据形状\n\n### START CODE HERE ### (≈ 2 lines of code)\ntrain_set_x_flatten = train_set_x_orig.reshape(m_train,-1)\ntest_set_x_flatten = test_set_x_orig.reshape(m_test,-1)\n### END CODE HERE ###\n\nprint (\"train_set_x_flatten shape: \" + str(train_set_x_flatten.shape))\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\nprint (\"test_set_x_flatten shape: \" + str(test_set_x_flatten.shape))\nprint (\"test_set_y shape: \" + str(test_set_y.shape))",
"train_set_x_flatten shape: (209, 12288)\ntrain_set_y shape: (1, 209)\ntest_set_x_flatten shape: (50, 12288)\ntest_set_y shape: (1, 50)\n"
]
],
[
[
"**期望输出**: \n\n<table style=\"width:35%\">\n <tr>\n <td>**train_set_x_flatten shape**</td>\n <td> (209, 12288)</td> \n </tr>\n <tr>\n <td>**train_set_y shape**</td>\n <td>(1, 209)</td> \n </tr>\n <tr>\n <td>**test_set_x_flatten shape**</td>\n <td>(50, 12288)</td> \n </tr>\n <tr>\n <td>**test_set_y shape**</td>\n <td>(1, 50)</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"在开始训练之前,还需要对数据进行归一化处理。图片采用红、绿、蓝三通道的方式来表示颜色,每个通道的单个像素点都存储着一个0-255的像素值,所以图片的归一化处理十分简单,只需要将数据集中的每个值除以255即可,但需要注意的是结果值应为float类型,直接除以255会导致结果错误,在Python中除以255.即可将结果转化为float类型。\n现在让我们来归一化数据吧!\n",
"_____no_output_____"
]
],
[
[
"### START CODE HERE ### (≈ 2 lines of code)\ntrain_set_x = train_set_x_flatten/255.\ntest_set_x = test_set_x_flatten/255.\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"为了方便后续的测试工作,添加了合并数据集和标签集的操作,使用numpy.hstack实现numpy数组的横向合并。\n",
"_____no_output_____"
]
],
[
[
"train_set = np.hstack((train_set_x, train_set_y.T))\ntest_set = np.hstack((test_set_x, test_set_y.T))",
"_____no_output_____"
]
],
[
[
"<font color='blue'>\n**经过上面的实验,大家应该记住:**\n\n对数据进行预处理的一般步骤是:\n \n- 了解数据的维度和形状等信息,例如(m_train, m_test, num_px, ...)\n- 降低数据纬度,例如将数据维度(num_px, num_px, 3)转化为(num_px \\* num_px \\* 3, 1)\n- 数据归一化",
"_____no_output_____"
],
[
"至此我们就完成了数据预处理工作!在接下来的练习中我们将构造reader,用于读取数据。",
"_____no_output_____"
],
[
"## 3 - 构造reader\n\n构造read_data()函数,来读取训练数据集train_set或者测试数据集test_set。它的具体实现是在read_data()函数内部构造一个reader(),使用yield关键字来让reader()成为一个Generator(生成器),注意,yield关键字的作用和使用方法类似return关键字,不同之处在于yield关键字可以构造生成器(Generator)。虽然我们可以直接创建一个包含所有数据的列表,但是由于内存限制,我们不可能创建一个无限大的或者巨大的列表,并且很多时候在创建了一个百万数量级别的列表之后,我们却只需要用到开头的几个或几十个数据,这样造成了极大的浪费,而生成器的工作方式是在每次循环时计算下一个值,不断推算出后续的元素,不会创建完整的数据集列表,从而节约了内存使用。\n\n** 练习:**现在让我们使用yield来构造一个reader()吧!",
"_____no_output_____"
]
],
[
[
"# 读取训练数据或测试数据\ndef read_data(data_set):\n \"\"\"\n 一个reader\n Args:\n data_set -- 要获取的数据集\n Return:\n reader -- 用于获取训练数据集及其标签的生成器generator\n \"\"\"\n def reader():\n \"\"\"\n 一个reader\n Args:\n Return:\n data[:-1], data[-1:] -- 使用yield返回生成器(generator),\n data[:-1]表示前n-1个元素,也就是训练数据,data[-1:]表示最后一个元素,也就是对应的标签\n \"\"\"\n for data in data_set:\n ### START CODE HERE ### (≈ 2 lines of code)\n yield data[:-1], data[-1:]\n ### END CODE HERE ###\n return reader\n\n\n",
"_____no_output_____"
],
[
"test_array = [[1,1,1,1,0],\n [2,2,2,2,1],\n [3,3,3,3,0]]\n\nprint(\"test_array for read_data:\")\nfor value in read_data(test_array)():\n print(value)",
"test_array for read_data:\n([1, 1, 1, 1], [0])\n([2, 2, 2, 2], [1])\n([3, 3, 3, 3], [0])\n"
]
],
[
[
"**期望输出**: \n\n<table>\n <tr>\n <td>([1, 1, 1, 1], [0])</td>\n </tr>\n <tr>\n <td>([2, 2, 2, 2], [1])</td> \n </tr>\n <td>([3, 3, 3, 3], [0])</td> \n </tr>\n</table>",
"_____no_output_____"
],
[
"## 4 - 训练过程\n\n完成了数据的预处理工作并构造了read_data()来读取数据,接下来将进入模型的训练过程,使用PaddlePaddle来定义构造可训练的Logistic回归模型,关键步骤如下:\n\n- 初始化\n\n- 配置网络结构和设置参数\n - 配置网络结构\n - 定义损失函数cost\n - 创建parameters\n - 定义优化器optimizer\n\n- 模型训练\n\n- 模型检验\n\n- 预测\n\n- 绘制学习曲线\n\n** (1)初始化 **\n\n首先进行最基本的初始化操作,在PaddlePaddle中使用paddle.init(use_gpu=False, trainer_count=1)来进行初始化:\n\n- use_gpu=False表示不使用gpu进行训练\n- trainer_count=1表示仅使用一个训练器进行训练",
"_____no_output_____"
]
],
[
[
"# 初始化\npaddle.init(use_gpu=False, trainer_count=1)",
"_____no_output_____"
]
],
[
[
"** (2)配置网络结构和设置参数 **\n\n** 配置网络结构 **\n\n我们知道Logistic回归模型结构相当于一个只含一个神经元的神经网络,如下图所示,只包含输入数据以及输出层,不存在隐藏层,所以只需配置输入层(input)、输出层(predict)和标签层(label)即可。\n\n<img src=\"images/logistic.png\" width=\"200px\">\n\n** 练习:**接下来让我们使用PaddlePaddle提供的接口开始配置Logistic回归模型的简单网络结构吧,一共需要配置三层:\n\n** 输入层: **\n\n我们可以定义image=paddle.layer.data(name=”image”, type=paddle.data_type.dense_vector(data_dim))来表示生成一个数据输入层,名称为“image”,数据类型为data_dim维向量;\n\n在定义输入层之前,我们需要使用之前计算的num_px来获取数据维度data_dim,data_dim=num_px \\* num_px \\* 3\n\n** 输出层: **\n\n我们可以定义predict=paddle.layer.fc(input=image, size=1, act=paddle.activation.Sigmoid())表示生成一个全连接层,输入数据为image,神经元个数为1,激活函数为Sigmoid();\n\n** 标签层 **\n\n我们可以定义label=paddle.layer.data(name=”label”, type=paddle.data_type.dense_vector(1))表示生成一个数据层,名称为“label”,数据类型为1维向量。\n",
"_____no_output_____"
]
],
[
[
"# 配置网络结构\n\n\n# 数据层需要使用到数据维度data_dim,根据num_px来计算data_dim\n\n### START CODE HERE ### (≈ 2 lines of code)\ndata_dim = num_px * num_px * 3\n### END CODE HERE ###\n\n# 输入层,paddle.layer.data表示数据层\n\n### START CODE HERE ### (≈ 2 lines of code)\nimage = paddle.layer.data(\n name='image', type=paddle.data_type.dense_vector(data_dim))\n### END CODE HERE ###\n\n# 输出层,paddle.layer.fc表示全连接层\n\n### START CODE HERE ### (≈ 2 lines of code)\npredict = paddle.layer.fc(\n input=image, size=1, act=paddle.activation.Sigmoid())\n### END CODE HERE ###\n\n# 标签数据层,paddle.layer.data表示数据层\n\n### START CODE HERE ### (≈ 2 lines of code)\nlabel = paddle.layer.data(\n name='label', type=paddle.data_type.dense_vector(1))\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"** 定义损失函数 **\n\n在配置网络结构之后,我们需要定义一个损失函数来计算梯度并优化参数,在这里我们可以使用PaddlePaddle提供的交叉熵损失函数,定义cost = paddle.layer.multi_binary_label_cross_entropy_cost(input=predict, label=label),使用predict与label计算成本。",
"_____no_output_____"
]
],
[
[
"# 损失函数,使用交叉熵损失函数\n### START CODE HERE ### (≈ 2 lines of code)\ncost = paddle.layer.multi_binary_label_cross_entropy_cost(input=predict, label=label)\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"** 创建parameters **\n\nPaddlePaddle中提供了接口paddle.parameters.create(cost)来创建和初始化参数,参数cost表示基于我们刚刚创建的cost损失函数来创建和初始化参数。",
"_____no_output_____"
]
],
[
[
"# 创建parameters\n\n### START CODE HERE ### (≈ 2 lines of code)\nparameters = paddle.parameters.create(cost)\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"** optimizer **\n\n参数创建完成后,定义参数优化器optimizer= paddle.optimizer.Momentum(momentum=0, learning_rate=0.00002),使用Momentum作为优化器,并设置动量momentum为零,学习率为0.00002。注意,读者暂时无需了解Momentum的含义,只需要学会使用即可。",
"_____no_output_____"
]
],
[
[
"#创建optimizer\n\n### START CODE HERE ### (≈ 2 lines of code)\noptimizer = paddle.optimizer.Momentum(momentum=0, learning_rate=0.00002)\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"** 其它配置 **\n\nfeeding={‘image’:0, ‘label’:1}是数据层名称和数组索引的映射,用于在训练时输入数据,costs数组用于存储cost值,记录成本变化情况。\n最后定义函数event_handler(event)用于事件处理,事件event中包含batch_id,pass_id,cost等信息,我们可以打印这些信息或作其它操作。",
"_____no_output_____"
]
],
[
[
"# 数据层和数组索引映射,用于trainer训练时喂数据\nfeeding = {\n 'image': 0,\n 'label': 1}\n\n# 记录成本cost\ncosts = []\n\n# 事件处理\ndef event_handler(event):\n \"\"\"\n 事件处理器,可以根据训练过程的信息作相应操作\n\n Args:\n event -- 事件对象,包含event.pass_id, event.batch_id, event.cost等信息\n Return:\n \"\"\"\n if isinstance(event, paddle.event.EndIteration):\n if event.pass_id % 100 == 0:\n print(\"Pass %d, Batch %d, Cost %f\" % (event.pass_id, event.batch_id, event.cost))\n costs.append(event.cost)",
"_____no_output_____"
]
],
[
[
"** 模型训练 **\n\n上述内容进行了模型初始化、网络结构的配置并创建了损失函数、参数、优化器,接下来利用上述配置进行模型训练。\n\n\n首先定义一个随机梯度下降trainer,配置三个参数cost、parameters、update_equation,它们分别表示损失函数、参数和更新公式。\n\n再利用trainer.train()即可开始真正的模型训练,我们可以设置参数如下:\n\n<img src=\"images/code1.png\" width=\"500px\">\n\n- paddle.reader.shuffle(train(), buf_size=5000)表示trainer从train()这个reader中读取了buf_size=5000大小的数据并打乱顺序\n- paddle.batch(reader(), batch_size=256)表示从打乱的数据中再取出batch_size=256大小的数据进行一次迭代训练\n- 参数feeding用到了之前定义的feeding索引,将数据层image和label输入trainer,也就是训练数据的来源。\n- 参数event_handler是事件管理机制,读者可以自定义event_handler,根据事件信息作相应的操作。\n- 参数num_passes=5000表示迭代训练5000次后停止训练。\n\n** 练习:**定义trainer并开始训练模型(大家可以自己定义buf_size,batch_size,num_passes等参数,但是建议大家先参考上述的参数设置,在完成整个训练之后,再回过头来调整这些参数,看看结果会有什么不同)",
"_____no_output_____"
]
],
[
[
"# 构造trainer\n\n### START CODE HERE ### (≈ 2 lines of code)\ntrainer = paddle.trainer.SGD(\n cost=cost, parameters=parameters, update_equation=optimizer)\n### END CODE HERE ###\n\n# 模型训练\n\n### START CODE HERE ### (≈ 2 lines of code)\ntrainer.train(\n reader=paddle.batch(\n paddle.reader.shuffle(read_data(train_set), buf_size=5000),\n batch_size=256),\n feeding=feeding,\n event_handler=event_handler,\n num_passes=2000)\n### END CODE HERE ###",
"Pass 0, Batch 0, Cost 0.718985\nPass 100, Batch 0, Cost 0.497979\nPass 200, Batch 0, Cost 0.431610\nPass 300, Batch 0, Cost 0.386631\nPass 400, Batch 0, Cost 0.352110\nPass 500, Batch 0, Cost 0.324237\nPass 600, Batch 0, Cost 0.301005\nPass 700, Batch 0, Cost 0.281201\nPass 800, Batch 0, Cost 0.264035\nPass 900, Batch 0, Cost 0.248960\nPass 1000, Batch 0, Cost 0.235580\nPass 1100, Batch 0, Cost 0.223603\nPass 1200, Batch 0, Cost 0.212803\nPass 1300, Batch 0, Cost 0.203003\nPass 1400, Batch 0, Cost 0.194064\nPass 1500, Batch 0, Cost 0.185871\nPass 1600, Batch 0, Cost 0.178331\nPass 1700, Batch 0, Cost 0.171367\nPass 1800, Batch 0, Cost 0.164913\nPass 1900, Batch 0, Cost 0.158914\n"
]
],
[
[
"** 模型检验 **\n\n模型训练完成后,接下来检验模型的准确率。\n\n在这里我们首先需要定义一个函数get_data()来帮助我们获得用于检验模型准确率的数据,而数据的来源是read_data()返回的训练数据和测试数据。 ",
"_____no_output_____"
]
],
[
[
"# 获取数据\ndef get_data(data_creator):\n \"\"\"\n 使用参数data_creator来获取测试数据\n\n Args:\n data_creator -- 数据来源,可以是train()或者test()\n Return:\n result -- 包含测试数据(image)和标签(label)的python字典\n \"\"\"\n data_creator = data_creator\n data_image = []\n data_label = []\n\n for item in data_creator():\n data_image.append((item[0],))\n data_label.append(item[1])\n\n ### START CODE HERE ### (≈ 4 lines of code)\n result = {\n \"image\": data_image,\n \"label\": data_label\n }\n ### END CODE HERE ###\n\n return result\n",
"_____no_output_____"
]
],
[
[
"获得数据之后,我们就可以开始利用paddle.infer()来进行预测,参数output_layer 表示输出层,参数parameters表示模型参数,参数input表示输入的测试数据。\n\n** 练习:**\n\n- 利用get_data()获取测试数据和训练数据\n\n- 使用paddle.infer()进行预测",
"_____no_output_____"
]
],
[
[
"# 获取测试数据和训练数据,用来验证模型准确度\n\n### START CODE HERE ### (≈ 2 lines of code)\ntrain_data = get_data(read_data(train_set))\ntest_data = get_data(read_data(test_set))\n### END CODE HERE ###\n \n# 根据train_data和test_data预测结果,output_layer表示输出层,parameters表示模型参数,input表示输入的测试数据\n\n### START CODE HERE ### (≈ 6 lines of code)\nprobs_train = paddle.infer(\n output_layer=predict, parameters=parameters, input=train_data['image']\n)\nprobs_test = paddle.infer(\n output_layer=predict, parameters=parameters, input=test_data['image']\n)\n### END CODE HERE ###",
"_____no_output_____"
]
],
[
[
"获得检测结果probs_train和probs_test之后,我们将结果转化为二分类结果并计算预测正确的结果数量,定义train_accuracy和test_accuracy来分别计算训练准确度和测试准确度。注意,在test_accuracy中,我们不仅计算了准确度,并且传入了一个test_data_y数组参数用于存储预测结果,方便后续的查看。",
"_____no_output_____"
]
],
[
[
"# 训练集准确度\ndef train_accuracy(probs_train, train_data):\n \"\"\"\n 根据训练数据集来计算训练准确度train_accuracy\n\n Args:\n probs_train -- 训练数据集的预测结果,调用paddle.infer()来获取\n train_data -- 训练数据集\n\n Return:\n train_accuracy -- 训练准确度train_accuracy\n \"\"\"\n train_right = 0\n train_total = len(train_data['label'])\n for i in range(len(probs_train)):\n if float(probs_train[i][0]) > 0.5 and train_data['label'][i] == 1:\n train_right += 1\n elif float(probs_train[i][0]) < 0.5 and train_data['label'][i] == 0:\n train_right += 1\n train_accuracy = (float(train_right) / float(train_total)) * 100\n\n return train_accuracy\n\n\n# 测试集准确度\ndef test_accuracy(probs_test, test_data, test_data_y):\n \"\"\"\n 根据测试数据集来计算测试准确度test_accuracy\n\n Args:\n probs_test -- 测试数据集的预测结果,调用paddle.infer()来获取\n test_data -- 测试数据集\n\n Return:\n test_accuracy -- 测试准确度test_accuracy\n \"\"\"\n test_right = 0\n test_total = len(test_data['label'])\n for i in range(len(probs_test)):\n if float(probs_test[i][0]) > 0.5:\n test_data_y.append(1)\n if test_data['label'][i] == 1:\n test_right += 1\n elif float(probs_test[i][0]) < 0.5:\n test_data_y.append(0)\n if test_data['label'][i] == 0:\n test_right += 1\n\n test_accuracy = (float(test_right) / float(test_total)) * 100\n\n return test_accuracy",
"_____no_output_____"
]
],
[
[
"调用上述两个函数并输出",
"_____no_output_____"
]
],
[
[
"# 计算train_accuracy和test_accuracy\ntest_data_y = []\n\n### START CODE HERE ### (≈ 6 lines of code)\nprint(\"train_accuracy: {} %\".format(train_accuracy(probs_train, train_data)))\nprint(\"test_accuracy: {} %\".format(test_accuracy(probs_test, test_data, test_data_y)))\n### END CODE HERE ###",
"train_accuracy: 98.5645933014 %\ntest_accuracy: 70.0 %\n"
]
],
[
[
"** 期望输出:**\n\n<table style=\"width:40%\"> \n\n <tr>\n <td> **train_accuracy ** </td> \n <td> $\\approx$ 98% </td>\n </tr>\n\n <tr>\n <td> **test Accuracy** </td> \n <td> $\\approx$ 70% </td>\n </tr>\n</table> \n\n\n",
"_____no_output_____"
],
[
"因为数据集和逻辑回归模型的限制,并且没有加入其它优化方式,所以70%的测试集准确率已经是相当好的结果,如果你也得到相似的结果,大约98%的训练集准确率和70%的测试集准确率,那么恭喜你到目前为止的工作都很棒,你已经配置了不错的模型和参数。当然你可以返回去调整一些参数,例如learning_rate/batch_size/num_passes,或者参考官方[PaddlePaddle文档](http://paddlepaddle.org/docs/develop/documentation/zh/getstarted/index_cn.html)来修改你的模型,尝试去犯错或者通过调参来得到更好的结果都能帮助你熟悉深度学习以及PaddlePaddle框架的使用!",
"_____no_output_____"
],
[
"** 学习曲线 **\n\n接下来我们利用之前保存的costs数据来输出成本的变化情况,利用学习曲线对模型进行分析。",
"_____no_output_____"
]
],
[
[
"costs = np.squeeze(costs)\nplt.plot(costs)\nplt.ylabel('cost')\nplt.xlabel('iterations (per hundreds)')\nplt.title(\"Learning rate = 0.00002\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"可以看到图中成本在刚开始收敛较快,随着迭代次数变多,收敛速度变慢,最终收敛到一个较小值。\n\n接下来,利用之前保存的测试结果test_data_y来对测试数据集中的单个图片进行预测,通过index来选择一张图片,看看你的模型是不是正确预测了这张图片吧!",
"_____no_output_____"
]
],
[
[
"# Example of a picture that was wrongly classified.\nindex = 14\nplt.imshow((np.array(test_data['image'][index])).reshape((64, 64, 3)))\nprint (\"y = \" + str(test_data_y[index]) + \", you predicted that it is a \\\"\" + classes[test_data_y[index]].decode(\"utf-8\") + \"\\\" picture.\")",
"y = 0, you predicted that it is a \"non-cat\" picture.\n"
]
],
[
[
"# 5 - 总结\n\n至此Logistic回归模型的训练工作完成,我们发现在使用PaddlePaddle进行模型配置和训练的过程中不用考虑参数的初始化、成本函数、激活函数、梯度下降、参数更新和预测等具体细节,只需要简单地配置网络结构和trainer即可,并且PaddlePaddle提供了许多接口来改变学习率、成本函数、批次大小等许多参数来改变模型的学习效果,使用起来更加灵活,方便测试。\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"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b1a2f96b451d8d58220eedeafd408d0bc2fc23 | 16,701 | ipynb | Jupyter Notebook | 2. ITW2/01_operator.ipynb | piyushmoolchandani/Lab_codes | 5b478f31b41856b10c0df9f847b4a7794556fea5 | [
"MIT"
] | null | null | null | 2. ITW2/01_operator.ipynb | piyushmoolchandani/Lab_codes | 5b478f31b41856b10c0df9f847b4a7794556fea5 | [
"MIT"
] | null | null | null | 2. ITW2/01_operator.ipynb | piyushmoolchandani/Lab_codes | 5b478f31b41856b10c0df9f847b4a7794556fea5 | [
"MIT"
] | 2 | 2020-04-09T08:52:51.000Z | 2021-09-24T13:45:04.000Z | 18.074675 | 323 | 0.425304 | [
[
[
"## Arithematic",
"_____no_output_____"
]
],
[
[
"3+5",
"_____no_output_____"
],
[
"'a' + 'b' ",
"_____no_output_____"
],
[
"-5.2",
"_____no_output_____"
],
[
"50 - 243",
"_____no_output_____"
],
[
"'a' + 2",
"_____no_output_____"
],
[
"'a' + '2'",
"_____no_output_____"
],
[
"# multiplication\n2 * 3",
"_____no_output_____"
],
[
"2 * 'aaaa'",
"_____no_output_____"
]
],
[
[
"### Power operator",
"_____no_output_____"
]
],
[
[
"print(3 ** 4)",
"81\n"
],
[
"print('abc' ** 3)",
"_____no_output_____"
],
[
"# divide\nprint(12/5)",
"2.4\n"
],
[
"# modulo\nprint(int(16/3) % 2)",
"1\n"
]
],
[
[
"# Relational Operator\nBoolean: True / False",
"_____no_output_____"
]
],
[
[
"print(5<3)\nprint(3< 5)\nprint(3 < 5 < 7)\nprint(3 > 5 < 7)",
"False\nTrue\nTrue\nFalse\n"
],
[
"print( \"piyusji\" <= \"piyusj\")",
"False\n"
],
[
"x = 'str' ; y = 'Str'\nx == y",
"_____no_output_____"
]
],
[
[
"- Python is case sensitive",
"_____no_output_____"
]
],
[
[
"x = 'Piyush' \ny = \"Piyush\"\nx == y",
"_____no_output_____"
],
[
"x != y",
"_____no_output_____"
],
[
"print(5 == 5.000)\nprint( 5 == 5.3)",
"True\nFalse\n"
]
],
[
[
"## Logical Operator\n- Short Circuit evaluation",
"_____no_output_____"
]
],
[
[
"x = True\nnot x",
"_____no_output_____"
],
[
"x = False",
"_____no_output_____"
],
[
"print(x and not x)",
"False\n"
],
[
"print(x or not x)",
"True\n"
]
],
[
[
"## User Input and Output",
"_____no_output_____"
]
],
[
[
"person_name = input('Enter your name: ')\nprint(person_name)",
"Enter your name: PIyush\nPIyush\n"
],
[
"age_str = input('Enter your age: ')\nage = int(age_str)\nprint('Age: '+ str(age))\nprint('Age: '+ age_str)",
"Enter your age: 78\nAge: 78\nAge: 78\n"
],
[
"age_1 = int(input('Enter your age: '))\nprint(type(age_1))\nprint('Age: '+str(age_1))\nprint('Age: ', age_1)",
"Enter your age: 19\n<class 'int'>\nAge: 19\nAge: 19\n"
]
],
[
[
"## Control Statements:",
"_____no_output_____"
]
],
[
[
"a = 2\nif a == 2:\n print(\"Condition is true\")\n print(\"Sample Statement\")\n if a > 3:\n print(\"This also satisfies double if\")\n print('Another Statement')",
"Condition is true\nSample Statement\nAnother Statement\n"
],
[
"a = 1\nif a == 0:\n print(\"I am in if block\")\nelse: \n print('I am in else block')\n if (a == 3):\n print('if in else')\n else:\n print('else in else')\n print(\"Another Statement\")",
"I am in else block\nelse in else\nAnother Statement\n"
]
],
[
[
"#### Question",
"_____no_output_____"
]
],
[
[
"a = int(input(\"Enter a number to check: \"))\nif (a % 2 == 0):\n print(\"Number is even\")\nelse:\n print(\"Number is odd\")",
"Enter a number to check: 8\nNumber is even\n"
],
[
"var = 100\nif var < 200 and var >= 50:\n print(\"Expression is greater than 50 but less and 200\")\n if var == 150:\n print(\"It is 150\")\n elif var == 100:\n print(\"It is 100\")\n elif var == 50:\n print(\"It is 50\")\nelif var < 50:\n print(\"Expression is less than 50\")\nelse: \n print(\"Cannot find the true expression\")\n\nprint(\"Good Bye\")",
"Expression is greater than 50 but less and 200\nIt is 100\nGood Bye\n"
],
[
"a = int(input(\"Enter a number to check: \"))\nif a == 0:\n print(\"It is zero, which is a neutral number.\")\nelse:\n if (a % 2 == 0):\n print(\"Number is even\")\n else: \n print(\"Number is odd\")",
"Enter a number to check: 9\nNumber is odd\n"
]
],
[
[
"## Loop Structure:",
"_____no_output_____"
]
],
[
[
" # help(range)\n\nfor i in range(17, 3 , -2):\n print(i)",
"17\n15\n13\n11\n9\n7\n5\n"
],
[
"for i in range(-7, -2, 3):\n print(i)",
"-7\n-4\n"
],
[
"# Question\nfinal = 0\nn = int(input(\"Enter the number: \"))\nfor i in range(n+1):\n final += i**2\nprint(final)",
"Enter the number: 9\n285\n"
],
[
"final = 0\nn = int(input(\"Enter your number: \"))\nfor i in range(1, n+1):\n if i%2:\n final += i**3\n else:\n final += i**2\nprint(final)",
"Enter your number: 34\n173893\n"
]
],
[
[
"- While",
"_____no_output_____"
]
],
[
[
"n = 5\ni = 1\nwhile(i <= n):\n print(i)\n i = i+1",
"1\n2\n3\n4\n5\n"
],
[
"final = 0\nn = int(input(\"Enter your number: \"))\ni = 0\nwhile (i < n):\n i += 1\n if i % 2:\n final += i**3\n else: \n final += i**2\nprint(final)",
"Enter your number: 8\n616\n"
]
],
[
[
"* Break and continue",
"_____no_output_____"
]
],
[
[
"for letter in 'Python':\n if letter == 'h':\n break;\n print(\"current letter: \", letter)\nprint('out of For')",
"current letter: P\ncurrent letter: y\ncurrent letter: t\nout of For\n"
],
[
"for letter in \"Django\":\n if letter == 'D':\n continue;\n print(\"current letter: \", letter)",
"current letter: j\ncurrent letter: a\ncurrent letter: n\ncurrent letter: g\ncurrent letter: o\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",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7b1b25d4b6525536143d25918b873251e20735a | 2,529 | ipynb | Jupyter Notebook | 05_transforms.ipynb | Samjoel3101/Self-Supervised-Learning-fastai2 | 08c6262ecd9497658c1143b67bc9ce432e7a0c20 | [
"Apache-2.0"
] | null | null | null | 05_transforms.ipynb | Samjoel3101/Self-Supervised-Learning-fastai2 | 08c6262ecd9497658c1143b67bc9ce432e7a0c20 | [
"Apache-2.0"
] | 1 | 2021-09-28T05:35:25.000Z | 2021-09-28T05:35:25.000Z | 05_transforms.ipynb | Samjoel3101/Self-Supervised-Learning-fastai2 | 08c6262ecd9497658c1143b67bc9ce432e7a0c20 | [
"Apache-2.0"
] | null | null | null | 2,529 | 2,529 | 0.662317 | [
[
[
"#default_exp transforms",
"_____no_output_____"
],
[
"import os \nos.chdir('/content/drive/My Drive/Semi Supervised Learning/Self-Supervised-Learning-fastai2')",
"_____no_output_____"
],
[
"!sh initialise.sh",
"_____no_output_____"
],
[
"#export \nfrom ssl_fastai2.imports import * ",
"_____no_output_____"
],
[
"#export \nclass TensorSSLImage(TensorImage): pass\nclass SSLImage(PILImage): \n _tensor_cls = TensorSSLImage\n\nclass SSLTransform(Transform):\n order = 25\n def __init__(self, augmentations = [Rotate(p = 1.), Flip(p = 1.), Dihedral(p = 1.), Warp(0.2, p = 1.), \n Brightness(0.5, p = 1.), Saturation(0.5, p = 1.)]):\n store_attr(self, 'augmentations')\n \n def encodes(self, x:TensorSSLImage):\n x = IntToFloatTensor(div = 1.)(x)\n for i in range(len(self.augmentations)):\n aug = random.choice(self.augmentations)\n x = aug(x)\n x = TensorImage(x)\n return x",
"_____no_output_____"
],
[
"!rm -r SelfSupervisedLearning",
"_____no_output_____"
],
[
"!git add -A",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b1bffa60ffadc6837aee10a0d710bb89629f86 | 60,028 | ipynb | Jupyter Notebook | pt2.ipynb | d4sein/Flowers-Recognition | 1afbc85b14e4ff64dd99d7866cedd985537b2182 | [
"Unlicense"
] | 1 | 2020-07-28T22:21:54.000Z | 2020-07-28T22:21:54.000Z | pt2.ipynb | d4sein/Flowers-Recognition | 1afbc85b14e4ff64dd99d7866cedd985537b2182 | [
"Unlicense"
] | null | null | null | pt2.ipynb | d4sein/Flowers-Recognition | 1afbc85b14e4ff64dd99d7866cedd985537b2182 | [
"Unlicense"
] | null | null | null | 189.962025 | 22,904 | 0.853202 | [
[
[
"# !pip install sklearn\n\nimport os\nimport time\nimport pickle\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow.keras.callbacks import TensorBoard, ReduceLROnPlateau\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.optimizers import SGD, Adam",
"_____no_output_____"
],
[
"X = pickle.load(open('X.pickle', 'rb'))\nY = pickle.load(open('Y.pickle', 'rb'))",
"_____no_output_____"
],
[
"X = X/255.0\nY = to_categorical(Y, num_classes=5)\n\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.25, random_state=42)",
"_____no_output_____"
],
[
"NAME = f'Flowers_Recognition-{int(time.time())}'\nDIR_NAME = os.path.abspath('')\n\ntensorboard = TensorBoard(log_dir=f'{DIR_NAME}\\logs\\\\{NAME}')\n\n# Network\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (5, 5), input_shape=x_train.shape[1:], activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\nmodel.add(Conv2D(96, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\nmodel.add(Conv2D(96, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(512, activation='relu'))\n\nmodel.add(Dense(5, activation='softmax'))\n\nred_lr = ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1, factor=0.1)\n\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 rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)\n zoom_range=0.1, # randomly zoom image \n width_shift_range=0.2, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.2, # randomly shift images vertically (fraction of total height)\n horizontal_flip=True, # randomly flip images\n vertical_flip=False) # randomly flip images\n\ndatagen.fit(x_train)\n\nx_test, y_test = x_train, y_train\n\nmodel.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001, amsgrad=True), metrics=['accuracy'])\n\nHistory = model.fit_generator(datagen.flow(x_train, y_train, batch_size=128),\n epochs=50, validation_data=(x_test, y_test),\n verbose=1, steps_per_epoch=x_train.shape[0]//128)\n\n\nmodel.save('Adam_AMSGrad_LR0.001.model')",
"WARNING:tensorflow:From <ipython-input-4-561bd44870b1>:49: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use Model.fit, which supports generators.\nWARNING:tensorflow:sample_weight modes were coerced from\n ...\n to \n ['...']\nTrain for 25 steps, validate on 3242 samples\nEpoch 1/50\n25/25 [==============================] - 38s 2s/step - loss: 1.5137 - accuracy: 0.3041 - val_loss: 1.2535 - val_accuracy: 0.4614\nEpoch 2/50\n25/25 [==============================] - 38s 2s/step - loss: 1.2360 - accuracy: 0.4522 - val_loss: 1.1884 - val_accuracy: 0.4920\nEpoch 3/50\n25/25 [==============================] - 40s 2s/step - loss: 1.1272 - accuracy: 0.5216 - val_loss: 1.0533 - val_accuracy: 0.5765\nEpoch 4/50\n25/25 [==============================] - 38s 2s/step - loss: 1.0590 - accuracy: 0.5620 - val_loss: 1.0343 - val_accuracy: 0.5700\nEpoch 5/50\n25/25 [==============================] - 37s 1s/step - loss: 1.0221 - accuracy: 0.5742 - val_loss: 0.9617 - val_accuracy: 0.6243\nEpoch 6/50\n25/25 [==============================] - 36s 1s/step - loss: 0.9982 - accuracy: 0.6031 - val_loss: 0.9347 - val_accuracy: 0.6329\nEpoch 7/50\n25/25 [==============================] - 37s 1s/step - loss: 0.9372 - accuracy: 0.6240 - val_loss: 0.8554 - val_accuracy: 0.6678\nEpoch 8/50\n25/25 [==============================] - 37s 1s/step - loss: 0.8944 - accuracy: 0.6474 - val_loss: 0.8455 - val_accuracy: 0.6626\nEpoch 9/50\n25/25 [==============================] - 36s 1s/step - loss: 0.8698 - accuracy: 0.6529 - val_loss: 0.8084 - val_accuracy: 0.6804\nEpoch 10/50\n25/25 [==============================] - 37s 1s/step - loss: 0.8403 - accuracy: 0.6731 - val_loss: 0.7881 - val_accuracy: 0.6863\nEpoch 11/50\n25/25 [==============================] - 36s 1s/step - loss: 0.8067 - accuracy: 0.6846 - val_loss: 0.7935 - val_accuracy: 0.6841\nEpoch 12/50\n25/25 [==============================] - 39s 2s/step - loss: 0.7941 - accuracy: 0.6882 - val_loss: 0.7095 - val_accuracy: 0.7233\nEpoch 13/50\n25/25 [==============================] - 39s 2s/step - loss: 0.8099 - accuracy: 0.6834 - val_loss: 0.7818 - val_accuracy: 0.6823\nEpoch 14/50\n25/25 [==============================] - 37s 1s/step - loss: 0.7746 - accuracy: 0.6901 - val_loss: 0.8898 - val_accuracy: 0.6582\nEpoch 15/50\n25/25 [==============================] - 37s 1s/step - loss: 0.7287 - accuracy: 0.7129 - val_loss: 0.6950 - val_accuracy: 0.7246\nEpoch 16/50\n25/25 [==============================] - 37s 1s/step - loss: 0.7290 - accuracy: 0.7161 - val_loss: 0.6701 - val_accuracy: 0.7415\nEpoch 17/50\n25/25 [==============================] - 37s 1s/step - loss: 0.7184 - accuracy: 0.7248 - val_loss: 0.7048 - val_accuracy: 0.7273\nEpoch 18/50\n25/25 [==============================] - 37s 1s/step - loss: 0.6937 - accuracy: 0.7171 - val_loss: 0.5931 - val_accuracy: 0.7761\nEpoch 19/50\n25/25 [==============================] - 37s 1s/step - loss: 0.6902 - accuracy: 0.7325 - val_loss: 0.6900 - val_accuracy: 0.7205\nEpoch 20/50\n25/25 [==============================] - 37s 1s/step - loss: 0.6860 - accuracy: 0.7306 - val_loss: 0.6329 - val_accuracy: 0.7535\nEpoch 21/50\n25/25 [==============================] - 37s 1s/step - loss: 0.6514 - accuracy: 0.7486 - val_loss: 0.6972 - val_accuracy: 0.7298\nEpoch 22/50\n25/25 [==============================] - 31s 1s/step - loss: 0.6670 - accuracy: 0.7341 - val_loss: 0.6140 - val_accuracy: 0.7671\nEpoch 23/50\n25/25 [==============================] - 32s 1s/step - loss: 0.6306 - accuracy: 0.7524 - val_loss: 0.5598 - val_accuracy: 0.7936\nEpoch 24/50\n25/25 [==============================] - 32s 1s/step - loss: 0.6060 - accuracy: 0.7585 - val_loss: 0.5646 - val_accuracy: 0.7835\nEpoch 25/50\n25/25 [==============================] - 32s 1s/step - loss: 0.6181 - accuracy: 0.7524 - val_loss: 0.5980 - val_accuracy: 0.7733\nEpoch 26/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5877 - accuracy: 0.7749 - val_loss: 0.5393 - val_accuracy: 0.7936\nEpoch 27/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5745 - accuracy: 0.7746 - val_loss: 0.5174 - val_accuracy: 0.8020\nEpoch 28/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5723 - accuracy: 0.7820 - val_loss: 0.5092 - val_accuracy: 0.8054\nEpoch 29/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5587 - accuracy: 0.7855 - val_loss: 0.4658 - val_accuracy: 0.8254\nEpoch 30/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5809 - accuracy: 0.7714 - val_loss: 0.5234 - val_accuracy: 0.8001\nEpoch 31/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5584 - accuracy: 0.7845 - val_loss: 0.5125 - val_accuracy: 0.8023\nEpoch 32/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5532 - accuracy: 0.7868 - val_loss: 0.4586 - val_accuracy: 0.8254\nEpoch 33/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5266 - accuracy: 0.7935 - val_loss: 0.4416 - val_accuracy: 0.8334\nEpoch 34/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5207 - accuracy: 0.7974 - val_loss: 0.5349 - val_accuracy: 0.7927\nEpoch 35/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5214 - accuracy: 0.7961 - val_loss: 0.4628 - val_accuracy: 0.8239\nEpoch 36/50\n25/25 [==============================] - 32s 1s/step - loss: 0.5108 - accuracy: 0.8009 - val_loss: 0.4201 - val_accuracy: 0.8368\nEpoch 37/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4925 - accuracy: 0.8067 - val_loss: 0.3922 - val_accuracy: 0.8455\nEpoch 38/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4606 - accuracy: 0.8186 - val_loss: 0.3929 - val_accuracy: 0.8479\nEpoch 39/50\n25/25 [==============================] - 33s 1s/step - loss: 0.4617 - accuracy: 0.8205 - val_loss: 0.3834 - val_accuracy: 0.8587\nEpoch 40/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4560 - accuracy: 0.8263 - val_loss: 0.3749 - val_accuracy: 0.8624\nEpoch 41/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4820 - accuracy: 0.8096 - val_loss: 0.4237 - val_accuracy: 0.8267\nEpoch 42/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4764 - accuracy: 0.8112 - val_loss: 0.4046 - val_accuracy: 0.8427\nEpoch 43/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4405 - accuracy: 0.8218 - val_loss: 0.3251 - val_accuracy: 0.8825\nEpoch 44/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4081 - accuracy: 0.8407 - val_loss: 0.3781 - val_accuracy: 0.8504\nEpoch 45/50\n25/25 [==============================] - 32s 1s/step - loss: 0.4291 - accuracy: 0.8365 - val_loss: 0.3153 - val_accuracy: 0.8772\nEpoch 46/50\n25/25 [==============================] - 33s 1s/step - loss: 0.3998 - accuracy: 0.8407 - val_loss: 0.3930 - val_accuracy: 0.8486\nEpoch 47/50\n25/25 [==============================] - 31s 1s/step - loss: 0.4440 - accuracy: 0.8202 - val_loss: 0.3028 - val_accuracy: 0.8899\nEpoch 48/50\n25/25 [==============================] - 30s 1s/step - loss: 0.3940 - accuracy: 0.8478 - val_loss: 0.2943 - val_accuracy: 0.8859\nEpoch 49/50\n25/25 [==============================] - 31s 1s/step - loss: 0.3721 - accuracy: 0.8590 - val_loss: 0.2820 - val_accuracy: 0.8936\nEpoch 50/50\n25/25 [==============================] - 33s 1s/step - loss: 0.3592 - accuracy: 0.8613 - val_loss: 0.3451 - val_accuracy: 0.8646\nWARNING:tensorflow:From D:\\Documents\\Python\\Flowers-Recognition\\env\\lib\\site-packages\\tensorflow_core\\python\\ops\\resource_variable_ops.py:1786: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\nINFO:tensorflow:Assets written to: Adam_AMSGrad_LR0.001.model\\assets\n"
],
[
"plt.plot(History.history['loss'])\nplt.plot(History.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('Epochs')\nplt.legend(['train', 'test'])\nplt.show()",
"_____no_output_____"
],
[
"plt.plot(History.history['accuracy'])\nplt.plot(History.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epochs')\nplt.legend(['train', 'test'])\nplt.show()",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b1c571f590f7b6171e2d936764671f6b3c1dc2 | 39,494 | ipynb | Jupyter Notebook | docs/tutorials/api/models.ipynb | aaguasca/gammapy | b1a4e9dbaeec23b3eaca1c874752e92432920a42 | [
"BSD-3-Clause"
] | null | null | null | docs/tutorials/api/models.ipynb | aaguasca/gammapy | b1a4e9dbaeec23b3eaca1c874752e92432920a42 | [
"BSD-3-Clause"
] | null | null | null | docs/tutorials/api/models.ipynb | aaguasca/gammapy | b1a4e9dbaeec23b3eaca1c874752e92432920a42 | [
"BSD-3-Clause"
] | null | null | null | 28.089616 | 576 | 0.588646 | [
[
[
"# Models\n\n\nThis is an introduction and overview on how to work with models in Gammapy. \n\nThe sub-package `~gammapy.modeling` contains all the functionality related to modeling and fitting\ndata. This includes spectral, spatial and temporal model classes, as well as the fit\nand parameter API. We will cover the following topics in order:\n\n1. [Spectral Models](#Spectral-Models)\n1. [Spatial Models](#Spatial-Models)\n1. [Temporal Models](#Temporal-Models)\n1. [SkyModel](#SkyModel)\n1. [Modifying model parameters](#Modifying-model-parameters)\n1. [Model Lists and Serialisation](#Model-Lists-and-Serialisation)\n1. [Models with shared parameter](#Models-with-shared-parameter)\n1. [Implementing as Custom Model](#Implementing-a-Custom-Model)\n1. [Energy dependent models](#Models-with-energy-dependent-morphology)\n\nThe models follow a naming scheme which contains the category as a suffix to the class name. An overview of all the available models can be found in the [model gallery](../../modeling/gallery/index.rst#spectral-models).\n\nNote that there are separate tutorials, [model_management](model_management.ipynb) and [fitting](fitting.ipynb) that explains about `~gammapy.modeling`,\nthe Gammapy modeling and fitting framework. You have to read that to learn how to work with models in order to analyse data.\n\n",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"from astropy import units as u\nfrom gammapy.maps import Map, WcsGeom, MapAxis",
"_____no_output_____"
]
],
[
[
"## Spectral models\n\nAll models are imported from the `~gammapy.modeling.models` namespace. Let's start with a `PowerLawSpectralModel`:",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import PowerLawSpectralModel",
"_____no_output_____"
],
[
"pwl = PowerLawSpectralModel()\nprint(pwl)",
"_____no_output_____"
]
],
[
[
"To get a list of all available spectral models you can import and print the spectral model registry or take a look at the [model gallery](https://docs.gammapy.org/dev/modeling/gallery/index.html#spectral-models):",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import SPECTRAL_MODEL_REGISTRY\n\nprint(SPECTRAL_MODEL_REGISTRY)",
"_____no_output_____"
]
],
[
[
"Spectral models all come with default parameters. Different parameter\nvalues can be passed on creation of the model, either as a string defining\nthe value and unit or as an `astropy.units.Quantity` object directly:",
"_____no_output_____"
]
],
[
[
"amplitude = 1e-12 * u.Unit(\"TeV-1 cm-2 s-1\")\npwl = PowerLawSpectralModel(amplitude=amplitude, index=2.2)",
"_____no_output_____"
]
],
[
[
"For convenience a `str` specifying the value and unit can be passed as well:",
"_____no_output_____"
]
],
[
[
"pwl = PowerLawSpectralModel(amplitude=\"2.7e-12 TeV-1 cm-2 s-1\", index=2.2)\nprint(pwl)",
"_____no_output_____"
]
],
[
[
"The model can be evaluated at given energies by calling the model instance:",
"_____no_output_____"
]
],
[
[
"energy = [1, 3, 10, 30] * u.TeV\ndnde = pwl(energy)\nprint(dnde)",
"_____no_output_____"
]
],
[
[
"The returned quantity is a differential photon flux. \n\nFor spectral models you can additionally compute the integrated and energy flux\nin a given energy range:",
"_____no_output_____"
]
],
[
[
"flux = pwl.integral(energy_min=1 * u.TeV, energy_max=10 * u.TeV)\nprint(flux)\n\neflux = pwl.energy_flux(energy_min=1 * u.TeV, energy_max=10 * u.TeV)\nprint(eflux)",
"_____no_output_____"
]
],
[
[
"This also works for a list or an array of integration boundaries:",
"_____no_output_____"
]
],
[
[
"energy = [1, 3, 10, 30] * u.TeV\nflux = pwl.integral(energy_min=energy[:-1], energy_max=energy[1:])\nprint(flux)",
"_____no_output_____"
]
],
[
[
"In some cases it can be useful to find use the inverse of a spectral model, to find the energy at which a given flux is reached:",
"_____no_output_____"
]
],
[
[
"dnde = 2.7e-12 * u.Unit(\"TeV-1 cm-2 s-1\")\nenergy = pwl.inverse(dnde)\nprint(energy)",
"_____no_output_____"
]
],
[
[
"As a convenience you can also plot any spectral model in a given energy range:",
"_____no_output_____"
]
],
[
[
"pwl.plot(energy_bounds=[1, 100] * u.TeV)",
"_____no_output_____"
]
],
[
[
"### Norm Spectral Models",
"_____no_output_____"
],
[
"Normed spectral models are a special class of Spectral Models, which have a dimension-less normalisation. These spectral models feature a norm parameter instead\nof amplitude and are named using the ``NormSpectralModel`` suffix. They **must** be used along with another spectral model, as a multiplicative correction factor according to their spectral shape. They can be typically used for adjusting template based models, or adding a EBL correction to some analytic model. \n\nTo check if a given `SpectralModel` is a norm model, you can simply look at the `is_norm_spectral_model` property",
"_____no_output_____"
]
],
[
[
"# To see the available norm models shipped with gammapy:\nfor model in SPECTRAL_MODEL_REGISTRY:\n if model.is_norm_spectral_model:\n print(model)",
"_____no_output_____"
]
],
[
[
"As an example, we see the `PowerLawNormSpectralModel`",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import PowerLawNormSpectralModel",
"_____no_output_____"
],
[
"pwl_norm = PowerLawNormSpectralModel(tilt=0.1)\nprint(pwl_norm)",
"_____no_output_____"
]
],
[
[
"We can check the correction introduced at each energy ",
"_____no_output_____"
]
],
[
[
"energy = [0.3, 1, 3, 10, 30] * u.TeV\npwl_norm(energy)",
"_____no_output_____"
]
],
[
[
"A typical use case of a norm model would be in applying spectral correction to a `TemplateSpectralModel`. A template model is defined by custom tabular values provided at initialization. ",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import TemplateSpectralModel",
"_____no_output_____"
],
[
"energy = [0.3, 1, 3, 10, 30] * u.TeV\nvalues = [40, 30, 20, 10, 1] * u.Unit(\"TeV-1 s-1 cm-2\")\ntemplate = TemplateSpectralModel(energy, values)\ntemplate.plot(energy_bounds=[0.2, 50] * u.TeV, label=\"template model\")\nnormed_template = template * pwl_norm\nnormed_template.plot(\n energy_bounds=[0.2, 50] * u.TeV, label=\"normed_template model\"\n)\nplt.legend();",
"_____no_output_____"
]
],
[
[
"### Compound Spectral Model\n\nA `CompoundSpectralModel` is an arithmetic combination of two spectral models. The model `normed_template` created in the preceding example is an example of a `CompoundSpectralModel`\n",
"_____no_output_____"
]
],
[
[
"print(normed_template)",
"_____no_output_____"
]
],
[
[
"To create an additive model, you can do simply:",
"_____no_output_____"
]
],
[
[
"model_add = pwl + template\nprint(model_add)",
"_____no_output_____"
]
],
[
[
"## Spatial models",
"_____no_output_____"
],
[
"Spatial models are imported from the same `~gammapy.modeling.models` namespace, let's start with a `GaussianSpatialModel`:",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import GaussianSpatialModel",
"_____no_output_____"
],
[
"gauss = GaussianSpatialModel(lon_0=\"0 deg\", lat_0=\"0 deg\", sigma=\"0.2 deg\")\nprint(gauss)",
"_____no_output_____"
]
],
[
[
"Again you can check the `SPATIAL_MODELS` registry to see which models are available or take a look at the [model gallery](https://docs.gammapy.org/dev/modeling/gallery/index.html#spatial-models).",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import SPATIAL_MODEL_REGISTRY\n\nprint(SPATIAL_MODEL_REGISTRY)",
"_____no_output_____"
]
],
[
[
"The default coordinate frame for all spatial models is ``\"icrs\"``, but the frame can be modified using the\n``frame`` argument:",
"_____no_output_____"
]
],
[
[
"gauss = GaussianSpatialModel(\n lon_0=\"0 deg\", lat_0=\"0 deg\", sigma=\"0.2 deg\", frame=\"galactic\"\n)",
"_____no_output_____"
]
],
[
[
"You can specify any valid `astropy.coordinates` frame. The center position of the model can be retrieved as a `astropy.coordinates.SkyCoord` object using `SpatialModel.position`: ",
"_____no_output_____"
]
],
[
[
"print(gauss.position)",
"_____no_output_____"
]
],
[
[
"Spatial models can be evaluated again by calling the instance:",
"_____no_output_____"
]
],
[
[
"lon = [0, 0.1] * u.deg\nlat = [0, 0.1] * u.deg\n\nflux_per_omega = gauss(lon, lat)\nprint(flux_per_omega)",
"_____no_output_____"
]
],
[
[
"The returned quantity corresponds to a surface brightness. Spatial model\ncan be also evaluated using `~gammapy.maps.Map` and `~gammapy.maps.Geom` objects:",
"_____no_output_____"
]
],
[
[
"m = Map.create(skydir=(0, 0), width=(1, 1), binsz=0.02, frame=\"galactic\")\nm.quantity = gauss.evaluate_geom(m.geom)\nm.plot(add_cbar=True);",
"_____no_output_____"
]
],
[
[
"Again for convenience the model can be plotted directly:",
"_____no_output_____"
]
],
[
[
"gauss.plot(add_cbar=True);",
"_____no_output_____"
]
],
[
[
"All spatial models have an associated sky region to it e.g. to illustrate the extend of the model on a sky image. The returned object is an `regions.SkyRegion` object:",
"_____no_output_____"
]
],
[
[
"print(gauss.to_region())",
"_____no_output_____"
]
],
[
[
"Now we can plot the region on an sky image:",
"_____no_output_____"
]
],
[
[
"# create and plot the model\ngauss_elongated = GaussianSpatialModel(\n lon_0=\"0 deg\", lat_0=\"0 deg\", sigma=\"0.2 deg\", e=0.7, phi=\"45 deg\"\n)\nax = gauss_elongated.plot(add_cbar=True)\n\n# add region illustration\nregion = gauss_elongated.to_region()\nregion_pix = region.to_pixel(ax.wcs)\nax.add_artist(region_pix.as_artist(ec=\"w\", fc=\"None\"));",
"_____no_output_____"
]
],
[
[
"The `.to_region()` method can also be useful to write e.g. ds9 region files using `write_ds9` from the `regions` package:",
"_____no_output_____"
]
],
[
[
"from regions import write_ds9\n\nregions = [gauss.to_region(), gauss_elongated.to_region()]\n\nfilename = \"regions.reg\"\nwrite_ds9(\n regions,\n filename,\n coordsys=\"galactic\",\n fmt=\".4f\",\n radunit=\"deg\",\n overwrite=True,\n)",
"_____no_output_____"
],
[
"!cat regions.reg",
"_____no_output_____"
]
],
[
[
"## Temporal models",
"_____no_output_____"
],
[
"Temporal models are imported from the same `~gammapy.modeling.models` namespace, let's start with a `GaussianTemporalModel`:",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import GaussianTemporalModel",
"_____no_output_____"
],
[
"gauss_temp = GaussianTemporalModel(t_ref=59240.0 * u.d, sigma=2.0 * u.d)\nprint(gauss_temp)",
"_____no_output_____"
]
],
[
[
"To check the `TEMPORAL_MODELS` registry to see which models are available:",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import TEMPORAL_MODEL_REGISTRY\n\nprint(TEMPORAL_MODEL_REGISTRY)",
"_____no_output_____"
]
],
[
[
"Temporal models can be evaluated on `astropy.time.Time` objects. The returned quantity is a dimensionless number",
"_____no_output_____"
]
],
[
[
"from astropy.time import Time\n\ntime = Time(\"2021-01-29 00:00:00.000\")\ngauss_temp(time)",
"_____no_output_____"
]
],
[
[
"As for other models, they can be plotted in a given time range",
"_____no_output_____"
]
],
[
[
"time = Time([59233.0, 59250], format=\"mjd\")\ngauss_temp.plot(time)",
"_____no_output_____"
]
],
[
[
"## SkyModel",
"_____no_output_____"
],
[
"The `~gammapy.modeling.models.SkyModel` class combines a spectral, and optionally, a spatial model and a temporal. It can be created\nfrom existing spectral, spatial and temporal model components:",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import SkyModel\n\nmodel = SkyModel(\n spectral_model=pwl,\n spatial_model=gauss,\n temporal_model=gauss_temp,\n name=\"my-source\",\n)\nprint(model)",
"_____no_output_____"
]
],
[
[
"It is good practice to specify a name for your sky model, so that you can access it later by name and have meaningful identifier you serilisation. If you don't define a name, a unique random name is generated:",
"_____no_output_____"
]
],
[
[
"model_without_name = SkyModel(spectral_model=pwl, spatial_model=gauss)\nprint(model_without_name.name)",
"_____no_output_____"
]
],
[
[
"The individual components of the source model can be accessed using `.spectral_model`, `.spatial_model` and `.temporal_model`:",
"_____no_output_____"
]
],
[
[
"model.spectral_model",
"_____no_output_____"
],
[
"model.spatial_model",
"_____no_output_____"
],
[
"model.temporal_model",
"_____no_output_____"
]
],
[
[
"And can be used as you have seen already seen above:",
"_____no_output_____"
]
],
[
[
"model.spectral_model.plot(energy_bounds=[1, 10] * u.TeV);",
"_____no_output_____"
]
],
[
[
"Note that the gammapy fitting can interface only with a `SkyModel` and **not** its individual components. So, it is customary to work with `SkyModel` even if you are not doing a 3D fit. Since the amplitude parameter resides on the `SpectralModel`, specifying a spectral component is compulsory. The temporal and spatial components are optional. The temporal model needs to be specified only for timing analysis. In some cases (e.g. when doing a spectral analysis) there is no need for a spatial component either, and only a spectral model is associated with the source. ",
"_____no_output_____"
]
],
[
[
"model_spectrum = SkyModel(spectral_model=pwl, name=\"source-spectrum\")\nprint(model_spectrum)",
"_____no_output_____"
]
],
[
[
"Additionally the spatial model of `~gammapy.modeling.models.SkyModel` can be used to represent source models based on templates, where the spatial and energy axes are correlated. It can be created e.g. from an existing FITS file:\n\n",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import TemplateSpatialModel\nfrom gammapy.modeling.models import PowerLawNormSpectralModel",
"_____no_output_____"
],
[
"diffuse_cube = TemplateSpatialModel.read(\n \"$GAMMAPY_DATA/fermi-3fhl-gc/gll_iem_v06_gc.fits.gz\", normalize=False\n)\ndiffuse = SkyModel(PowerLawNormSpectralModel(), diffuse_cube)\nprint(diffuse)",
"_____no_output_____"
]
],
[
[
"Note that if the spatial model is not normalized over the sky it has to be combined with a normalized spectral model, for example `~gammapy.modeling.models.PowerLawNormSpectralModel`. This is the only case in `gammapy.models.SkyModel` where the unit is fully attached to the spatial model.",
"_____no_output_____"
],
[
"## Modifying model parameters\n\nModel parameters can be modified (eg: frozen, values changed, etc at any point), eg:",
"_____no_output_____"
]
],
[
[
"# Freezing a parameter\nmodel.spectral_model.index.frozen = True\n# Making a parameter free\nmodel.spectral_model.index.frozen = False",
"_____no_output_____"
],
[
"# Changing a value\nmodel.spectral_model.index.value = 3",
"_____no_output_____"
],
[
"# Setting min and max ranges on parameters\nmodel.spectral_model.index.min = 1.0\nmodel.spectral_model.index.max = 5.0",
"_____no_output_____"
],
[
"# Visualise the model as a table\nmodel.parameters.to_table().show_in_notebook()",
"_____no_output_____"
]
],
[
[
"You can use the interactive boxes to choose model parameters by name, type or other attrributes mentioned in the column names.",
"_____no_output_____"
],
[
"## Model lists and serialisation\n\nIn a typical analysis scenario a model consists of multiple model components, or a \"catalog\" or \"source library\". To handle this list of multiple model components, Gammapy has a `Models` class:",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import Models",
"_____no_output_____"
],
[
"models = Models([model, diffuse])\nprint(models)",
"_____no_output_____"
]
],
[
[
"Individual model components in the list can be accessed by their name:",
"_____no_output_____"
]
],
[
[
"print(models[\"my-source\"])",
"_____no_output_____"
]
],
[
[
"**Note:**To make the access by name unambiguous, models are required to have a unique name, otherwise an error will be thrown.\n\nTo see which models are available you can use the `.names` attribute:",
"_____no_output_____"
]
],
[
[
"print(models.names)",
"_____no_output_____"
]
],
[
[
"Note that a `SkyModel` object can be evaluated for a given longitude, latitude, and energy, but the `Models` object cannot. This `Models` container object will be assigned to `Dataset` or `Datasets` together with the data to be fitted as explained in other analysis tutorials (see for example the [modeling](../analysis/2D/modeling_2D.ipynb) notebook).\n\nThe `Models` class also has in place `.append()` and `.extend()` methods:",
"_____no_output_____"
]
],
[
[
"model_copy = model.copy(name=\"my-source-copy\")\nmodels.append(model_copy)",
"_____no_output_____"
]
],
[
[
"This list of models can be also serialised to a custom YAML based format: ",
"_____no_output_____"
]
],
[
[
"models_yaml = models.to_yaml()\nprint(models_yaml)",
"_____no_output_____"
]
],
[
[
"The structure of the yaml files follows the structure of the python objects.\nThe `components` listed correspond to the `SkyModel` and `SkyDiffuseCube` components of the `Models`. \nFor each `SkyModel` we have information about its `name`, `type` (corresponding to the tag attribute) and sub-mobels (i.e `spectral` model and eventually `spatial` model). Then the spatial and spectral models are defined by their type and parameters. The `parameters` keys name/value/unit are mandatory, while the keys min/max/frozen are optionnals (so you can prepare shorter files).\n\nIf you want to write this list of models to disk and read it back later you can use:",
"_____no_output_____"
]
],
[
[
"models.write(\"models.yaml\", overwrite=True)",
"_____no_output_____"
],
[
"models_read = Models.read(\"models.yaml\")",
"_____no_output_____"
]
],
[
[
"Additionally the models can exported and imported togeter with the data using the `Datasets.read()` and `Datasets.write()` methods as shown in the [analysis_mwl](../analysis/3D/analysis_mwl.ipynb) notebook.\n\n## Models with shared parameter\n\nA model parameter can be shared with other models, for example we can define two power-law models with the same spectral index but different amplitudes: ",
"_____no_output_____"
]
],
[
[
"pwl2 = PowerLawSpectralModel()\npwl2.index = pwl.index\npwl.index.value = 2.3 # also update pwl2 as the parameter object is now the same as shown below\nprint(pwl.index)\nprint(pwl2.index)",
"_____no_output_____"
]
],
[
[
"In the YAML files the shared parameter is flagged by the additional `link` entry that follows the convention `parameter.name@unique_id`:",
"_____no_output_____"
]
],
[
[
"models = Models(\n [SkyModel(pwl, name=\"source1\"), SkyModel(pwl2, name=\"source2\")]\n)\nmodels_yaml = models.to_yaml()\nprint(models_yaml)",
"_____no_output_____"
]
],
[
[
"## Implementing a custom model\n\nIn order to add a user defined spectral model you have to create a SpectralModel subclass.\nThis new model class should include:\n\n- a tag used for serialization (it can be the same as the class name)\n- an instantiation of each Parameter with their unit, default values and frozen status\n- the evaluate function where the mathematical expression for the model is defined.\n\nAs an example we will use a PowerLawSpectralModel plus a Gaussian (with fixed width).\nFirst we define the new custom model class that we name `MyCustomSpectralModel`:",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling import Parameter\nfrom gammapy.modeling.models import SpectralModel\n\n\nclass MyCustomSpectralModel(SpectralModel):\n \"\"\"My custom spectral model, parametrising a power law plus a Gaussian spectral line.\n\n Parameters\n ----------\n amplitude : `astropy.units.Quantity`\n Amplitude of the spectra model.\n index : `astropy.units.Quantity`\n Spectral index of the model.\n reference : `astropy.units.Quantity`\n Reference energy of the power law.\n mean : `astropy.units.Quantity`\n Mean value of the Gaussian.\n width : `astropy.units.Quantity`\n Sigma width of the Gaussian line.\n\n \"\"\"\n\n tag = \"MyCustomSpectralModel\"\n amplitude = Parameter(\"amplitude\", \"1e-12 cm-2 s-1 TeV-1\", min=0)\n index = Parameter(\"index\", 2, min=0)\n reference = Parameter(\"reference\", \"1 TeV\", frozen=True)\n mean = Parameter(\"mean\", \"1 TeV\", min=0)\n width = Parameter(\"width\", \"0.1 TeV\", min=0, frozen=True)\n\n @staticmethod\n def evaluate(energy, index, amplitude, reference, mean, width):\n pwl = PowerLawSpectralModel.evaluate(\n energy=energy,\n index=index,\n amplitude=amplitude,\n reference=reference,\n )\n gauss = amplitude * np.exp(-((energy - mean) ** 2) / (2 * width ** 2))\n return pwl + gauss",
"_____no_output_____"
]
],
[
[
"It is good practice to also implement a docstring for the model, defining the parameters and also definig a `tag`, which specifies the name of the model for serialisation. Also note that gammapy assumes that all SpectralModel evaluate functions return a flux in unit of `\"cm-2 s-1 TeV-1\"` (or equivalent dimensions).\n\n\n\nThis model can now be used as any other spectral model in Gammapy:",
"_____no_output_____"
]
],
[
[
"my_custom_model = MyCustomSpectralModel(mean=\"3 TeV\")\nprint(my_custom_model)",
"_____no_output_____"
],
[
"my_custom_model.integral(1 * u.TeV, 10 * u.TeV)",
"_____no_output_____"
],
[
"my_custom_model.plot(energy_bounds=[1, 10] * u.TeV)",
"_____no_output_____"
]
],
[
[
"As a next step we can also register the custom model in the `SPECTRAL_MODELS` registry, so that it becomes available for serilisation:",
"_____no_output_____"
]
],
[
[
"SPECTRAL_MODEL_REGISTRY.append(MyCustomSpectralModel)",
"_____no_output_____"
],
[
"model = SkyModel(spectral_model=my_custom_model, name=\"my-source\")\nmodels = Models([model])\nmodels.write(\"my-custom-models.yaml\", overwrite=True)",
"_____no_output_____"
],
[
"!cat my-custom-models.yaml",
"_____no_output_____"
]
],
[
[
"Similarly you can also create custom spatial models and add them to the `SPATIAL_MODELS` registry. In that case gammapy assumes that the evaluate function return a normalized quantity in \"sr-1\" such as the model integral over the whole sky is one.",
"_____no_output_____"
],
[
"## Models with energy dependent morphology\n\nA common science case in the study of extended sources is to probe for energy dependent morphology, eg: in Supernova Remnants or Pulsar Wind Nebulae. Traditionally, this has been done by splitting the data into energy bands and doing individual fits of the morphology in these energy bands.\n\n`SkyModel` offers a natural framework to simultaneously model the energy and morphology, e.g. spatial extent described by a parametric model expression with energy dependent parameters.\n\nThe models shipped within gammapy use a “factorised” representation of the source model, where the spatial ($l,b$), energy ($E$) and time ($t$) dependence are independent model components and not correlated:\n\n $$f(l, b, E, t) = F(l, b) \\cdot G(E) \\cdot H(t) $$\n \nTo use full 3D models, ie $f(l, b, E) = F(l, b, E) \\cdot G(E) $, you have to implement your own custom `SpatialModel`. Note that it is still necessary to multiply by a `SpectralModel`, $G(E)$ to be dimensionally consistent.\n\nIn this example, we create Gaussian Spatial Model with the extension varying with energy. For simplicity, we assume a linear dependence on energy and parameterize this by specifying the extension at 2 energies. You can add more complex dependences, probably motivated by physical models.",
"_____no_output_____"
]
],
[
[
"from gammapy.modeling.models import SpatialModel\nfrom astropy.coordinates.angle_utilities import angular_separation\n\n\nclass MyCustomGaussianModel(SpatialModel):\n \"\"\"My custom Energy Dependent Gaussian model.\n\n Parameters\n ----------\n lon_0, lat_0 : `~astropy.coordinates.Angle`\n Center position\n sigma_1TeV : `~astropy.coordinates.Angle`\n Width of the Gaussian at 1 TeV\n sigma_10TeV : `~astropy.coordinates.Angle`\n Width of the Gaussian at 10 TeV\n\n \"\"\"\n\n tag = \"MyCustomGaussianModel\"\n is_energy_dependent = True\n lon_0 = Parameter(\"lon_0\", \"0 deg\")\n lat_0 = Parameter(\"lat_0\", \"0 deg\", min=-90, max=90)\n\n sigma_1TeV = Parameter(\"sigma_1TeV\", \"2.0 deg\", min=0)\n sigma_10TeV = Parameter(\"sigma_10TeV\", \"0.2 deg\", min=0)\n\n @staticmethod\n def evaluate(lon, lat, energy, lon_0, lat_0, sigma_1TeV, sigma_10TeV):\n\n sep = angular_separation(lon, lat, lon_0, lat_0)\n\n # Compute sigma for the given energy using linear interpolation in log energy\n sigma_nodes = u.Quantity([sigma_1TeV, sigma_10TeV])\n energy_nodes = [1, 10] * u.TeV\n log_s = np.log(sigma_nodes.to(\"deg\").value)\n log_en = np.log(energy_nodes.to(\"TeV\").value)\n log_e = np.log(energy.to(\"TeV\").value)\n sigma = np.exp(np.interp(log_e, log_en, log_s)) * u.deg\n\n exponent = -0.5 * (sep / sigma) ** 2\n norm = 1 / (2 * np.pi * sigma ** 2)\n return norm * np.exp(exponent)",
"_____no_output_____"
]
],
[
[
"Serialisation of this model can be achieved as explained in the previous section.\nYou can now use it as stadard `SpatialModel` in your analysis. Note that this is still a `SpatialModel`, and not a `SkyModel`, so it needs to be multiplied by a `SpectralModel` as before. ",
"_____no_output_____"
]
],
[
[
"spatial_model = MyCustomGaussianModel()\nspectral_model = PowerLawSpectralModel()\nsky_model = SkyModel(\n spatial_model=spatial_model, spectral_model=spectral_model\n)",
"_____no_output_____"
],
[
"spatial_model.evaluation_radius",
"_____no_output_____"
]
],
[
[
"To visualise it, we evaluate it on a 3D geom. ",
"_____no_output_____"
]
],
[
[
"energy_axis = MapAxis.from_energy_bounds(\n energy_min=0.1 * u.TeV, energy_max=10.0 * u.TeV, nbin=3, name=\"energy_true\"\n)\ngeom = WcsGeom.create(\n skydir=(0, 0), width=5.0 * u.deg, binsz=0.1, axes=[energy_axis]\n)\n\nspatial_model.plot_grid(geom=geom, add_cbar=True, figsize=(14, 3));",
"_____no_output_____"
]
],
[
[
"For computational purposes, it is useful to specify a `evaluation_radius` for `SpatialModels` - this gives a size on which to compute the model. Though optional, it is highly recommended for Custom Spatial Models. This can be done, for ex, by defining the following function inside the above class:",
"_____no_output_____"
]
],
[
[
"@property\ndef evaluation_radius(self):\n \"\"\"Evaluation radius (`~astropy.coordinates.Angle`).\"\"\"\n return 5 * np.max([self.sigma_1TeV.value, self.sigma_10TeV.value]) * u.deg",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b1d70728608fe3bcd0dccb629e8d2647b32347 | 16,633 | ipynb | Jupyter Notebook | Recurrent_neural_network.ipynb | jaivanti/Simple-RNN-Model | 56feb4b87655aee31406f9fa4a012faf3fb8b1e2 | [
"MIT"
] | null | null | null | Recurrent_neural_network.ipynb | jaivanti/Simple-RNN-Model | 56feb4b87655aee31406f9fa4a012faf3fb8b1e2 | [
"MIT"
] | null | null | null | Recurrent_neural_network.ipynb | jaivanti/Simple-RNN-Model | 56feb4b87655aee31406f9fa4a012faf3fb8b1e2 | [
"MIT"
] | null | null | null | 29.231986 | 809 | 0.457103 | [
[
[
"TASK1: INTRODUCTION",
"_____no_output_____"
]
],
[
[
"!pip install nn_utils",
"Collecting nn_utils\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/dc/9d/e71db8903643a187b55310289bcd6175bbba7cae6547d9511a4334056cd2/nn_utils-0.1.0-py2.py3-none-any.whl (326kB)\n\u001b[K |████████████████████████████████| 327kB 2.7MB/s \n\u001b[?25hRequirement already satisfied: numpy>=0.1.4 in /usr/local/lib/python3.6/dist-packages (from nn_utils) (1.18.4)\nInstalling collected packages: nn-utils\nSuccessfully installed nn-utils-0.1.0\n"
],
[
"import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import TimeDistributed, Dense, Dropout, SimpleRNN, RepeatVector\nfrom tensorflow.keras.callbacks import EarlyStopping, LambdaCallback\nimport nn_utils\nfrom termcolor import colored",
"_____no_output_____"
]
],
[
[
"TASK2: GENERATE DATA",
"_____no_output_____"
]
],
[
[
"all_chars='0123456789+'",
"_____no_output_____"
],
[
"num_feature=len(all_chars)\nprint('number of features:',num_feature)\nchar_to_index=dict((c,i) for i,c in enumerate(all_chars))\nindex_to_char=dict((i,c) for i,c in enumerate (all_chars))",
"number of features: 11\n"
],
[
"def generate_data():\n first=np.random.randint(0,100)\n second=np.random.randint(0,100)\n example=str(first)+ '+'+str(second)\n label=str(first+second)\n return example,label\ngenerate_data() ",
"_____no_output_____"
]
],
[
[
"TASK3: CREATE THE MODEL\n\nconsider two reviews:\n\nreview 1: This movie is not terrible at all.\n\nreview 2: This movie is pretty descent.",
"_____no_output_____"
]
],
[
[
"hidden_units=128\nmax_time_steps=5\nmodel=Sequential([\n SimpleRNN(hidden_units, input_shape=(None, num_feature)),\n RepeatVector(max_time_steps),\n SimpleRNN(hidden_units, return_sequences=True),\n TimeDistributed(Dense(num_feature, activation='softmax'))\n])\nmodel.compile(\n loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy']\n)\nmodel.summary()",
"Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nsimple_rnn (SimpleRNN) (None, 128) 17920 \n_________________________________________________________________\nrepeat_vector (RepeatVector) (None, 5, 128) 0 \n_________________________________________________________________\nsimple_rnn_1 (SimpleRNN) (None, 5, 128) 32896 \n_________________________________________________________________\ntime_distributed (TimeDistri (None, 5, 11) 1419 \n=================================================================\nTotal params: 52,235\nTrainable params: 52,235\nNon-trainable params: 0\n_________________________________________________________________\n"
]
],
[
[
"TASK4: VECTORISE AND DEVECTORISE DATA",
"_____no_output_____"
]
],
[
[
"def vectorize_example(example, label):\n x=np.zeros((max_time_steps, num_feature))\n y=np.zeros((max_time_steps, num_feature))\n\n diff_x=max_time_steps - len(example)\n diff_y=max_time_steps - len(label)\n\n for i,c in enumerate(example):\n x[i+diff_x, char_to_index[c]]=1\n for i in range(diff_x):\n x[i,char_to_index['0']]=1 \n for i,c in enumerate(label):\n y[i+diff_y, char_to_index[c]]=1\n for i in range(diff_y):\n y[i,char_to_index['0']]=1 \n return x, y\nm=1 \ne,m=generate_data()\nprint(e, m)\n\nx, y = vectorize_example(e, m)\nprint(x.shape, y.shape)\n",
"74+82 156\n(5, 11) (5, 11)\n"
],
[
"def devectorize_example(example):\n result=[index_to_char[np.argmax(vec)] for i,vec in enumerate(example)]\n return''.join(result)\n\ndevectorize_example(x) ",
"_____no_output_____"
],
[
" devectorize_example(y)",
"_____no_output_____"
]
],
[
[
"TASK5:CREATE DATASET",
"_____no_output_____"
]
],
[
[
"def create_dataset(num_examples=2000):\n x=np.zeros((num_examples, max_time_steps, num_feature))\n y=np.zeros((num_examples, max_time_steps, num_feature))\n for i in range(num_examples):\n m=1\n e, m = generate_data()\n e_v, m_v = vectorize_example(e,m)\n x[i]=e_v\n y[i]=m_v\n return x, y\nx,y= create_dataset()\nprint(x.shape,y.shape) ",
"(2000, 5, 11) (2000, 5, 11)\n"
],
[
"devectorize_example(x[0])",
"_____no_output_____"
],
[
"devectorize_example(y[0])",
"_____no_output_____"
]
],
[
[
"TASK6:TRAINING THE MODEL",
"_____no_output_____"
]
],
[
[
"\nm_cb = LambdaCallback(\n on_epoch_end=lambda\n e, m: print('{:.2f}'.format(m['val_accuracy']), end='-')\n)\nes_cb=EarlyStopping(monitor='val_loss',patience=10)\nmodel.fit(x, y, epochs=500, batch_size=256, validation_split=0.2,\n verbose=False, callbacks=[es_cb,m_cb])",
"0.55-0.60-0.62-0.61-0.62-0.63-0.63-0.63-0.64-0.63-0.64-0.65-0.66-0.65-0.65-0.66-0.66-0.67-0.67-0.68-0.69-0.70-0.70-0.70-0.71-0.72-0.72-0.72-0.71-0.72-0.74-0.74-0.75-0.74-0.75-0.75-0.74-0.75-0.77-0.76-0.77-0.76-0.77-0.77-0.78-0.78-0.79-0.80-0.80-0.80-0.80-0.81-0.82-0.82-0.82-0.83-0.83-0.84-0.84-0.85-0.85-0.86-0.87-0.86-0.87-0.88-0.87-0.88-0.88-0.87-0.88-0.89-0.89-0.89-0.90-0.90-0.90-0.90-0.91-0.90-0.91-0.91-0.91-0.91-0.92-0.92-0.92-0.92-0.93-0.92-0.92-0.93-0.92-0.92-0.93-0.93-0.93-0.93-0.93-0.93-0.94-0.93-0.93-0.94-0.94-0.93-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.94-0.95-0.94-0.94-0.94-0.94-0.95-0.94-0.95-0.94-0.95-0.94-0.94-0.95-0.95-0.95-0.95-0.94-0.95-0.95-0.95-"
],
[
"x_test, y_test= create_dataset(10)\npreds = model.predict(x_test)\n\nfor i,pred in enumerate(preds):\n y=devectorize_example(y_test[i])\n y_hat=devectorize_example(pred)\n col='green'\n if y != y_hat:\n col='red'\n out='Input:'+devectorize_example(x_test[i])+'out:'+y+'pred:'+y_hat \n print(colored(out,col))",
"\u001b[32mInput:04+26out:00030pred:00030\u001b[0m\n\u001b[32mInput:62+15out:00077pred:00077\u001b[0m\n\u001b[31mInput:10+95out:00105pred:00106\u001b[0m\n\u001b[32mInput:90+62out:00152pred:00152\u001b[0m\n\u001b[32mInput:49+69out:00118pred:00118\u001b[0m\n\u001b[32mInput:22+50out:00072pred:00072\u001b[0m\n\u001b[32mInput:54+61out:00115pred:00115\u001b[0m\n\u001b[32mInput:49+56out:00105pred:00105\u001b[0m\n\u001b[32mInput:47+33out:00080pred:00080\u001b[0m\n\u001b[31mInput:49+36out:00085pred:00075\u001b[0m\n"
],
[
"",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7b1e77f25f1d725637f55cd5e0beb90ef35765d | 196,608 | ipynb | Jupyter Notebook | ranking/PositionRankEval.ipynb | YinghanUVA/AutoPhrase | 7e2a6b794791bbf29993545ceec35a4c8fa118d4 | [
"Apache-2.0"
] | null | null | null | ranking/PositionRankEval.ipynb | YinghanUVA/AutoPhrase | 7e2a6b794791bbf29993545ceec35a4c8fa118d4 | [
"Apache-2.0"
] | null | null | null | ranking/PositionRankEval.ipynb | YinghanUVA/AutoPhrase | 7e2a6b794791bbf29993545ceec35a4c8fa118d4 | [
"Apache-2.0"
] | null | null | null | 77.131424 | 486 | 0.698166 | [
[
[
"empty"
]
]
] | [
"empty"
] | [
[
"empty"
]
] |
e7b201bdda72b1d37cbaf18905c48c5cdb7bc7b1 | 78,471 | ipynb | Jupyter Notebook | 5-sequence-models/week4/QA_dataset.ipynb | alekshiidenhovi/Deep-Learning-Specialization | a58e4c8dbd6a71f41363bfebe4f8fa10ee45e541 | [
"MIT"
] | null | null | null | 5-sequence-models/week4/QA_dataset.ipynb | alekshiidenhovi/Deep-Learning-Specialization | a58e4c8dbd6a71f41363bfebe4f8fa10ee45e541 | [
"MIT"
] | null | null | null | 5-sequence-models/week4/QA_dataset.ipynb | alekshiidenhovi/Deep-Learning-Specialization | a58e4c8dbd6a71f41363bfebe4f8fa10ee45e541 | [
"MIT"
] | null | null | null | 31.238455 | 713 | 0.593519 | [
[
[
"# Transformer Network Application: Question Answering\n\nWelcome to Week 4's third, and the last lab of the course! Congratulations on making it this far. In this notebook you'll explore another application of the transformer architecture that you built.\n\n**After this assignment you'll be able to**:\n\n* Perform extractive Question Answering \n* Fine-tune a pre-trained transformer model to a custom dataset\n* Implement a QA model in TensorFlow and PyTorch",
"_____no_output_____"
],
[
"## Table of Contents\n\n\n- [1 - Extractive Question Answering](#1)\n - [1.1 - Data Cleaning](#1-1)\n - [1.2 - Tokenize and Align Labels with 🤗 Library](#1-2)\n- [2 - Training](#2)\n - [2.1 TensorFlow implementation](#2-1)\n - [2.2 PyTorch implementation](#2-2)\n",
"_____no_output_____"
],
[
"<a name='1'></a>\n## 1 - Extractive Question Answering\n\nQuestion answering (QA) is a task of natural language processing that aims to automatically answer questions. The goal of *extractive* QA is to identify the portion of the text that contains the answer to a question. For example, when tasked with answering the question 'When will Jane go to Africa?' given the text data 'Jane visits Africa in September', the question answering model will highlight 'September'.\n\n* You will use a variation of the Transformer model you built in the last assignment to answer questions about stories.\n* You will implement extractive QA model in TensorFlow and in PyTorch.\n\n**Recommendation:**\n* If you are interested, check out the [Course 4: Natural Language Processing with Attention Models](https://www.coursera.org/learn/attention-models-in-nlp/home/welcome) of our [Natural Language Processing Specialization](https://www.coursera.org/specializations/natural-language-processing?=) where you can learn how to build Transformers and perform QA using the [Trax](https://trax.readthedocs.io/en/latest/) library. \n\n<a name='1-1'></a>\n### 1.1 - Data preprocessing\n\nRun the following cell to load the [QA bAbI dataset](https://research.fb.com/downloads/babi/), which is one of the bAbI datasets generated by Facebook AI Research to advance natural language processing.",
"_____no_output_____"
]
],
[
[
"from datasets import load_from_disk\n\n# Load a dataset and print the first example in the training set\nbabi_dataset = load_from_disk('data/')\nprint(babi_dataset['train'][0])",
"_____no_output_____"
]
],
[
[
"Take a look at the format of the data. For a given story, there are two sentences which serve as the context, and one question. Each of these phrases has an ID. There is also a supporting fact ID which refers to a sentence in the story that helps answer the question. For example, for the question 'What is east of the hallway?', the supporting fact 'The bedroom is east of the hallway' has the ID '2'. There is also the answer, 'bedroom' for the question.",
"_____no_output_____"
]
],
[
[
"babi_dataset['train'][102]",
"_____no_output_____"
]
],
[
[
"Check and see if the entire dataset of stories has this format.",
"_____no_output_____"
]
],
[
[
"type_set = set()\nfor story in babi_dataset['train']:\n if str(story['story']['type'] )not in type_set:\n type_set.add(str(story['story']['type'] ))",
"_____no_output_____"
],
[
"type_set",
"_____no_output_____"
]
],
[
[
"To make the data easier to work with, you will flatten the dataset to transform it from a dictionary structure to a table structure.",
"_____no_output_____"
]
],
[
[
"flattened_babi = babi_dataset.flatten()",
"_____no_output_____"
],
[
"flattened_babi",
"_____no_output_____"
],
[
"next(iter(flattened_babi['train']))",
"_____no_output_____"
]
],
[
[
"Now it is much easier to access the information you need! You can now easily extract the answer, question, and facts from the story, and also join the facts into a single entry under 'sentences'.",
"_____no_output_____"
]
],
[
[
"def get_question_and_facts(story):\n dic = {}\n dic['question'] = story['story.text'][2]\n dic['sentences'] = ' '.join([story['story.text'][0], story['story.text'][1]])\n dic['answer'] = story['story.answer'][2]\n return dic",
"_____no_output_____"
],
[
"processed = flattened_babi.map(get_question_and_facts)",
"_____no_output_____"
],
[
"processed['train'][2]",
"_____no_output_____"
],
[
"processed['test'][2]",
"_____no_output_____"
]
],
[
[
"The goal of extractive QA is to find the part of the text that contains the answer to the question. You will identify the position of the answer using the indexes of the string. For example, if the answer to some question was 'September', you would need to find the start and end string indices of the word 'September' in the context sentence 'Jane visits Africa in September.'\n\n\nUse this next function to get the start and end indices of the answer in each of the stories in your dataset.",
"_____no_output_____"
]
],
[
[
"def get_start_end_idx(story):\n str_idx = story['sentences'].find(story['answer'])\n end_idx = str_idx + len(story['answer'])\n return {'str_idx':str_idx,\n 'end_idx': end_idx}",
"_____no_output_____"
],
[
"processed = processed.map(get_start_end_idx)",
"_____no_output_____"
],
[
"num = 187\nprint(processed['test'][num])\nstart_idx = processed['test'][num]['str_idx']\nend_idx = processed['test'][num]['end_idx']\nprint('answer:', processed['test'][num]['sentences'][start_idx:end_idx])",
"_____no_output_____"
]
],
[
[
"<a name='1-2'></a>\n### 1.2 - Tokenize and Align with 🤗 Library\n\nNow you have all the data you need to train a Transformer model to perform Question Answering! You are ready for a task you may have already encountered in the Named-Entity Recognition lab - tokenizing and aligning your input. To feed text data to a Transformer model, you will need to tokenize your input using a [🤗 Transformer tokenizer](https://huggingface.co/transformers/main_classes/tokenizer.html). It is crucial that the tokenizer you use must match the Transformer model type you are using! In this exercise, you will use the 🤗 [DistilBERT fast tokenizer](https://huggingface.co/transformers/model_doc/distilbert.html), which standardizes the length of your sequence to 512 and pads with zeros. ",
"_____no_output_____"
],
[
"Transformer models are often trained by tokenizers that split words into subwords. For instance, the word 'Africa' might get split into multiple subtokens. This can create some misalignment between the list of tags for the dataset and the list of labels generated by the tokenizer, since the tokenizer can split one word into several, or add special tokens. Before processing, it is important that you align the start and end indices with the tokens associated with the target answer word with a `tokenize_and_align()` function. In this case, since you are interested in the start and end indices of the answer, you will want to align the index of the sentence to match the index of the token for a word. \n",
"_____no_output_____"
]
],
[
[
"from transformers import DistilBertTokenizerFast\ntokenizer = DistilBertTokenizerFast.from_pretrained('tokenizer/')",
"_____no_output_____"
],
[
"def tokenize_align(example):\n encoding = tokenizer(example['sentences'], example['question'], truncation=True, padding=True, max_length=tokenizer.model_max_length)\n start_positions = encoding.char_to_token(example['str_idx'])\n end_positions = encoding.char_to_token(example['end_idx']-1)\n if start_positions is None:\n start_positions = tokenizer.model_max_length\n if end_positions is None:\n end_positions = tokenizer.model_max_length\n return {'input_ids': encoding['input_ids'],\n 'attention_mask': encoding['attention_mask'],\n 'start_positions': start_positions,\n 'end_positions': end_positions}",
"_____no_output_____"
],
[
"qa_dataset = processed.map(tokenize_align)",
"_____no_output_____"
],
[
"qa_dataset = qa_dataset.remove_columns(['story.answer', 'story.id', 'story.supporting_ids', 'story.text', 'story.type'])",
"_____no_output_____"
],
[
"qa_dataset['train'][200]",
"_____no_output_____"
]
],
[
[
"<font color='blue'><b>What you should remember:</b>\n- The goal of *extractive* QA is to identify the portion of the text that contains the answer to a question.\n- Transformer models are often trained by tokenizers that split words into subwords.\n - Before processing, it is important that you align the start and end indices with the tokens associated with the target answer word.\n</font>",
"_____no_output_____"
],
[
"<a name='2'></a>\n# 2 - Training \n\nNow that you have finished tokenizing and aligning your data, you can feed it into a pre-trained 🤗 Transformer model! You will use a DistilBERT model, which matches the tokenizer you used to preprocess your data.",
"_____no_output_____"
]
],
[
[
"train_ds = qa_dataset['train']\ntest_ds = qa_dataset['test']",
"_____no_output_____"
],
[
"from transformers import TFDistilBertForQuestionAnswering\nmodel = TFDistilBertForQuestionAnswering.from_pretrained(\"model/tensorflow\", return_dict=False)",
"_____no_output_____"
]
],
[
[
"<a name='2-1'></a>\n### 2.1 - TensorFlow implementation\nFor this assignment you will execute two implemenations, one in TensorFlow and one in PyTorch.\n\n\n",
"_____no_output_____"
],
[
"\n#### Train and test datasets\n\n**Note:**\n* In the TensorFlow implementation, you will have to set the data format type to tensors, which may create ragged tensors (tensors of different lengths). \n* You will have to convert the ragged tensors to normal tensors using the `to_tensor()` method, which pads the tensors and sets the dimensions to `[None, tokenizer.model_max_length]` so you can feed different size tensors into your model based on the batch size. ",
"_____no_output_____"
]
],
[
[
"import tensorflow as tf\n\ncolumns_to_return = ['input_ids','attention_mask', 'start_positions', 'end_positions']\n\ntrain_ds.set_format(type='tf', columns=columns_to_return)\n\ntrain_features = {x: train_ds[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) for x in ['input_ids', 'attention_mask']}\ntrain_labels = {\"start_positions\": tf.reshape(train_ds['start_positions'], shape=[-1,1]),\n 'end_positions': tf.reshape(train_ds['end_positions'], shape=[-1,1])}\n\n\ntrain_tfdataset = tf.data.Dataset.from_tensor_slices((train_features, train_labels)).batch(8)",
"_____no_output_____"
]
],
[
[
"#### Training \n\nIt is finally time to start training your model! \n\n* Create a custom training function using [tf.GradientTape()](https://www.tensorflow.org/api_docs/python/tf/GradientTape)\n* Target two loss functions, one for the start index and one for the end index. \n* `tf.GradientTape()` records the operations performed during forward prop for automatic differentiation during backprop. \n",
"_____no_output_____"
]
],
[
[
"EPOCHS = 3\nloss_fn1 = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True)\nloss_fn2 = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True)\nopt = tf.keras.optimizers.Adam(learning_rate=3e-5)\n\nlosses = []\nfor epoch in range(EPOCHS):\n print(\"Starting epoch: %d\"% epoch )\n for step, (x_batch_train, y_batch_train) in enumerate(train_tfdataset):\n with tf.GradientTape() as tape:\n answer_start_scores, answer_end_scores = model(x_batch_train)\n loss_start = loss_fn1(y_batch_train['start_positions'], answer_start_scores)\n loss_end = loss_fn2(y_batch_train['end_positions'], answer_end_scores)\n loss = 0.5 * (loss_start + loss_end)\n losses.append(loss)\n grads = tape.gradient(loss, model.trainable_weights)\n opt.apply_gradients(zip(grads, model.trainable_weights))\n\n if step % 20 == 0:\n print(\"Training loss (for one batch) at step %d: %.4f\"% (step, \n float(loss_start)))\n",
"_____no_output_____"
]
],
[
[
"Take a look at your losses and try playing around with some of the hyperparameters for better results!",
"_____no_output_____"
]
],
[
[
"from matplotlib.pyplot import plot\n\nplot(losses)",
"_____no_output_____"
]
],
[
[
"You have successfully trained your model to help automatically answer questions! Try asking it a question about a story.",
"_____no_output_____"
]
],
[
[
"question, text = 'What is south of the bedroom?','The hallway is south of the garden. The garden is south of the bedroom.'\ninput_dict = tokenizer(text, question, return_tensors='tf')\noutputs = model(input_dict)\nstart_logits = outputs[0]\nend_logits = outputs[1]\n\nall_tokens = tokenizer.convert_ids_to_tokens(input_dict[\"input_ids\"].numpy()[0])\nanswer = ' '.join(all_tokens[tf.math.argmax(start_logits, 1)[0] : tf.math.argmax(end_logits, 1)[0]+1])\nprint(question, answer.capitalize())",
"_____no_output_____"
]
],
[
[
"Congratulations! You just implemented your first QA model in TensorFlow. ",
"_____no_output_____"
],
[
"<a name='2-1'></a>\n## 2.2 PyTorch implementation\n\n[PyTorch](https://pytorch.org/) is an open source machine learning framework developed by Facebook's AI Research lab that can be used for computer vision and natural language processing. As you can imagine, it is quite compatible with the bAbI dataset.",
"_____no_output_____"
],
[
"#### Train and test dataset\n\nGo ahead and try creating a train and test dataset by importing PyTorch.",
"_____no_output_____"
]
],
[
[
"from torch.utils.data import DataLoader\n\ncolumns_to_return = ['input_ids','attention_mask', 'start_positions', 'end_positions']\ntrain_ds.set_format(type='pt', columns=columns_to_return)\ntest_ds.set_format(type='pt', columns=columns_to_return)",
"_____no_output_____"
]
],
[
[
"For the accuracy metrics for the PyTorch implementation, you will change things up a bit and use the [F1 score](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html) for start and end indicies over the entire test dataset as the loss functions. ",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import f1_score\n\ndef compute_metrics(pred):\n start_labels = pred.label_ids[0]\n start_preds = pred.predictions[0].argmax(-1)\n end_labels = pred.label_ids[1]\n end_preds = pred.predictions[1].argmax(-1)\n \n f1_start = f1_score(start_labels, start_preds, average='macro')\n f1_end = f1_score(end_labels, end_preds, average='macro')\n \n return {\n 'f1_start': f1_start,\n 'f1_end': f1_end,\n }",
"_____no_output_____"
]
],
[
[
"#### Training\n\nNow it is time to load a pre-trained model. \n\n**Note:** You will be using the DistilBERT instead of TFDistilBERT for a PyTorch implementation.",
"_____no_output_____"
]
],
[
[
"del model # We delete the tensorflow model to avoid memory issues",
"_____no_output_____"
],
[
"from transformers import DistilBertForQuestionAnswering\n\npytorch_model = DistilBertForQuestionAnswering.from_pretrained(\"model/pytorch\")",
"_____no_output_____"
]
],
[
[
"Instead of a custom training loop, you will use the [🤗 Trainer](https://huggingface.co/transformers/main_classes/trainer.html), which contains a basic training loop and is fairly easy to implement in PyTorch.",
"_____no_output_____"
]
],
[
[
"from transformers import Trainer, TrainingArguments\n\ntraining_args = TrainingArguments(\n output_dir='results', # output directory\n overwrite_output_dir=True,\n num_train_epochs=3, # total number of training epochs\n per_device_train_batch_size=8, # batch size per device during training\n per_device_eval_batch_size=8, # batch size for evaluation\n warmup_steps=20, # number of warmup steps for learning rate scheduler\n weight_decay=0.01, # strength of weight decay\n logging_dir=None, # directory for storing logs\n logging_steps=50\n)\n\ntrainer = Trainer(\n model=pytorch_model, # the instantiated 🤗 Transformers model to be trained\n args=training_args, # training arguments, defined above\n train_dataset=train_ds, # training dataset\n eval_dataset=test_ds,\n compute_metrics=compute_metrics # evaluation dataset\n)\n\ntrainer.train()",
"_____no_output_____"
],
[
"trainer.evaluate(test_ds)",
"_____no_output_____"
]
],
[
[
"Now it is time to ask your PyTorch model a question! \n* Before testing your model with a question, you can tell PyTorch to send your model and inputs to the GPU if your machine has one, or the CPU if it does not. \n* You can then proceed to tokenize your input and create PyTorch tensors and send them to your device. \n* The rest of the pipeline is relatively similar to the one you implemented for TensorFlow. \n",
"_____no_output_____"
]
],
[
[
"import torch\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\npytorch_model.to(device)\n\nquestion, text = 'What is east of the hallway?','The kitchen is east of the hallway. The garden is south of the bedroom.'\n\ninput_dict = tokenizer(text, question, return_tensors='pt')\n\ninput_ids = input_dict['input_ids'].to(device)\nattention_mask = input_dict['attention_mask'].to(device)\n\noutputs = pytorch_model(input_ids, attention_mask=attention_mask)\n\nstart_logits = outputs[0]\nend_logits = outputs[1]\n\nall_tokens = tokenizer.convert_ids_to_tokens(input_dict[\"input_ids\"].numpy()[0])\nanswer = ' '.join(all_tokens[torch.argmax(start_logits, 1)[0] : torch.argmax(end_logits, 1)[0]+1])\n\nprint(question, answer.capitalize())",
"_____no_output_____"
]
],
[
[
"### Congratulations!\n \nYou've completed this notebook, and can now implement Transformer models for QA tasks!\n\nYou are now able to:\n* Perform extractive Question Answering \n* Fine-tune a pre-trained transformer model to a custom dataset\n* Implement a QA model in TensorFlow and PyTorch",
"_____no_output_____"
],
[
"<font color='blue'><b>What you should remember</b>:\n- Transformer models are often trained by tokenizers that split words into subwords.\n - Before processing, it is important that you align the start and end indices with the tokens associated with the target answer word.\n- PyTorch is a relatively light and easy to implement framework that can make rapid prototyping easier, while TensorFlow has advantages in scaling and is more widely used in production\n - `tf.GradientTape` allows you to build custom training loops in TensorFlow\n - The `Trainer` API in PyTorch gives you a basic training loop that is compatible with 🤗 models and datasets",
"_____no_output_____"
]
],
[
[
"%%javascript\nlet element = document.getElementById('submit-notebook-button-group');\nif (!element) {\n window._save_and_close = function(){\n IPython.notebook.save_checkpoint();\n IPython.notebook.session.delete();\n window.onbeforeunload = null\n setTimeout(function() {window.close();}, 1000)\n }\n let header = document.getElementById('maintoolbar-container');\n element = document.createElement(\"div\");\n element.setAttribute(\"class\", \"btn-group\");\n element.setAttribute(\"id\", \"submit-notebook-button-group\");\n element.setAttribute(\"align\", \"right\");\n element.setAttribute(\"style\", \"float:right\")\n element.innerHTML = '<button class=\"btn btn-default\" title=\"Save and close this notebook.\" style=\"background-color:rgb(42, 115, 204); color:white; padding:4px 8px\" onclick=window._save_and_close()>Save and close</button>'\n header.appendChild(element); \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",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
e7b2038a4fa099307413ad5736ebbecaf9073c25 | 9,910 | ipynb | Jupyter Notebook | module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb | extrajp2014/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments | 4da94de894cf729f0e91ea8fbf95c26ee80e44cf | [
"MIT"
] | null | null | null | module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb | extrajp2014/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments | 4da94de894cf729f0e91ea8fbf95c26ee80e44cf | [
"MIT"
] | null | null | null | module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb | extrajp2014/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments | 4da94de894cf729f0e91ea8fbf95c26ee80e44cf | [
"MIT"
] | null | null | null | 40.950413 | 408 | 0.571746 | [
[
[
"# Lambda School Data Science Module 142\n## Sampling, Confidence Intervals, and Hypothesis Testing",
"_____no_output_____"
],
[
"## Prepare - examine other available hypothesis tests\n\nIf you had to pick a single hypothesis test in your toolbox, t-test would probably be the best choice - but the good news is you don't have to pick just one! Here's some of the others to be aware of:",
"_____no_output_____"
]
],
[
[
"import numpy as np\nfrom scipy.stats import chisquare # One-way chi square test\n\n# Chi square can take any crosstab/table and test the independence of rows/cols\n# The null hypothesis is that the rows/cols are independent -> low chi square\n# The alternative is that there is a dependence -> high chi square\n# Be aware! Chi square does *not* tell you direction/causation\n\nind_obs = np.array([[1, 1], [2, 2]]).T\nprint(ind_obs)\nprint(chisquare(ind_obs, axis=None))\n\ndep_obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T\nprint(dep_obs)\nprint(chisquare(dep_obs, axis=None))",
"[[1 2]\n [1 2]]\nPower_divergenceResult(statistic=0.6666666666666666, pvalue=0.8810148425137847)\n[[16 32]\n [18 24]\n [16 16]\n [14 28]\n [12 20]\n [12 24]]\nPower_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565)\n"
],
[
"# Distribution tests:\n# We often assume that something is normal, but it can be important to *check*\n\n# For example, later on with predictive modeling, a typical assumption is that\n# residuals (prediction errors) are normal - checking is a good diagnostic\n\nfrom scipy.stats import normaltest\n# Poisson models arrival times and is related to the binomial (coinflip)\nsample = np.random.poisson(5, 1000)\nprint(normaltest(sample)) # Pretty clearly not normal",
"NormaltestResult(statistic=38.69323106073592, pvalue=3.961609200867749e-09)\n"
],
[
"# Kruskal-Wallis H-test - compare the median rank between 2+ groups\n# Can be applied to ranking decisions/outcomes/recommendations\n# The underlying math comes from chi-square distribution, and is best for n>5\nfrom scipy.stats import kruskal\n\nx1 = [1, 3, 5, 7, 9]\ny1 = [2, 4, 6, 8, 10]\nprint(kruskal(x1, y1)) # x1 is a little better, but not \"significantly\" so\n\nx2 = [1, 1, 1]\ny2 = [2, 2, 2]\nz = [2, 2] # Hey, a third group, and of different size!\nprint(kruskal(x2, y2, z)) # x clearly dominates",
"KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)\nKruskalResult(statistic=7.0, pvalue=0.0301973834223185)\n"
]
],
[
[
"And there's many more! `scipy.stats` is fairly comprehensive, though there are even more available if you delve into the extended world of statistics packages. As tests get increasingly obscure and specialized, the importance of knowing them by heart becomes small - but being able to look them up and figure them out when they *are* relevant is still important.",
"_____no_output_____"
],
[
"## Live Lecture - let's explore some more of scipy.stats",
"_____no_output_____"
]
],
[
[
"# Taking requests! Come to lecture with a topic or problem and we'll try it.",
"_____no_output_____"
]
],
[
[
"## Assignment - Build a confidence interval\n\nA confidence interval refers to a neighborhood around some point estimate, the size of which is determined by the desired p-value. For instance, we might say that 52% of Americans prefer tacos to burritos, with a 95% confidence interval of +/- 5%.\n\n52% (0.52) is the point estimate, and +/- 5% (the interval $[0.47, 0.57]$) is the confidence interval. \"95% confidence\" means a p-value $\\leq 1 - 0.95 = 0.05$.\n\nIn this case, the confidence interval includes $0.5$ - which is the natural null hypothesis (that half of Americans prefer tacos and half burritos, thus there is no clear favorite). So in this case, we could use the confidence interval to report that we've failed to reject the null hypothesis.\n\nBut providing the full analysis with a confidence interval, including a graphical representation of it, can be a helpful and powerful way to tell your story. Done well, it is also more intuitive to a layperson than simply saying \"fail to reject the null hypothesis\" - it shows that in fact the data does *not* give a single clear result (the point estimate) but a whole range of possibilities.\n\nHow is a confidence interval built, and how should it be interpreted? It does *not* mean that 95% of the data lies in that interval - instead, the frequentist interpretation is \"if we were to repeat this experiment 100 times, we would expect the average result to lie in this interval ~95 times.\"\n\nFor a 95% confidence interval and a normal(-ish) distribution, you can simply remember that +/-2 standard deviations contains 95% of the probability mass, and so the 95% confidence interval based on a given sample is centered at the mean (point estimate) and has a range of +/- 2 (or technically 1.96) standard deviations.\n\nDifferent distributions/assumptions (90% confidence, 99% confidence) will require different math, but the overall process and interpretation (with a frequentist approach) will be the same.\n\nYour assignment - using the data from the prior module ([congressional voting records](https://archive.ics.uci.edu/ml/datasets/Congressional+Voting+Records)):\n\n1. Generate and numerically represent a confidence interval\n2. Graphically (with a plot) represent the confidence interval\n3. Interpret the confidence interval - what does it tell you about the data and its distribution?\n\nStretch goals:\n\n1. Write a summary of your findings, mixing prose and math/code/results. *Note* - yes, this is by definition a political topic. It is challenging but important to keep your writing voice *neutral* and stick to the facts of the data. Data science often involves considering controversial issues, so it's important to be sensitive about them (especially if you want to publish).\n2. Apply the techniques you learned today to your project data or other data of your choice, and write/discuss your findings here.",
"_____no_output_____"
]
],
[
[
"# TODO - your code!",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b204d972aec1d5de0b4c0379ec10c9c946bf81 | 79,666 | ipynb | Jupyter Notebook | feature extraction vgg19.ipynb | Navinsrirangan/Visualizing_features | 998494a4184651fb937f7b523cd2fda3d72f332f | [
"MIT"
] | null | null | null | feature extraction vgg19.ipynb | Navinsrirangan/Visualizing_features | 998494a4184651fb937f7b523cd2fda3d72f332f | [
"MIT"
] | null | null | null | feature extraction vgg19.ipynb | Navinsrirangan/Visualizing_features | 998494a4184651fb937f7b523cd2fda3d72f332f | [
"MIT"
] | null | null | null | 308.782946 | 70,256 | 0.923393 | [
[
[
"# load vgg model\nfrom tensorflow.keras.applications.vgg19 import VGG19\n",
"_____no_output_____"
],
[
"from tensorflow.keras.applications.vgg19 import preprocess_input\nfrom tensorflow.keras.preprocessing import image\nfrom keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import Model\nfrom matplotlib import pyplot\nfrom numpy import expand_dims",
"_____no_output_____"
],
[
"model = VGG19(weights = 'imagenet', include_top = False)",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"vgg19\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_24 (InputLayer) [(None, None, None, 3)] 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, None, None, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, None, None, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, None, None, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, None, None, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, None, None, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, None, None, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, None, None, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, None, None, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, None, None, 256) 590080 \n_________________________________________________________________\nblock3_conv4 (Conv2D) (None, None, None, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, None, None, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, None, None, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, None, None, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, None, None, 512) 2359808 \n_________________________________________________________________\nblock4_conv4 (Conv2D) (None, None, None, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, None, None, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, None, None, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, None, None, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, None, None, 512) 2359808 \n_________________________________________________________________\nblock5_conv4 (Conv2D) (None, None, None, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, None, None, 512) 0 \n=================================================================\nTotal params: 20,024,384\nTrainable params: 20,024,384\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"ixs = [1, 2, 5]\noutputs = [model.layers[i].output for i in ixs]\nmodel = Model(inputs = model.inputs, outputs=outputs)\nmodel.summary()",
"Model: \"model_38\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_28 (InputLayer) [(None, None, None, 3)] 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, None, None, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, None, None, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, None, None, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, None, None, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, None, None, 128) 147584 \n=================================================================\nTotal params: 260,160\nTrainable params: 260,160\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"img_path = 'C:/Users/navee/OneDrive/Desktop/papaya augmented dataset/anthracnose/a3.jpg'\nimg = image.load_img(img_path, target_size=(224, 224))\nimg = image.img_to_array(img)\nimg = expand_dims(img, axis=0)\nimg = preprocess_input(img)\nfeature_maps = model.predict(img)",
"_____no_output_____"
],
[
"square = 8\nfor fmap in feature_maps:\n ix = 1\n for _ in range(square):\n for _ in range(square):\n ax = pyplot.subplot(square, square, ix)\n ax.set_xticks([])\n ax.set_yticks([])\n pyplot.imshow(fmap[0, :, :, ix - 1], cmap='gray')\n ix += 1\n\n# pyplot.show()\npyplot.savefig('block2conv2.jpg')",
"C:\\Users\\navee\\.conda\\envs\\test\\lib\\site-packages\\ipykernel_launcher.py:6: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.\n \n"
],
[
"import matplotlib.pyplot as plt\nplt.savefig('feature_map_2.jpg')",
"_____no_output_____"
],
[
"\n",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b208cfee0a1d3dfc18be3cf5104946e23e6562 | 58,091 | ipynb | Jupyter Notebook | Instructions/.ipynb_checkpoints/Mission_to_Mars-Starter-checkpoint.ipynb | jcus/web-scraping-challenge | 3ae46ddb96df10731942de23bcdc0e91790f7fc1 | [
"ADSL"
] | null | null | null | Instructions/.ipynb_checkpoints/Mission_to_Mars-Starter-checkpoint.ipynb | jcus/web-scraping-challenge | 3ae46ddb96df10731942de23bcdc0e91790f7fc1 | [
"ADSL"
] | null | null | null | Instructions/.ipynb_checkpoints/Mission_to_Mars-Starter-checkpoint.ipynb | jcus/web-scraping-challenge | 3ae46ddb96df10731942de23bcdc0e91790f7fc1 | [
"ADSL"
] | null | null | null | 43.710309 | 8,634 | 0.4882 | [
[
[
"# Import Splinter, BeautifulSoup, and Pandas\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as soup\nimport pandas as pd\nfrom webdriver_manager.chrome import ChromeDriverManager",
"_____no_output_____"
],
[
"# Set up Splinter\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)",
"\n\n====== WebDriver manager ======\nCurrent google-chrome version is 98.0.4758\nGet LATEST chromedriver version for 98.0.4758 google-chrome\nDriver [C:\\Users\\juch0\\.wdm\\drivers\\chromedriver\\win32\\98.0.4758.80\\chromedriver.exe] found in cache\n"
]
],
[
[
"## Visit the NASA mars news site",
"_____no_output_____"
]
],
[
[
"# Visit the Mars news site\nurl = 'https://redplanetscience.com/'\nbrowser.visit(url)\n\n# Optional delay for loading the page--wait_time\nbrowser.is_element_present_by_css('div.list_text', wait_time=1)",
"_____no_output_____"
],
[
"# Convert the browser html to a soup object\nhtml = browser.html\nnews_soup = soup(html, 'html.parser')",
"_____no_output_____"
],
[
"# display the current title content\nslide_elem = news_soup.select_one('div.list_text')\nslide_elem",
"_____no_output_____"
],
[
"# Use the parent element to find the first a tag and save it as `news_title`\nnews_title = news_soup.find('div', class_='content_title').text\nprint(news_title)",
"NASA Wins Two Emmy Awards for Interactive Mission Coverage\n"
],
[
"# Use the parent element to find the paragraph text\nnews_parent = news_soup.find('div', class_='article_teaser_body').text\nprint(news_parent)",
"NASA-JPL's coverage of the Mars InSight landing earns one of the two wins, making this the NASA center's second Emmy.\n"
]
],
[
[
"## JPL Space Images Featured Image",
"_____no_output_____"
]
],
[
[
"# Visit URL\nurl = 'https://spaceimages-mars.com'\nbrowser.visit(url)",
"_____no_output_____"
],
[
"# Find and click the full image button\nimage_url = browser.find_by_tag('button')[1]\nimage_url.click()",
"_____no_output_____"
],
[
"# Parse the resulting html with soup\n# get HTML object\nhtml = browser.html\n# use beautiful soup parser on HTML\nimage_soup = soup(html, 'html.parser')\nimage_soup",
"_____no_output_____"
],
[
"print(image_soup.prettify())",
"<html class=\"fancybox-margin fancybox-lock\">\n <head>\n <meta charset=\"utf-8\"/>\n <meta content=\"width=device-width, initial-scale=1\" name=\"viewport\"/>\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n <!-- <link rel=\"stylesheet\" type=\"text/css\" href=\"css/font.css\"> -->\n <link href=\"css/app.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>\n Space Image\n </title>\n <style type=\"text/css\">\n .fancybox-margin{margin-right:17px;}\n </style>\n </head>\n <body>\n <div class=\"header\">\n <nav class=\"navbar navbar-expand-lg\">\n <a class=\"navbar-brand\" href=\"#\">\n <img id=\"logo\" src=\"image/nasa.png\"/>\n <span class=\"logo\">\n Jet Propulsion Laboratory\n </span>\n <span class=\"logo1\">\n California Institute of Technology\n </span>\n </a>\n <button aria-controls=\"navbarNav\" aria-expanded=\"false\" aria-label=\"Toggle navigation\" class=\"navbar-toggler\" data-target=\"#navbarNav\" data-toggle=\"collapse\" type=\"button\">\n <span class=\"navbar-toggler-icon\">\n </span>\n </button>\n <div class=\"collapse navbar-collapse justify-content-end\" id=\"navbarNav\">\n <ul class=\"navbar-nav\">\n <li class=\"nav-item active\">\n <a class=\"nav-link\" href=\"#\">\n <i aria-hidden=\"true\" class=\"fa fa-bars\">\n </i>\n MENU\n <i aria-hidden=\"true\" class=\"fa fa-search\">\n </i>\n </a>\n </li>\n </ul>\n </div>\n </nav>\n <div class=\"floating_text_area\">\n <h2 class=\"brand_title\">\n FEATURED IMAGE\n </h2>\n <h1 class=\"media_feature_title\">\n Dusty Space Cloud\n </h1>\n <br/>\n <a class=\"showimg fancybox-thumbs\" href=\"image/featured/mars1.jpg\" target=\"_blank\">\n <button class=\"btn btn-outline-light\">\n FULL IMAGE\n </button>\n </a>\n </div>\n <img class=\"headerimage fade-in\" src=\"image/featured/mars1.jpg\"/>\n </div>\n <div class=\"search sticky\">\n <div class=\"col-md-12\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <input name=\"Search\" placeholder=\"Search\" type=\"text\"/>\n </div>\n <div class=\"col-md-6\">\n <select aria-label=\"Default select example\" class=\"form-select\" id=\"options\">\n <option onchange=\"0\" selected=\"\">\n Mars\n </option>\n <!-- <option data-filter=\"sun\" class=\"button\">Mars</option> -->\n <option class=\"button\" data-filter=\"Sun\">\n Sun\n </option>\n <option class=\"button\" data-filter=\"earth\">\n Earth\n </option>\n <option class=\"button\" data-filter=\"ida\">\n Ida\n </option>\n <option class=\"button\" data-filter=\"jupiter\">\n Jupiter\n </option>\n <option class=\"button\" data-filter=\"venus\">\n Venus\n </option>\n </select>\n </div>\n </div>\n </div>\n </div>\n <div class=\"container mt-5\">\n <div class=\"col-md-12\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <h1>\n Images\n </h1>\n </div>\n <div class=\"col-md-6\" id=\"icon\">\n <div class=\"icon2\">\n </div>\n <div class=\"icon1\">\n </div>\n </div>\n </div>\n </div>\n <!-- first div -->\n <div class=\"div1\" id=\"filter\">\n <div class=\"thmbgroup\">\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Icaria Fossae7.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Icaria Fossae7.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Icaria Fossae7\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Proctor Crater Dunes 7.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Proctor Crater Dunes 7.jpg\"/>\n <p class=\"thumbcontent\">\n December 31, 2020\n <br/>\n Proctor Crater Dunes\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Icaria Fossae7.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Icaria Fossae7.jpg\"/>\n <p class=\"thumbcontent\">\n December 31, 2020\n <br/>\n Icaria Fossae\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Proctor Crater Dunes 7.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Proctor Crater Dunes 7.jpg\"/>\n <p class=\"thumbcontent\">\n December 29, 2020\n <br/>\n Proctor Crater Dunes\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Proctor Crater Dunes 7.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Proctor Crater Dunes 7.jpg\"/>\n <p class=\"thumbcontent\">\n December 28, 2020\n <br/>\n roctor Crater Dunes\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Icaria Fossae7.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Icaria Fossae7.jpg\"/>\n <p class=\"thumbcontent\">\n December 22, 2020\n <br/>\n Icaria Fossae\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Icaria Fossae.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Icaria Fossae.jpg\"/>\n <p class=\"thumbcontent\">\n December 21, 2020\n <br/>\n Icaria Fossae\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Ariadnes Colles4.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Ariadnes Colles4.jpg\"/>\n <p class=\"thumbcontent\">\n December 18, 2020\n <br/>\n Ariadnes Colles\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Niger Vallis.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Niger Vallis.jpg\"/>\n <p class=\"thumbcontent\">\n December 17, 2020\n <br/>\n Niger Vallis\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Proctor Crater Dunes.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Proctor Crater Dunes.jpg\"/>\n <p class=\"thumbcontent\">\n December 16, 2020\n <br/>\n Proctor Crater Dunes\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Niger Vallis.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Niger Vallis.jpg\"/>\n <p class=\"thumbcontent\">\n December 15, 2020\n <br/>\n Niger Vallis\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Daedalia Planum.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Daedalia Planum.jpg\"/>\n <p class=\"thumbcontent\">\n December 11, 2020\n <br/>\n Daedalia Planum\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Sirenum Fossae.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Sirenum Fossae.jpg\"/>\n <p class=\"thumbcontent\">\n November,11, 2020\n <br/>\n Sirenum Fossae\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Ariadnes Colles4.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Ariadnes Colles4.jpg\"/>\n <p class=\"thumbcontent\">\n November,13, 2020\n <br/>\n Ariadnes Colles\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/South Polar Cap.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/South Polar Cap.jpg\"/>\n <p class=\"thumbcontent\">\n November,14, 2020\n <br/>\n South Polar Cap\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Daedalia Planum.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Daedalia Planum.jpg\"/>\n <p class=\"thumbcontent\">\n November,17, 2020\n <br/>\n Daedalia Planum\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Ariadnes Colles3.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Ariadnes Colles3.jpg\"/>\n <p class=\"thumbcontent\">\n November,11, 2020\n <br/>\n Ariadnes Colles\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Atlantis Chaos.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Atlantis Chaos.jpg\"/>\n <p class=\"thumbcontent\">\n November,09, 2020\n <br/>\n Atlantis Chaos\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Daedalia Planum.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Daedalia Planum.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Daedalia Planum\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Icaria Fossae.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Icaria Fossae.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Icaria Fossae\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Niger Vallis.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Niger Vallis.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Niger Vallis\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Proctor Crater Dunes.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Proctor Crater Dunes.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Proctor Crater Dunes\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Reull Vallis.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Reull Vallis.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Reull Vallis\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Ariadnes Colles3.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Ariadnes Colles3.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Ariadnes Colles\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Sirenum Fossae.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Sirenum Fossae.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Sirenum Fossae\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/South Polar Cap.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/South Polar Cap.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n South Polar Cap\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Niger Vallis.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Niger Vallis.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Niger Vallis\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Daedalia Planum.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Daedalia Planum.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Daedalia Planum\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Icaria Fossae.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Icaria Fossae.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Icaria Fossae\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Ariadnes Colles4.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Ariadnes Colles4.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Ariadnes Colles\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/South Polar Cap.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/South Polar Cap.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n South Polar Cap\n </p>\n </div>\n </a>\n <a class=\"fancybox-thumbs\" data-fancybox-group=\"thumb\" href=\"image/mars/Daedalia Planum.jpg\">\n <div class=\"thmb\">\n <img alt=\"\" class=\"thumbimg\" src=\"image/mars/Daedalia Planum.jpg\"/>\n <p class=\"thumbcontent\">\n January 1, 2020\n <br/>\n Daedalia Planum\n </p>\n </div>\n </a>\n </div>\n </div>\n <!-- first div ends -->\n <!-- second div starts -->\n <div class=\"col-md-12 grid-margin\" id=\"column\">\n <ul class=\"post-list\">\n <li class=\"post-heading\">\n </li>\n </ul>\n </div>\n <!-- second div starts -->\n </div>\n <div class=\"first imgcontainer mt-3\">\n <div class=\"col-md-12\">\n <div class=\"row\">\n <div class=\"col-md-3\">\n <img id=\"pic\" src=\"\"/>\n </div>\n </div>\n </div>\n </div>\n <!-- end -->\n <div class=\"module_gallery container\">\n <div class=\"col-md-12\">\n <div class=\"row\">\n <div class=\"col-md-6\">\n <div class=\"card\">\n <img alt=\"Card image cap\" class=\"card-img-top\" src=\"https://www.jpl.nasa.gov/assets/images/content/tmp/images/jpl_photojournal(3x1).jpg\"/>\n <div class=\"card-body\">\n <h5 class=\"card-title\">\n JPL Photojournal\n </h5>\n <p class=\"card-text\">\n Access to the full library of publicly released images from various Solar System exploration programs\n </p>\n </div>\n </div>\n </div>\n <div class=\"col-md-6\">\n <div class=\"card\">\n <img alt=\"Card image cap\" class=\"card-img-top\" src=\"https://www.jpl.nasa.gov/assets/images/content/tmp/images/nasa_images(3x1).jpg\"/>\n <div class=\"card-body\">\n <h5 class=\"card-title\">\n Great images in NASA\n </h5>\n <p class=\"card-text\">\n A selection of the best-known images from a half-century of exploration and discovery\n </p>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class=\"multi_teaser\">\n <div class=\"container\">\n <h1>\n You Might Also Like\n </h1>\n <div class=\"col-md-12 mt-5\">\n <div class=\"row\">\n <div class=\"col-md-4\">\n <div class=\"card\">\n <img alt=\"Card image cap\" class=\"card-img-top\" src=\"https://imagecache.jpl.nasa.gov/images/640x350/C1-PIA24304---CatScanMars-16-640x350.gif\"/>\n <div class=\"card-body\">\n <p class=\"card-text\">\n Access to the full library of publicly released images from various Solar System exploration programs\n </p>\n </div>\n </div>\n </div>\n <div class=\"col-md-4\">\n <div class=\"card\">\n <img alt=\"Card image cap\" class=\"card-img-top\" src=\"https://imagecache.jpl.nasa.gov/images/640x350/PIA23491-16-640x350.jpg\"/>\n <div class=\"card-body\">\n <p class=\"card-text\">\n Access to the full library of publicly released images from various Solar System exploration programs\n </p>\n </div>\n </div>\n </div>\n <div class=\"col-md-4\">\n <div class=\"card\">\n <img alt=\"Card image cap\" class=\"card-img-top\" src=\"https://imagecache.jpl.nasa.gov/images/640x350/C1-PIA23180-16-640x350.gif\"/>\n <div class=\"card-body\">\n <p class=\"card-text\">\n Access to the full library of publicly released images from various Solar System exploration programs\n </p>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n <div class=\"footer\">\n <div class=\"container\">\n <div class=\"col-md-12\">\n <div class=\"row\">\n <div class=\"col-md-3\">\n <h4>\n About JPL\n </h4>\n <ul>\n <li>\n About JPL\n </li>\n <li>\n JPL Vision\n </li>\n <li>\n Executive Council\n </li>\n <li>\n History\n </li>\n </ul>\n </div>\n <div class=\"col-md-3\">\n <h4>\n Education\n </h4>\n <ul>\n <li>\n Intern\n </li>\n <li>\n Learn\n </li>\n <li>\n Teach\n </li>\n <li>\n News\n </li>\n </ul>\n </div>\n <div class=\"col-md-3\">\n <h4>\n Our Sites\n </h4>\n <ul>\n <li>\n Asteroid Watch\n </li>\n <li>\n Basics of Spaceflight\n </li>\n <li>\n Cassini - Mission to Saturn\n </li>\n <li>\n Climate Kids\n </li>\n </ul>\n </div>\n <div class=\"col-md-3\">\n <h4>\n Galleries\n </h4>\n <ul>\n <li>\n JPL Space Images\n </li>\n <li>\n Videos\n </li>\n <li>\n Infographics\n </li>\n <li>\n Photojournal\n </li>\n </ul>\n </div>\n </div>\n </div>\n </div>\n </div>\n <!--<div class=\"showFullimage\">\n\t<button class=\"btn btn-outline-light hideimage\" onclick=hideimage()> Close</button>\n\t<img class=\"fullimage fade-in\" src=\"\">\n</div>-->\n <!-- <script src=\"js/jquery.easeScroll.js\"></script> -->\n <script src=\"js/jquery-3.5.1.min.js\">\n </script>\n <!-- <script src=\"js/jquery-3.2.1.slim.min.js\"></script> -->\n <script src=\"js/demo.js\">\n </script>\n <!-- <script src=\"js/app.js\"></script> -->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\">\n </script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\">\n </script>\n <script src=\"js/fancyBox/jquery.fancybox.pack.js?v=2.1.5\" type=\"text/javascript\">\n </script>\n <link href=\"js/fancyBox/jquery.fancybox.css?v=2.1.5\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"js/fancyBox/helpers/jquery.fancybox-thumbs.css?v=1.0.7\" rel=\"stylesheet\" type=\"text/css\"/>\n <script src=\"js/fancyBox/helpers/jquery.fancybox-thumbs.js?v=1.0.7\" type=\"text/javascript\">\n </script>\n <div class=\"fancybox-overlay fancybox-overlay-fixed\" style=\"width: auto; height: auto; display: block;\">\n <div class=\"fancybox-wrap fancybox-desktop fancybox-type-image fancybox-opened\" style=\"width: 670px; height: auto; position: absolute; top: 117px; left: 176px; opacity: 1; overflow: visible;\" tabindex=\"-1\">\n <div class=\"fancybox-skin\" style=\"padding: 15px; width: auto; height: auto;\">\n <div class=\"fancybox-outer\">\n <div class=\"fancybox-inner\" style=\"overflow: visible; width: 640px; height: 350px;\">\n <img alt=\"\" class=\"fancybox-image\" src=\"image/featured/mars1.jpg\"/>\n </div>\n </div>\n <a class=\"fancybox-item fancybox-close\" href=\"javascript:;\" title=\"Close\">\n </a>\n </div>\n </div>\n </div>\n </body>\n</html>\n"
],
[
"# find the relative image url\n##thumbimg\nimg_url_rel = image_soup.find('img', class_='fancybox-image').get('src')\nimg_url_rel",
"_____no_output_____"
],
[
"# Use the base url to create an absolute url\nimg_url = f'https://spaceimages-mars.com/{img_url_rel}'\nimg_url",
"_____no_output_____"
]
],
[
[
"## Mars Facts",
"_____no_output_____"
]
],
[
[
"# Use `pd.read_html` to pull the data from the Mars-Earth Comparison section\n# hint use index 0 to find the table\ndf = pd.read_html('https://galaxyfacts-mars.com/')[0]\ndf.head()",
"_____no_output_____"
],
[
"df.to_html()\ndf",
"_____no_output_____"
],
[
"df.to_html()",
"_____no_output_____"
]
],
[
[
"## Hemispheres",
"_____no_output_____"
]
],
[
[
"url = 'https://marshemispheres.com/'\n\nbrowser.visit(url)",
"_____no_output_____"
],
[
"# Create a list to hold the images and titles.\nhemisphere_image_urls = []\n\n# Get a list of all of the hemispheres\nlinks = browser.find_by_css('a.product-item img')\n\n# Next, loop through those links, click the link, find the sample anchor, return the href\nfor i in range(len(links)):\n \n \n # We have to find the elements on each loop to avoid a stale element exception\n \n \n # Next, we find the Sample image anchor tag and extract the href\n \n \n # Get Hemisphere title\n \n \n # Append hemisphere object to list\n \n \n # Finally, we navigate backwards\n browser.back()",
"_____no_output_____"
],
[
"hemisphere_image_urls",
"_____no_output_____"
],
[
"browser.quit()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
e7b21525b50c83d6d20297ba9cafcb8374c233f3 | 1,840 | ipynb | Jupyter Notebook | shakespeare.ipynb | farooq-teqniqly/blog-pyspark-for-noobs-part-2 | 11816d48498bec354a9fc393252ad5b6a677acec | [
"MIT"
] | null | null | null | shakespeare.ipynb | farooq-teqniqly/blog-pyspark-for-noobs-part-2 | 11816d48498bec354a9fc393252ad5b6a677acec | [
"MIT"
] | null | null | null | shakespeare.ipynb | farooq-teqniqly/blog-pyspark-for-noobs-part-2 | 11816d48498bec354a9fc393252ad5b6a677acec | [
"MIT"
] | null | null | null | 27.878788 | 98 | 0.525543 | [
[
[
"import urllib.request\n\nfrom pyspark.sql import SparkSession \nfrom pyspark.sql import functions as F\n\nspark = SparkSession.builder.getOrCreate()\n\nfile_name = \"shakespeare.txt\"\n\nurllib.request.urlretrieve(f\"http://www.gutenberg.org/files/100/100-0.txt\", file_name) \n\nstop_words_df = (spark.read.text(\"./stopwords.txt\")\n .select(F.lower(F.col(\"value\")).alias(\"words_lower\"))\n .select(F.rtrim(F.col(\"words_lower\")).alias(\"word\")))\n\nword_counts_df = (spark.read.text(f\"./{file_name}\")\n .select(F.lower(F.col(\"value\")).alias(\"words_lower\"))\n .select(F.split(F.col(\"words_lower\"), \" \").alias(\"words_split\"))\n .select(F.explode(F.col(\"words_split\")).alias(\"word\"))\n .select(F.regexp_extract(F.col(\"word\"), \"[a-z]+\", 0).alias(\"word\"))\n .where(F.ltrim(F.col(\"word\")) != \"\")\n .join(stop_words_df, \"word\", \"leftanti\")\n .groupBy(\"word\")\n .count()\n .orderBy(F.col(\"count\").desc()))",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code"
]
] |
e7b21f221d2ea964c715d6e3bd7a4cae9a70d646 | 315,085 | ipynb | Jupyter Notebook | notebooks/windstatistics.ipynb | SalishSeaCast/SoG_upwelling_EOF_paper | aa06a12137a67925b35241bd30b7407d86e673dc | [
"Apache-2.0"
] | null | null | null | notebooks/windstatistics.ipynb | SalishSeaCast/SoG_upwelling_EOF_paper | aa06a12137a67925b35241bd30b7407d86e673dc | [
"Apache-2.0"
] | null | null | null | notebooks/windstatistics.ipynb | SalishSeaCast/SoG_upwelling_EOF_paper | aa06a12137a67925b35241bd30b7407d86e673dc | [
"Apache-2.0"
] | null | null | null | 943.368263 | 304,172 | 0.950753 | [
[
[
"# Wind statistics\n\nFig. 3 from:\n\n>B. Moore-Maley and S. E. Allen: Wind-driven upwelling and surface nutrient delivery in a semi-enclosed coastal sea, Ocean Sci., 2022.\n\nDescription:\n\nHourly wind observations and HRDPS results for the 2015-2019 period at Sentry Shoal, Sisters Islet, Halibut Bank and Sand Heads.\n\n***",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport xarray as xr\nimport requests\nfrom pandas import read_csv\nfrom datetime import datetime\nfrom io import BytesIO\nfrom xml.etree import cElementTree as ElementTree\nfrom matplotlib import pyplot as plt\nfrom windrose import WindroseAxes\nfrom tqdm.notebook import tqdm\n\n%matplotlib inline",
"_____no_output_____"
],
[
"plt.rcParams['font.size'] = 12",
"_____no_output_____"
]
],
[
[
"***\n\n### Functions for loading data",
"_____no_output_____"
]
],
[
[
"def load_HRDPS(HRDPS, j, i, timerange):\n \"\"\"Load HRDPS model results from salishsea.eos.ubc.ca/erddap\n \"\"\"\n\n # Extract velocities from ERDDAP and calculate wspd, wdir\n tslc = slice(*timerange)\n u, v = [HRDPS.sel(time=tslc)[var][:, j, i].values for var in ('u_wind', 'v_wind')]\n time = HRDPS.sel(time=tslc).time.values.astype('datetime64[s]').astype(datetime)\n wspd = np.sqrt(u**2 + v**2)\n wdir = np.rad2deg(np.arctan2(v, u))\n \n # Transform wdir to degrees FROM, CW from N\n wdir = 270 - wdir\n wdir[wdir < 0] = wdir[wdir < 0] + 360\n \n return time, wspd, wdir\n\n\ndef load_EC(ID, year, month):\n \"\"\"Load EC met station data from climate.weather.gc.ca\n \"\"\"\n\n # Submit query\n url = 'http://climate.weather.gc.ca/climate_data/bulk_data_e.html'\n query = {\n 'timeframe': 1,\n 'stationID': ID,\n 'format': 'xml',\n 'time': 'UTC',\n 'Year': year,\n 'Month': month,\n 'Day': 1,\n }\n response = requests.get(url, params=query)\n tree = ElementTree.parse(BytesIO(response.content))\n root = tree.getroot()\n\n # Extract data\n time, wspd, wdir, values = [], [], [], {}\n for record in root.findall('stationdata'):\n for var in ('windspd', 'winddir'):\n try:\n values[var] = float(record.find(var).text)\n except:\n break\n else:\n dateargs = [int(record.get(field)) for field in ('year', 'month', 'day', 'hour')]\n time.append(datetime(*dateargs))\n wspd.append(values['windspd'])\n wdir.append(values['winddir'])\n \n # Convert lists to arrays\n time = np.array(time)\n wspd = np.array(wspd) / 3.6 # km/h to m/s\n wdir = np.array(wdir) * 10 # tens of degrees to degrees\n \n return time, wspd, wdir\n\n\ndef load_DFO(ID):\n \"\"\"Load DFO wave buoy data from www.meds-sdmm.dfo-mpo.gc.ca\n \"\"\"\n\n # Extract data from csv link\n fn = f'https://www.meds-sdmm.dfo-mpo.gc.ca/alphapro/wave/waveshare/csvData/c{ID}_csv.zip'\n df = read_csv(fn, index_col='DATE', parse_dates=True)\n time = df.index.values.astype('datetime64[s]').astype(datetime)\n wspd, wdir = [df[var].values for var in ('WSPD', 'WDIR')]\n \n return time, wspd, wdir",
"_____no_output_____"
]
],
[
[
"***\n\n### Load data\n\nDefinitions",
"_____no_output_____"
]
],
[
[
"# Station attributes\nstations = {\n 'Sentry Shoal' : {'ID': 46131, 'ji': (183, 107)},\n 'Sisters Islet': {'ID': 6813, 'ji': (160, 120)},\n 'Halibut Bank' : {'ID': 46146, 'ji': (149, 141)},\n 'Sand Heads' : {'ID': 6831, 'ji': (135, 151)},\n}\n\n# Assign HRDPS as netcdf object from erddap\nHRDPS = xr.open_dataset('https://salishsea.eos.ubc.ca/erddap/griddap/ubcSSaSurfaceAtmosphereFieldsV1')",
"_____no_output_____"
]
],
[
[
"Load data (~15 minutes)",
"_____no_output_____"
]
],
[
[
"# Initialize lists\nkeys, variables = ('obs', 'HRDPS'), ('time', 'wspd', 'wdir')\ndata = {station: {key: {var: [] for var in variables} for key in keys} for station in stations}\n\n# Load DFO data and truncate to the 2015-2019 range\ntimerange = [datetime(2015, 1, 1), datetime(2020, 1, 1)]\nfor station in ['Halibut Bank', 'Sentry Shoal']:\n time, wspd, wdir = load_DFO(stations[station]['ID'])\n index = np.array([timerange[0] <= t < timerange[1] for t in time])\n for var, values in zip(variables, [time, wspd, wdir]):\n data[station]['obs'][var] = values[index]\n\n# Loop through years\nfor year in tqdm(range(2015, 2020)):\n \n # Time range\n timerange = [datetime(year, 1, 1), datetime(year, 12, 31, 23, 59)]\n\n # Loop through stations\n for station in stations:\n\n # Load HRDPS from erddap (whole year)\n time, wspd, wdir = load_HRDPS(HRDPS, *stations[station]['ji'], timerange)\n for var, values in zip(variables, [time, wspd, wdir]):\n data[station]['HRDPS'][var].append(values)\n\n # Load EC data (month by month)\n if station in ['Sand Heads', 'Sisters Islet']:\n for month in range(1, 13):\n time, wspd, wdir = load_EC(stations[station]['ID'], year, month)\n for var, values in zip(variables, [time, wspd, wdir]):\n data[station]['obs'][var].append(values)\n\n# Concatenate\nfor station in stations:\n for key in keys:\n for var in variables:\n data[station][key][var] = np.hstack(data[station][key][var])",
"_____no_output_____"
]
],
[
[
"***\n\n### Plot windroses",
"_____no_output_____"
]
],
[
[
"# Make figure\nsubplot_kw, gridspec_kw = {'axes_class': WindroseAxes}, {'wspace': 0.15, 'hspace': 0.15}\nfig, axs = plt.subplots(4, 4, figsize=(12, 14), subplot_kw=subplot_kw, gridspec_kw=gridspec_kw)\n\n# Loop through stations and seasons\nkeylist, seasonlist = np.meshgrid(keys, ['Oct-Mar', 'Apr-Sep'])\nfor row, key, season in zip(axs, keylist.ravel(), seasonlist.ravel()):\n for ax, station in zip(row, stations):\n\n # Plot wind data\n tindex = np.array([3 < t.month < 10 for t in data[station][key]['time']])\n if season == 'Oct-Mar': tindex = ~tindex\n wspd, wdir = [data[station][key][var][tindex] for var in ('wspd', 'wdir')]\n ax.bar(\n wdir, wspd, bins=range(0, 11, 2), normed=True, nsector=18,\n opening=0.8, edgecolor='k', cmap=plt.get_cmap('YlGn'),\n )\n\n # Formatting axis\n ax.set_ylim([0, 30])\n ax.yaxis.set_ticks([10, 20, 30])\n ax.yaxis.set_ticklabels('')\n ax.xaxis.set_ticklabels('')\n if key == 'obs':\n ax.set_title(station, fontsize=12, y=1.1)\n if station == 'Sentry Shoal':\n ax.xaxis.set_ticklabels(['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE'])\n ax.yaxis.set_ticklabels([0.1, 0.2, 0.3])\n ax.text(2.05, 1.25, season, transform=ax.transAxes, fontdict={'weight': 'bold'})\n else:\n pos = ax.get_position()\n ax.set_position([pos.x0, pos.y0+0.02, pos.width, pos.height])\n if station == 'Sentry Shoal':\n ax.text(-0.2, 0.15, key, transform=ax.transAxes, fontdict={'style': 'italic', 'weight': 'bold'})\n\n# Add legend and panel labels\n# (manually get legend handles, since WindroseAxes.bar returns None)\nhandles, labels = ax.get_children()[:6], ['0-2', '2-4', '4-6', '6-8', '8-10', '> 10']\nfig.legend(handles=handles, labels=labels, title='m/s', ncol=6, frameon=False, loc=8, bbox_to_anchor=(0.5, 0.1))\nfor k, ax in enumerate(axs.ravel()):\n ax.text(0, 1, f'({chr(97+k)})', transform=ax.transAxes)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b223a365a34e0f96ff4401b154e71dd780ae9a | 11,343 | ipynb | Jupyter Notebook | Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb | lmwalkowicz/LSSTC-DSFP-Sessions | 19cb5c84a9c7d1c14a7b22d652a7f1dab34ed570 | [
"MIT"
] | null | null | null | Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb | lmwalkowicz/LSSTC-DSFP-Sessions | 19cb5c84a9c7d1c14a7b22d652a7f1dab34ed570 | [
"MIT"
] | null | null | null | Session12/Day3/NotebookIII_part2_overview_regular_3d.ipynb | lmwalkowicz/LSSTC-DSFP-Sessions | 19cb5c84a9c7d1c14a7b22d652a7f1dab34ed570 | [
"MIT"
] | null | null | null | 31.684358 | 635 | 0.577625 | [
[
[
"# Getting an Overview of Regular 3D Data\n\nIn this notebook, we're going to talk a little bit about how you might get an overview of regularized 3D data, specifically using matplotlib.\n\nIn a subsequent notebook we'll address the next few steps, specifically how you might use tools like ipyvolume and yt.\n\nTo start with, let's generate some fake data! (Now, I say 'fake,' but that's a bit pejorative, isn't it? Data is data! Ours is just synthetic.)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport scipy.special",
"_____no_output_____"
]
],
[
[
"We'll use the scipy [spherical harmonics](https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.sph_harm.html) function to make some data, but first we need a reference coordinate system. We'll start with $x, y, z$ and then transform them into spherical coordinates.\n\n**Note**: we'll be using the convention that $\\theta \\in [0, \\pi]$ and $\\phi \\in[0,2\\pi)$, which is reverse from what SciPy expects. So if you compare to the docstring for sph_harm, keep that in mind. Feel free to switch the definitions if you like!",
"_____no_output_____"
]
],
[
[
"N = 64\nx = np.mgrid[-1.0:1.0:N*1j][:,None,None]\ny = np.mgrid[-1.0:1.0:N*1j][None,:,None]\nz = np.mgrid[-1.0:1.0:N*1j][None,None,:]\n\nr = np.sqrt(x*x + y*y + z*z)\ntheta = np.arctan2(np.sqrt(x*x + y*y), z)\nphi = np.arctan2(y, x)",
"_____no_output_____"
],
[
"np.abs(x - r * np.sin(theta)*np.cos(phi)).max()",
"_____no_output_____"
],
[
"np.abs(y - r * np.sin(theta)*np.sin(phi)).max()",
"_____no_output_____"
],
[
"np.abs(z - r * np.cos(theta)).max()",
"_____no_output_____"
],
[
"data = {}\nfor n in [1, 4]:\n for m in range(n + 1):\n data[f\"sph_n{n}_m{m}\"] = np.absolute(scipy.special.sph_harm(m, n, phi, theta))",
"_____no_output_____"
]
],
[
[
"Now we have some data! And, we can use matplotlib to visualize it in *reduced* form. Let's try this out:",
"_____no_output_____"
]
],
[
[
"plt.imshow(data[\"sph_n4_m4\"][:,:,N//4], norm=LogNorm())\nplt.colorbar()",
"_____no_output_____"
],
[
"phi.min(), phi.max()",
"_____no_output_____"
],
[
"plt.imshow(data[\"sph_n1_m0\"].max(axis=0), norm=LogNorm())\nplt.colorbar()",
"_____no_output_____"
]
],
[
[
"This is getting a bit cumbersome, though! Let's try using the [`ipywidgets`](https://ipywidgets.readthedocs.org) library to speed this up just a bit.\n\nWe're going to use the `ipywidgets.interact` decorator around our function to add some inputs. This is a pretty powerful decorator, as it sets up new widgets based on the info that you feed it, and then re-executes the function every time those inputs change.",
"_____no_output_____"
]
],
[
[
"import ipywidgets",
"_____no_output_____"
],
[
"@ipywidgets.interact(dataset = list(sorted(data.keys())), slice_position = (0, N, 1))\ndef make_plots(dataset, slice_position):\n plt.imshow(data[dataset][slice_position,:,:], norm=LogNorm())\n plt.colorbar()",
"_____no_output_____"
]
],
[
[
"We still have some artifacts here we want to get rid of; let's see if we can restrict our colorbar a bit.",
"_____no_output_____"
]
],
[
[
"print(min(_.min() for _ in data.values()), max(_.max() for _ in data.values()))",
"_____no_output_____"
]
],
[
[
"Typically in these cases, the more interesting values are the ones at the top -- the bottom are usually falling off rather quickly to zero. So let's set our maximum, and then drop 5 orders of magnitude for the minimum. I'm changing the colorbar's \"extend\" value to reflect this.",
"_____no_output_____"
]
],
[
[
"@ipywidgets.interact(dataset = list(sorted(data.keys())), slice_position = (0, N, 1))\ndef make_plots(dataset, slice_position):\n plt.imshow(data[dataset][slice_position,:,:], norm=LogNorm(vmin=1e-5, vmax=1.0))\n plt.colorbar(extend = 'min')",
"_____no_output_____"
]
],
[
[
"We're going to do one more thing for getting an overview, and then we'll see if we can do some other, cooler things with it using plotly.\n\nWe're going to change our `slice_position` to be in units of actual coordinates, instead of integers, and we'll add on a multiplot so we can see all three at once.",
"_____no_output_____"
]
],
[
[
"@ipywidgets.interact(dataset = list(sorted(data.keys())), x = (-1.0, 1.0, 2.0/N), y = (-1.0, 1.0, 2.0/N), z = (-1.0, 1.0, 2.0/N))\ndef make_plots(dataset, x, y, z):\n xi, yi, zi = (int(_*N + 1.0) for _ in (x, y, z))\n fig, axes = plt.subplots(nrows=2, ncols=2, dpi = 200)\n datax = data[dataset][xi,:,:]\n datay = data[dataset][:,yi,:]\n dataz = data[dataset][:,:,zi]\n vmax = max(_.max() for _ in (datax, datay, dataz))\n vmin = max( min(_.min() for _ in (datax, datay, dataz)), vmax / 1e5)\n imx = axes[0][0].imshow(datax, norm=LogNorm(vmin=vmin, vmax=vmax), extent = [-1.0, 1.0, -1.0, 1.0])\n imy = axes[0][1].imshow(datay, norm=LogNorm(vmin=vmin, vmax=vmax), extent = [-1.0, 1.0, -1.0, 1.0])\n imz = axes[1][0].imshow(dataz, norm=LogNorm(vmin=vmin, vmax=vmax), extent = [-1.0, 1.0, -1.0, 1.0])\n fig.delaxes(axes[1][1])\n fig.colorbar(imx, ax=axes, extend = 'min', fraction = 0.1)",
"_____no_output_____"
],
[
"import plotly.graph_objects as go",
"_____no_output_____"
],
[
"plt.hist(data[\"sph_n4_m3\"].flatten())",
"_____no_output_____"
],
[
"iso_data=go.Isosurface(\n x=(x * np.ones((N,N,N))).flatten(),\n y=(y * np.ones((N,N,N))).flatten(),\n z=(z * np.ones((N,N,N))).flatten(),\n value=data[\"sph_n4_m3\"].flatten(),\n isomin=0,\n isomax=data[\"sph_n4_m3\"].max(),\n surface_count=5, # number of isosurfaces, 2 by default: only min and max\n colorbar_nticks=5, # colorbar ticks correspond to isosurface values\n caps=dict(x_show=False, y_show=False))\nfig = go.Figure(data = iso_data)\nfig",
"_____no_output_____"
]
],
[
[
"One thing I've run into with plotly while making this notebook has been that in many cases, the 3D plots strain a bit under large data sizes. This is to be expected, and is completely understandable! One of the really nice things about regular mesh data like this is that you can usually cut it down quite effectively with slices. Unfortunately, what I have found -- and I may have done something completely wrong! -- is that plotly some times appears to almost work, and then doesn't quite make it when I throw too much data at it. I've found that it seems to work best in the neighborhood of $64^3$ zones, maybe a bit more.",
"_____no_output_____"
],
[
"## Other Summary Techniques\n\nThere are, of course, other ways you can take a look at a set of values! Given a regular mesh, it's straightforward with numpy to apply any of the reduction operations along one of the axes. For instance, you might take the min, the max, the sum, the mean and so forth. If we do this with our spherical harmonics data:",
"_____no_output_____"
]
],
[
[
"plt.imshow(data[\"sph_n4_m3\"].sum(axis=0), extent=[-1.0, 1.0, -1.0, 1.0])",
"_____no_output_____"
]
],
[
[
"One thing you might keep in mind, when doing things like sums, is that if your cells aren't equally spaced along an axis, your sum will not necessarily be what you expect! You may want to integrate instead, where you multiple by a path length.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b224443cbc6173e6156bc092d3479b2937e2d0 | 190,397 | ipynb | Jupyter Notebook | notebooks/5_scrap_per_machine.ipynb | SanTaroZ/production-_analysis | 3373b86a3ee74a35d5547ef2e5e2e69e29dafd5b | [
"MIT"
] | null | null | null | notebooks/5_scrap_per_machine.ipynb | SanTaroZ/production-_analysis | 3373b86a3ee74a35d5547ef2e5e2e69e29dafd5b | [
"MIT"
] | null | null | null | notebooks/5_scrap_per_machine.ipynb | SanTaroZ/production-_analysis | 3373b86a3ee74a35d5547ef2e5e2e69e29dafd5b | [
"MIT"
] | null | null | null | 145.009139 | 71,816 | 0.84733 | [
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"%ls",
" Volume in drive D is D\n Volume Serial Number is 02D3-2159\n\n Directory of D:\\Notas de Estudio\\Proyectos\\production_analysis__project\\production_analysis\\data\\processed\n\n02/06/2022 11:11 PM <DIR> .\n02/06/2022 11:11 PM <DIR> ..\n01/20/2022 06:23 PM 0 .gitkeep\n01/01/2022 12:05 PM <DIR> .ipynb_checkpoints\n02/06/2022 11:11 PM 76 common list.txt\n02/06/2022 11:11 PM 330,645 data.csv\n02/06/2022 11:11 PM 648 machines_days_of_work.csv\n02/06/2022 11:11 PM 103,984 scrap per machine.png\n02/06/2022 11:11 PM 17,782 scrap_vs_production.pdf\n02/06/2022 11:11 PM 16,711 scrap_vs_total_scrap.pdf\n02/06/2022 11:11 PM 30,340 tendency_scrap_vs_production.pdf\n02/06/2022 11:11 PM 30,486 tendency_scrap_vs_total_scrap.pdf\n 9 File(s) 530,672 bytes\n 3 Dir(s) 223,127,322,624 bytes free\n"
],
[
"%cd D:\\Notas de Estudio\\Proyectos\\production_analysis__project\\production_analysis\\data\\processed",
"D:\\Notas de Estudio\\Proyectos\\production_analysis__project\\production_analysis\\data\\processed\n"
],
[
"%ls",
" Volume in drive D is D\n Volume Serial Number is 02D3-2159\n\n Directory of D:\\Notas de Estudio\\Proyectos\\production_analysis__project\\production_analysis\\data\\processed\n\n02/06/2022 11:11 PM <DIR> .\n02/06/2022 11:11 PM <DIR> ..\n01/20/2022 06:23 PM 0 .gitkeep\n01/01/2022 12:05 PM <DIR> .ipynb_checkpoints\n02/06/2022 11:11 PM 76 common list.txt\n02/06/2022 11:11 PM 330,645 data.csv\n02/06/2022 11:11 PM 648 machines_days_of_work.csv\n02/06/2022 11:11 PM 103,984 scrap per machine.png\n02/06/2022 11:11 PM 17,782 scrap_vs_production.pdf\n02/06/2022 11:11 PM 16,711 scrap_vs_total_scrap.pdf\n02/06/2022 11:11 PM 30,340 tendency_scrap_vs_production.pdf\n02/06/2022 11:11 PM 30,486 tendency_scrap_vs_total_scrap.pdf\n 9 File(s) 530,672 bytes\n 3 Dir(s) 223,127,322,624 bytes free\n"
],
[
"data = pd.read_csv(\"data.csv\")\ndata.head(5)",
"_____no_output_____"
],
[
"data.drop(['FECHA', 'TURNO', 'GRUPO', 'CODIGO', 'PRODUCCION (PZAS)', 'DIA', 'NOMBRE_DIA'], inplace = True, axis = 1)\ndata.head(5)",
"_____no_output_____"
],
[
"data = data.groupby('MÁQ.').sum()\ndata.head(5)",
"_____no_output_____"
],
[
"len(data.index.values)",
"_____no_output_____"
],
[
"data['PORCENTAJE'] = data['SCRAP']/(data['SCRAP']+data['TOTAL KG'])*100\ndata.head(5)",
"_____no_output_____"
],
[
"data.sort_values(by = 'PORCENTAJE', ascending = True) # just to check if there is a strange value\n",
"_____no_output_____"
],
[
"#removing machines with scrap = 0\n\ndata = data.loc[data['SCRAP']>0]\ndata.sort_values(by = 'PORCENTAJE', ascending = True, inplace = True)\ndata",
"_____no_output_____"
],
[
"len(data.index.values)",
"_____no_output_____"
],
[
"machines = data.index.values\nmachines",
"_____no_output_____"
],
[
"#number of charts\nn = 1\nmac = len(machines)\nwhile mac>15:\n mac = mac -15\n n=n+1\nprint(n)\n ",
"3\n"
],
[
"machines[0:15]",
"_____no_output_____"
],
[
"data[\"PORCENTAJE\"].iloc[0:15]",
"_____no_output_____"
],
[
"#Example of one chart\nfig, axs = plt.subplots(figsize = [15,10] )\nx = machines[0:15]\ny = data[\"PORCENTAJE\"].iloc[0:15]\nbars = axs.bar(x, y, color = 'indianred', alpha = 1 ,linewidth = 0.2)\naxs.set_xlabel('Máquinas')\naxs.set_ylabel('Scrap')\naxs.set_title('Porcentaje de scrap por máquina')\naxs.bar_label(bars, label_type = \"edge\", fmt='%0.1f')\n#plt.show()\nplt.savefig('scrap per machine_b')",
"_____no_output_____"
],
[
"color = ['indianred', 'darkolivegreen','steelblue', 'saddlebrown']\nfig = plt.subplots(figsize = [20,40],constrained_layout=True)\n\ninitial_value = 0 \nlast_value = 15\nfor i in range(n):\n plt.subplot(4,1,i+1)\n x = machines[initial_value:last_value]\n y = data[\"PORCENTAJE\"].iloc[initial_value:last_value]\n bars = plt.bar(x, y, color = color[i], alpha = 1, linewidth = 0.2)\n plt.xlabel('Máquinas')\n plt.ylabel('Scrap')\n plt.title('Porcentaje de scrap por máquina')\n plt.bar_label(bars, label_type = \"edge\", fmt='%0.1f')\n plt.minorticks_on()\n \n \n \n initial_value = initial_value + 15\n last_value = last_value +15\n\n \n#plt.show()\nplt.savefig('scrap per machine')\n ",
"_____no_output_____"
]
],
[
[
"* Creating one graph per group",
"_____no_output_____"
]
],
[
[
"machine_number = len(data.index.values)\nprint(machine_number)",
"36\n"
],
[
"color = ['indianred', 'darkolivegreen','steelblue', 'saddlebrown']\ninit_list = [0,15,30,45]\nfor i in range(1,5): # 1 to 4\n target = 15 * i \n if init_list[i-1] < machine_number:\n fig, axs = plt.subplots(figsize = [15,10] )\n x = machines[init_list[i-1]:target]\n y = data[\"PORCENTAJE\"].iloc[init_list[i-1]:target]\n bars = axs.bar(x, y, color = color[i-1], alpha = 1 ,linewidth = 0.2)\n axs.set_xlabel('Máquinas')\n axs.set_ylabel('% de Scrap')\n axs.set_title('Porcentaje de scrap por máquina')\n axs.bar_label(bars, label_type = \"edge\", fmt='%0.1f')\n plt.savefig('scrap per machine_'+str(init_list[i-1]))\n else:\n continue",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7b2261a36511b44d72547cd3cc05e3d3375ae95 | 60,694 | ipynb | Jupyter Notebook | notebooks/ParseEventData.ipynb | rubattino/apprecsys | 1b1796259d8c5b3cd72fae2b693dc4438640f251 | [
"BSD-2-Clause"
] | null | null | null | notebooks/ParseEventData.ipynb | rubattino/apprecsys | 1b1796259d8c5b3cd72fae2b693dc4438640f251 | [
"BSD-2-Clause"
] | null | null | null | notebooks/ParseEventData.ipynb | rubattino/apprecsys | 1b1796259d8c5b3cd72fae2b693dc4438640f251 | [
"BSD-2-Clause"
] | null | null | null | 93.808346 | 148 | 0.663295 | [
[
[
"import os\ndata_path = os.environ[\"YAHOO_DATA\"]\nprint data_path\nrawEventsRdd = sc.textFile(data_path + \"events.txt\")",
"/home/mertergun/yahoo_data/\n"
],
[
"sc.parallelize(rawEventsRdd.take(1000)).cache().saveAsTextFile(data_path + \"filteredEvents.txt\")",
"_____no_output_____"
],
[
"rawEventsRdd = sc.textFile(data_path + \"filteredEvents.txt\")\nexecfile(\"../script/context.py\")\ncontext",
"_____no_output_____"
],
[
"userIdConversionDictionary = rawEventsRdd.map(get_user_id).distinct().zipWithIndex().collectAsMap()\nuserIdConversionDictionaryBroadcast = sc.broadcast(userIdConversionDictionary)\nitemIdConversionDictionary = rawEventsRdd.map(get_item_id).distinct().zipWithIndex().collectAsMap()\nitemIdConversionDictionaryBroadcast = sc.broadcast(itemIdConversionDictionary)\ncityConversionDictionary = rawEventsRdd.map(context_city).distinct().zipWithIndex().collectAsMap()\ncityConversionDictionaryBroadcast = sc.broadcast(cityConversionDictionary)",
"_____no_output_____"
],
[
"userIdConversionDictionary",
"_____no_output_____"
],
[
"def set_context(line):\n key1 = (userIdConversionDictionary[get_user_id(line)], \n itemIdConversionDictionary[get_item_id(line)])\n list = []\n for f in context:\n list = list + [(context.index(f), f(line))]\n #convert city to id\n list[3] = list[3][0], cityConversionDictionary[list[3][1]]\n return [key1,list]\n \neventRDDConverted = rawEventsRdd.map(set_context).cache()\neventRDDConverted.take(3)",
"_____no_output_____"
],
[
"def flat_context(lst):\n l = []\n for x in lst[1]:\n l = l + [[(lst[0][0], lst[0][1], x[0]), x[1]]]\n return l\neventRDD = eventRDDConverted.flatMap(flat_context).cache()\neventRDD.take(3)",
"_____no_output_____"
]
],
[
[
"# Read parsed, and splitted data:",
"_____no_output_____"
]
],
[
[
"import os\nexecfile(\"../script/utils.py\")\neventsPath = os.environ[\"YAHOO_DATA\"]\nsplitedRdd = sc.textFile(eventsPath + \"/splitedData\")\nsplitedRdd = splitedRdd.map(parseContextData2)\na = splitedRdd.take(1)\nlen(a[0][1][0]) + len(a[0][1][1]) #80% training and #20%test data already separated\na",
"_____no_output_____"
],
[
"number = 5\nsplitedRdd.filter(lambda row: len(row[1][1]) >= number).count()",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
e7b22e75a534ebb584a0aedfc103c50136b21c0e | 32,827 | ipynb | Jupyter Notebook | examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb | andreas-hjortgaard/PySyft | 179c5b70b10140af4fc2c2eba7f328183f1a534b | [
"Apache-2.0"
] | 2 | 2018-12-24T14:46:16.000Z | 2018-12-24T16:53:47.000Z | examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb | R-Stefano/PySyft | 33e23644b026815d76c9e5d6594e3d0b8fe6830b | [
"Apache-2.0"
] | null | null | null | examples/tutorials/Part 6 - Build an Encrypted, Decentralized Database.ipynb | R-Stefano/PySyft | 33e23644b026815d76c9e5d6594e3d0b8fe6830b | [
"Apache-2.0"
] | 1 | 2019-12-24T19:47:38.000Z | 2019-12-24T19:47:38.000Z | 27.062655 | 453 | 0.511713 | [
[
[
"# Part 6: Build an Encrypted, Decentralized Database\n\nIn the last section (Part 5), we learned about the basic tools PySyft supports for encrypted computation. In this section, we're going to give one example of how to use those tools to build an encrypted, decentralized database. \n\n# Encrypted\n\nThe database will be encrypted because BOTH the values in the database will be encrypted AND all queries to the database will be encrypted.\n\n# Decentralized\n\nThe database will be decentralized because, using SMPC, all values will be \"shared\" amongst a variety of owners, meaning that all owners must agree to allow a query to be performed. It has no central \"owner\".\n\n# The Schema:\n\nWhile we could construct a variety of database types, for this first tutorial we're going to focus on a simple key-value store, where both the keys and values are strings.\n\n\nAuthors:\n- Andrew Trask - Twitter: [@iamtrask](https://twitter.com/iamtrask)",
"_____no_output_____"
]
],
[
[
"import syft as sy\nhook = sy.TorchHook()\n\nbob = sy.VirtualWorker(id=\"bob\")\nalice = sy.VirtualWorker(id=\"alice\")\nbill = sy.VirtualWorker(id=\"bill\")",
"_____no_output_____"
]
],
[
[
"# Section 1: Constructing a Key System\n\nIn this section, we're going to show how to use the equality operation to build a simple key system. The only tricky part about this is that we need to choose the datatype we want to use for keys. The most common usecase is probably strings, so that's what we're going to use here.\n\nNow, one thing you'll notice about our SMPC techniques, they all use exclusively numbers. Thus, we now have an issue. We need to decide how to encode our strings into numbers so that we can query them efficiently as \"keys\". The fastest way would be to map every possible key to a unique hash (integer) and then key based on that. Let's use that approach.",
"_____no_output_____"
]
],
[
[
"# Note that sy.mpc.securenn.field is the max value that we can encode using SMPC by default\n# This is, however, somewhat configurable in the system.\ndef string2key(input_str):\n return sy.LongTensor([hash(input_str) % sy.mpc.securenn.field])",
"_____no_output_____"
],
[
"string2key(\"hello\")",
"_____no_output_____"
],
[
"string2key(\"world\")",
"_____no_output_____"
]
],
[
[
"# Section 2: Constructing a Value Storage System\n\nNow, we are able to convert our string \"keys\" to integers which we can use for our database, but now we need to figure out how to encode the values in our database using numbers as well. For this, we're going to simply encode each string as a list of numbers like so.",
"_____no_output_____"
]
],
[
[
"import string\nstring.punctuation",
"_____no_output_____"
],
[
"import string\nchar2int = {}\nint2char = {}\nfor i, c in enumerate(' ' + string.ascii_letters + '0123456789' + string.punctuation):\n char2int[c] = i\n int2char[i] = c",
"_____no_output_____"
],
[
"def string2values(input_str):\n values = list()\n for char in input_str:\n values.append(char2int[char])\n return sy.LongTensor(values)\n\ndef values2string(input_values):\n s = \"\"\n for v in input_values:\n s += int2char[int(v)]\n return s",
"_____no_output_____"
],
[
"vs = string2values(\"hello world\")\nvs",
"_____no_output_____"
],
[
"values2string(vs)",
"_____no_output_____"
]
],
[
[
"# Section 3: Creating the Tensor Based Key-Value Store\n\nNow for our next operation, we want to write some logic which will allow us to query this database using ONLY addition, multiplication, and comparison operations. For this we will use a simple strategy. \n\nThe database will be a list of integer keys and a list of integer arrays (values).",
"_____no_output_____"
]
],
[
[
"keys = list()\nvalues = list()",
"_____no_output_____"
]
],
[
[
"To add a value to the database, we'll just add its key and value to the lists.",
"_____no_output_____"
]
],
[
[
"def add_entry(string_key, string_value):\n keys.append(string2key(string_key))\n values.append(string2values(string_value))",
"_____no_output_____"
],
[
"add_entry(\"Bob\",\"(123) 456-7890\")\nadd_entry(\"Bill\", \"(234) 567-8901\")\nadd_entry(\"Sue\",\"(345) 678-9012\")",
"_____no_output_____"
],
[
"keys",
"_____no_output_____"
],
[
"values",
"_____no_output_____"
]
],
[
[
"# Section 4: Querying the Key->Value Store\n\nOur query will be in three:\n\n- 1) check for equality between the query key and every key in the database - returning a 1 or 0 for each row. We'll call each row's result it's \"key_match\" integer.\n\n- 2) Multiply each row's \"key_match\" integer by all the values in its corresponding row. This will zero out all rows in the database which don't have matching keys.\n\n- 3) Sum all the masked rows in the database together. \n\n- 4) Return the result.",
"_____no_output_____"
]
],
[
[
"# this is our query\nquery = \"Bob\"\n\n# convert our query to a hash\nqhash = string2key(query)\nqhash[0]",
"_____no_output_____"
],
[
"# see if our query matches any key\nkey_match = list()\nfor key in keys:\n key_match.append((key == qhash).long())\nkey_match",
"_____no_output_____"
],
[
"# Multiply each row's value by its corresponding keymatch\nvalue_match = list()\nfor i, value in enumerate(values):\n value_match.append(key_match[i].expand(value.shape) * value)",
"_____no_output_____"
],
[
"# sum the values together\nfinal_value = value_match[0]\nfor v in value_match[1:]:\n final_value = final_value + v",
"_____no_output_____"
],
[
"# Decypher final value\nvalues2string(final_value)",
"_____no_output_____"
]
],
[
[
"# Section 5: Putting It Together\n\nHere's what this logic looks like when put together in a simple database class.",
"_____no_output_____"
]
],
[
[
"import string\n\nchar2int = {}\nint2char = {}\n\nfor i, c in enumerate(' ' + string.ascii_letters + '0123456789' + string.punctuation):\n char2int[c] = i\n int2char[i] = c\n\ndef string2key(input_str):\n return sy.LongTensor([hash(input_str) % sy.mpc.securenn.field])\n\ndef string2values(input_str):\n values = list()\n for char in input_str:\n values.append(char2int[char])\n return sy.LongTensor(values)\n\ndef values2string(input_values):\n s = \"\"\n for v in input_values:\n s += int2char[int(v)]\n return s\n\nclass TensorDB:\n\n def __init__(self):\n self.keys = list()\n self.values = list()\n \n def add_entry(self, string_key, string_value):\n self.keys.append(string2key(string_key))\n self.values.append(string2values(string_value))\n \n def query(self, str_query):\n # hash the query string\n qhash = string2key(str_query)\n \n # see if our query matches any key\n key_match = list()\n for key in self.keys:\n key_match.append((key == qhash).long())\n\n # Multiply each row's value by its corresponding keymatch\n value_match = list()\n for i,value in enumerate(self.values):\n value_match.append(key_match[i].expand(value.shape) * value)\n \n # sum the values together\n final_value = value_match[0]\n for v in value_match[1:]:\n final_value = final_value + v\n \n # Decypher final value\n return values2string(final_value)",
"_____no_output_____"
],
[
"db = TensorDB()",
"_____no_output_____"
],
[
"db.add_entry(\"Bob\",\"(123) 456-7890\")\ndb.add_entry(\"Bill\", \"(234) 567-8901\")\ndb.add_entry(\"Sue\",\"(345) 678-9012\")",
"_____no_output_____"
],
[
"db.query(\"hey\")",
"_____no_output_____"
],
[
"db.query(\"Bob\")",
"_____no_output_____"
],
[
"db.query(\"Bill\")",
"_____no_output_____"
],
[
"db.query(\"Sue\")",
"_____no_output_____"
]
],
[
[
"# Section 6: Building an Encrypted, Decentralized Database\n\nNow, the interesting thing here is that we have not used a single operation other than addition, multiplication, and comparison (equality). Thus, we can trivially create an encrypted database by simply encrypting all of our keys and values!",
"_____no_output_____"
]
],
[
[
"import string\n\nchar2int = {}\nint2char = {}\n\nfor i, c in enumerate(' ' + string.ascii_letters + '0123456789' + string.punctuation):\n char2int[c] = i\n int2char[i] = c\n\ndef string2key(input_str):\n return sy.LongTensor([(hash(input_str)+1234) % int(sy.mpc.securenn.field)])\n\ndef string2values(input_str):\n values = list()\n for char in input_str:\n values.append(char2int[char])\n return sy.LongTensor(values)\n\ndef values2string(input_values):\n s = \"\"\n for v in input_values:\n if(int(v) in int2char):\n s += int2char[int(v)]\n else:\n s += \".\"\n return s\n\n\nclass DecentralizedDB:\n \n def __init__(self, *owners):\n self.owners = owners\n self.keys = list()\n self.values = list()\n \n def add_entry(self, string_key, string_value):\n key = string2key(string_key).share(*self.owners)\n value = string2values(string_value).share(*self.owners)\n \n self.keys.append(key)\n self.values.append(value)\n \n def query(self, str_query):\n # hash the query string\n qhash = sy.LongTensor([string2key(str_query)])\n qhash = qhash.share(*self.owners)\n \n # see if our query matches any key\n key_match = list()\n for key in self.keys:\n key_match.append((key == qhash))\n\n # Multiply each row's value by its corresponding keymatch\n value_match = list()\n for i, value in enumerate(self.values):\n shape = list(value.get_shape())\n km = key_match[i]\n expanded_key = km.expand(1,shape[0])[0]\n value_match.append(expanded_key * value)\n \n # sum the values together\n final_value = value_match[0]\n for v in value_match[1:]:\n final_value = final_value + v\n \n result = values2string(final_value.get())\n \n # there is a certain element of randomness\n # which can cause the database to return empty\n # so if this happens, just try again\n if(list(set(result))[0] == '.'):\n return self.query(str_query)\n \n # Decypher final value\n return result",
"_____no_output_____"
],
[
"db = DecentralizedDB(bob, alice)\ndb.add_entry(\"Bob\",\"(123) 456-7890\")\ndb.add_entry(\"Bill\", \"(234) 567-8901\")\ndb.add_entry(\"Sam\",\"(345) 678-9012\")",
"_____no_output_____"
],
[
"db.query(\"Bob\")",
"_____no_output_____"
],
[
"db.query(\"Bill\")",
"_____no_output_____"
],
[
"db.query(\"Sam\")",
"_____no_output_____"
]
],
[
[
"### Success!!!\n\nAnd there you have it! We now have a key-value store capable of storing arbitrary strings and values in an encrypted, decentralized state such that even the queries are also private/encrypted.",
"_____no_output_____"
],
[
"# Section 7: Increasing Performance\n\n\n### Strategy 1: One-hot Encoded Keys\n\nAs it turns out, comparisons (like ==) can be very expensive to compute, which make the query take a long time. Thus, we also have another option. We can encode our strings using one_hot encodings. This allows us to exclusively use multiplication for our database query, like so.\n\n### Strategy 2: Fixed Length Values\nBy using fixed length values, we can encode the whole database as a single tensor which lets us use the underlying hardware to work a bit faster.",
"_____no_output_____"
]
],
[
[
"import string\n\nchar2int = {}\nint2char = {}\n\nfor i, c in enumerate(' ' + string.ascii_lowercase + '0123456789' + string.punctuation):\n char2int[c] = i\n int2char[i] = c\n\ndef one_hot(index, length):\n vect = sy.zeros(length).long()\n vect[index] = 1\n return vect\n \ndef string2one_hot_matrix(str_input, max_len=8):\n # truncate strings longer than max_len\n str_input = str_input[:max_len].lower()\n \n # pad strings shorter than max_len\n if(len(str_input) < max_len):\n str_input = str_input + \".\" * (max_len - len(str_input))\n \n char_vectors = list()\n for char in str_input:\n char_vectors.append(one_hot(char2int[char],len(int2char)).unsqueeze(0))\n \n return sy.cat(char_vectors,dim=0)\n\ndef string2values(str_input, max_len=128):\n # truncate strings longer than max_len\n str_input = str_input[:max_len].lower()\n \n # pad strings shorter than max_len\n if(len(str_input) < max_len):\n str_input = str_input + \".\" * (max_len - len(str_input))\n \n \n values = list()\n for char in str_input:\n values.append(char2int[char])\n \n return sy.LongTensor(values)",
"_____no_output_____"
],
[
"one_hots = string2one_hot_matrix(\"hey\")",
"_____no_output_____"
],
[
"class DecentralizedDB:\n \n def __init__(self, *owners, max_key_len=8, max_value_len=256):\n self.max_key_len = max_key_len\n self.max_value_len = max_value_len\n self.owners = owners\n self.keys = list()\n self.values = list()\n \n def add_entry(self, string_key, string_value):\n key = string2one_hot_matrix(string_key, self.max_key_len).share(*self.owners)\n value = string2values(string_value, self.max_value_len).share(*self.owners)\n \n self.keys.append(key)\n self.values.append(value)\n \n def query(self,query_str):\n query = string2one_hot_matrix(query_str, self.max_key_len).send(*self.owners)\n \n # see if our query matches any key\n # note: this is the slowest part of the program\n # it could probably be greatly faster with minimal improvements\n key_match = list()\n for key in self.keys:\n vect = (key * query).sum(1)\n x = vect[0]\n for i in range(vect.get_shape()[0]):\n x = x * vect[i]\n key_match.append(x)\n\n # Multiply each row's value by its corresponding keymatch\n value_match = list()\n for i, value in enumerate(self.values):\n shape = list(value.get_shape())\n km = key_match[i]\n expanded_key = km.expand(1,shape[0])[0]\n value_match.append(expanded_key * value)\n\n # NOTE: everything before this line could (in theory) happen in full parallel\n # on different threads.\n \n # sum the values together\n final_value = value_match[0]\n for v in value_match[1:]:\n final_value = final_value + v\n\n result = values2string(final_value.get())\n \n return result.replace(\".\",\"\")",
"_____no_output_____"
],
[
"db = DecentralizedDB(bob, alice, bill, max_key_len=3)\ndb.add_entry(\"Bob\",\"(123) 456 7890\")\ndb.add_entry(\"Bill\", \"(234) 567 8901\")\ndb.add_entry(\"Sam\",\"(345) 678 9012\")\ndb.add_entry(\"Key\",\"really big json value\")",
"_____no_output_____"
],
[
"db.query(\"Bob\")",
"_____no_output_____"
],
[
"db.query(\"Bill\")",
"_____no_output_____"
],
[
"db.query(\"Sam\")",
"_____no_output_____"
],
[
"db.query(\"Not a Person\")",
"_____no_output_____"
],
[
"db.query(\"Key\")",
"_____no_output_____"
]
],
[
[
"# Success!!\n\nAnd there we have it - a marginally more performant version. We could further add performance by running the query on all the rows in parallel, but we'll leave that for someone else to work on :).\n\n\nNote: we can add as many owners to the database as we want! (although the more owners you have the slower queries will be)",
"_____no_output_____"
]
],
[
[
"import syft as sy\nhook = sy.TorchHook()\n\nbob = sy.VirtualWorker(id=\"bob\")\nalice = sy.VirtualWorker(id=\"alice\")\nbill = sy.VirtualWorker(id=\"bill\")\nsue = sy.VirtualWorker(id=\"sue\")\ntara = sy.VirtualWorker(id=\"tara\")\n\ndb = DecentralizedDB(bob, alice, bill, sue, tara, max_key_len=3)\ndb.add_entry(\"Bob\",\"(123) 456 7890\")\ndb.add_entry(\"Bill\", \"(234) 567 8901\")\ndb.add_entry(\"Sam\",\"(345) 678 9012\")\ndb.add_entry(\"Key\",\"really big json value\")",
"WARNING:root:Torch was already hooked... skipping hooking process\nWARNING:root:Worker bob already exists. Replacing old worker which could cause unexpected behavior\nWARNING:root:Worker alice already exists. Replacing old worker which could cause unexpected behavior\nWARNING:root:Worker bill already exists. Replacing old worker which could cause unexpected behavior\n"
],
[
"db.query(\"Bob\")",
"_____no_output_____"
]
],
[
[
"# Congratulations!!! - Time to Join the Community!\n\nCongraulations on completing this notebook tutorial! If you enjoyed this and would like to join the movement toward privacy preserving, decentralized ownership of AI and the AI supply chain (data), you can do so in the following ways!\n\n### Star PySyft on Github\n\nThe easiest way to help our community is just by starring the Repos! This helps raise awareness of the cool tools we're building.\n\n- [Star PySyft](https://github.com/OpenMined/PySyft)\n\n### Join our Slack!\n\nThe best way to keep up to date on the latest advancements is to join our community! You can do so by filling out the form at [http://slack.openmined.org](http://slack.openmined.org)\n\n### Join a Code Project!\n\nThe best way to contribute to our community is to become a code contributor! At any time you can go to PySyft Github Issues page and filter for \"Projects\". This will show you all the top level Tickets giving an overview of what projects you can join! If you don't want to join a project, but you would like to do a bit of coding, you can also look for more \"one off\" mini-projects by searching for github issues marked \"good first issue\".\n\n- [PySyft Projects](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3AProject)\n- [Good First Issue Tickets](https://github.com/OpenMined/PySyft/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)\n\n### Donate\n\nIf you don't have time to contribute to our codebase, but would still like to lend support, you can also become a Backer on our Open Collective. All donations go toward our web hosting and other community expenses such as hackathons and meetups!\n\n[OpenMined's Open Collective Page](https://opencollective.com/openmined)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
e7b23f6017fc24776356ea6e295c0714ed461fe3 | 13,687 | ipynb | Jupyter Notebook | 02 Python Introduction.ipynb | m6121/Jupyter-Workshop | b864ce19153a5a70c23e374eb95a6f62ef9e2193 | [
"CC-BY-4.0",
"CC0-1.0"
] | 1 | 2020-10-13T12:33:34.000Z | 2020-10-13T12:33:34.000Z | 02 Python Introduction.ipynb | m6121/Jupyter-Workshop | b864ce19153a5a70c23e374eb95a6f62ef9e2193 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | 02 Python Introduction.ipynb | m6121/Jupyter-Workshop | b864ce19153a5a70c23e374eb95a6f62ef9e2193 | [
"CC-BY-4.0",
"CC0-1.0"
] | 2 | 2020-10-13T12:33:39.000Z | 2020-10-15T18:43:11.000Z | 24.930783 | 372 | 0.545773 | [
[
[
"_by Max Schröder$^{1,2}$ and Frank Krüger$^1$_\n\n$^1$ Institute of Communications Engineering, University of Rostock, Rostock <br>\n$^2$ University Library, University of Rostock, Rostock\n \n**Abstract**:\nThis introduction to the Python programming language is based on [this NLP course program](\nhttps://github.com/stefanluedtke/NLP-Exercises) as well as [this tutorial on audio signal processing](https://github.com/spatialaudio/selected-topics-in-audio-signal-processing-exercises).",
"_____no_output_____"
],
[
"## Basics\n\nBelow is a Python program containing a lot of the operations you will typically need: Assignments, arithmetics, logical operators, printing, comments. As you see, Python is quite easy to read.\n\n**Task 1:** Figure out the meaning of each line yourself.",
"_____no_output_____"
]
],
[
[
"x = 34 - 23 # A comment.\ny = \"Hello\" # Another one.\nz = 3.45\nif z == 3.45 or y == \"Hello\":\n x = x + 1\n y = y + \" World\"\nprint(x)\nprint(y)",
"_____no_output_____"
]
],
[
[
"## Indentation\nPython handles blocks in a different way than other programming languages you might know, like Java or C: The first line with less indentation is outside of the block, the first line with more indentation starts a nested block. A colon often starts a new block. For example, in the code below, the fourth line is always executed, because it is not part of the block:",
"_____no_output_____"
]
],
[
[
"if 17<16:\n print(\"executed conditionally\")\n print(\"also conditionally\")\nprint(\"always executed, because not part of the block above\")",
"_____no_output_____"
]
],
[
[
"## Reference Semantics\nAssignments behave as you might know from Java: For atomic data types, assignments work \"by value\", for all other data types (e.g. lists), assignments work \"by reference\": If we manipulate an object, this influences all references.",
"_____no_output_____"
]
],
[
[
"a=17\nb=a #assign the *value* of a to b\na=12\nprint(b) #still 17, because assinment by value\n\nx=[1,2,3] #this is what lists look like\ny=x #assign reference to the list to y\nx.append(4) #manipulate the list by adding a value\nprint(y) #y also changed, because of assingment by reference",
"_____no_output_____"
]
],
[
[
"## Lists\nLists are written in square brackets, as you have seen above. Lists can contain values of mixed types. List indices start with 0, as you can see here:",
"_____no_output_____"
]
],
[
[
"li = [17,\"Hello\",4.1,\"Bar\",5,6]\nli[2]",
"_____no_output_____"
]
],
[
[
"You can also use negative indices, which means that we start counting from the right:",
"_____no_output_____"
]
],
[
[
"li[-2]",
"_____no_output_____"
]
],
[
[
"You can also select subsets of lists (\"slicing\"), like this:",
"_____no_output_____"
]
],
[
[
"li[-4:-2]",
"_____no_output_____"
]
],
[
[
"Note that slicing returns a copy of the sub-list.",
"_____no_output_____"
],
[
"### Some more list operators\nHere are some more operators you might find useful.",
"_____no_output_____"
]
],
[
[
"# Boolean test whether a value is in a list: the in operator\nt = [1,2,3,4]\n2 in t \n\n# Concatenate lists: the + operator\na = [1,2,3,4]\nb = [5,6,7]\nc = a + b\nc\n\n# Repeat a list n times: the * operator\na=[1,2,3]\n3*a\n\n# Append lists\na=[1,2,3]\na.append(4)\n\n# Index of first occurence\na.index(2)\n\n# Number of occurences\na = [1,2,3,2,1,2]\na.count(2)\n\n# Remove first occurence\na.remove(2)\n\n# Revese the list\na.reverse()\n\n# Sort the list\na.sort()",
"_____no_output_____"
]
],
[
[
"## Dictionaries: A mapping type\nDictionaries are known as maps in other languages: They store a mapping between a set of keys and a set of values. Below is an example on how to use dictionaries:",
"_____no_output_____"
]
],
[
[
"# Create a new dictionary\nd = {'user':'bozo', 'pswd':1234}\n\n# Access the values via a key\nd['user']\nd['pswd']\n\n# Add key-value pairs\nd['id']=17\n\n# List of keys\nd.keys()\n\n# List of values\nd.values()",
"_____no_output_____"
]
],
[
[
"## Functions\nFunctions in Python work as you would expect: Arguments to functions are passed by assignment, that means passed arguments are assigned to local names. Assignments to arguments cannot affect the caller, but changing mutable arguments might. Here is an example of defining and calling a function:\n",
"_____no_output_____"
]
],
[
[
"def myfun(x,y):\n print(\"The function is executed.\")\n y[0]=8 # This changes the list that y points to\n return(y[1]+x)\n\nmylist = [1,2,3]\nresult=myfun(17,mylist)\nprint(\"Function returned: \",result)\nprint(\"List is now: \",mylist)",
"_____no_output_____"
]
],
[
[
"### Optional Arguments\nWe can define defaults for arguments that do not need to be passed:",
"_____no_output_____"
]
],
[
[
"def func(a, b, c=10, d=100):\n print(a, b, c, d)\nfunc(1,2)\nfunc(1,2,3,4)",
"_____no_output_____"
]
],
[
[
"Some more facts about functions:\n* All functions in Python have a return value, functions without a return statement have the special return value None\n* There is no function overloading in Python\n* Functions can be used as any other data types: They can be arguments to functions, return values of functions, assigned to variables, etc. This means Python is a functional programming language, and we can do many of things you know and love from Haskell, like higher-order functions!",
"_____no_output_____"
],
[
"## Control of Flow\nWe have already seen If-branches above. For- and While-Loops also work exactly as you would expect, Here are just some examples:",
"_____no_output_____"
]
],
[
[
"x = 3\nwhile x < 10:\n if x > 7:\n x += 2\n continue\n x = x + 1\n print(\"Still in the loop.\")\n if x == 8:\n break\nprint(\"Outside of the loop.\")",
"_____no_output_____"
],
[
"for x in [0,1,2,3,4,5,6,7,8,9]:\n if x > 7:\n x += 2\n continue\n x = x + 1\n print(\"Still in the loop.\")\n if x == 8:\n break\nprint(\"Outside of the loop.\")",
"_____no_output_____"
]
],
[
[
"**Task 2:** Implement a function that tests whether a given number is prime.",
"_____no_output_____"
]
],
[
[
"for i in range(-1, 15):\n print('%i is %s' % (i, is_prime(i)))",
"_____no_output_____"
]
],
[
[
"## List Comprehensions\nThere is a special syntax for list comprehensions (which you might know from Haskell).",
"_____no_output_____"
]
],
[
[
"# List of all multiples of 3 that are <100:\nevens = [x for x in range(3,100) if x%3==0]\nprint(evens)",
"_____no_output_____"
]
],
[
[
"**Task 3:** Use a list comprehension to make a list of all primes < 1000.",
"_____no_output_____"
],
[
"## Importing Modules/Packages\n\nIn order to work with numeric arrays, we import the [NumPy](http://www.numpy.org) package.\nNumpy is a very popular Python package that allows to work more easily with numeric arrays. It is the basis for much of what you will see in this course.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"Now we can use all NumPy functions (by prefixing \"`np.`\").",
"_____no_output_____"
]
],
[
[
"np.zeros(10000)",
"_____no_output_____"
]
],
[
[
"## Tab Completion\n\n**Task 4:** Type \"`np.ze`\" (without the quotes) and then hit the *Tab* key ...",
"_____no_output_____"
],
[
"## Getting Help\n\nIf you want to know details about the usage of `np.zeros()` and all its supported arguments, have a look at its help text.\nJust append a question mark to the function name (without parentheses!):",
"_____no_output_____"
]
],
[
[
"np.arange?",
"_____no_output_____"
]
],
[
[
"A help window should open in the lower part of the browser window.\nThis window can be closed by hitting the *q* key (like \"quit\").\n\nYou can also get help for the whole NumPy package:",
"_____no_output_____"
]
],
[
[
"np?",
"_____no_output_____"
]
],
[
[
"You can get help for any object by appending (or prepending) a question mark to the name of the object.\nLet's check what the help system can tell us about our variable `a`:",
"_____no_output_____"
]
],
[
[
"a?",
"_____no_output_____"
]
],
[
[
"## Useful Jupyter Notebook Commands\n\nIn addition to the general python programming, there are some very useful Jupyter Notebook specific commands starting with '%'.\nLet's first look at the variables, we have already defined including their type and the current value by the following command:",
"_____no_output_____"
]
],
[
[
"%whos",
"_____no_output_____"
]
],
[
[
"Other commands for timing python expressions might also be helpful, e.g. `%time` and `%timeit`\n\n**%%time in first line of cell for timing the entire cell, %time before comment for a single line** ",
"_____no_output_____"
]
],
[
[
"%time?",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b26a55fc28ef7fb3dbf07684d8362f2d074b7c | 895,978 | ipynb | Jupyter Notebook | Code/Query_and_Explore_data.ipynb | Alerovere/WALIS | ddd9ea65055f2849ee59e7be7d39629218ff14e4 | [
"MIT"
] | null | null | null | Code/Query_and_Explore_data.ipynb | Alerovere/WALIS | ddd9ea65055f2849ee59e7be7d39629218ff14e4 | [
"MIT"
] | null | null | null | Code/Query_and_Explore_data.ipynb | Alerovere/WALIS | ddd9ea65055f2849ee59e7be7d39629218ff14e4 | [
"MIT"
] | null | null | null | 950.135737 | 230,120 | 0.955932 | [
[
[
"# Query and explore data included in WALIS",
"_____no_output_____"
],
[
"This notebook contains scripts that allow querying and extracting data from the \"World Atlas of Last Interglacial Shorelines\" (WALIS) database. The notebook calls scripts contained in the /scripts folder. After downloading the database (internet connection required), field headers are renamed, and field values are substituted, following 1:n or n:n relationships. The tables composing the database are then saved in CSV, XLSS (multi-sheet), and geoJSON formats. The notebook also contains some plotting functions.",
"_____no_output_____"
],
[
"## Dependencies and packages\nThis notebook calls various scripts that are included in the \\scripts folder. The following is a list of the python libraries needed to run this notebook.",
"_____no_output_____"
]
],
[
[
"#Main packages\nimport pandas as pd\nimport pandas.io.sql as psql\nimport geopandas\nimport pygeos\nimport numpy as np\nimport mysql.connector\nfrom datetime import date\nimport xlsxwriter as writer\nimport math\nfrom scipy import optimize\nfrom scipy import stats\n\n#Plots\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n#Jupyter data display\nimport tqdm\nfrom tqdm.notebook import tqdm_notebook\nfrom IPython.display import *\nimport ipywidgets as widgets\nfrom ipywidgets import *\n\n#Geographic \nfrom shapely.geometry import Point\nfrom shapely.geometry import box\nimport cartopy as ccrs\nimport cartopy.feature as cfeature\n\n#System\nimport os\nimport glob\nimport shutil\n\n#pandas options for debugging\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\n#Set a date string for exported file names\ndate=date.today()\ndt_string = date.strftime(\"_%d_%m_%Y\")\n\n# Ignore warnings\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"## Import database\nConnect to the online MySQL database containing WALIS data and download data into a series of pandas data frames.",
"_____no_output_____"
]
],
[
[
"## Connect to the WALIS database server\n%run -i scripts/connection.py\n\n## Import data tables and show progress bar\nwith tqdm_notebook(total=len(SQLtables),desc='Importing tables from WALIS') as pbar:\n for i in range(len(SQLtables)): \n query = \"SELECT * FROM {}\".format(SQLtables[i])\n walis_dict[i] = psql.read_sql(query, con=db)\n query2 = \"SHOW FULL COLUMNS FROM {}\".format(SQLtables[i])\n walis_cols[i] = psql.read_sql(query2, con=db) \n pbar.update(1)\n\n%run -i scripts/create_outfolder.py",
"_____no_output_____"
]
],
[
[
"## Query the database\nNow, the data is ready to be queried according to a user input. There are two ways to extact data of interest from WALIS. Run either one and proceed.\n\n1. [Select by author](#Query-option-1---Select-by-author)\n2. [Select by geographic coordinates](#Query-option-2---Select-by-geographic-extent)",
"_____no_output_____"
],
[
"### Query option 1 - Select by author\n\nThis option compiles data from multiple users who collaborated to create regional datasets for the WALIS Special Issue in ESSD. Select \"WALIS Admin\" in the dropdown menu if you want to extract the entire database.\n\n**NOTE: If you want to change users, just re-run this cell and select a different set of values**",
"_____no_output_____"
]
],
[
[
"%run -i scripts/select_user.py\nmultiUsr",
"_____no_output_____"
]
],
[
[
"Once the selection is done, run the following cell to query the database and extract only the data inserted by the selected user(s)",
"_____no_output_____"
]
],
[
[
"%run -i scripts/multi_author_query.py",
"Extracting values for: WALIS Admin\n\nThe database you are exporting contains:\n4006 RSL datapoints from stratigraphy\n463 RSL datapoints from single corals\n76 RSL datapoints from single speleothems\n30 RSL indicators\n19 Elevation measurement techniques\n11 Geographic positioning techniques\n28 Sea level datums\n2717 U-Series ages (including RSL datapoints from corals and speleothems)\n583 Amino Acid Racemization samples\n213 Electron Spin Resonance ages\n597 Luminescence ages\n120 Chronostratigraphic constraints\n160 Other age constraints\n2130 References\n"
]
],
[
[
"### Query option 2 - Select by geographic extent\nThis option allows the download of data by geographic extent, defined as maximum-minimum bounds on Latitude and Longitude. Use this website to quickly find bounding coordinates: http://bboxfinder.com.",
"_____no_output_____"
]
],
[
[
"# bounding box coordinates in decimal degrees (x=Lon, y=Lat)\nxmin=-69.292145\nxmax=-68.616486\nymin=12.009771\nymax=12.435235\n\n# Curacao: -69.292145,12.009771,-68.616486,12.435235\n#2.103882,39.219487,3.630981,39.993956",
"_____no_output_____"
],
[
"# From the dictionary in connection.py, extract the dataframes\n%run -i scripts/geoextent_query.py",
"Extracting values for the coordinates you specified\nThe database you are exporting contains:\n11 RSL datapoints from stratigraphy\n15 RSL datapoints from single corals\n0 RSL datapoints from single speleothems\n2 RSL indicators\n3 Elevation measurement techniques\n3 Geographic positioning techniques\n4 Sea level datums\n30 U-Series ages\n0 Amino Acid Racemization samples\n24 Electron Spin Resonance ages\n0 Luminescence ages\n0 Chronostratigraphic constraints\n0 Other age constraints\n11 References\n"
]
],
[
[
"## Substitute data codes \nThe following code makes joins between the data, substituting numerical or comma-separated codes with the corresponding text values.\n\n**WARNING - MODIFICATIONS TO THE ORIGINAL DATA**\n\n<u>The following adjustments to the data are made:</u>\n1. If there is an age in ka, but the uncertainty field is empty, the age uncertainty is set to 30%\n2. If the \"timing constraint\" is missing, the \"MIS limit\" is taken. If still empty, it is set to \"Equal to\"",
"_____no_output_____"
]
],
[
[
"%run -i scripts/substitutions.py\n%run -i scripts/make_summary.py",
"We are substituting values in your dataframes....\nquerying by user\nPutting nice names to the database columns....\nDone!!\nmaking summary table....\nDone!\n"
]
],
[
[
"## Write output\nThe following scripts save the data in Xlsx, CSV, and geoJSON format (for use in GIS software).",
"_____no_output_____"
]
],
[
[
"%run -i scripts/write_spreadsheets.py\n%run -i scripts/write_geojson.py\nprint ('Done!')",
"Your file will be created in /Users/alessiorovere/Dropbox/Mac/Documents/GitHub/WALIS/Code/Output/Data/ \nDone!\n"
]
],
[
[
"## Explore queried data through graphs\nThe following scrips produce a series of images representing different aspects of the data included in the database. Each graph is saved in the \"Output/Images\" folder in svg format.\n\nThe following graphs can be plotted:\n1. [Monthly data insertion/update](#Monthly-data-insertion/update)\n2. [References by year of publication](#References-by-year-of-publication)\n3. [Elevation errors](#Elevation-errors)\n4. [Sea level index points](#Sea-level-index-points)\n5. [Elevation and positioning histograms](#Elevation-and-positioning-histograms)\n6. [Quality plots](#Quality-plots)\n7. [Maps](#Maps)\n8. [Radiometric ages distribution](#Radiometric-ages-distribution)",
"_____no_output_____"
],
[
"### Monthly data insertion/update\nThis graph explores the timeline of data insertion or update in WALIS since its inception. Peaks in this graph correspond to data updated in bulk by the admin. ",
"_____no_output_____"
]
],
[
[
"%run -i scripts/Database_contributions.py",
"_____no_output_____"
]
],
[
[
"### References by year of publication\nThis graph shows the year of publication of the manuscripts included in the WALIS \"References\" table. Note that these might not all be used in further data compilations.",
"_____no_output_____"
]
],
[
[
"References_query=References_query[References_query['Year'] != 0] #to eliminate works that are marked as \"in prep\" from the graph\n%run -i scripts/References_hist.py",
"_____no_output_____"
]
],
[
[
"### Elevation errors\nThese two graphs show the measured elevation errors (plotted as Kernel Density Estimate) reported for sea-level data within WALIS. These include \"RSL from statigraphy\" data points and single coral or speleothems indicating former RSL positions. The difference in the two plots resides in the treatment of outliers. Points having elevation uncertainties higher than 3.5 times the median absolute deviation are excluded from the graph in the left. All points are considered on the graph on the right side.\n\nThe outlier exclusion is bases on this reference:\n>Boris Iglewicz and David Hoaglin (1993), \"Volume 16: How to Detect and Handle Outliers\", The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka, Ph.D., Editor.\n\nAnd was derived from this link: https://stackoverflow.com/questions/11882393/matplotlib-disregard-outliers-when-plotting",
"_____no_output_____"
]
],
[
[
"%run -i scripts/Elevation_error.py",
"_____no_output_____"
]
],
[
[
"### Sea level index points \nThis graph shows the frequency of sea-level indicators within the query, including the grouping in indicator types.",
"_____no_output_____"
]
],
[
[
"%run -i scripts/SL_Ind_Hist.py",
"_____no_output_____"
]
],
[
[
"### Elevation and positioning histograms\nThese graphs show the distributions of the elevation metadata (Elevation measurement technique and sea-level datum) used to describe sea-level datapoints in WALIS.",
"_____no_output_____"
]
],
[
[
"%run -i scripts/Vrt_meas_hist.py",
"_____no_output_____"
],
[
"%run -i scripts/SL_datum_hist.py",
"_____no_output_____"
]
],
[
[
"### Quality plots\nThe RSL datapoints from stratigraphy contain two \"data quality\" fields, one for age and one for RSL information. Database compilers scored each site following standard guidelines (as per database documentation). This plot shows these quality scores plotted against each other. As the quality scores of one area can be better appreciated by comparison with other areas, tools to compare two nations or two regions are given.",
"_____no_output_____"
],
[
"#### Overall quality of selected area",
"_____no_output_____"
]
],
[
[
"%run -i scripts/Quality_plot.py",
"_____no_output_____"
]
],
[
[
"#### Compare two nations",
"_____no_output_____"
]
],
[
[
"%run -i scripts/select_nation_quality.py\nbox",
"_____no_output_____"
],
[
"%run -i scripts/Quality_nations.py",
"_____no_output_____"
]
],
[
[
"#### Compare two regions",
"_____no_output_____"
]
],
[
[
"%run -i scripts/select_region_quality.py\nbox",
"_____no_output_____"
],
[
"%run -i scripts/Quality_regions.py",
"_____no_output_____"
]
],
[
[
"## Maps\nIn this section, the data is organized in a series of maps. Some styling choices are available.",
"_____no_output_____"
]
],
[
[
"%run -i scripts/select_map_options.py",
"_____no_output_____"
],
[
"%run -i scripts/Static_maps.py",
"_____no_output_____"
]
],
[
[
"Global map of RSL datapoints. The following cell works only if the previous one is run choosing \"RSL Datapoints\" as Map Choice.",
"_____no_output_____"
]
],
[
[
"%run -i scripts/global_maps.py",
"_____no_output_____"
]
],
[
[
"## Radiometric ages distribution\nThe code below plots the age distribution of radiometric ages within the query. The data is run through a Monte-Carlo sampling of the gaussian distribution of each radiometric age, and Kernel density estimate (KDE) plots are derived. ",
"_____no_output_____"
]
],
[
[
"#Insert age limits to be plotted\nmin_age=0\nmax_age=150",
"_____no_output_____"
],
[
"%run -i scripts/age_kde.py",
"_____no_output_____"
]
],
[
[
"# Create ZIP archive\nCreate a ZIP archive of the entire \"Output\" folder.",
"_____no_output_____"
]
],
[
[
"shutil.make_archive('Output', 'zip', Output_path)",
"_____no_output_____"
]
],
[
[
"# Suggested acknowledgments\nWALIS is the result of the work of several people, within different projects. For this reason, we kindly ask you to follow these simple rules to properly acknowledge those who worked on it:\n\n1. Cite the original authors - Please maintain the original citations for each datapoint, to give proper credit to those who worked to collect the original data in the field or in the lab.\n2. Acknowledge the database contributor - The name of each contributor is listed in all public datapoints. This is the data creator, who spent time to make sure the data is standardized and (as much as possible) free of errors.\n3. Acknowledge the database structure and interface creators - The database template used in this study was developed by the ERC Starting Grant \"WARMCOASTS\" (ERC-StG-802414) and is a community effort under the PALSEA (PAGES / INQUA) working group.\n\nExample of acknowledgments: The data used in this study were *[extracted from / compiled in]* WALIS, a sea-level database interface developed by the ERC Starting Grant \"WARMCOASTS\" (ERC-StG-802414), in collaboration with PALSEA (PAGES / INQUA) working group. The database structure was designed by A. Rovere, D. Ryan, T. Lorscheid, A. Dutton, P. Chutcharavan, D. Brill, N. Jankowski, D. Mueller, M. Bartz, E. Gowan and K. Cohen. The data points used in this study were contributed to WALIS by *[list names of contributors here]*.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b2776b4830899776096970510982d82310b7f2 | 141,033 | ipynb | Jupyter Notebook | code/Heart Disease.ipynb | PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn | d7118c772f9dae22b010368cd353052041fbc4ed | [
"MIT"
] | 11 | 2018-04-03T22:25:03.000Z | 2021-10-31T18:50:33.000Z | code/Heart Disease.ipynb | PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn | d7118c772f9dae22b010368cd353052041fbc4ed | [
"MIT"
] | null | null | null | code/Heart Disease.ipynb | PacktPublishing/Hands-On-Machine-Learning-with-Python-and-Scikit-Learn | d7118c772f9dae22b010368cd353052041fbc4ed | [
"MIT"
] | 13 | 2018-04-16T02:04:24.000Z | 2022-01-28T02:05:55.000Z | 54.139347 | 34,356 | 0.630789 | [
[
[
"# Predicting Heart Disease\n\nThis dataset contains 76 features, but all published experiments refer to using a subset of 14 of them. The \"goal\" feature refers to the presence of heart disease in the patient. It is integer valued from 0 (no presence) to 4 (values 1,2,3,4) from absence (value 0). It is therefore a multiclass classification problem.\n\n*For our example, we will use several more features than the traditional 14.*\n\nFeature info (attributes used): \n1. feature 3 (age) - Age in years\n2. feature 4 (sex) - male or female\n3. feature 9 (cp) - chest pain type (typical angina, atypical angina, non-anginal, asymptomatic)\n4. feature 10 (trestbps) - resting blood pressure (mm Hg)\n5. feature 12 (chol) - cholesterol (mg/dl)\n6. feature 14 (cigperday) - number of cigarettes per day\n7. feature 16 (fbs) - fasting blood sugar > 120 mg/dl (1 = true; 0 = false) \n8. feature 18 (famhist) - family history of heart disease (1 = true; 0 = false)\n9. feature 19 (restecg) - resting electrocardiographic results (normal; st-t = having ST-T wave abnormality (T wave inversions and/or ST elevation or depression of > 0.05 mV); vent = showing probable or definite left ventricular hypertrophy by Estes' criteria)\n10. feature 32 (thalach) - maximum heart rate achieved\n11. feature 38 (exang) - exercise induced angina (1 = yes; 0 = no)\n12. feature 40 (oldpeak) - ST depression induced by exercise relative to rest\n13. feature 41 (slope) - the slope of the peak exercise ST segment (upsloping, flat, downsloping)\n14. feature 44 (ca) - number of major vessels (0-3) colored by flourosopy\n15. feature 51 (thal) - normal, fixed defect, or reversable defect\n16. feature 58 (target) (the predicted attribute) \n - 0: < 50% diameter narrowing\n - 1+: > 50% diameter narrowing\n\n### Our focus in using this dataset will be exploring pre-processing methods more thoroughly\n\nMore details can be found at [the UCI repository](https://archive.ics.uci.edu/ml/datasets/Heart+Disease).\n\n### Acknowledgments\n\nThe authors of the dataset have requested that any use of the data include the names of the principal investigator responsible for the data collection at each institution. They would be: \n\n1. Hungarian Institute of Cardiology. Budapest: Andras Janosi, M.D. \n2. University Hospital, Zurich, Switzerland: William Steinbrunn, M.D. \n3. University Hospital, Basel, Switzerland: Matthias Pfisterer, M.D. \n4. V.A. Medical Center, Long Beach and Cleveland Clinic Foundation:Robert Detrano, M.D., Ph.D.",
"_____no_output_____"
],
[
"## Loading the data from CSV\n\nWe can read the data directly from the CSV located in the [data/](data/) directory. The [raw data](data/heart-disease-raw.csv) was pre-processed to re-name categorical features where they are otherwise ordinal variables. This allows us to walk through an entire pre-processing pipeline",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n\nfrom functions import cls as packt_classes\n\n# read the raw csv\nX = pd.read_csv('data/heart-disease-2.csv', header=None)\n\n# rename the columns\ncols = ['age', 'sex', 'cp', 'trestbps', 'chol', 'cigperday', 'fbs', 'famhist',\n 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal', 'target']\n\nX.columns = cols\ny = X.pop('target') # don't want target in the X matrix\nX.head()",
"_____no_output_____"
]
],
[
[
"## Pre-split: any major imbalance?\n\nIf there are any categorical features with rare factor levels that need to be considered before splitting, we'll find out here.",
"_____no_output_____"
]
],
[
[
"def examine_cats(frame):\n for catcol in frame.columns[frame.dtypes == 'object'].tolist():\n print(catcol)\n print(frame[catcol].value_counts())\n print(\"\")\n \nexamine_cats(X)",
"sex\nmale 206\nfemale 97\nName: sex, dtype: int64\n\ncp\nasymptomatic 144\nnon-anginal 86\natypical anginal 50\ntypical anginal 23\nName: cp, dtype: int64\n\nrestecg\nnormal 151\nvent 148\nst-t 4\nName: restecg, dtype: int64\n\nslope\nupsloping 142\nflat 140\ndownsloping 21\nName: slope, dtype: int64\n\nthal\nnormal 166\nreversable 117\nfixed 18\nName: thal, dtype: int64\n\n"
]
],
[
[
"# Perform train/test split\n\nRemember, we always need to split! We will also stratify on the '`restecg`' variable since it's the most likely to be poorly split.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\n\nseed = 42\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=seed, \n stratify=X['restecg'])\n\nprint(\"Train size: %i\" % X_train.shape[0])\nprint(\"Test size: %i\" % X_test.shape[0])\nX_train.head()",
"Train size: 227\nTest size: 76\n"
],
[
"examine_cats(X_train)",
"sex\nmale 153\nfemale 74\nName: sex, dtype: int64\n\ncp\nasymptomatic 105\nnon-anginal 66\natypical anginal 37\ntypical anginal 19\nName: cp, dtype: int64\n\nrestecg\nnormal 113\nvent 111\nst-t 3\nName: restecg, dtype: int64\n\nslope\nflat 110\nupsloping 102\ndownsloping 15\nName: slope, dtype: int64\n\nthal\nnormal 121\nreversable 92\nfixed 12\nName: thal, dtype: int64\n\n"
]
],
[
[
"# Custom Transformers\n\nThere are several custom transformers that will be useful for this data:\n\n- Custom one-hot encoding that drops one level to avoid the [dummy variable trap](http://www.algosome.com/articles/dummy-variable-trap-regression.html)\n- Model-based imputation of continuous variables, since mean/median centering is rudimentary",
"_____no_output_____"
],
[
"### Custom base class\n\nWe'll start with a cusom base class that depends on the input to be a Pandas dataframe. This base class will provide super methods for validating the input type as well as the presence of any prescribed columns.",
"_____no_output_____"
]
],
[
[
"from sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.utils.validation import check_is_fitted\n\nclass CustomPandasTransformer(BaseEstimator, TransformerMixin):\n def _validate_input(self, X):\n if not isinstance(X, pd.DataFrame):\n raise TypeError(\"X must be a DataFrame, but got type=%s\" \n % type(X))\n return X\n \n @staticmethod\n def _validate_columns(X, cols):\n scols = set(X.columns) # set for O(1) lookup\n if not all(c in scols for c in cols):\n raise ValueError(\"all columns must be present in X\")",
"_____no_output_____"
]
],
[
[
"## Explanation of LabelEncoder",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import LabelEncoder\n\nlabels = ['banana', 'apple', 'orange', 'apple', 'orange']\nle = LabelEncoder()\nle.fit(labels)\nle.transform(labels)",
"_____no_output_____"
]
],
[
[
"# One-hot encode categorical data\n\nIt is probably (hopefully) obvious why we need to handle data that is in string format. There is not much we can do numerically with data that resembles the following:\n\n [flat, upsloping, downsloping, ..., flat, flat, downsloping]\n \nThere is a natural procedure to force numericism amongst string data: map each unique string to a unique level (1, 2, 3). This is, in fact, exactly what the sklearn [`LabelEncoder`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html) does. However, this is not sufficient for modeling purposes, since most algorithms will treat this as [ordinal data](https://en.wikipedia.org/wiki/Ordinal_data), where in many cases it is not. Imagine you fit a regression on data you've label-encoded, and one feature (type of chest pain, for instance) is now:\n\n [0, 2, 3, ..., 1, 0]\n \nYou might get coefficients back that make no sense since \"asymptomatic\" or \"non-anginal\", etc., are not inherently numerically greater or less than one another. Therefore, we [*one-hot encode*](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html) our categorical data into a numerical representation. Now we have dummy data and a binary feature for each variable/factor-level combination.",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import OneHotEncoder, LabelEncoder\n\nclass DummyEncoder(CustomPandasTransformer):\n \"\"\"A custom one-hot encoding class that handles previously unseen\n levels and automatically drops one level from each categorical\n feature to avoid the dummy variable trap.\n \n Parameters\n ----------\n columns : list\n The list of columns that should be dummied\n \n sep : str or unicode, optional (default='_')\n The string separator between the categorical feature name\n and the level name.\n \n drop_one_level : bool, optional (default=True)\n Whether to drop one level for each categorical variable.\n This helps avoid the dummy variable trap.\n \n tmp_nan_rep : str or unicode, optional (default=\"N/A\")\n Each categorical variable adds a level for missing values\n so test data that is missing data will not break the encoder\n \"\"\"\n def __init__(self, columns, sep='_', drop_one_level=True, \n tmp_nan_rep='N/A'):\n self.columns = columns\n self.sep = sep\n self.drop_one_level = drop_one_level\n self.tmp_nan_rep = tmp_nan_rep\n \n def fit(self, X, y=None):\n # validate the input, and get a copy of it\n X = self._validate_input(X).copy()\n \n # load class attributes into local scope\n tmp_nan = self.tmp_nan_rep\n \n # validate all the columns present\n cols = self.columns\n self._validate_columns(X, cols)\n \n # begin fit\n # for each column, fit a label encoder\n lab_encoders = {}\n for col in cols:\n vec = [tmp_nan if pd.isnull(v) \n else v for v in X[col].tolist()]\n \n # if the tmp_nan value is not present in vec, make sure it is\n # so the transform won't break down\n svec = list(set(vec))\n if tmp_nan not in svec:\n svec.append(tmp_nan)\n \n le = LabelEncoder()\n lab_encoders[col] = le.fit(svec)\n \n # transform the column, re-assign\n X[col] = le.transform(vec)\n \n # fit a single OHE on the transformed columns - but we need to ensure\n # the N/A tmp_nan vals make it into the OHE or it will break down later.\n # this is a hack - add a row of all transformed nan levels\n ohe_set = X[cols]\n ohe_nan_row = {c: lab_encoders[c].transform([tmp_nan])[0] for c in cols}\n ohe_set = ohe_set.append(ohe_nan_row, ignore_index=True)\n ohe = OneHotEncoder(sparse=False).fit(ohe_set)\n \n # assign fit params\n self.ohe_ = ohe\n self.le_ = lab_encoders\n self.cols_ = cols\n \n return self\n \n def transform(self, X):\n check_is_fitted(self, 'ohe_')\n X = self._validate_input(X).copy()\n \n # fit params that we need\n ohe = self.ohe_\n lenc = self.le_\n cols = self.cols_\n tmp_nan = self.tmp_nan_rep\n sep = self.sep\n drop = self.drop_one_level\n \n # validate the cols and the new X\n self._validate_columns(X, cols)\n col_order = []\n drops = []\n \n for col in cols:\n # get the vec from X, transform its nans if present\n vec = [tmp_nan if pd.isnull(v) \n else v for v in X[col].tolist()]\n \n le = lenc[col]\n vec_trans = le.transform(vec) # str -> int\n X[col] = vec_trans\n \n # get the column names (levels) so we can predict the \n # order of the output cols\n le_clz = le.classes_.tolist()\n classes = [\"%s%s%s\" % (col, sep, clz) for clz in le_clz]\n col_order.extend(classes)\n \n # if we want to drop one, just drop the last\n if drop and len(le_clz) > 1:\n drops.append(classes[-1])\n \n # now we can get the transformed OHE\n ohe_trans = pd.DataFrame.from_records(data=ohe.transform(X[cols]), \n columns=col_order)\n \n # set the index to be equal to X's for a smooth concat\n ohe_trans.index = X.index\n \n # if we're dropping one level, do so now\n if drops:\n ohe_trans = ohe_trans.drop(drops, axis=1)\n \n # drop the original columns from X\n X = X.drop(cols, axis=1)\n \n # concat the new columns\n X = pd.concat([X, ohe_trans], axis=1)\n return X",
"_____no_output_____"
],
[
"de = DummyEncoder(columns=['sex', 'cp', 'restecg', 'slope', 'thal'])\nde.fit(X_train)\nX_train_dummied = de.transform(X_train)\nX_train_dummied.head()",
"_____no_output_____"
]
],
[
[
"# Imputation\n\nWe can either use a built-in scikit-learn `Imputer`, which will require mean/median as a statistic, or we can build a model.\n\n## Statistic-based imputation",
"_____no_output_____"
]
],
[
[
"from sklearn.preprocessing import Imputer\n\nimputer = Imputer(strategy='median')\nimputer.fit(X_train_dummied)\nimputer.transform(X_train_dummied)[:5]",
"_____no_output_____"
]
],
[
[
"\n\n## Model-based imputation\n\nAs discussed in the iris notebook, there are many pitfalls to using mean or median for scaling. In instances where our data is too large to examine all features graphically, many times we cannot discern whether all features are normally distributed (a pre-requisite for mean-scaling). If we want to get more sophisticated, we can use an approach for imputation that is based on a model; we will use a [`BaggingRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingRegressor.html) (since we are filling in NaN continuous variables only at this point).\n\nNote that there are other common approaches for this, like KNN imputation, but nearest neighbors models require your data to be scaled, which we're trying to avoid.\n\n### Beware:\n\nSometimes missing data is informative. For instance... failure to report `cigperday` could be a bias on part of the patient who may not want to receive judgment or a lecture, or could indicate 0.",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble import BaggingRegressor\nfrom sklearn.externals import six\n\nclass BaggedRegressorImputer(CustomPandasTransformer):\n \"\"\"Fit bagged regressor models for each of the impute columns in order\n to impute the missing values.\n \n Parameters\n ----------\n impute_cols : list\n The columns to impute\n \n base_estimator : object or None, optional (default=None)\n The base estimator to fit on random subsets of the dataset.\n If None, then the base estimator is a decision tree.\n\n n_estimators : int, optional (default=10)\n The number of base estimators in the ensemble.\n\n max_samples : int or float, optional (default=1.0)\n The number of samples to draw from X to train each base estimator.\n - If int, then draw `max_samples` samples.\n - If float, then draw `max_samples * X.shape[0]` samples.\n\n max_features : int or float, optional (default=1.0)\n The number of features to draw from X to train each base estimator.\n - If int, then draw `max_features` features.\n - If float, then draw `max_features * X.shape[1]` features.\n\n bootstrap : boolean, optional (default=True)\n Whether samples are drawn with replacement.\n\n bootstrap_features : boolean, optional (default=False)\n Whether features are drawn with replacement.\n \n n_jobs : int, optional (default=1)\n The number of jobs to run in parallel for both `fit` and `predict`.\n If -1, then the number of jobs is set to the number of cores.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n verbose : int, optional (default=0)\n Controls the verbosity of the building process.\n \"\"\"\n def __init__(self, impute_cols, base_estimator=None, n_estimators=10, \n max_samples=1.0, max_features=1.0, bootstrap=True, \n bootstrap_features=False, n_jobs=1,\n random_state=None, verbose=0):\n \n self.impute_cols = impute_cols\n self.base_estimator = base_estimator\n self.n_estimators = n_estimators\n self.max_samples = max_samples\n self.max_features = max_features\n self.bootstrap = bootstrap\n self.bootstrap_features = bootstrap_features\n self.n_jobs = n_jobs\n self.random_state = random_state\n self.verbose = verbose\n \n def fit(self, X, y=None):\n # validate that the input is a dataframe\n X = self._validate_input(X) # don't need a copy this time\n \n # validate the columns exist in the dataframe\n cols = self.impute_cols\n self._validate_columns(X, cols)\n \n # this dictionary will hold the models\n regressors = {}\n \n # this dictionary maps the impute column name(s) to the vecs\n targets = {c: X[c] for c in cols}\n \n # drop off the columns we'll be imputing as targets\n X = X.drop(cols, axis=1) # these should all be filled in (no NaN)\n \n # iterate the column names and the target columns\n for k, target in six.iteritems(targets):\n # split X row-wise into train/test where test is the missing\n # rows in the target\n test_mask = pd.isnull(target)\n train = X.loc[~test_mask]\n train_y = target[~test_mask]\n \n # fit the regressor\n regressors[k] = BaggingRegressor(\n base_estimator=self.base_estimator,\n n_estimators=self.n_estimators,\n max_samples=self.max_samples,\n max_features=self.max_features,\n bootstrap=self.bootstrap,\n bootstrap_features=self.bootstrap_features,\n n_jobs=self.n_jobs, \n random_state=self.random_state,\n verbose=self.verbose, oob_score=False,\n warm_start=False).fit(train, train_y)\n \n # assign fit params\n self.regressors_ = regressors\n return self\n \n def transform(self, X):\n check_is_fitted(self, 'regressors_')\n X = self._validate_input(X).copy() # need a copy\n \n cols = self.impute_cols\n self._validate_columns(X, cols)\n \n # fill in the missing\n models = self.regressors_\n for k, model in six.iteritems(models):\n target = X[k]\n \n # split X row-wise into train/test where test is the missing\n # rows in the target\n test_mask = pd.isnull(target)\n \n # if there's nothing missing in the test set for this feature, skip\n if test_mask.sum() == 0:\n continue\n test = X.loc[test_mask].drop(cols, axis=1) # drop impute cols\n \n # generate predictions\n preds = model.predict(test)\n \n # impute!\n X.loc[test_mask, k] = preds\n \n return X",
"_____no_output_____"
],
[
"bagged_imputer = BaggedRegressorImputer(impute_cols=['cigperday', 'ca'], \n random_state=seed)\nbagged_imputer.fit(X_train_dummied)\n\n# save the masks so we can look at them afterwards\nca_nan_mask = pd.isnull(X_train_dummied.ca)\ncpd_nan_mask = pd.isnull(X_train_dummied.cigperday)\n\n# impute\nX_train_imputed = bagged_imputer.transform(X_train_dummied)\nX_train_imputed.head()",
"_____no_output_____"
],
[
"X_train_imputed[ca_nan_mask].ca",
"_____no_output_____"
],
[
"X_train_imputed[cpd_nan_mask].cigperday",
"_____no_output_____"
],
[
"X_train_imputed.isnull().sum().sum()",
"_____no_output_____"
]
],
[
[
"# Feature selection/dimensionality reduction\n\nOften times, when there is very high-dimensional data (100s or 1000s of features), it's useful to perform feature selection techniques to create more simple models that can be understood by analysts. A common one is [principal components analysis](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html), but one of its drawbacks is diminished model clarity.",
"_____no_output_____"
]
],
[
[
"from sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nscaler.fit(X_train_imputed)\n\n# fit PCA, get explained variance of ALL features\npca_all = PCA(n_components=None)\npca_all.fit(scaler.transform(X_train_imputed))",
"_____no_output_____"
],
[
"explained_var = np.cumsum(pca_all.explained_variance_ratio_)\nexplained_var",
"_____no_output_____"
],
[
"from matplotlib import pyplot as plt\n%matplotlib inline\n\nx_axis = np.arange(X_train_imputed.shape[1]) + 1\nplt.plot(x_axis, explained_var)\n\n# At which point to cut off?\nminexp = np.where(explained_var > 0.9)[0][0]\nplt.axvline(x=minexp, linestyle='dashed', color='red', alpha=0.5)\nplt.xticks(x_axis)\nplt.show()\n\nprint(\"Cumulative explained variance at %i components: %.5f\" % (minexp, explained_var[minexp]))",
"_____no_output_____"
]
],
[
[
"At 15 (of 25) features, we finally explain >90% cumulative variance in our components. This is not a significant enough feature reduction to warrant use of PCA, so we'll skip it.\n\n# Setup our CV",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import StratifiedKFold\n\n# set up our CV\ncv = StratifiedKFold(n_splits=3, shuffle=True, random_state=seed)",
"_____no_output_____"
]
],
[
[
"## Examine folds",
"_____no_output_____"
]
],
[
[
"folds = cv.split(X_train, y_train)\nfor i, fold in enumerate(folds):\n tr, te = fold\n print(\"Fold %i:\" % i)\n print(\"Training sample indices:\\n%r\" % tr)\n print(\"Testing sample indices:\\n%r\" % te)\n print(\"\\n\")",
"Fold 0:\nTraining sample indices:\narray([ 1, 3, 4, 5, 6, 8, 9, 10, 12, 13, 15, 17, 18,\n 21, 23, 24, 25, 26, 27, 28, 30, 31, 32, 34, 35, 36,\n 37, 38, 39, 41, 42, 43, 44, 45, 47, 49, 51, 53, 54,\n 55, 56, 58, 59, 62, 65, 66, 69, 70, 71, 73, 74, 75,\n 79, 81, 82, 85, 87, 89, 90, 93, 94, 95, 96, 97, 99,\n 100, 102, 103, 105, 106, 107, 108, 110, 111, 114, 115, 116, 117,\n 118, 119, 121, 123, 125, 127, 129, 131, 132, 134, 135, 136, 139,\n 140, 143, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 156,\n 157, 158, 160, 162, 163, 166, 169, 170, 171, 172, 173, 174, 177,\n 180, 181, 183, 184, 185, 186, 187, 188, 189, 190, 191, 193, 194,\n 198, 199, 200, 201, 203, 204, 205, 207, 209, 210, 211, 213, 215,\n 216, 218, 219, 220, 221, 224, 226])\nTesting sample indices:\narray([ 0, 2, 7, 11, 14, 16, 19, 20, 22, 29, 33, 40, 46,\n 48, 50, 52, 57, 60, 61, 63, 64, 67, 68, 72, 76, 77,\n 78, 80, 83, 84, 86, 88, 91, 92, 98, 101, 104, 109, 112,\n 113, 120, 122, 124, 126, 128, 130, 133, 137, 138, 141, 142, 144,\n 155, 159, 161, 164, 165, 167, 168, 175, 176, 178, 179, 182, 192,\n 195, 196, 197, 202, 206, 208, 212, 214, 217, 222, 223, 225])\n\n\nFold 1:\nTraining sample indices:\narray([ 0, 1, 2, 3, 7, 11, 14, 16, 19, 20, 22, 23, 26,\n 29, 30, 33, 35, 36, 39, 40, 43, 46, 47, 48, 49, 50,\n 52, 53, 54, 57, 59, 60, 61, 62, 63, 64, 65, 66, 67,\n 68, 69, 70, 72, 76, 77, 78, 79, 80, 81, 83, 84, 86,\n 87, 88, 91, 92, 93, 96, 98, 100, 101, 102, 103, 104, 108,\n 109, 111, 112, 113, 114, 115, 117, 118, 119, 120, 121, 122, 123,\n 124, 126, 128, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140,\n 141, 142, 143, 144, 145, 147, 153, 155, 156, 159, 161, 162, 163,\n 164, 165, 166, 167, 168, 171, 175, 176, 177, 178, 179, 180, 181,\n 182, 183, 185, 186, 189, 190, 191, 192, 194, 195, 196, 197, 198,\n 200, 201, 202, 206, 208, 209, 210, 211, 212, 213, 214, 217, 218,\n 219, 220, 221, 222, 223, 224, 225, 226])\nTesting sample indices:\narray([ 4, 5, 6, 8, 9, 10, 12, 13, 15, 17, 18, 21, 24,\n 25, 27, 28, 31, 32, 34, 37, 38, 41, 42, 44, 45, 51,\n 55, 56, 58, 71, 73, 74, 75, 82, 85, 89, 90, 94, 95,\n 97, 99, 105, 106, 107, 110, 116, 125, 127, 129, 136, 146, 148,\n 149, 150, 151, 152, 154, 157, 158, 160, 169, 170, 172, 173, 174,\n 184, 187, 188, 193, 199, 203, 204, 205, 207, 215, 216])\n\n\nFold 2:\nTraining sample indices:\narray([ 0, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 27, 28, 29,\n 31, 32, 33, 34, 37, 38, 40, 41, 42, 44, 45, 46, 48,\n 50, 51, 52, 55, 56, 57, 58, 60, 61, 63, 64, 67, 68,\n 71, 72, 73, 74, 75, 76, 77, 78, 80, 82, 83, 84, 85,\n 86, 88, 89, 90, 91, 92, 94, 95, 97, 98, 99, 101, 104,\n 105, 106, 107, 109, 110, 112, 113, 116, 120, 122, 124, 125, 126,\n 127, 128, 129, 130, 133, 136, 137, 138, 141, 142, 144, 146, 148,\n 149, 150, 151, 152, 154, 155, 157, 158, 159, 160, 161, 164, 165,\n 167, 168, 169, 170, 172, 173, 174, 175, 176, 178, 179, 182, 184,\n 187, 188, 192, 193, 195, 196, 197, 199, 202, 203, 204, 205, 206,\n 207, 208, 212, 214, 215, 216, 217, 222, 223, 225])\nTesting sample indices:\narray([ 1, 3, 23, 26, 30, 35, 36, 39, 43, 47, 49, 53, 54,\n 59, 62, 65, 66, 69, 70, 79, 81, 87, 93, 96, 100, 102,\n 103, 108, 111, 114, 115, 117, 118, 119, 121, 123, 131, 132, 134,\n 135, 139, 140, 143, 145, 147, 153, 156, 162, 163, 166, 171, 177,\n 180, 181, 183, 185, 186, 189, 190, 191, 194, 198, 200, 201, 209,\n 210, 211, 213, 218, 219, 220, 221, 224, 226])\n\n\n"
]
],
[
[
"\n# Baseline several models\n\nWe will build three models with default parameters and look at how the cross validation scores perform across folds, then we'll select the two better models to take into the model tuning stage.\n\n__NOTE__ we could theoretically go straight to tuning all three models to select the best, but it is often times not feasible to run grid searches for every model you want to try.",
"_____no_output_____"
]
],
[
[
"from sklearn.pipeline import Pipeline\nimport numpy as np\n\n# these are the pre-processing stages\nstages = [\n ('dummy', packt_classes.DummyEncoder(columns=['sex', 'cp', 'restecg', 'slope', 'thal'])),\n ('impute', packt_classes.BaggedRegressorImputer(impute_cols=['cigperday', 'ca'], \n random_state=seed))\n]\n\n# we'll add a new estimator onto the end of the pre-processing stages\ndef build_pipeline(pipe_stages, estimator, est_name='clf'):\n # copy the stages\n pipe_stages = [stage for stage in pipe_stages]\n pipe_stages.append((est_name, estimator))\n \n # return the pipe\n return Pipeline(pipe_stages)\n\n# report how the model did\ndef cv_report(cv_scores):\n mean = np.average(cv_scores)\n std = np.std(cv_scores)\n \n print(\"CV scores: %r\" % cv_scores)\n print(\"Average CV score: %.4f\" % mean)\n print(\"CV score standard deviation: %.4f\" % std)",
"_____no_output_____"
],
[
"from sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\n\n# fit a Logistic regression\nlgr_pipe = build_pipeline(stages, LogisticRegression(random_state=seed))\ncv_report(cross_val_score(lgr_pipe, X=X_train, y=y_train, \n scoring='neg_log_loss', cv=cv))",
"CV scores: array([-1.25219065, -1.13973284, -1.06839339])\nAverage CV score: -1.1534\nCV score standard deviation: 0.0757\n"
],
[
"from sklearn.ensemble import GradientBoostingClassifier\n\n# fit a GBM\ngbm_pipe = build_pipeline(stages, GradientBoostingClassifier(n_estimators=25, max_depth=3, random_state=seed))\ncv_report(cross_val_score(gbm_pipe, X=X_train, y=y_train, \n scoring='neg_log_loss', cv=cv))",
"CV scores: array([-1.14662777, -1.19505187, -1.31838939])\nAverage CV score: -1.2200\nCV score standard deviation: 0.0723\n"
],
[
"from sklearn.ensemble import RandomForestClassifier\n\n# fit a RF\nrf_pipe = build_pipeline(stages, RandomForestClassifier(n_estimators=25, random_state=seed))\ncv_report(cross_val_score(rf_pipe, X=X_train, y=y_train, \n scoring='neg_log_loss', cv=cv))",
"CV scores: array([-1.09616462, -2.26438127, -1.94406386])\nAverage CV score: -1.7682\nCV score standard deviation: 0.4929\n"
]
],
[
[
"## Initial thoughts\n\n* Our GBM and logistic regression perform similarly\n* Random forest did not perform very well and showed high variability across training folds\n* Let's move forward with LR & GBM",
"_____no_output_____"
],
[
"# Tuning hyper-params\n\nNow that we've baselined several models, let's choose a couple of the better-performing models to tune.",
"_____no_output_____"
]
],
[
[
"from scipy.stats import randint, uniform\nfrom sklearn.model_selection import RandomizedSearchCV\n\ngbm_pipe = Pipeline([\n ('dummy', packt_classes.DummyEncoder(columns=['sex', 'cp', 'restecg', 'slope', 'thal'])),\n ('impute', packt_classes.BaggedRegressorImputer(impute_cols=['cigperday', 'ca'], \n random_state=seed)),\n ('clf', GradientBoostingClassifier(random_state=seed))\n])\n\n# define the hyper-params\nhyper_params = {\n 'impute__n_estimators': randint(10, 50),\n 'impute__max_samples': uniform(0.75, 0.125),\n 'impute__max_features': uniform(0.75, 0.125),\n 'clf__n_estimators': randint(50, 400),\n 'clf__max_depth': [1, 3, 4, 5, 7],\n 'clf__learning_rate': uniform(0.05, 0.1),\n 'clf__min_samples_split': [2, 4, 5, 10],\n 'clf__min_samples_leaf': [1, 2, 5]\n}\n\n# define the search\ngbm_search = RandomizedSearchCV(gbm_pipe, param_distributions=hyper_params,\n random_state=seed, cv=cv, n_iter=100,\n n_jobs=-1, verbose=1, scoring='neg_log_loss',\n return_train_score=False)\n\ngbm_search.fit(X_train, y_train)",
"Fitting 3 folds for each of 100 candidates, totalling 300 fits\n"
],
[
"lgr_pipe = Pipeline([\n ('dummy', packt_classes.DummyEncoder(columns=['sex', 'cp', 'restecg', 'slope', 'thal'])),\n ('impute', packt_classes.BaggedRegressorImputer(impute_cols=['cigperday', 'ca'], \n random_state=seed)),\n ('clf', LogisticRegression(random_state=seed))\n])\n\n# define the hyper-params\nhyper_params = {\n 'impute__n_estimators': randint(10, 50),\n 'impute__max_samples': uniform(0.75, 0.125),\n 'impute__max_features': uniform(0.75, 0.125),\n 'clf__penalty': ['l1', 'l2'],\n 'clf__C': uniform(0.5, 0.125),\n 'clf__max_iter': randint(100, 500)\n}\n\n# define the search\nlgr_search = RandomizedSearchCV(lgr_pipe, param_distributions=hyper_params,\n random_state=seed, cv=cv, n_iter=100,\n n_jobs=-1, verbose=1, scoring='neg_log_loss',\n return_train_score=False)\n\nlgr_search.fit(X_train, y_train)",
"Fitting 3 folds for each of 100 candidates, totalling 300 fits\n"
]
],
[
[
"# Examine the results\n\nRight away we can tell that the logistic regression model was *much* faster than the gradient boosting model. However, does the extra time spent fitting end up giving us a performance boost? Let's introduce our test set to the optimized models and select the one that performs better. We are using [__log loss__](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html) as a scoring metric.\n\nSee [this answer](https://stats.stackexchange.com/questions/208443/intuitive-explanation-of-logloss) for a full intuitive explanation of log loss, but note that lower (closer to zero) is better. There is no maximum to log loss, and typically, the more classes you have, the higher it will be.",
"_____no_output_____"
],
[
"### First the CV scores",
"_____no_output_____"
]
],
[
[
"from sklearn.utils import gen_batches\n\ndef grid_report(search, n_splits, key='mean_test_score'):\n res = search.cv_results_\n arr = res[key]\n slices = gen_batches(arr.shape[0], n_splits)\n \n return pd.Series({\n '%s_MEAN' % key: arr.mean(),\n '%s_STD' % key: arr.std(),\n \n # the std of fold scores for each set of hyper-params,\n # averaged over all sets of params\n '%s_STD_OVER_FOLDS' % key: np.asarray([\n arr[slc].std()\n for slc in slices\n ]).mean()})\n \npd.DataFrame.from_records([grid_report(gbm_search, cv.get_n_splits()), \n grid_report(lgr_search, cv.get_n_splits())],\n index=[\"GBM\", \"Log. Reg\"]).T",
"_____no_output_____"
]
],
[
[
"### If the CV scores meet business requirements, move on to model selection",
"_____no_output_____"
]
],
[
[
"from sklearn.metrics import log_loss\n\ngbm_preds = gbm_search.predict_proba(X_test)\nlgr_preds = lgr_search.predict_proba(X_test)\n\nprint(\"GBM test LOSS: %.5f\" % log_loss(y_true=y_test, y_pred=gbm_preds))\nprint(\"Logistic regression test LOSS: %.5f\" % log_loss(y_true=y_test, y_pred=lgr_preds))",
"GBM test LOSS: 0.96101\nLogistic regression test LOSS: 0.97445\n"
]
],
[
[
"Note that in log loss, greater is WORSE. Therefore, the logistic regression was out-performed by the GBM. If the greater time to fit is not an issue for you, then this would be the better model to select. Likewise, you may favor model transparency over the extra few decimal points of accuracy, in which case the logistic regression might be favorable.\n\n# Variable importance\n\nMost times, it's not enough to build a good model. Most executives will want to know *why* something works. Moreover, in regulated industries like banking or insurance, knowing why a model is working is incredibly important for defending models to a regulatory board.\n\nOne of the methods commonly used for observing variable importance for non-linear methods (like our gradient boosting model) is to break the model into piecewise linear functions and measure how the model performs against each variable. This is called a \"partial dependency plot.\"\n\n### Raw feature importances\n\nWe can get the raw feature importances from the estimator itself, and match them up with the transformed column names:",
"_____no_output_____"
]
],
[
[
"# feed data through the pipe stages to get the transformed feature names\nX_trans = X_train\nfor step in gbm_search.best_estimator_.steps[:-1]:\n X_trans = step[1].transform(X_trans)\n \ntransformed_feature_names = X_trans.columns\ntransformed_feature_names",
"_____no_output_____"
],
[
"best_gbm = gbm_search.best_estimator_.steps[-1][1]\nimportances = best_gbm.feature_importances_\nimportances",
"_____no_output_____"
],
[
"feature_importances = sorted(zip(np.arange(len(transformed_feature_names)), \n transformed_feature_names, \n importances), \n key=(lambda ici: ici[2]),\n reverse=True)\n\nfeature_importances",
"_____no_output_____"
]
],
[
[
"### Partial dependency\n\nIn the following section, we'll break our GBM into a piecewise linear functions to gauge how different variables impact the target, and create [partial dependency plots](http://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html)",
"_____no_output_____"
]
],
[
[
"from sklearn.ensemble.partial_dependence import plot_partial_dependence\nfrom sklearn.ensemble.partial_dependence import partial_dependence\n\ndef plot_partial(est, which_features, X, names, label):\n fig, axs = plot_partial_dependence(est, X, which_features,\n feature_names=names,\n n_jobs=3, grid_resolution=50,\n label=label)\n \n fig.suptitle('Partial dependence of %i features\\n'\n 'on heart disease' % (len(which_features)))\n plt.subplots_adjust(top=0.8) # tight_layout causes overlap with suptitle\n \nplot_partial(est=best_gbm, X=X_trans,\n which_features=[2, 8, 9, 0, 6, (2, 9)],\n names=transformed_feature_names,\n label=1)",
"_____no_output_____"
]
],
[
[
"# Post-processing\n\nSuppose our board of surgeons only cares if the prediction is class \"3\" with a probability of >=0.3. In this segment we'll write and test a piece of code that we'll use as post-processing in our Flask API.",
"_____no_output_____"
]
],
[
[
"def is_certain_class(predictions, cls=3, proba=0.3):\n # find the row arg maxes (ones that are predicted 'cls')\n argmaxes = predictions.argmax(axis=1)\n \n # get the probas for the cls of interest\n probas = predictions[:, cls]\n \n # boolean mask that becomes our prediction vector\n return ((argmaxes == cls) & (probas >= proba)).astype(int)",
"_____no_output_____"
]
],
[
[
"This means we'll need to use \"`predict_proba`\" rather than \"`predict`\":",
"_____no_output_____"
]
],
[
[
"P = lgr_search.predict_proba(X_test)\nP[:5]",
"_____no_output_____"
],
[
"is_certain_class(P)",
"_____no_output_____"
]
],
[
[
"# Persist the model",
"_____no_output_____"
],
[
"Scikit-learn makes model persistence extraordinarily easily. Everything can be pickled via the \"joblib\" submodule. There are some exceptions:\n\n1. Classes that contain unbound methods\n2. Classes that contain instances of loggers\n3. Others...\n\n**In general, this is why we design our transformers to take string args as keys for callables rather than callables themselves!!!**",
"_____no_output_____"
]
],
[
[
"from sklearn.externals import joblib\nimport pickle\nimport os\n\nmodel_location = \"heart_disease_model.pkl\"\nwith open(model_location, \"wb\") as mod:\n joblib.dump(lgr_search.best_estimator_, mod, protocol=pickle.HIGHEST_PROTOCOL)\n assert os.path.exists(model_location)\n \n# demo how we can load and predict in one line!\nis_certain_class(joblib.load(model_location).predict_proba(X_test))",
"_____no_output_____"
]
],
[
[
"We can also use a Jupyter \"magic function\" to see that the pkl file exists in the file system:",
"_____no_output_____"
]
],
[
[
"!ls | grep \"heart_disease_model\"",
"heart_disease_model.pkl\r\n"
]
],
[
[
"## Accessing the REST API\n\nOnce the Flask app is live, we can test its `predict` endpoint:",
"_____no_output_____"
]
],
[
[
"import requests\n\n# if you have a proxy...\nos.environ['NO_PROXY'] = 'localhost'\n\n# test if it's running\nurl = \"http://localhost:5000/predict\"\n\n# print the GET result\nresponse = requests.get(url)\nprint(response.json()['message'])",
"Send me a valid POST! I accept JSON data only:\n\n\t{data=[...]}\n"
]
],
[
[
"## Sending data:\n\nLet's create a function that will accept a chunk of data, make it into a JSON and ship it to the REST API",
"_____no_output_____"
]
],
[
[
"import json\n\nheaders = {\n 'Content-Type': 'application/json'\n}\n\ndef get_predictions(data, url, headers):\n data = np.asarray(data)\n \n # if data is a vector and not a matrix, we need a vec...\n if len(data.shape) == 1:\n data = np.asarray([data.tolist()])\n \n # make a JSON out of it\n jdata = json.dumps({'data': data.tolist()})\n response = requests.post(url, data=jdata, headers=headers).json()\n print(response['message'])\n return response['predictions']\n\n# ship last few for X_test\nprint(get_predictions(X_test[-10:], url, headers))",
"Valid POST (n_samples=10)\n[1, 1, 1, 1, 0, 0, 0, 0, 0, 0]\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b28642de6de061a0f5aaf7a934538edc0ffea7 | 159,420 | ipynb | Jupyter Notebook | cs224w/test.ipynb | kidrabit/Data-Visualization-Lab-RND | baa19ee4e9f3422a052794e50791495632290b36 | [
"Apache-2.0"
] | 1 | 2022-01-18T01:53:34.000Z | 2022-01-18T01:53:34.000Z | cs224w/test.ipynb | kidrabit/Data-Visualization-Lab-RND | baa19ee4e9f3422a052794e50791495632290b36 | [
"Apache-2.0"
] | null | null | null | cs224w/test.ipynb | kidrabit/Data-Visualization-Lab-RND | baa19ee4e9f3422a052794e50791495632290b36 | [
"Apache-2.0"
] | null | null | null | 175.379538 | 111,764 | 0.875856 | [
[
[
"import TCDF\nimport argparse\nimport torch\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nimport pylab\nimport copy\nimport matplotlib.pyplot as plt\nimport os\nimport sys",
"_____no_output_____"
],
[
"%run -i \"runTCDF.py\" --data data/gang_morning.csv --cuda --significance 0.8 --hidden_layers 2 --kernel_size 3 --log_interval 500 --epochs 1000 --plot --dilation_coefficient 3",
"Arguments: Namespace(cuda=True, data=['data/gang_morning.csv'], dilation_coefficient=3, epochs=1000, ground_truth=None, hidden_layers=2, kernel_size=3, learning_rate=0.01, log_interval=500, optimizer='Adam', plot=True, seed=1111, significance=0.8)\n\n Dataset: gang_morning.csv\n\n Analysis started for target: 1220029700\nEpoch: 1 [0%] \tLoss: 605.279053\nEpoch: 500 [50%] \tLoss: 0.028918\nEpoch: 1000 [100%] \tLoss: 0.001470\nPotential causes: [48, 19]\n48 : 0.04467816278338432\n19 : 0.4035017192363739\nValidated causes: [48, 19]\n\n Analysis started for target: 1220032100\nEpoch: 1 [0%] \tLoss: 440.392792\nEpoch: 500 [50%] \tLoss: 0.000001\nEpoch: 1000 [100%] \tLoss: 0.000003\nPotential causes: [48, 54, 19]\n48 : 0.08401568233966827\n54 : 0.39414486289024353\n19 : 0.39144963026046753\nValidated causes: [48, 54, 19]\n\n Analysis started for target: 1220033000\nEpoch: 1 [0%] \tLoss: 273.131317\nEpoch: 500 [50%] \tLoss: 0.001356\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [48, 54, 20]\n48 : 0.46098941564559937\n54 : 0.06156744062900543\n20 : 8.969963528215885e-05\nValidated causes: [48, 54, 20]\n\n Analysis started for target: 1220024600\nEpoch: 1 [0%] \tLoss: 386.947571\nEpoch: 500 [50%] \tLoss: 0.031352\nEpoch: 1000 [100%] \tLoss: 0.000003\nPotential causes: [48, 24]\n48 : 1.650892734527588\n24 : 0.1400696337223053\nValidated causes: [48, 24]\n\n Analysis started for target: 1220028200\nEpoch: 1 [0%] \tLoss: 48.486725\nEpoch: 500 [50%] \tLoss: 0.000000\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [48, 24, 37, 52]\n48 : 0.11285966634750366\n24 : 0.007874266244471073\n37 : 0.00019137503113597631\n52 : 0.002797321882098913\nValidated causes: [48, 24, 37, 52]\n\n Analysis started for target: 1220025300\nEpoch: 1 [0%] \tLoss: 519.322449\nEpoch: 500 [50%] \tLoss: 0.000044\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [54, 19]\n54 : 1.3630681037902832\n19 : 0.4429045617580414\nValidated causes: [54, 19]\n\n Analysis started for target: 1220029200\nEpoch: 1 [0%] \tLoss: 508.880585\nEpoch: 500 [50%] \tLoss: 0.000000\nEpoch: 1000 [100%] \tLoss: 0.000004\nPotential causes: [48, 54, 24, 19]\n48 : 0.255662739276886\n54 : 0.03960583359003067\n24 : 0.014486677944660187\n19 : 0.7623491287231445\nValidated causes: [48, 54, 24, 19]\n\n Analysis started for target: 1220034000\nEpoch: 1 [0%] \tLoss: 444.442841\nEpoch: 500 [50%] \tLoss: 0.000045\nEpoch: 1000 [100%] \tLoss: 0.000002\nPotential causes: [48, 19]\n48 : 0.36734434962272644\n19 : 2.8493337631225586\nValidated causes: [48, 19]\n\n Analysis started for target: 1220034300\nEpoch: 1 [0%] \tLoss: 299.251251\nEpoch: 500 [50%] \tLoss: 0.001428\nEpoch: 1000 [100%] \tLoss: 0.000003\nPotential causes: [48, 54, 19]\n48 : 0.028807219117879868\n54 : 0.11472716927528381\n19 : 0.07823176681995392\nValidated causes: [48, 54, 19]\n\n Analysis started for target: 1220027500\nEpoch: 1 [0%] \tLoss: 679.250549\nEpoch: 500 [50%] \tLoss: 0.005830\nEpoch: 1000 [100%] \tLoss: 0.000162\nPotential causes: [48, 19]\n48 : 0.05860693007707596\n19 : 0.5456047058105469\nValidated causes: [48, 19]\n\n Analysis started for target: 1220034200\nEpoch: 1 [0%] \tLoss: 475.009644\nEpoch: 500 [50%] \tLoss: 0.000008\nEpoch: 1000 [100%] \tLoss: 0.000001\nPotential causes: [48, 56]\n48 : 5.776999473571777\n56 : 0.020302850753068924\nValidated causes: [48, 56]\n\n Analysis started for target: 1220026100\nEpoch: 1 [0%] \tLoss: 542.750122\nEpoch: 500 [50%] \tLoss: 0.015697\nEpoch: 1000 [100%] \tLoss: 0.001344\nPotential causes: [19, 54]\n19 : 0.44035983085632324\n54 : 0.3080860376358032\nValidated causes: [19, 54]\n\n Analysis started for target: 1220033700\nEpoch: 1 [0%] \tLoss: 396.135437\nEpoch: 500 [50%] \tLoss: 0.003913\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [56, 55]\n56 : 0.07753124833106995\n55 : 0.09816376864910126\nValidated causes: [56, 55]\n\n Analysis started for target: 1220026700\nEpoch: 1 [0%] \tLoss: 200.582932\nEpoch: 500 [50%] \tLoss: 0.000065\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [48, 43, 54, 2]\n48 : 0.12172680348157883\n43 : 0.000127644365420565\n54 : 0.005810612812638283\n2 : 0.00012910649820696563\nValidated causes: [48, 43, 54, 2]\n\n Analysis started for target: 1220035900\nEpoch: 1 [0%] \tLoss: 720.253662\nEpoch: 500 [50%] \tLoss: 0.007021\nEpoch: 1000 [100%] \tLoss: 0.000004\nPotential causes: [48, 20]\n48 : 0.1427745521068573\n20 : 0.013145467266440392\nValidated causes: [48, 20]\n\n Analysis started for target: 1220031900\nEpoch: 1 [0%] \tLoss: 345.197723\nEpoch: 500 [50%] \tLoss: 0.007326\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [20, 37, 54]\n20 : 0.002119832206517458\n37 : 0.0007639965042471886\n54 : 0.031844362616539\nValidated causes: [20, 37, 54]\n\n Analysis started for target: 1220035300\nEpoch: 1 [0%] \tLoss: 302.411102\nEpoch: 500 [50%] \tLoss: 0.000065\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [20, 48, 24, 54]\n20 : 0.0026281396858394146\n48 : 0.02666696533560753\n24 : 0.01942550577223301\n54 : 0.058734726160764694\nValidated causes: [20, 48, 24, 54]\n\n Analysis started for target: 1220032600\nEpoch: 1 [0%] \tLoss: 647.790161\nEpoch: 500 [50%] \tLoss: 0.056073\nEpoch: 1000 [100%] \tLoss: 0.000231\nPotential causes: [2, 24]\n2 : 0.0019051235867664218\n24 : 0.04717305302619934\nValidated causes: [2, 24]\n\n Analysis started for target: 1220034500\nEpoch: 1 [0%] \tLoss: 981.227539\nEpoch: 500 [50%] \tLoss: 0.415551\nEpoch: 1000 [100%] \tLoss: 0.055484\nPotential causes: [20, 48]\n20 : 2.0579168796539307\n48 : 46.5123291015625\nValidated causes: [20, 48]\n\n Analysis started for target: 1220030400\nEpoch: 1 [0%] \tLoss: 240.560471\nEpoch: 500 [50%] \tLoss: 0.000001\nEpoch: 1000 [100%] \tLoss: 0.000004\nPotential causes: [48, 35, 50]\n48 : 1.4258869886398315\n35 : 0.6377642154693604\n50 : 0.47933435440063477\nValidated causes: [48, 35, 50]\n\n Analysis started for target: 1220033500\nEpoch: 1 [0%] \tLoss: 475.229004\nEpoch: 500 [50%] \tLoss: 0.001506\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [35, 48]\n35 : 0.10289808362722397\n48 : 0.9545532464981079\nValidated causes: [35, 48]\n\n Analysis started for target: 1220030000\nEpoch: 1 [0%] \tLoss: 312.355438\nEpoch: 500 [50%] \tLoss: 0.007068\nEpoch: 1000 [100%] \tLoss: 0.000007\nPotential causes: [48, 20, 54, 45]\n48 : 0.043609559535980225\n20 : 5.866487845196389e-05\n54 : 0.13131839036941528\n45 : 0.03049342893064022\nValidated causes: [48, 20, 54, 45]\n\n Analysis started for target: 1220029600\nEpoch: 1 [0%] \tLoss: 284.456970\nEpoch: 500 [50%] \tLoss: 0.003642\nEpoch: 1000 [100%] \tLoss: 0.000030\nPotential causes: [52, 20]\n52 : 0.014403278939425945\n20 : 6.786087033106014e-05\nValidated causes: [52, 20]\n\n Analysis started for target: 1220024000\nEpoch: 1 [0%] \tLoss: 716.443604\nEpoch: 500 [50%] \tLoss: 0.137395\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [48, 24, 19]\n48 : 0.5609588623046875\n24 : 0.0983615443110466\n19 : 0.3155716359615326\nValidated causes: [48, 24, 19]\n\n Analysis started for target: 1220026600\nEpoch: 1 [0%] \tLoss: 462.224609\nEpoch: 500 [50%] \tLoss: 0.000002\nEpoch: 1000 [100%] \tLoss: 0.000363\nPotential causes: [48, 56, 50]\n48 : 0.25416314601898193\n56 : 0.02818216383457184\n50 : 0.3745408058166504\nValidated causes: [48, 56, 50]\n\n Analysis started for target: 1220030900\nEpoch: 1 [0%] \tLoss: 540.165222\nEpoch: 500 [50%] \tLoss: 0.042316\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [24, 54, 56, 18, 48]\n24 : 0.1555452048778534\n54 : 0.09195569157600403\n56 : 0.001231649424880743\n18 : 0.002266030991449952\n48 : 0.0035069852601736784\nValidated causes: [24, 54, 56, 18, 48]\n\n Analysis started for target: 1220031100\nEpoch: 1 [0%] \tLoss: 399.926697\nEpoch: 500 [50%] \tLoss: 0.000482\nEpoch: 1000 [100%] \tLoss: 0.000004\nPotential causes: [48, 50]\n48 : 2.2124228477478027\n50 : 0.0006862107547931373\nValidated causes: [48, 50]\n\n Analysis started for target: 1220034700\nEpoch: 1 [0%] \tLoss: 612.939575\nEpoch: 500 [50%] \tLoss: 0.003466\nEpoch: 1000 [100%] \tLoss: 0.000000\nPotential causes: [54, 19, 20]\n54 : 0.4395900368690491\n19 : 0.1780434250831604\n20 : 7.454905426129699e-05\nValidated causes: [54, 19, 20]\n\n Analysis started for target: 1220031200\nEpoch: 1 [0%] \tLoss: 265.329163\nEpoch: 500 [50%] \tLoss: 0.033246\nEpoch: 1000 [100%] \tLoss: 0.000013\nPotential causes: [48, 24, 46, 54, 2, 56]\n48 : 0.41719573736190796\n24 : 0.0008625412592664361\n46 : 2.216083521489054e-05\n54 : 0.00011931908375117928\n2 : 2.550698809500318e-05\n56 : 8.141246507875621e-05\nValidated causes: [48, 24, 46, 54, 2, 56]\n\n Analysis started for target: 1220028100\nEpoch: 1 [0%] \tLoss: 427.113831\n"
],
[
"a = np.load('scores_list.npy')",
"_____no_output_____"
],
[
"fig, axarr = plt.subplots( figsize=(10, 5))\naxarr.imshow(a, cmap='Blues', vmin=0, vmax=1, extent=(0, len(a), len(a), 0))\naxarr.set_ylabel('Affected series')\naxarr.set_xlabel('Causal series')\nprint('Estimated variable usage = %.2f%%' % (100 * np.mean(a)))\n#print('less loss = ',min(train_loss_adam).cpu().numpy())",
"Estimated variable usage = 28.08%\n"
],
[
"for i in range(57):\n for j in range(57):\n if a[i,j] <= 1:\n a[i,j] = 0",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b28e3b9e4f47cb499db1f5011dbc55d2f31ebe | 271,405 | ipynb | Jupyter Notebook | AlphaFold2PredictStructure.ipynb | hongqin/alphafold-local-sandbox | cc3d24f24a699ca14d79e7e855dce714ba7ac2f4 | [
"MIT"
] | 1 | 2022-03-28T05:05:27.000Z | 2022-03-28T05:05:27.000Z | AlphaFold2PredictStructure.ipynb | hongqin/alphafold-local-sandbox | cc3d24f24a699ca14d79e7e855dce714ba7ac2f4 | [
"MIT"
] | null | null | null | AlphaFold2PredictStructure.ipynb | hongqin/alphafold-local-sandbox | cc3d24f24a699ca14d79e7e855dce714ba7ac2f4 | [
"MIT"
] | 1 | 2022-03-28T05:05:33.000Z | 2022-03-28T05:05:33.000Z | 231.970085 | 81,051 | 0.565343 | [
[
[
"<a href=\"https://colab.research.google.com/github/hongqin/alphafold-local-sandbox/blob/main/AlphaFold2PredictStructure.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"#Protein structure prediction with AlphaFold2 and MMseqs2",
"_____no_output_____"
],
[
"Easy to use version of AlphaFold 2 (Jumper et al. 2021, Nature) using an API hosted at the Södinglab based on the MMseqs2 server (Mirdita et al. 2019, Bioinformatics) for the multiple sequence alignment creation. \n\n**Quickstart**\n1. Change the runtime type to GPU at \"Runtime\" -> \"Change runtime type\" (improves speed)\n2. Paste your protein sequence in the input field below\n3. Press \"Runtime\" -> \"Run all\"\n4. The pipeline has 8 steps. The currently running steps is indicated by a circle with a stop sign next to it. \n\n**Result**\n\nWe produce two result files (1) a PDB formated structure and (2) a plot of the model quality. At the end of the computation a download modal box will pop with a `result.tar.gz` file.\n\n**Troubleshooting**\n* Try to restart the session \"Runntime\" -> \"Factory reset runtime\"\n* Check your input sequence \n\n**Limitations**\n* MSAs: MMseqs2 might not find as many hits compared to HHblits/HMMer searched against BFD and Mgnify.\n* Templates: Currently we do not use template information. But this is work in progress. \n* Computing resources: MMseqs2 can probably handle >20k requests per day since we run it only on 16 cores.\n\nFor best results, we recommend using the full pipeline: https://github.com/deepmind/alphafold\n\nMost of the python code was written by Sergey Ovchinnikov (@sokrypton). The API is hosted at the Södinglab (@SoedingL) and maintained by Milot Mirdita (@milot_mirdita). Martin Steinegger (@thesteinegger) integrated everything.\n\n",
"_____no_output_____"
]
],
[
[
"#@title Input protein sequence here before you \"Run all\"\n\nquery_sequence = 'MAKTIKITQTRSAIGRLPKHKATLLGLGLRRIGHTVEREDTPAIRGMINAVSFMVKVEE' #@param {type:\"string\"}\n# remove whitespaces\nquery_sequence=\"\".join(query_sequence.split())\njobname = 'RL30_ECOLI' #@param {type:\"string\"}\n# remove whitespaces\njobname=\"\".join(jobname.split())\n\nwith open(f\"{jobname}.fasta\", \"w\") as text_file:\n text_file.write(\">1\\n%s\" % query_sequence)\n\n# number of models to use\n#@markdown ---\n#@markdown ### Advanced settings\nnum_models = 5 #@param [1,2,3,4,5] {type:\"raw\"}\nuse_amber = True #@param {type:\"boolean\"}\nuse_msa = True #@param {type:\"boolean\"}\n#@markdown ---",
"_____no_output_____"
],
[
"#@title Install dependencies\n%%bash -s \"$use_amber\"\nif [ ! -f AF2_READY ]; then\n # install dependencies\n apt-get -qq -y update 2>&1 1>/dev/null\n apt-get -qq -y install jq curl zlib1g gawk 2>&1 1>/dev/null\n pip -q install biopython 2>&1 1>/dev/null\n pip -q install dm-haiku 2>&1 1>/dev/null\n pip -q install ml-collections 2>&1 1>/dev/null\n pip -q install py3Dmol 2>&1 1>/dev/null\n touch AF2_READY\nfi\n# download model\nif [ ! -d \"alphafold/\" ]; then\n git clone https://github.com/deepmind/alphafold.git --quiet\n mv alphafold alphafold_\n mv alphafold_/alphafold .\nfi\n# download model params (~1 min)\nif [ ! -d \"params/\" ]; then\n wget -qnc https://storage.googleapis.com/alphafold/alphafold_params_2021-07-14.tar\n mkdir params\n tar -xf alphafold_params_2021-07-14.tar -C params/\n rm alphafold_params_2021-07-14.tar\nfi\n# install openmm for refinement\nif [ $1 == \"True\" ] && [ ! -f \"alphafold/common/stereo_chemical_props.txt\" ]; then\n wget -qnc https://git.scicore.unibas.ch/schwede/openstructure/-/raw/7102c63615b64735c4941278d92b554ec94415f8/modules/mol/alg/src/stereo_chemical_props.txt\n mv stereo_chemical_props.txt alphafold/common/\n wget -qnc https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\n bash Miniconda3-latest-Linux-x86_64.sh -bfp /usr/local 2>&1 1>/dev/null\n conda install -y -q -c conda-forge openmm=7.5.1 python=3.7 pdbfixer 2>&1 1>/dev/null\n (cd /usr/local/lib/python3.7/site-packages; patch -s -p0 < /content/alphafold_/docker/openmm.patch)\nfi",
"\r 0%| | 0/36 [00:00<?, ?it/s]\rExtracting : pycparser-2.20-py_2.conda: 0%| | 0/36 [00:00<?, ?it/s]\rExtracting : pycparser-2.20-py_2.conda: 3%|▎ | 1/36 [00:00<00:05, 6.27it/s]\rExtracting : wheel-0.35.1-pyhd3eb1b0_0.conda: 3%|▎ | 1/36 [00:00<00:05, 6.27it/s]\rExtracting : python-3.8.5-h7579374_1.conda: 6%|▌ | 2/36 [00:02<00:05, 6.27it/s] \rExtracting : python-3.8.5-h7579374_1.conda: 8%|▊ | 3/36 [00:02<00:13, 2.48it/s]\rExtracting : ncurses-6.2-he6710b0_1.conda: 8%|▊ | 3/36 [00:02<00:13, 2.48it/s] \rExtracting : libffi-3.3-he6710b0_2.conda: 11%|█ | 4/36 [00:02<00:12, 2.48it/s] \rExtracting : conda-package-handling-1.7.2-py38h03888b9_0.conda: 14%|█▍ | 5/36 [00:02<00:12, 2.48it/s]\rExtracting : xz-5.2.5-h7b6447c_0.conda: 17%|█▋ | 6/36 [00:02<00:12, 2.48it/s] \rExtracting : ruamel_yaml-0.15.87-py38h7b6447c_1.conda: 19%|█▉ | 7/36 [00:02<00:11, 2.48it/s]\rExtracting : pyopenssl-19.1.0-pyhd3eb1b0_1.conda: 22%|██▏ | 8/36 [00:02<00:11, 2.48it/s] \rExtracting : libgcc-ng-9.1.0-hdf63c60_0.conda: 25%|██▌ | 9/36 [00:02<00:10, 2.48it/s] \rExtracting : certifi-2020.6.20-pyhd3eb1b0_3.conda: 28%|██▊ | 10/36 [00:02<00:10, 2.48it/s]\rExtracting : ca-certificates-2020.10.14-0.conda: 31%|███ | 11/36 [00:02<00:10, 2.48it/s] \rExtracting : conda-4.9.2-py38h06a4308_0.conda: 33%|███▎ | 12/36 [00:02<00:09, 2.48it/s] \rExtracting : cryptography-3.2.1-py38h3c74f83_1.conda: 36%|███▌ | 13/36 [00:02<00:09, 2.48it/s]\rExtracting : tqdm-4.51.0-pyhd3eb1b0_0.conda: 39%|███▉ | 14/36 [00:02<00:08, 2.48it/s] \rExtracting : idna-2.10-py_0.conda: 42%|████▏ | 15/36 [00:02<00:08, 2.48it/s] \rExtracting : setuptools-50.3.1-py38h06a4308_1.conda: 44%|████▍ | 16/36 [00:02<00:08, 2.48it/s]\rExtracting : readline-8.0-h7b6447c_0.conda: 47%|████▋ | 17/36 [00:02<00:07, 2.48it/s] \rExtracting : cffi-1.14.3-py38h261ae71_2.conda: 50%|█████ | 18/36 [00:02<00:07, 2.48it/s]\rExtracting : yaml-0.2.5-h7b6447c_0.conda: 53%|█████▎ | 19/36 [00:02<00:06, 2.48it/s] \rExtracting : _libgcc_mutex-0.1-main.conda: 56%|█████▌ | 20/36 [00:02<00:06, 2.48it/s]\rExtracting : pysocks-1.7.1-py38h06a4308_0.conda: 58%|█████▊ | 21/36 [00:02<00:06, 2.48it/s]\rExtracting : chardet-3.0.4-py38h06a4308_1003.conda: 61%|██████ | 22/36 [00:02<00:05, 2.48it/s]\rExtracting : pycosat-0.6.3-py38h7b6447c_1.conda: 64%|██████▍ | 23/36 [00:02<00:05, 2.48it/s] \rExtracting : zlib-1.2.11-h7b6447c_3.conda: 67%|██████▋ | 24/36 [00:02<00:04, 2.48it/s] \rExtracting : tk-8.6.10-hbc83047_0.conda: 69%|██████▉ | 25/36 [00:02<00:04, 2.48it/s] \rExtracting : requests-2.24.0-py_0.conda: 72%|███████▏ | 26/36 [00:02<00:04, 2.48it/s]\rExtracting : libstdcxx-ng-9.1.0-hdf63c60_0.conda: 75%|███████▌ | 27/36 [00:02<00:03, 2.48it/s]\rExtracting : urllib3-1.25.11-py_0.conda: 78%|███████▊ | 28/36 [00:02<00:03, 2.48it/s] \rExtracting : six-1.15.0-py38h06a4308_0.conda: 81%|████████ | 29/36 [00:02<00:02, 2.48it/s]\rExtracting : ld_impl_linux-64-2.33.1-h53a641e_7.conda: 83%|████████▎ | 30/36 [00:02<00:02, 2.48it/s]\rExtracting : brotlipy-0.7.0-py38h27cfd23_1003.conda: 86%|████████▌ | 31/36 [00:02<00:02, 2.48it/s] \rExtracting : libedit-3.1.20191231-h14c3975_1.conda: 89%|████████▉ | 32/36 [00:02<00:01, 2.48it/s] \rExtracting : sqlite-3.33.0-h62c20be_0.conda: 92%|█████████▏| 33/36 [00:02<00:01, 2.48it/s] \rExtracting : openssl-1.1.1h-h7b6447c_0.conda: 94%|█████████▍| 34/36 [00:02<00:00, 2.48it/s]\rExtracting : pip-20.2.4-py38h06a4308_0.conda: 97%|█████████▋| 35/36 [00:02<00:00, 2.48it/s]\rExtracting : pip-20.2.4-py38h06a4308_0.conda: 100%|██████████| 36/36 [00:02<00:00, 3.54it/s]\r \r"
],
[
"#@title Build MSA\n%%bash -s \"$use_msa\" \"$jobname\"\nif [ $1 == \"True\" ]; then\n if [ -f $2.result.tar.gz ]; then\n echo \"looks done\"\n tar xzf $2.result.tar.gz\n tr -d '\\000' < uniref.a3m > $2.a3m\n else\n # build msa using the MMseqs2 search server\n echo \"submitting job\"\n ID=$(curl -s -F q=@$2.fasta -F mode=all https://a3m.mmseqs.com/ticket/msa | jq -r '.id')\n STATUS=$(curl -s https://a3m.mmseqs.com/ticket/${ID} | jq -r '.status')\n while [ \"${STATUS}\" == \"RUNNING\" ]; do\n STATUS=$(curl -s https://a3m.mmseqs.com/ticket/${ID} | jq -r '.status')\n sleep 1\n done\n if [ \"${STATUS}\" == \"COMPLETE\" ]; then\n curl -s https://a3m.mmseqs.com/result/download/${ID} > $2.result.tar.gz\n tar xzf $2.result.tar.gz\n tr -d '\\000' < uniref.a3m > $2.a3m\n else\n echo \"MMseqs2 server did not return a valid result.\"\n exit 1\n fi\n fi\n echo \"Found $(grep -c \">\" $2.a3m) sequences (after redundacy filtering)\"\nelse\n cp $2.fasta $2.a3m\nfi",
"submitting job\nFound 3351 sequences (after redundacy filtering)\n"
],
[
"#@title Setup model\n# the following code is written by Sergey Ovchinnikov\n# setup the model\nif \"model\" not in dir():\n import warnings\n warnings.filterwarnings('ignore')\n import os\n import sys\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n import tensorflow as tf\n import numpy as np\n import pickle\n import py3Dmol\n import matplotlib.pyplot as plt\n from alphafold.common import protein\n from alphafold.data import pipeline\n from alphafold.data import templates\n from alphafold.model import data\n from alphafold.model import config\n from alphafold.model import model\n\n import ipywidgets\n from ipywidgets import interact, fixed\n\n tf.get_logger().setLevel('ERROR')\n\nif use_amber and \"relax\" not in dir():\n sys.path.insert(0, '/usr/local/lib/python3.7/site-packages/')\n from alphafold.relax import relax\n\nif \"model_params\" not in dir(): model_params = {}\nfor model_name in [\"model_1\",\"model_2\",\"model_3\",\"model_4\",\"model_5\"][:num_models]:\n if model_name not in model_params:\n model_config = config.model_config(model_name)\n model_config.data.eval.num_ensemble = 1\n model_params[model_name] = data.get_model_haiku_params(model_name=model_name, data_dir=\".\")\n if model_name == \"model_1\":\n model_runner_1 = model.RunModel(model_config, model_params[model_name])\n if model_name == \"model_3\":\n model_runner_3 = model.RunModel(model_config, model_params[model_name])\n\ndef mk_mock_template(query_sequence):\n # since alphafold's model requires a template input\n # we create a blank example w/ zero input, confidence -1\n ln = len(query_sequence)\n output_templates_sequence = \"-\"*ln\n output_confidence_scores = np.full(ln,-1)\n templates_all_atom_positions = np.zeros((ln, templates.residue_constants.atom_type_num, 3))\n templates_all_atom_masks = np.zeros((ln, templates.residue_constants.atom_type_num))\n templates_aatype = templates.residue_constants.sequence_to_onehot(output_templates_sequence,\n templates.residue_constants.HHBLITS_AA_TO_ID)\n template_features = {'template_all_atom_positions': templates_all_atom_positions[None],\n 'template_all_atom_masks': templates_all_atom_masks[None],\n 'template_sequence': [f'none'.encode()],\n 'template_aatype': np.array(templates_aatype)[None],\n 'template_confidence_scores': output_confidence_scores[None],\n 'template_domain_names': [f'none'.encode()],\n 'template_release_date': [f'none'.encode()]}\n return template_features\n\ndef set_bfactor(pdb_filename, bfac):\n I = open(pdb_filename,\"r\").readlines()\n O = open(pdb_filename,\"w\")\n for line in I:\n if line[0:6] == \"ATOM \":\n seq_id = int(line[23:26].strip()) - 1\n O.write(\"{prefix}{bfac:6.2f}{suffix}\".format(prefix=line[:60], bfac=bfac[seq_id], suffix=line[66:]))\n O.close()\n\ndef predict_structure(prefix, feature_dict, do_relax=True, random_seed=0): \n \"\"\"Predicts structure using AlphaFold for the given sequence.\"\"\"\n\n # Run the models.\n plddts = []\n unrelaxed_pdb_lines = []\n relaxed_pdb_lines = []\n\n for model_name, params in model_params.items():\n print(f\"running {model_name}\")\n # swap params to avoid recompiling\n # note: models 1,2 have diff number of params compared to models 3,4,5\n if any(str(m) in model_name for m in [1,2]): model_runner = model_runner_1\n if any(str(m) in model_name for m in [3,4,5]): model_runner = model_runner_3\n model_runner.params = params\n \n processed_feature_dict = model_runner.process_features(feature_dict, random_seed=random_seed)\n prediction_result = model_runner.predict(processed_feature_dict)\n unrelaxed_protein = protein.from_prediction(processed_feature_dict,prediction_result)\n unrelaxed_pdb_lines.append(protein.to_pdb(unrelaxed_protein))\n plddts.append(prediction_result['plddt'])\n\n if do_relax:\n # Relax the prediction.\n amber_relaxer = relax.AmberRelaxation(max_iterations=0,tolerance=2.39,\n stiffness=10.0,exclude_residues=[],\n max_outer_iterations=20) \n relaxed_pdb_str, _, _ = amber_relaxer.process(prot=unrelaxed_protein)\n relaxed_pdb_lines.append(relaxed_pdb_str)\n\n # rerank models based on predicted lddt\n lddt_rank = np.mean(plddts,-1).argsort()[::-1]\n plddts_ranked = {}\n for n,r in enumerate(lddt_rank):\n print(f\"model_{n+1} {np.mean(plddts[r])}\")\n\n unrelaxed_pdb_path = f'{prefix}_unrelaxed_model_{n+1}.pdb' \n with open(unrelaxed_pdb_path, 'w') as f: f.write(unrelaxed_pdb_lines[r])\n set_bfactor(unrelaxed_pdb_path,plddts[r]/100)\n\n if do_relax:\n relaxed_pdb_path = f'{prefix}_relaxed_model_{n+1}.pdb'\n with open(relaxed_pdb_path, 'w') as f: f.write(relaxed_pdb_lines[r])\n set_bfactor(relaxed_pdb_path,plddts[r]/100)\n\n plddts_ranked[f\"model_{n+1}\"] = plddts[r]\n\n return plddts_ranked",
"_____no_output_____"
],
[
"#@title Predict structure\na3m_lines = \"\".join(open(f\"{jobname}.a3m\",\"r\").readlines())\nmsa, deletion_matrix = pipeline.parsers.parse_a3m(a3m_lines)\nquery_sequence = msa[0]\nfeature_dict = {\n **pipeline.make_sequence_features(sequence=query_sequence,\n description=\"none\",\n num_res=len(query_sequence)),\n **pipeline.make_msa_features(msas=[msa],deletion_matrices=[deletion_matrix]),\n **mk_mock_template(query_sequence)\n}\nplddts = predict_structure(jobname, feature_dict, do_relax=use_amber)",
"model_1 92.44848268102942\nmodel_2 90.9884386024141\nmodel_3 93.22937379857797\nmodel_4 94.80244068565474\nmodel_5 91.9913274542571\n"
],
[
"#@title Plot lDDT per residue\n# confidence per position\nplt.figure(dpi=100)\nfor model_name,value in plddts.items():\n plt.plot(value,label=model_name)\nplt.legend()\nplt.ylim(0,100)\nplt.ylabel(\"predicted lDDT\")\nplt.xlabel(\"positions\")\nplt.savefig(jobname+\"_lDDT.png\")\nplt.show()",
"_____no_output_____"
],
[
"#@title Plot Number of Sequences per Position\n# confidence per position\nplt.figure(dpi=100)\nplt.plot((feature_dict[\"msa\"] != 21).sum(0))\nplt.xlabel(\"positions\")\nplt.ylabel(\"number of sequences\")\nplt.show()",
"_____no_output_____"
],
[
"#@title Show 3D structure\ndef show_pdb(model_name,\n show_sidechains=False,\n show_mainchain=False,\n color=\"None\"):\n\n def mainchain(p, color=\"white\", model=0):\n BB = ['C','O','N','CA']\n p.addStyle({\"model\":model,'atom':BB},\n {'stick':{'colorscheme':f\"{color}Carbon\",'radius':0.4}})\n\n def sidechain(p, model=0):\n HP = [\"ALA\",\"GLY\",\"VAL\",\"ILE\",\"LEU\",\"PHE\",\"MET\",\"PRO\",\"TRP\",\"CYS\",\"TYR\"]\n BB = ['C','O','N']\n p.addStyle({\"model\":model,'and':[{'resn':HP},{'atom':BB,'invert':True}]},\n {'stick':{'colorscheme':\"yellowCarbon\",'radius':0.4}})\n p.addStyle({\"model\":model,'and':[{'resn':\"GLY\"},{'atom':'CA'}]},\n {'sphere':{'colorscheme':\"yellowCarbon\",'radius':0.4}})\n p.addStyle({\"model\":model,'and':[{'resn':\"PRO\"},{'atom':['C','O'],'invert':True}]},\n {'stick':{'colorscheme':\"yellowCarbon\",'radius':0.4}}) \n p.addStyle({\"model\":model,'and':[{'resn':HP,'invert':True},{'atom':BB,'invert':True}]},\n {'stick':{'colorscheme':\"whiteCarbon\",'radius':0.4}})\n\n if use_amber:\n pdb_filename = f\"{jobname}_relaxed_{model_name}.pdb\"\n else:\n pdb_filename = f\"{jobname}_unrelaxed_{model_name}.pdb\"\n\n p = py3Dmol.view(js='https://3dmol.org/build/3Dmol.js')\n p.addModel(open(pdb_filename,'r').read(),'pdb')\n if color == \"lDDT\":\n p.setStyle({'cartoon': {'colorscheme': {'prop':'b','gradient': 'roygb','min':0,'max':1}}})\n elif color == \"rainbow\":\n p.setStyle({'cartoon': {'color':'spectrum'}})\n else:\n p.setStyle({'cartoon':{}})\n\n if show_sidechains: sidechain(p)\n if show_mainchain: mainchain(p)\n p.zoomTo()\n return p.show()\n\ninteract(show_pdb,\n model_name=ipywidgets.Dropdown(options=model_params.keys(), value='model_1'),\n show_sidechains=ipywidgets.Checkbox(value=False),\n show_mainchain=ipywidgets.Checkbox(value=False),\n color=ipywidgets.Dropdown(options=['None', 'rainbow', 'lDDT'], value='lDDT'))",
"_____no_output_____"
],
[
"#@title Download result\n!tar cfz $jobname\".result.tar.gz\" $jobname\"_\"*\"relaxed_model_\"*\".pdb\" $jobname\"_lDDT.png\"\nfrom google.colab import files\nfiles.download(f\"{jobname}.result.tar.gz\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b2aa319ad60bf79f9b7cfbc8c1b399d0987010 | 408,634 | ipynb | Jupyter Notebook | example/feature_overview.ipynb | eigensteve/pysindy | 0456bed59d63f5d6b3d5937cedd341d7f7644357 | [
"MIT"
] | 7 | 2020-04-02T00:19:29.000Z | 2021-11-02T07:22:28.000Z | example/feature_overview.ipynb | eigensteve/pysindy | 0456bed59d63f5d6b3d5937cedd341d7f7644357 | [
"MIT"
] | null | null | null | example/feature_overview.ipynb | eigensteve/pysindy | 0456bed59d63f5d6b3d5937cedd341d7f7644357 | [
"MIT"
] | null | null | null | 391.411877 | 129,068 | 0.939562 | [
[
[
"# PySINDy Package Feature Overview\n\nThis notebook provides a simple overview of the basic functionality of the PySINDy software package. In addition to demonstrating the basic usage for fitting a SINDy model, we demonstrate several means of customizing the SINDy fitting procedure. These include different forms of input data, different optimization methods, different differentiation methods, and custom feature libraries.",
"_____no_output_____"
]
],
[
[
"import warnings\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nfrom scipy.integrate import odeint\nfrom sklearn.linear_model import Lasso\n\nimport pysindy as ps\n\n%matplotlib inline\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"# Basic usage",
"_____no_output_____"
]
],
[
[
"def lorenz(z, t):\n return [\n 10 * (z[1] - z[0]),\n z[0] * (28 - z[2]) - z[1],\n z[0] * z[1] - (8 / 3) * z[2]\n ]",
"_____no_output_____"
]
],
[
[
"## Train the model",
"_____no_output_____"
]
],
[
[
"dt = .002\n\nt_train = np.arange(0, 10, dt)\nx0_train = [-8, 8, 27]\nx_train = odeint(lorenz, x0_train, t_train)",
"_____no_output_____"
],
[
"model = ps.SINDy()\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Assess results on a test trajectory",
"_____no_output_____"
]
],
[
[
"t_test = np.arange(0, 15, dt)\nx0_test = np.array([8, 7, 15])\nx_test = odeint(lorenz, x0_test, t_test)\nx_test_sim = model.simulate(x0_test, t_test)\n\nx_dot_test_computed = model.differentiate(x_test, t=dt)\nx_dot_test_predicted = model.predict(x_test)\n\nprint('Model score: %f' % model.score(x_test, t=dt))",
"Model score: 1.000000\n"
]
],
[
[
"## Predict derivatives with learned model",
"_____no_output_____"
]
],
[
[
"fig, axs = plt.subplots(x_test.shape[1], 1, sharex=True, figsize=(7, 9))\nfor i in range(x_test.shape[1]):\n axs[i].plot(t_test, x_dot_test_computed[:, i],\n 'k', label='numerical derivative')\n axs[i].plot(t_test, x_dot_test_predicted[:, i],\n 'r--', label='model prediction')\n axs[i].legend()\n axs[i].set(xlabel='t', ylabel='$\\dot x_{}$'.format(i))\nfig.show()",
"_____no_output_____"
]
],
[
[
"## Simulate forward in time",
"_____no_output_____"
]
],
[
[
"fig, axs = plt.subplots(x_test.shape[1], 1, sharex=True, figsize=(7, 9))\nfor i in range(x_test.shape[1]):\n axs[i].plot(t_test, x_test[:, i], 'k', label='true simulation')\n axs[i].plot(t_test, x_test_sim[:, i], 'r--', label='model simulation')\n axs[i].legend()\n axs[i].set(xlabel='t', ylabel='$x_{}$'.format(i))\n\nfig = plt.figure(figsize=(10, 4.5))\nax1 = fig.add_subplot(121, projection='3d')\nax1.plot(x_test[:, 0], x_test[:, 1], x_test[:, 2], 'k')\nax1.set(xlabel='$x_0$', ylabel='$x_1$',\n zlabel='$x_2$', title='true simulation')\n\nax2 = fig.add_subplot(122, projection='3d')\nax2.plot(x_test_sim[:, 0], x_test_sim[:, 1], x_test_sim[:, 2], 'r--')\nax2.set(xlabel='$x_0$', ylabel='$x_1$',\n zlabel='$x_2$', title='model simulation')\n\nfig.show()",
"_____no_output_____"
]
],
[
[
"# Different forms of input data",
"_____no_output_____"
],
[
"## Single trajectory, pass in collection times",
"_____no_output_____"
]
],
[
[
"model = ps.SINDy()\nmodel.fit(x_train, t=t_train)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Single trajectory, pass in pre-computed derivatives",
"_____no_output_____"
]
],
[
[
"x_dot_true = np.zeros(x_train.shape)\nfor i in range(t_train.size):\n x_dot_true[i] = lorenz(x_train[i], t_train[i])\n \nmodel = ps.SINDy()\nmodel.fit(x_train, t=t_train, x_dot=x_dot_true)\nmodel.print()",
"x0' = -10.000 x0 + 10.000 x1\nx1' = 28.000 x0 + -1.000 x1 + -1.000 x0 x2\nx2' = -2.667 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Multiple trajectories",
"_____no_output_____"
]
],
[
[
"n_trajectories = 20\nx0s = np.array([36, 48, 41]) * (\n np.random.rand(n_trajectories, 3) - 0.5\n) + np.array([0, 0, 25])\nx_train_multi = []\nfor i in range(n_trajectories):\n x_train_multi.append(odeint(lorenz, x0s[i], t_train))\n\nmodel = ps.SINDy()\nmodel.fit(x_train_multi, t=dt, multiple_trajectories=True)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Multiple trajectories, different lengths of time",
"_____no_output_____"
]
],
[
[
"n_trajectories = 20\nx0s = np.array([36, 48, 41]) * (\n np.random.rand(n_trajectories, 3) - 0.5\n) + np.array([0, 0, 25])\nx_train_multi = []\nt_train_multi = []\nfor i in range(n_trajectories):\n n_samples = np.random.randint(500, 1500)\n t = np.arange(0, n_samples * dt, dt)\n x_train_multi.append(odeint(lorenz, x0s[i], t))\n t_train_multi.append(t)\n\nmodel = ps.SINDy()\nmodel.fit(x_train_multi, t=t_train_multi, multiple_trajectories=True)\nmodel.print()",
"x0' = -10.000 x0 + 10.000 x1\nx1' = 27.993 x0 + -0.999 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Discrete time dynamical system (map)",
"_____no_output_____"
]
],
[
[
"def f(x):\n return 3.6 * x * (1 - x)\n\n\nn_steps = 1000\neps = 0.001\nx_train_map = np.zeros((n_steps))\nx_train_map[0] = 0.5\nfor i in range(1, n_steps):\n x_train_map[i] = f(x_train_map[i - 1]) + eps * np.random.randn()\n\nmodel = ps.SINDy(discrete_time=True)\nmodel.fit(x_train_map)\nmodel.print()",
"x0[k+1] = 3.600 x0[k] + -3.600 x0[k]^2\n"
]
],
[
[
"# Optimization options",
"_____no_output_____"
],
[
"## STLSQ - change parameters",
"_____no_output_____"
]
],
[
[
"stlsq_optimizer = ps.STLSQ(threshold=.01, alpha=.5)\n\nmodel = ps.SINDy(optimizer=stlsq_optimizer)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## SR3",
"_____no_output_____"
]
],
[
[
"sr3_optimizer = ps.SR3(threshold=0.1, nu=1)\n\nmodel = ps.SINDy(optimizer=sr3_optimizer)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## LASSO",
"_____no_output_____"
]
],
[
[
"lasso_optimizer = Lasso(alpha=100, fit_intercept=False)\n\nmodel = ps.SINDy(optimizer=lasso_optimizer)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -0.310 x0 x2 + 0.342 x1 x2 + -0.002 x2^2\nx1' = 15.952 x1 + 0.009 x0 x1 + -0.219 x0 x2 + -0.474 x1 x2 + 0.007 x2^2\nx2' = 0.711 x0^2 + 0.533 x0 x1 + -0.005 x1 x2 + -0.119 x2^2\n"
]
],
[
[
"# Differentiation options",
"_____no_output_____"
],
[
"## Pass in pre-computed derivatives",
"_____no_output_____"
]
],
[
[
"x_dot_precomputed = ps.FiniteDifference()._differentiate(x_train, t_train)\n \nmodel = ps.SINDy()\nmodel.fit(x_train, t=t_train, x_dot=x_dot_precomputed)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Drop end points from finite difference computation",
"_____no_output_____"
]
],
[
[
"fd_dropEndpoints = ps.FiniteDifference(drop_endpoints=True)\n \nmodel = ps.SINDy(differentiation_method=fd_dropEndpoints)\nmodel.fit(x_train, t=t_train)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.998 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Smoothed finite difference",
"_____no_output_____"
]
],
[
[
"smoothedFD = ps.SmoothedFiniteDifference()\n \nmodel = ps.SINDy(differentiation_method=smoothedFD)\nmodel.fit(x_train, t=t_train)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 27.992 x0 + -0.998 x1 + -1.000 x0 x2\nx2' = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"# Feature libraries",
"_____no_output_____"
],
[
"## Custom feature names",
"_____no_output_____"
]
],
[
[
"feature_names = ['x', 'y', 'z']\nmodel = ps.SINDy(feature_names=feature_names)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x' = -9.999 x + 9.999 y\ny' = 27.992 x + -0.999 y + -1.000 x z\nz' = -2.666 z + 1.000 x y\n"
]
],
[
[
"## Custom left hand side when printing the model",
"_____no_output_____"
]
],
[
[
"model = ps.SINDy()\nmodel.fit(x_train, t=dt)\nmodel.print(lhs=['dx0/dt', 'dx1/dt', 'dx2/dt'])",
"dx0/dt = -9.999 x0 + 9.999 x1\ndx1/dt = 27.992 x0 + -0.999 x1 + -1.000 x0 x2\ndx2/dt = -2.666 x2 + 1.000 x0 x1\n"
]
],
[
[
"## Customize polynomial library",
"_____no_output_____"
]
],
[
[
"poly_library = ps.PolynomialLibrary(include_interaction=False)\n\nmodel = ps.SINDy(feature_library=poly_library)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = -72.092 1 + -13.015 x0 + 9.230 x1 + 9.452 x2 + 0.598 x0^2 + -0.289 x1^2 + -0.247 x2^2\nx2' = -41.053 1 + 0.624 x0 + -0.558 x1 + 2.866 x2 + 1.001 x0^2 + 0.260 x1^2 + -0.176 x2^2\n"
]
],
[
[
"## Fourier library",
"_____no_output_____"
]
],
[
[
"fourier_library = ps.FourierLibrary(n_frequencies=3)\n\nmodel = ps.SINDy(feature_library=fourier_library)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = 0.361 sin(1 x0) + 1.015 cos(1 x0) + 6.068 cos(1 x1) + -2.618 sin(1 x2) + 4.012 cos(1 x2) + -0.468 cos(2 x0) + -0.326 sin(2 x1) + -0.883 cos(2 x1) + 0.353 sin(2 x2) + 0.281 cos(2 x2) + 0.436 sin(3 x0) + 0.134 cos(3 x0) + 2.860 sin(3 x1) + 0.780 cos(3 x1) + 2.413 sin(3 x2) + -1.869 cos(3 x2)\nx1' = -2.693 sin(1 x0) + -4.096 cos(1 x0) + -0.425 sin(1 x1) + 0.466 cos(1 x1) + -4.697 sin(1 x2) + 7.946 cos(1 x2) + -1.108 sin(2 x0) + -5.631 cos(2 x0) + -1.089 sin(2 x1) + -1.079 cos(2 x1) + 3.288 sin(2 x2) + 1.151 cos(2 x2) + 1.949 sin(3 x0) + 4.829 cos(3 x0) + -0.555 sin(3 x1) + 0.635 cos(3 x1) + 4.257 sin(3 x2) + -3.065 cos(3 x2)\nx2' = 5.015 sin(1 x0) + 4.775 cos(1 x0) + 5.615 sin(1 x1) + -3.112 cos(1 x1) + -1.019 sin(1 x2) + 0.345 cos(1 x2) + 2.535 sin(2 x0) + 2.008 cos(2 x0) + -4.250 sin(2 x1) + -13.784 cos(2 x1) + -0.797 sin(2 x2) + 2.578 sin(3 x0) + -0.399 cos(3 x0) + 5.208 sin(3 x1) + -8.286 cos(3 x1) + 0.720 sin(3 x2) + -0.229 cos(3 x2)\n"
]
],
[
[
"## Fully custom library",
"_____no_output_____"
]
],
[
[
"library_functions = [\n lambda x : np.exp(x),\n lambda x : 1./x,\n lambda x : x,\n lambda x,y : np.sin(x+y)\n]\nlibrary_function_names = [\n lambda x : 'exp(' + x + ')',\n lambda x : '1/' + x,\n lambda x : x,\n lambda x,y : 'sin(' + x + ',' + y + ')'\n]\ncustom_library = ps.CustomLibrary(\n library_functions=library_functions, function_names=library_function_names\n)\n\nmodel = ps.SINDy(feature_library=custom_library)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = 1.407 1/x0 + -48.091 1/x2 + -12.472 x0 + 9.296 x1 + 0.381 x2 + 0.879 sin(x0,x1) + 1.896 sin(x0,x2) + -0.468 sin(x1,x2)\nx2' = 1.094 1/x0 + -7.674 1/x2 + 0.102 x0 + 0.157 x1 + 3.603 sin(x0,x1) + -3.323 sin(x0,x2) + -3.047 sin(x1,x2)\n"
]
],
[
[
"## Fully custom library, default function names",
"_____no_output_____"
]
],
[
[
"library_functions = [\n lambda x : np.exp(x),\n lambda x : 1./x,\n lambda x : x,\n lambda x,y : np.sin(x+y)\n]\ncustom_library = ps.CustomLibrary(library_functions=library_functions)\n\nmodel = ps.SINDy(feature_library=custom_library)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -9.999 f2(x0) + 9.999 f2(x1)\nx1' = 1.407 f1(x0) + -48.091 f1(x2) + -12.472 f2(x0) + 9.296 f2(x1) + 0.381 f2(x2) + 0.879 f3(x0,x1) + 1.896 f3(x0,x2) + -0.468 f3(x1,x2)\nx2' = 1.094 f1(x0) + -7.674 f1(x2) + 0.102 f2(x0) + 0.157 f2(x1) + 3.603 f3(x0,x1) + -3.323 f3(x0,x2) + -3.047 f3(x1,x2)\n"
]
],
[
[
"## Identity library",
"_____no_output_____"
]
],
[
[
"identity_library = ps.IdentityLibrary()\n\nmodel = ps.SINDy(feature_library=identity_library)\nmodel.fit(x_train, t=dt)\nmodel.print()",
"x0' = -9.999 x0 + 9.999 x1\nx1' = -12.451 x0 + 9.314 x1 + 0.299 x2\nx2' = 0.159 x0 + 0.101 x1\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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b2afb8431ffd637e3e1a41aa786df1440b7aa4 | 8,983 | ipynb | Jupyter Notebook | basics/example solutions/Latin square SAT.ipynb | jochemsoons/KRR-course-2021 | 2af108175253658317b865ca7e5fc1d442a089ea | [
"MIT"
] | 7 | 2021-05-31T07:00:21.000Z | 2022-03-10T15:48:30.000Z | basics/example solutions/Latin square SAT.ipynb | jochemsoons/KRR-course-2021 | 2af108175253658317b865ca7e5fc1d442a089ea | [
"MIT"
] | null | null | null | basics/example solutions/Latin square SAT.ipynb | jochemsoons/KRR-course-2021 | 2af108175253658317b865ca7e5fc1d442a089ea | [
"MIT"
] | 25 | 2021-06-01T11:22:41.000Z | 2021-12-07T02:50:46.000Z | 32.197133 | 134 | 0.452076 | [
[
[
"from pysat.formula import CNF\nfrom pysat.solvers import MinisatGH",
"_____no_output_____"
],
[
"from itertools import combinations\n'''\nWe make use of a class that we give facts (the setup of the board) to encode the problem in SAT.\nInstead of A-E we make use of the numbers 1-5\nWe number each cell 1-25 starting from the top left corner and going row by row. \nThen for each square we have 5 possibilities. Cell 1 having value 1 will be encoded by variable 1.\nCell 1 having value 2 will be encoded by variable 2. Then cell 2 having value 1 will be encoded by 6 etc..\n\n'''\nclass LatinSquare():\n def __init__(self, facts):\n self.formula = CNF()\n self.board = self.create_board()\n #First we encode that each cell must have exactly 1 number between 1 and 5 (A-E)\n self.encode_exact_1_number()\n \n # Each row contains distinct values\n self.row_unique()\n # Each column contains distinct values\n self.column_unique()\n # Add the facts to the model \n self.add_facts(facts)\n\n \n def create_board(self):\n '''\n creates the board, used to quickly translate from the variable encoding to tupple encoding\n E.g. key: (3,4) has value: 14\n '''\n board = {}\n for cell in range(25):\n possible_values_cell = [cell * 5 + i for i in range(1,6)]\n\n for i in range(1,6):\n board[cell * 5 + i ] = (cell, i) # tuple row, columns\n return board\n \n \n def encode_exact_1_number(self):\n # Each cell must have one unique value. \n for cell in range(25):\n possible_values_cell = [cell * 5 + i for i in range(1,6)]\n self.formula.append(possible_values_cell)\n #Next encode that each cell must have at most 1 possible value.\n self.add_exclusion_rule([possible_values_cell])\n \n def row_unique(self):\n # Each row must have distinct values. This get encoded by saying that 1 until 5 must appear exactly once in each row.\n for i in range(1,6):\n rows = self.get_row_one_value(i)\n self.add_exclusion_rule(rows)\n \n def column_unique(self):\n # Similar to row_unique. \n for i in range(1,6):\n columns = self.get_column_one_value(i)\n self.add_exclusion_rule(columns)\n \n def add_facts(self, facts):\n board_inverse = {value: key for key, value in self.board.items()}\n \n for fact in facts:\n self.formula.append([board_inverse[fact]])\n \n \n def add_exclusion_rule(self, lists):\n '''\n Given a list of lists, will add a pairwise exclusion rule to the formula.\n \n E.g:\n [[1,2, 3], [5,6]] will add the rules:\n [-1, -2], [-1, -3], [-2, -3] and [-5,-6] to the formula\n This ensures that not both values can be true at the same time. \n '''\n for l in lists:\n # Pairswise exclusion\n for combination in combinations(l, 2):\n p1 = combination[0]\n p2 = combination[1]\n # not both can be true at the same time so at least one must be false.\n both_not_true = [-p1, -p2]\n self.formula.append(both_not_true)\n \n \n \n def get_row_one_value(self, value):\n rows_value = []\n possible_values_row = []\n for cell in range(25):\n possible_values_row.append(cell * 5 + value)\n if (cell + 1) % 5 == 0:\n rows_value.append(possible_values_row)\n \n possible_values_row = []\n return rows_value\n \n def get_column_one_value(self, value):\n columns_value = [ [] for i in range(5)]\n possible_values_row = []\n for cell in range(25):\n index = cell % 5 \n columns_value[index].append(cell * 5 + value)\n return columns_value\n\n \n def get_solutions(self):\n solver = MinisatGH()\n solver.append_formula(self.formula)\n for i, model in enumerate(solver.enum_models(), 1):\n print(\"MODEL #{}:\".format(i))\n filled_in_values = []\n for lit in model:\n if lit > 0:\n filled_in_values.append(lit)\n values = [self.board[value] for value in filled_in_values]\n \n self.pretty_print(values)\n def pretty_print(self, values):\n string = \"\"\n for expected_cell, (cell,value) in zip([i for i in range(25)], values):\n assert expected_cell == cell, \"expected_cell != actual cell, {}, {}\".format(expected_cell, cell)\n string += \"|\" + str(value) + \"|\"\n if (cell + 1) % 5 == 0:\n string += \"\\n\"\n print(string)\n \n\n ",
"_____no_output_____"
],
[
"def pretty_print(facts):\n string = \"\"\n index = 0\n (cell, value) = facts[index]\n for expected_cell in range(25):\n if expected_cell == cell:\n string += \"|\" + str(value) + \"|\"\n index += 1\n if index < len(facts):\n (cell, value) = facts[index]\n else:\n string += \"|?|\"\n if (expected_cell + 1) % 5 == 0:\n string += \"\\n\"\n print(string)",
"_____no_output_____"
],
[
"# This is the board that we are given:\nfacts = [\n (0,1),\n (1, 3),\n (7,5),\n (9,1),\n (12,2),\n (15, 4),\n (17, 3),\n (23, 5),\n (24, 3),\n \n]\npretty_print(facts)\n\n",
"|1||3||?||?||?|\n|?||?||5||?||1|\n|?||?||2||?||?|\n|4||?||3||?||?|\n|?||?||?||5||3|\n\n"
],
[
"# Initialize with the given facts\nlatin_square = LatinSquare(facts)",
"_____no_output_____"
],
[
"# get the solutions (which in this case is unique)\nlatin_square.get_solutions()",
"MODEL #1:\n|1||3||4||2||5|\n|3||2||5||4||1|\n|5||1||2||3||4|\n|4||5||3||1||2|\n|2||4||1||5||3|\n\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b2afc60c44f47859b2b03cf8424969d7da25d4 | 83,107 | ipynb | Jupyter Notebook | Data Cleaning(Part-1).ipynb | Jyotiranjan404/data_cleaning-part-1- | ecf294b95ea7aeeba88cdfe8577ca40638b7b98e | [
"Apache-2.0"
] | null | null | null | Data Cleaning(Part-1).ipynb | Jyotiranjan404/data_cleaning-part-1- | ecf294b95ea7aeeba88cdfe8577ca40638b7b98e | [
"Apache-2.0"
] | null | null | null | Data Cleaning(Part-1).ipynb | Jyotiranjan404/data_cleaning-part-1- | ecf294b95ea7aeeba88cdfe8577ca40638b7b98e | [
"Apache-2.0"
] | null | null | null | 34.441359 | 153 | 0.34322 | [
[
[
"# Data cleaning\n* Data cleaning is the process of fixing or removing incorrect, corrupted, incorrectly formatted, duplicate, or incomplete data within a dataset...",
"_____no_output_____"
]
],
[
[
"# Task:\n# Delete unnecessary Rows and Columns\n# Clean Rank with value '0'.\n# Clean '-' values with column mean\n# Clean '.' with column mean\n# Convert Lending Asset Size = Category like 0, 1, 2 etc based on levels available\n# Make sure every column in its respective data type.\n# Save the model as csv file",
"_____no_output_____"
],
[
"import pandas as pd\ndf=pd.read_csv(r'C:\\Users\\Jyotiranjan padhi\\Desktop\\bepec files\\Lending_Data.csv')\ndf.head()",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"# Task-1",
"_____no_output_____"
]
],
[
[
"# Delete unnecessary Rows and Columns\ndel df['Unnamed: 10'] #Here all values are NaN.",
"_____no_output_____"
],
[
"#Here i used drop(),in order to delete the rows\n#I need to mention index name, after that i need to delete row wise,so i put axis=0\ndf=df.drop([0,94,95,96],axis=0)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"# Task-2",
"_____no_output_____"
]
],
[
[
"# Clean Rank with value '0'\ndf[\"Rank\"]=df[\"Rank\"].replace(\"NR\",0)",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"# Task-3",
"_____no_output_____"
]
],
[
[
"# Clean '-' values with column mean\nimport numpy as np\ndf=df.replace('-', np.nan)\ndf=df.replace(' - ', np.nan)",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
],
[
"df['Amount ($1,000)'].unique()",
"_____no_output_____"
],
[
"#Here you can see like there is some \",\" in between integers.i need to remove that",
"_____no_output_____"
],
[
"df.columns",
"_____no_output_____"
],
[
"columns=['TA Ratio1','TBL Ratio1','Amount ($1,000)','Number ',\"Amount ($1,000).1\",'Number .1','Amount ($1,000).2','Number .2']\nfor i in columns:\n df[i]=df[i].replace(to_replace='[^0-9]',value=\"\",regex=True)",
"_____no_output_____"
],
[
"df['Amount ($1,000)'].unique()",
"_____no_output_____"
],
[
"#Now you can see like there is no \",\" in between integers,so i can move further",
"_____no_output_____"
],
[
"#I need to covert all into int format\nfor i in columns:\n df[i]=pd.to_numeric(df[i])",
"_____no_output_____"
],
[
"#Here i am filling all null values with columns mean\nfor i in columns:\n mean=df[i].mean()\n df[i]=df[i].fillna(mean)\ndf.tail()",
"_____no_output_____"
]
],
[
[
"# Task-4",
"_____no_output_____"
]
],
[
[
"# Clean '.' with column mean\ndf['CC Amount/TA1'].unique()",
"_____no_output_____"
],
[
"df['CC Amount/TA1']=df['CC Amount/TA1'].replace(' . ',np.nan)",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
],
[
"df['CC Amount/TA1']=pd.to_numeric(df['CC Amount/TA1'])",
"_____no_output_____"
],
[
"df['CC Amount/TA1']=df['CC Amount/TA1'].fillna(df['CC Amount/TA1'].mean())",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"# Task-5",
"_____no_output_____"
]
],
[
[
"# Convert Lending Asset Size = Category like 0, 1, 2 etc based on levels available\ndf['Lender Asset Size'].unique()",
"_____no_output_____"
],
[
"#Here i used lamda function to conver these to Category \ndf['Lender Asset Size']=df['Lender Asset Size'].apply(lambda x:0 if x=='>$10B '\n else(0 if x==' >$10B '\n else 1 if x==' $10B-$50B '\n else 2))",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"#Another way\n\"\"\"\"Lending_data['Lender Asset Size']=Lending_data['Lender Asset Size'].replace([' >$50B ', ' $10B-$50B ',\n ' >$10B ', '>$50B ',\n '>$10B '],[2,1,0,2,0])\"\"\"\"\"",
"_____no_output_____"
],
[
"#Another way\n#We can use label encoding as well\n\"\"\"\"from sklearn.preprocessing import LabelEncoder\nLabel_encoder=LabelEncoder()\ndf=Label_encoder.fit(Lending_data['Lender Asset Size'])\nLending_data['Lender Asset Size']=df.transform(Lending_data['Lender Asset Size'])\"\"\"\"\"",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.tail()",
"_____no_output_____"
]
],
[
[
"# Task-6",
"_____no_output_____"
]
],
[
[
"# Make sure every column in its respective data type.\ndf.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 93 entries, 1 to 93\nData columns (total 13 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Name of Lending Institution 93 non-null object \n 1 HQ State 93 non-null object \n 2 Rank 93 non-null object \n 3 TA Ratio1 93 non-null float64\n 4 TBL Ratio1 93 non-null float64\n 5 Amount ($1,000) 93 non-null float64\n 6 Number 93 non-null float64\n 7 Lender Asset Size 93 non-null int64 \n 8 Amount ($1,000).1 93 non-null float64\n 9 Number .1 93 non-null float64\n 10 Amount ($1,000).2 93 non-null float64\n 11 Number .2 93 non-null float64\n 12 CC Amount/TA1 93 non-null float64\ndtypes: float64(9), int64(1), object(3)\nmemory usage: 12.7+ KB\n"
],
[
"df['Rank']=pd.to_numeric(df['Rank'])",
"_____no_output_____"
],
[
"df['Lender Asset Size']=df['Lender Asset Size'].astype(\"object\")",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 93 entries, 1 to 93\nData columns (total 13 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Name of Lending Institution 93 non-null object \n 1 HQ State 93 non-null object \n 2 Rank 93 non-null int64 \n 3 TA Ratio1 93 non-null float64\n 4 TBL Ratio1 93 non-null float64\n 5 Amount ($1,000) 93 non-null float64\n 6 Number 93 non-null float64\n 7 Lender Asset Size 93 non-null object \n 8 Amount ($1,000).1 93 non-null float64\n 9 Number .1 93 non-null float64\n 10 Amount ($1,000).2 93 non-null float64\n 11 Number .2 93 non-null float64\n 12 CC Amount/TA1 93 non-null float64\ndtypes: float64(9), int64(1), object(3)\nmemory usage: 12.7+ KB\n"
]
],
[
[
"# Task-7",
"_____no_output_____"
]
],
[
[
"# Save this model\ndf.to_csv(r\"C:\\Users\\Jyotiranjan padhi\\Desktop\\data folder\\updated_Lending_Data.csv\")",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b2b0fe1b0bf60aa09a3a7df12e4aa4a20b522e | 33,400 | ipynb | Jupyter Notebook | notebooks/BillDwyer/EDA/EDA_twitter.ipynb | datakind/Mar21-vaccine-uptake | 97bcb8204b6cdef9cd1286a0cfecd20db79fb63b | [
"MIT"
] | 11 | 2021-03-01T03:51:12.000Z | 2022-01-17T16:15:36.000Z | BillDwyer/EDA/EDA_twitter.ipynb | datakind/Mar21-vaccine-uptake | 97bcb8204b6cdef9cd1286a0cfecd20db79fb63b | [
"MIT"
] | 16 | 2021-03-05T19:11:54.000Z | 2021-03-06T22:45:26.000Z | BillDwyer/EDA/EDA_twitter.ipynb | datakind/Mar21-vaccine-uptake | 97bcb8204b6cdef9cd1286a0cfecd20db79fb63b | [
"MIT"
] | 4 | 2021-03-05T18:27:53.000Z | 2021-03-06T20:39:53.000Z | 41.854637 | 7,160 | 0.513952 | [
[
[
"%config IPCompleter.greedy=True\nimport pandas as pd\nimport pandas_profiling\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"data = pd.read_csv('../../data/twitter/twitter_data_cleaned.csv')",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"hashtag_regex = re.compile('#\\S*(?:\\s+|$)')",
"_____no_output_____"
],
[
"hashtag_regex.findall('test #foo #bar potato lorem #ipsum')",
"_____no_output_____"
],
[
"findHashtags = lambda x :hashtag_regex.findall(x)",
"_____no_output_____"
],
[
"data['hashtags'] = data.full_text.apply(findHashtags)",
"_____no_output_____"
],
[
"data.head()",
"_____no_output_____"
],
[
"checkifempty = lambda x : not x\ntweet_with_hashtags = data[data['hashtags'].apply(checkifempty)]",
"_____no_output_____"
],
[
"x = data['hashtags'].apply(lambda x: len(x))\ny = data['retweet_count']\nplt.xlim(0, 5);\nplt.plot(x, y, 'o', color='black');\n\n",
"_____no_output_____"
],
[
"print(int(data.sort_values(['retweet_count'], ascending=False)['tweet_id'][0]))",
"1364223054851813376\n"
],
[
"print(int(data.sort_values(['retweet_count'], ascending=False)['user_id'][0]))",
"29501253\n"
],
[
"data.sort_values(['retweet_count'], ascending=False).head(10)",
"_____no_output_____"
],
[
"data_sorted = data.sort_values(['retweet_count'], ascending=False).reset_index()",
"_____no_output_____"
],
[
"int(data_sorted['tweet_id'][3])",
"_____no_output_____"
],
[
"int(data_sorted['user_id'][3])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b2bfb33899f0c0162bcae7f4c141e20d0b2ca2 | 16,339 | ipynb | Jupyter Notebook | exploring_tensorflow_probability.ipynb | sselonick/tensorflow-probability-fun | d3e3130e919373dea9e67c3435c9eaeade52b8c2 | [
"MIT"
] | null | null | null | exploring_tensorflow_probability.ipynb | sselonick/tensorflow-probability-fun | d3e3130e919373dea9e67c3435c9eaeade52b8c2 | [
"MIT"
] | null | null | null | exploring_tensorflow_probability.ipynb | sselonick/tensorflow-probability-fun | d3e3130e919373dea9e67c3435c9eaeade52b8c2 | [
"MIT"
] | null | null | null | 52.536977 | 7,562 | 0.700288 | [
[
[
"# Some Experimentation with Tensorflow Probability",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom tensorflow_probability import edward2 as ed\nimport tensorflow_probability as tfp\nimport tensorflow as tf\nimport numpy as np",
"\nWARNING: The TensorFlow contrib module will not be included in TensorFlow 2.0.\nFor more information, please see:\n * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n * https://github.com/tensorflow/addons\nIf you depend on functionality not listed there, please file an issue.\n\n"
],
[
"import sys\nsys.executable",
"_____no_output_____"
],
[
"data = pd.read_csv('fatal_airline_accidents.csv')",
"_____no_output_____"
],
[
"y = np.array(data['accidents'])\ny = tf.convert_to_tensor(y, dtype=tf.float32)\n",
"_____no_output_____"
],
[
"alpha=tf.convert_to_tensor(np.array([5.0]*10),dtype=tf.float32)\nbeta=tf.convert_to_tensor(np.array([2.0]*10),dtype=tf.float32)\ntfd = tfp.distributions",
"_____no_output_____"
],
[
"alpha, beta",
"_____no_output_____"
],
[
"def accidents_model_prior_predictive_dist(alpha, beta):\n theta = ed.Gamma(concentration=alpha, rate=beta, name=\"theta\")\n accidents = ed.Poisson(rate=theta,name=\"accidents\")\n return accidents\n \naccidents_gen = accidents_model_prior_predictive_dist(alpha=alpha, beta=beta)\n\n",
"_____no_output_____"
],
[
"# inital state\ninitial_state = tf.random_gamma([10], alpha=5.0, beta=2.0, dtype=tf.float32)\n\n\n\n",
"_____no_output_____"
],
[
"result = []\nwith tf.Session() as sess:\n for i in range(10000):\n accidents_ = sess.run(accidents_gen)\n result.append(accidents_)",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"print('Mean: %s Var: %s ' % (np.mean(result), np.var(result) ) )",
"Mean: 2.49438 Var: 3.7474282 \n"
],
[
"plt.hist(np.array(result).flatten(),bins=15)\nplt.show()",
"_____no_output_____"
],
[
"log_joint = ed.make_log_joint_fn(accidents_model_prior_predictive_dist)\n\n\n\ndef target_log_prob_fn(theta):\n \"\"\"Target log-probability as a function of states.\"\"\"\n return log_joint(alpha, beta, theta=theta, accidents=y) ",
"_____no_output_____"
],
[
"# Initialize the HMC transition kernel.\nnum_samples = int(10e3)\nnum_burnin_steps = int(1e3)\n\nhmc = tfp.mcmc.HamiltonianMonteCarlo(\n target_log_prob_fn=target_log_prob_fn,\n num_leapfrog_steps=5,\n step_size=0.01)",
"_____no_output_____"
],
[
"samples, kernel_results = tfp.mcmc.sample_chain(\n num_results=num_samples,\n current_state=[initial_state],\n num_burnin_steps=num_burnin_steps,\n kernel=hmc)\n\n\n",
"_____no_output_____"
],
[
"# sample from posterior\nwith tf.Session() as sess:\n samples, is_accepted_ = sess.run([samples, kernel_results.is_accepted])\n accepted = np.sum(is_accepted_)\n print(\"pct accepted: %s\"%(accepted / num_samples))\n\n\n\nprint(samples)\n",
"pct accepted: 0.9999\n[array([[ 6.746139 , 7.760075 , 9.008763 , ..., 5.072694 , 4.4772816,\n 6.278378 ],\n [ 6.7090974, 7.7435775, 8.994854 , ..., 5.026912 , 4.548915 ,\n 6.35964 ],\n [ 6.674753 , 7.727055 , 9.020736 , ..., 5.053764 , 4.6378536,\n 6.350527 ],\n ...,\n [10.115327 , 11.060875 , 10.204517 , ..., 8.380159 , 8.087912 ,\n 8.548069 ],\n [10.151785 , 11.03296 , 10.163288 , ..., 8.402973 , 8.165112 ,\n 8.4707155],\n [10.17069 , 10.995087 , 10.170074 , ..., 8.397022 , 8.152656 ,\n 8.500627 ]], dtype=float32)]\n"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b2c596beaef7c53d5d3914f57a171b305156d1 | 2,112 | ipynb | Jupyter Notebook | examples/reference/panes/JPG.ipynb | rupakgoyal/panel- | 4e1e01e1766ebfc2fc1efb409734fd51efc60c01 | [
"BSD-3-Clause"
] | 1 | 2019-10-15T13:21:20.000Z | 2019-10-15T13:21:20.000Z | examples/reference/panes/JPG.ipynb | rupakgoyal/panel- | 4e1e01e1766ebfc2fc1efb409734fd51efc60c01 | [
"BSD-3-Clause"
] | null | null | null | examples/reference/panes/JPG.ipynb | rupakgoyal/panel- | 4e1e01e1766ebfc2fc1efb409734fd51efc60c01 | [
"BSD-3-Clause"
] | 2 | 2020-01-02T08:57:18.000Z | 2020-11-04T06:57:49.000Z | 28.16 | 212 | 0.585227 | [
[
[
"import panel as pn\n\npn.extension()",
"_____no_output_____"
]
],
[
[
"The ``JPG`` pane embeds a ``.jpg`` or ``.jpeg`` image file in a panel if provided a local path, or it will link to a remote image if provided a URL.\n\n#### Parameters:\n\nFor layout and styling related parameters see the [customization user guide](../../user_guide/Customization.ipynb).\n\n* **``embed``** (boolean, default=False): If given a URL to an image this determines whether the image will be embedded as base64 or merely linked to.\n* **``object``** (str or object): The JPEG file to display. Can be a string pointing to a local or remote file, or an object with a ``_repr_jpg_`` method.\n* **``style``** (dict): Dictionary specifying CSS styles\n\n___",
"_____no_output_____"
],
[
"The ``JPG`` pane can be pointed at any local or remote ``.jpg`` file. If given a URL starting with ``http`` or ``https``, the ``embed`` parameter determines whether the image will be embedded or linked to:",
"_____no_output_____"
]
],
[
[
"jpg_pane = pn.pane.JPG('https://upload.wikimedia.org/wikipedia/commons/b/b2/JPEG_compression_Example.jpg', width=500)\n\njpg_pane",
"_____no_output_____"
]
],
[
[
"Like any other pane, the ``JPG`` pane can be updated by setting the ``object`` parameter:",
"_____no_output_____"
]
],
[
[
"jpg_pane.object = 'https://upload.wikimedia.org/wikipedia/commons/3/38/JPEG_example_JPG_RIP_001.jpg'",
"_____no_output_____"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b2c5be1381411ea7c8696a385b376487826e53 | 82,629 | ipynb | Jupyter Notebook | web/10/Solving_equations.ipynb | lnc394/lectures-2021 | c8447d7c81b8d0f8dec035cbba518c0b39859e00 | [
"MIT"
] | null | null | null | web/10/Solving_equations.ipynb | lnc394/lectures-2021 | c8447d7c81b8d0f8dec035cbba518c0b39859e00 | [
"MIT"
] | null | null | null | web/10/Solving_equations.ipynb | lnc394/lectures-2021 | c8447d7c81b8d0f8dec035cbba518c0b39859e00 | [
"MIT"
] | null | null | null | 26.585907 | 8,456 | 0.517603 | [
[
[
"# Lecture 10: Solving equations",
"_____no_output_____"
],
[
"[Download on GitHub](https://github.com/NumEconCopenhagen/lectures-2021)\n\n[<img src=\"https://mybinder.org/badge_logo.svg\">](https://mybinder.org/v2/gh/NumEconCopenhagen/lectures-2021/master?urlpath=lab/tree/10/Solving_equations.ipynb)",
"_____no_output_____"
],
[
"1. [Systems of linear equations](#Systems-of-linear-equations)\n2. [Symbolically](#Symbolically)\n3. [Non-linear equations - one dimensional](#Non-linear-equations---one-dimensional)\n4. [Solving non-linear equations (multi-dimensional)](#Solving-non-linear-equations-(multi-dimensional))\n5. [Summary](#Summary)\n",
"_____no_output_____"
],
[
"You will learn about working with matrices and linear algebra (**scipy.linalg**), including solving systems of linear equations. You will learn to find roots of linear and non-linear equations both numerically (**scipy.optimize**) and symbolically (**sympy**).",
"_____no_output_____"
],
[
"**Note:** The algorithms written here are meant to be illustrative. The scipy implementations are always both the *fastest* and the *safest* choice.",
"_____no_output_____"
],
[
"**Links:**\n\n1. **scipy.linalg:** [overview](https://docs.scipy.org/doc/scipy/reference/linalg.html) + [tutorial](https://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html)\n2. **sympy:** [overview](https://docs.sympy.org/latest/index.html) + [tutorial](https://docs.sympy.org/latest/tutorial/index.html#tutorial)\n3. **scipy.optimize:** [overview](https://docs.scipy.org/doc/scipy/reference/optimize.html) + [turtorial](https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html)",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn-whitegrid')\nimport ipywidgets as widgets\nimport time\nfrom scipy import linalg\nfrom scipy import optimize\nimport sympy as sm\nfrom IPython.display import display\n\n# local module for linear algebra\n%load_ext autoreload\n%autoreload 2\nimport numecon_linalg",
"_____no_output_____"
]
],
[
[
"<a id=\"Systems-of-linear-equations\"></a>\n\n# 1. Systems of linear equations",
"_____no_output_____"
],
[
"## 1.1 Introduction",
"_____no_output_____"
],
[
"We consider **matrix equations** with $n$ equations and $n$ unknowns:\n\n$$\n\\begin{aligned}\nAx = b \\Leftrightarrow\n\\begin{bmatrix}a_{11} & a_{12} & \\cdots & a_{1n}\\\\\na_{21} & a_{22} & \\cdots & a_{2n}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\na_{n1} & a_{n2} & \\cdots & a_{nn}\n\\end{bmatrix}\\cdot\\begin{bmatrix}x_{1}\\\\\nx_{2}\\\\\n\\vdots\\\\\nx_{n}\n\\end{bmatrix} & = \\begin{bmatrix}b_{1}\\\\\nb_{2}\\\\\n\\vdots\\\\\nb_{n}\n\\end{bmatrix}\n\\end{aligned}\n$$\n\nwhere $A$ is a square parameter matrix, $b$ is a parameter vector, and $x$ is the vector of unknowns.",
"_____no_output_____"
],
[
"A specific **example** could be:\n\n$$ \n\\begin{aligned}\nAx = b \\Leftrightarrow\n\\begin{bmatrix} \n3 & 2 & 0 \\\\ \n1 & -1 & 0 \\\\\n0 & 5 & 1\n\\end{bmatrix} \\cdot\n\\begin{bmatrix} \nx_1 \\\\ \nx_2 \\\\\nx_3\n\\end{bmatrix} \\,=\\,\n\\begin{bmatrix} \n2 \\\\ \n4 \\\\\n-1\n\\end{bmatrix} \n\\end{aligned}\n$$",
"_____no_output_____"
],
[
"**How to solve this?**",
"_____no_output_____"
]
],
[
[
"A = np.array([[3.0, 2.0, 0.0], [1.0, -1.0, 0], [0.0, 5.0, 1.0]])\nb = np.array([2.0, 4.0, -1.0])",
"_____no_output_____"
]
],
[
[
"Trial-and-error:",
"_____no_output_____"
]
],
[
[
"Ax = A@[2,-1,9] # @ is matrix multiplication\nprint('A@x: ',Ax)\n\nif np.allclose(Ax,b): \n print('solution found')\nelse:\n print('solution not found')",
"A@x: [4. 3. 4.]\nsolution not found\n"
]
],
[
[
"**Various matrix operations:**",
"_____no_output_____"
]
],
[
[
"A.T # transpose",
"_____no_output_____"
],
[
"np.diag(A) # diagonal",
"_____no_output_____"
],
[
"np.tril(A) # lower triangular matrix",
"_____no_output_____"
],
[
"np.triu(A) # upper triangular matrix",
"_____no_output_____"
],
[
"B = A.copy()\nnp.fill_diagonal(B,0) # fill diagonal with zeros\nprint(B)",
"[[0. 2. 0.]\n [1. 0. 0.]\n [0. 5. 0.]]\n"
],
[
"linalg.inv(A) # inverse",
"_____no_output_____"
],
[
"linalg.eigvals(A) # eigen values",
"_____no_output_____"
]
],
[
[
"## 1.2 Direct solution with Gauss-Jordan elimination",
"_____no_output_____"
],
[
"Consider the column stacked matrix:\n\n$$\nX=[A\\,|\\,b]=\\begin{bmatrix}a_{11} & a_{12} & \\cdots & a_{1n} & b_{1}\\\\\na_{21} & a_{22} & \\cdots & a_{2n} & b_{2}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots & \\vdots\\\\\na_{n1} & a_{n2} & \\cdots & a_{nn} & b_{n}\n\\end{bmatrix}\n$$",
"_____no_output_____"
],
[
"Find the **row reduced echelon form** by performing row operations, i.e.\n\n1. Multiply row with constant\n2. Swap rows\n3. Add one row to another row,",
"_____no_output_____"
],
[
"until the $A$ part of the matrix is the identity matrix.",
"_____no_output_____"
],
[
"**Manually:**",
"_____no_output_____"
]
],
[
[
"# a. stack\nX = np.column_stack((A,b))\nprint('stacked:\\n',X)\n\n# b. row operations\nX[0,:] += 2*X[1,:]\nX[0,:] /= 5.0\nX[1,:] -= X[0,:]\nX[1,:] *= -1\nX[2,:] -= 5*X[1,:]\nprint('row reduced echelon form:\\n',X)\n\n# c. print result (the last column in X in row reduced echelon form)\nprint('solution',X[:,-1])",
"stacked:\n [[ 3. 2. 0. 2.]\n [ 1. -1. 0. 4.]\n [ 0. 5. 1. -1.]]\nrow reduced echelon form:\n [[ 1. 0. 0. 2.]\n [-0. 1. -0. -2.]\n [ 0. 0. 1. 9.]]\nsolution [ 2. -2. 9.]\n"
]
],
[
[
"**General function:**",
"_____no_output_____"
]
],
[
[
"Y = np.column_stack((A,b))\nnumecon_linalg.gauss_jordan(Y)\nprint('solution',Y[:,-1])",
"solution [ 2. -2. 9.]\n"
]
],
[
[
"which can also be used to find the inverse if we stack with the identity matrix instead,",
"_____no_output_____"
]
],
[
[
"# a. construct stacked matrix\nZ = np.hstack((A,np.eye(3)))\nprint('stacked:\\n',Z)\n\n# b. apply gauss jordan elimination\nnumecon_linalg.gauss_jordan(Z)\n\n# b. find inverse\ninv_Z = Z[:,3:] # last 3 columns of Z in row reduced echelon form\nprint('inverse:\\n',inv_Z)\n\nassert np.allclose(Z[:,3:]@A,np.eye(3))",
"stacked:\n [[ 3. 2. 0. 1. 0. 0.]\n [ 1. -1. 0. 0. 1. 0.]\n [ 0. 5. 1. 0. 0. 1.]]\ninverse:\n [[ 0.2 0.4 0. ]\n [ 0.2 -0.6 0. ]\n [-1. 3. 1. ]]\n"
]
],
[
[
"## 1.3 Iteative Gauss-Seidel (+)",
"_____no_output_____"
],
[
"We can always decompose $A$ into additive lower and upper triangular matrices,\n\n$$\nA=L+U=\\begin{bmatrix}a_{11} & 0 & \\cdots & 0\\\\\na_{21} & a_{22} & \\cdots & 0\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\na_{n1} & a_{n2} & \\cdots & a_{nn}\n\\end{bmatrix}+\\begin{bmatrix}0 & a_{12} & \\cdots & a_{1n}\\\\\n0 & 0 & \\cdots & a_{2n}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\n0 & 0 & \\cdots & 0\n\\end{bmatrix}\n$$\n\nsuch that\n\n$$\nAx=b\\Leftrightarrow Lx=b-Ux\n$$",
"_____no_output_____"
],
[
"**Algorithm:** `gauss_seidel()`\n\n1. Choose tolerance $\\epsilon > 0$, guess on $x_0$, and set $n=1$.\n2. Find $x_n$ by solving \\\\( Lx_n = y \\equiv (b-Ux_{n-1}) \\\\).\n3. If $|x_n-x_{n-1}|_{\\infty} < \\epsilon$ stop, else $n=n+1 $ and return to step 2.",
"_____no_output_____"
],
[
"> **Note:** Step 2 is very easy because the equation can be solved directly by *forward substitution*:\n>\n> $x_1 = \\frac{y_1}{a_{11}}$\n>\n> $x_2 = \\frac{(y_2 - a_{21} x_1)}{a_{22}}$\n>\n> $x_3 = \\frac{(y_3 - a_{31} x_1 - a_{32} x_2)}{a_{33}}$\n>\n> etc.",
"_____no_output_____"
],
[
"**Apply Gauss-Seidel:**",
"_____no_output_____"
]
],
[
[
"x0 = np.array([1,1,1])\nx = numecon_linalg.gauss_seidel(A,b,x0)\nprint('solution',x)",
"solution [ 2. -2. 9.]\n"
]
],
[
[
"> **Note:** Convergence is not ensured unless the matrix is *diagonally dominant* or *symmetric* and *positive definite*.",
"_____no_output_____"
]
],
[
[
"x = numecon_linalg.gauss_seidel(A,b,x0,do_print=True)",
" [1 1 1]\n 0: [ 0.00000000 -4.00000000 19.00000000]\n 1: [ 3.33333333 -0.66666667 2.33333333]\n 2: [ 1.11111111 -2.88888889 13.44444444]\n 3: [ 2.59259259 -1.40740741 6.03703704]\n 4: [ 1.60493827 -2.39506173 10.97530864]\n 5: [ 2.26337449 -1.73662551 7.68312757]\n 6: [ 1.82441701 -2.17558299 9.87791495]\n 7: [ 2.11705533 -1.88294467 8.41472337]\n 8: [ 1.92196312 -2.07803688 9.39018442]\n 9: [ 2.05202459 -1.94797541 8.73987705]\n 10: [ 1.96531694 -2.03468306 9.17341530]\n 11: [ 2.02312204 -1.97687796 8.88438980]\n 12: [ 1.98458531 -2.01541469 9.07707347]\n 13: [ 2.01027646 -1.98972354 8.94861769]\n 14: [ 1.99314903 -2.00685097 9.03425487]\n 15: [ 2.00456732 -1.99543268 8.97716342]\n 16: [ 1.99695512 -2.00304488 9.01522439]\n 17: [ 2.00202992 -1.99797008 8.98985041]\n 18: [ 1.99864672 -2.00135328 9.00676639]\n 19: [ 2.00090219 -1.99909781 8.99548907]\n 20: [ 1.99939854 -2.00060146 9.00300729]\n 21: [ 2.00040097 -1.99959903 8.99799514]\n 22: [ 1.99973269 -2.00026731 9.00133657]\n 23: [ 2.00017821 -1.99982179 8.99910895]\n 24: [ 1.99988119 -2.00011881 9.00059403]\n 25: [ 2.00007920 -1.99992080 8.99960398]\n 26: [ 1.99994720 -2.00005280 9.00026401]\n 27: [ 2.00003520 -1.99996480 8.99982399]\n 28: [ 1.99997653 -2.00002347 9.00011734]\n 29: [ 2.00001565 -1.99998435 8.99992177]\n 30: [ 1.99998957 -2.00001043 9.00005215]\n 31: [ 2.00000695 -1.99999305 8.99996523]\n 32: [ 1.99999536 -2.00000464 9.00002318]\n 33: [ 2.00000309 -1.99999691 8.99998455]\n 34: [ 1.99999794 -2.00000206 9.00001030]\n 35: [ 2.00000137 -1.99999863 8.99999313]\n 36: [ 1.99999908 -2.00000092 9.00000458]\n 37: [ 2.00000061 -1.99999939 8.99999695]\n 38: [ 1.99999959 -2.00000041 9.00000203]\n 39: [ 2.00000027 -1.99999973 8.99999864]\n 40: [ 1.99999982 -2.00000018 9.00000090]\n 41: [ 2.00000012 -1.99999988 8.99999940]\n 42: [ 1.99999992 -2.00000008 9.00000040]\n 43: [ 2.00000005 -1.99999995 8.99999973]\n 44: [ 1.99999996 -2.00000004 9.00000018]\n 45: [ 2.00000002 -1.99999998 8.99999988]\n 46: [ 1.99999998 -2.00000002 9.00000008]\n 47: [ 2.00000001 -1.99999999 8.99999995]\n 48: [ 1.99999999 -2.00000001 9.00000004]\n 49: [ 2.00000000 -2.00000000 8.99999998]\n 50: [ 2.00000000 -2.00000000 9.00000002]\n 51: [ 2.00000000 -2.00000000 8.99999999]\n 52: [ 2.00000000 -2.00000000 9.00000001]\n 53: [ 2.00000000 -2.00000000 9.00000000]\n 54: [ 2.00000000 -2.00000000 9.00000000]\n"
]
],
[
[
"## 1.4 Scipy functions",
"_____no_output_____"
],
[
"**Option 1:** Use `.solve()` (scipy chooses what happens).",
"_____no_output_____"
]
],
[
[
"x1 = linalg.solve(A, b)\nprint(x1)\nassert np.all(A@x1 == b)",
"[ 2. -2. 9.]\n"
]
],
[
[
"**Option 2:** Compute `.inv()` first and then solve.",
"_____no_output_____"
]
],
[
[
"Ainv = linalg.inv(A)\nx2 = Ainv@b\nprint(x2)",
"[ 2. -2. 9.]\n"
]
],
[
[
"> **Note:** Computing the inverse is normally not a good idea due to numerical stability.",
"_____no_output_____"
],
[
"**Option 3:** Compute LU decomposition and then solve.",
"_____no_output_____"
]
],
[
[
"LU,piv = linalg.lu_factor(A) # decomposition (factorization)\nx3 = linalg.lu_solve((LU,piv),b)\nprint(x3)",
"[ 2. -2. 9.]\n"
]
],
[
[
"**Detail:** `piv` contains information on a numerical stable reordering.",
"_____no_output_____"
],
[
"## 1.5 Comparisons\n\n1. `linalg.solve()` is the best choice for solving once.\n2. `linalg.lu_solve()` is the best choice when solving for multipe $b$'s for a fixed $A$ (the LU decomposition only needs to be done once).\n3. Gauss-Seidel is an alternative when e.g. only an approximate solution is needed.",
"_____no_output_____"
],
[
"## 1.6 Details on LU factorization (+)\n\nWhen $A$ is *regular* (invertible), we can decompose it into a *lower unit triangular matrix*, $L$, and an *upper triangular matrix*, $U$:\n\n$$\nA= L\\cdot U = \\begin{bmatrix}1 & 0 & \\cdots & 0\\\\\nl_{21} & 1 & \\cdots & 0\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\nl_{n1} & l_{n2} & \\cdots & 1\n\\end{bmatrix}\\cdot\\begin{bmatrix}u_{11} & u_{12} & \\cdots & u_{1n}\\\\\n0 & u_{22} & \\cdots & u_{2n}\\\\\n\\vdots & \\vdots & \\ddots & \\vdots\\\\\n0 & 0 & \\cdots & u_{nn}\n\\end{bmatrix}\n$$\n\nwhere it can be shown that we can compute the elements by\n\n$$\n\\begin{aligned}\nu_{ij} &= a_{ij} - \\sum_{k=1}^{i-1} u_{kj} l_{ik} \\\\\nl_{ij} &= \\frac{1}{u_{jj}} \\big( a_{ij} - \\sum_{k=1}^{j-1} u_{kj} l_{ik} \\big)\n\\end{aligned}\n$$\n\nThis implies that the equation system can be written\n\n$$ \nL(Ux) = b \n$$",
"_____no_output_____"
],
[
"**Algorithm:** `lu_solve()`\n\n1. Perform LU decomposition (factorization)\n2. Solve $Ly = b$ for $y$ (by *forward substitution*) where $y = Ux$\n3. Solve $Ux = y$ for $x$ (by *backward substitution*)",
"_____no_output_____"
]
],
[
[
"L,U = numecon_linalg.lu_decomposition(A) # step 1\ny = numecon_linalg.solve_with_forward_substitution(L,b) # step 2\nx = numecon_linalg.solve_with_backward_substitution(U,y) # step 3\nprint('L:\\n',L)\nprint('\\nU:\\n',U)\nprint('\\nsolution:',x)",
"L:\n [[ 1. 0. 0. ]\n [ 0.33333333 1. 0. ]\n [ 0. -3. 1. ]]\n\nU:\n [[ 3. 2. 0. ]\n [ 0. -1.66666667 0. ]\n [ 0. 0. 1. ]]\n\nsolution: [ 2. -2. 9.]\n"
]
],
[
[
"**Relation to scipy:**\n\n1. Scipy use pivoting to improve numerical stability.\n2. Scipy is implemented much much better than here.",
"_____no_output_____"
],
[
"## 1.7 Sparse matrices (+)",
"_____no_output_____"
],
[
"**Sparse matrix:** A matrix with many zeros. Letting the computer know where they are is extremely valuable.\n\n**Documentation:** [basics](https://docs.scipy.org/doc/scipy/reference/sparse.html) + [linear algebra](https://docs.scipy.org/doc/scipy/reference/sparse.linalg.html#module-scipy.sparse.linalg)",
"_____no_output_____"
],
[
"**Create a sparse matrix**, where most elements are on the diagonal:",
"_____no_output_____"
]
],
[
[
"from scipy import sparse\nimport scipy.sparse.linalg\n\nS = sparse.lil_matrix((1000, 1000)) # 1000x1000 matrix with zeroes\nS.setdiag(np.random.rand(1000)) # some values on the diagonal\nS[200, :100] = np.random.rand(100) # some values in a row\nS[200:210, 100:200] = S[200, :100] # and the same value in some other rows",
"_____no_output_____"
]
],
[
[
"Create a plot of the values in the matrix:",
"_____no_output_____"
]
],
[
[
"S_np = S.toarray() # conversion to numpy\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\nax.matshow(S_np,cmap=plt.cm.binary);",
"_____no_output_____"
]
],
[
[
"**Solve it in four different ways:**\n\n1. Like it was not sparse\n2. Using the sparsity\n3. Using the sparsity + explicit factorization\n4. Iterative solver (similar to Gauss-Seidel)",
"_____no_output_____"
]
],
[
[
"k = np.random.rand(1000) # random RHS\n\n# a. solve\nt0 = time.time()\nx = linalg.solve(S_np,k)\nprint(f'{\"solve\":12s}: {time.time()-t0:.5f} secs')\n\n# b. solve with spsolve\nt0 = time.time()\nx_alt = sparse.linalg.spsolve(S.tocsr(), k)\nprint(f'{\"spsolve\":12s}: {time.time()-t0:.5f} secs')\nassert np.allclose(x,x_alt)\n \n# c. solve with explicit factorization\nt0 = time.time()\nS_solver = sparse.linalg.factorized(S.tocsc())\nx_alt = S_solver(k)\nprint(f'{\"factorized\":12s}: {time.time()-t0:.5f} secs')\nassert np.allclose(x,x_alt)\n \n# d. solve with iterative solver (bicgstab)\nt0 = time.time()\nx_alt,_info = sparse.linalg.bicgstab(S,k,x0=1.001*x,tol=10**(-8))\nprint(f'{\"bicgstab\":12s}: {time.time()-t0:.5f} secs')\nassert np.allclose(x,x_alt),x-x_alt",
"solve : 0.02707 secs\nspsolve : 0.00201 secs\nfactorized : 0.00100 secs\nbicgstab : 0.12334 secs\n"
]
],
[
[
"**Conclusion:** \n\n1. Using the sparsity can be very important.\n2. Iterative solvers can be very very slow.",
"_____no_output_____"
],
[
"<a id=\"Symbolically\"></a>\n\n# 2. Symbolically",
"_____no_output_____"
],
[
"## 2.1 Solve consumer problem",
"_____no_output_____"
],
[
"Consider solving the following problem:\n\n$$ \n\\max_{x_1,x_2} x_1^{\\alpha} x_2^{\\beta} \\text{ s.t. } p_1x_1 + p_2x_2 = I \n$$",
"_____no_output_____"
],
[
"Define all symbols:",
"_____no_output_____"
]
],
[
[
"x1 = sm.symbols('x_1') # x1 is a Python variable representing the symbol x_1\nx2 = sm.symbols('x_2')\nalpha = sm.symbols('alpha')\nbeta = sm.symbols('beta')\np1 = sm.symbols('p_1')\np2 = sm.symbols('p_2')\nI = sm.symbols('I')",
"_____no_output_____"
]
],
[
[
"Define objective and budget constraint:",
"_____no_output_____"
]
],
[
[
"objective = x1**alpha*x2**beta\nobjective",
"_____no_output_____"
],
[
"budget_constraint = sm.Eq(p1*x1+p2*x2,I)\nbudget_constraint",
"_____no_output_____"
]
],
[
[
"Solve in **four steps**:\n\n1. **Isolate** $x_2$ from the budget constraint\n2. **Substitute** in $x_2$\n3. **Take the derivative** wrt. $x_1$\n4. **Solve the FOC** for $x_1$",
"_____no_output_____"
],
[
"**Step 1: Isolate**",
"_____no_output_____"
]
],
[
[
"x2_from_con = sm.solve(budget_constraint,x2)\nx2_from_con[0]",
"_____no_output_____"
]
],
[
[
"**Step 2: Substitute**",
"_____no_output_____"
]
],
[
[
"objective_subs = objective.subs(x2,x2_from_con[0])\nobjective_subs",
"_____no_output_____"
]
],
[
[
"**Step 3: Take the derivative**",
"_____no_output_____"
]
],
[
[
"foc = sm.diff(objective_subs,x1)\nfoc",
"_____no_output_____"
]
],
[
[
"**Step 4: Solve the FOC**",
"_____no_output_____"
]
],
[
[
"sol = sm.solve(sm.Eq(foc,0),x1)\nsol[0]",
"_____no_output_____"
]
],
[
[
"> An alternative is `sm.solveset()`, which will be the default in the future, but it is still a bit immature in my view.",
"_____no_output_____"
],
[
"**Task:** Solve the consumer problem with quasi-linear preferences,\n\n$$ \\max_{x_1,x_2} \\sqrt{x_1} + \\gamma x_2 \\text{ s.t. } p_1x_1 + p_2x_2 = I $$",
"_____no_output_____"
]
],
[
[
"# write your code here ",
"_____no_output_____"
],
[
"gamma = sm.symbols('gamma')\nobjective_alt = sm.sqrt(x1) + gamma*x2\nobjective_alt_subs = objective_alt.subs(x2,x2_from_con[0])\nfoc_alt = sm.diff(objective_alt_subs,x1)\nsol_alt = sm.solve(foc_alt,x1)\nsol_alt[0]",
"_____no_output_____"
]
],
[
[
"## 2.2 Use solution",
"_____no_output_____"
],
[
"**LaTex:** Print in LaTex format:",
"_____no_output_____"
]
],
[
[
"print(sm.latex(sol[0]))",
"\\frac{I \\alpha}{p_{1} \\left(\\alpha + \\beta\\right)}\n"
]
],
[
[
"**Turn into Python function:**",
"_____no_output_____"
]
],
[
[
"_sol_func = sm.lambdify((p1,I,alpha,beta),sol[0])\ndef sol_func(p1,I=10,alpha=1,beta=1):\n return _sol_func(p1,I,alpha,beta)\n \n# test\np1_vec = np.array([1.2,3,5,9])\ndemand_p1 = sol_func(p1_vec)\nprint(demand_p1)",
"[4.16666667 1.66666667 1. 0.55555556]\n"
]
],
[
[
"**Is demand always positive?**",
"_____no_output_____"
],
[
"Give the computer the **information** we have. I.e. that $p_1$, $p_2$, $\\alpha$, $\\beta$, $I$ are all strictly positive:",
"_____no_output_____"
]
],
[
[
"for var in [p1,p2,alpha,beta,I]:\n sm.assumptions.assume.global_assumptions.add(sm.Q.positive(var))\nsm.assumptions.assume.global_assumptions ",
"_____no_output_____"
]
],
[
[
"**Ask** the computer a **question**:",
"_____no_output_____"
]
],
[
[
"answer = sm.ask(sm.Q.positive(sol[0]))\nprint(answer)",
"True\n"
]
],
[
[
"We need the assumption that $p_1 > 0$:",
"_____no_output_____"
]
],
[
[
"sm.assumptions.assume.global_assumptions.remove(sm.Q.positive(p1))\nanswer = sm.ask(sm.Q.positive(sol[0]))\nprint(answer)",
"None\n"
]
],
[
[
"To clear all assumptions we can use:",
"_____no_output_____"
]
],
[
[
"sm.assumptions.assume.global_assumptions.clear()",
"_____no_output_____"
]
],
[
[
"## 2.3 Solving matrix equations (+)",
"_____no_output_____"
],
[
"$$ Ax = b $$",
"_____no_output_____"
],
[
"**Remember:**",
"_____no_output_____"
]
],
[
[
"print('A:\\n',A)\nprint('b:',b)",
"A:\n [[ 3. 2. 0.]\n [ 1. -1. 0.]\n [ 0. 5. 1.]]\nb: [ 2. 4. -1.]\n"
]
],
[
[
"**Construct symbolic matrix:**",
"_____no_output_____"
]
],
[
[
"A_sm = numecon_linalg.construct_sympy_matrix(['11','12','21','22','32','33']) # somewhat complicated function\nA_sm",
"_____no_output_____"
]
],
[
[
"**Find the inverse symbolically:**",
"_____no_output_____"
]
],
[
[
"A_sm_inv = A_sm.inv()\nA_sm_inv",
"_____no_output_____"
]
],
[
[
"**Fill in the numeric values:**",
"_____no_output_____"
]
],
[
[
"A_inv_num = numecon_linalg.fill_sympy_matrix(A_sm_inv,A) # somewhat complicated function\nx = A_inv_num@b\nprint('solution:',x)",
"solution: [ 2. -2. 9.]\n"
]
],
[
[
"**Note:** The inverse multiplied by the determinant looks nicer...",
"_____no_output_____"
]
],
[
[
"A_sm_det = A_sm.det()\nA_sm_det",
"_____no_output_____"
],
[
"A_sm_inv_raw = sm.simplify(A_sm_inv*A_sm_det)\nA_sm_inv_raw",
"_____no_output_____"
]
],
[
[
"## 2.4 More features (mixed goodies)",
"_____no_output_____"
]
],
[
[
"x = sm.symbols('x')",
"_____no_output_____"
]
],
[
[
"**Derivatives:** Higher order derivatives are also availible",
"_____no_output_____"
]
],
[
[
"sm.Derivative('x**4',x,x)",
"_____no_output_____"
],
[
"sm.diff('x**4',x,x)",
"_____no_output_____"
]
],
[
[
"Alternatively,",
"_____no_output_____"
]
],
[
[
"expr = sm.Derivative('x**4',x,x)\nexpr.doit()",
"_____no_output_____"
]
],
[
[
"**Integrals:**",
"_____no_output_____"
]
],
[
[
"sm.Integral(sm.exp(-x), (x, 0, sm.oo))",
"_____no_output_____"
],
[
"sm.integrate(sm.exp(-x), (x, 0, sm.oo))",
"_____no_output_____"
]
],
[
[
"**Limits:**",
"_____no_output_____"
]
],
[
[
"c = sm.symbols('c')\nrho = sm.symbols('rho')\nsm.Limit((c**(1-rho)-1)/(1-rho),rho,1)",
"_____no_output_____"
],
[
"sm.limit((c**(1-rho)-1)/(1-rho),rho,1)",
"_____no_output_____"
]
],
[
[
"**Integers:**",
"_____no_output_____"
]
],
[
[
"X = sm.Integer(7)/sm.Integer(3)\nY = sm.Integer(3)/sm.Integer(8)\ndisplay(X)\ndisplay(Y)\nZ = 3\n(X*Y)**Z",
"_____no_output_____"
]
],
[
[
"**Simplify:**",
"_____no_output_____"
]
],
[
[
"expr = sm.sin(x)**2 + sm.cos(x)**2\ndisplay(expr)",
"_____no_output_____"
],
[
"sm.simplify(expr)",
"_____no_output_____"
]
],
[
[
"**Solve multiple equations at once:**",
"_____no_output_____"
]
],
[
[
"x = sm.symbols('x')\ny = sm.symbols('y')\nEq1 = sm.Eq(x**2+y-2,0)\nEq2 = sm.Eq(y**2-4,0)\nsol = sm.solve([Eq1,Eq2],[x,y])\n\n# print all solutions\nfor xy in sol:\n print(f'(x,y) = ({xy[0]},{xy[1]})')",
"(x,y) = (-2,-2)\n(x,y) = (0,2)\n(x,y) = (0,2)\n(x,y) = (2,-2)\n"
]
],
[
[
"<a id=\"Non-linear-equations---one-dimensional\"></a>\n\n# 3. Non-linear equations - one dimensional",
"_____no_output_____"
],
[
"## 3.1 Introduction",
"_____no_output_____"
],
[
"We consider **solving non-linear equations** on the form,\n\n$$ \nf(x) = 0, x \\in \\mathbb{R} \n$$\n\nThis is also called **root-finding**.",
"_____no_output_____"
],
[
"A specific **example** is:\n\n$$\nf(x) = 10x^3 - x^2 -1\n$$",
"_____no_output_____"
],
[
"## 3.2 Derivative based methods",
"_____no_output_____"
],
[
"**Newton methods:** Assume you know the function value and derivatives at $x_0$. ",
"_____no_output_____"
],
[
"A **first order** approximate value of the function at $x_1$ then is:\n\n$$ \nf(x_1) \\approx f(x_0) + f^{\\prime}(x_0)(x_1-x_0)\n$$\n\nimplying \n\n$$\nf(x_1) = 0 \\Leftrightarrow x_1 = x_0 - \\frac{f(x_0)}{f^{\\prime}(x_0)}\n$$",
"_____no_output_____"
],
[
"This is called **Newtons method**.",
"_____no_output_____"
],
[
"An alternative is **Halleys method** (see [derivation](https://mathworld.wolfram.com/HalleysMethod.html)), which uses\n\n$$\nx_1 = x_0 - \\frac{f(x_0)}{f^{\\prime}(x_0)} \\Big[ 1-\\frac{f(x_0)}{f^{\\prime}(x_0)}\\frac{f^{\\prime\\prime}(x_0)}{2f^{\\prime}(x_0)} \\Big]^{-1}\n$$\n\nmaking use of information from the **second derivative**.",
"_____no_output_____"
],
[
"**Algorithm:** `find_root()`\n\n1. Choose tolerance $\\epsilon > 0$, guess on $x_0$ and set $n = 0$.\n2. Calculate $f(x_n)$, $f^{\\prime}(x_n)$, and perhaps $f^{\\prime\\prime}(x_n)$.\n3. If $|f(x_n)| < \\epsilon$ stop.\n4. Calculate $x_{n+1}$ using Newtons or Halleys formula (see above).\n5. Set $n = n + 1$ and return to step 2.",
"_____no_output_____"
]
],
[
[
"def find_root(x0,f,fp,fpp=None,method='newton',max_iter=500,tol=1e-8,full_info=False):\n \"\"\" find root\n \n Args:\n \n x0 (float): initial value\n f (callable): function\n fp (callable): derivative\n fp (callable): second derivative\n method (str): newton or halley\n max_iter (int): maximum number of iterations\n tol (float): tolerance\n full_info (bool): controls information returned\n \n Returns:\n \n x (float/ndarray): root (if full_info, all x tried)\n i (int): number of iterations used\n fx (ndarray): function values used (if full_info) \n fpx (ndarray): derivative values used (if full_info)\n fppx (ndarray): second derivative values used (if full_info)\n \n \"\"\"\n \n # initialize\n x = np.zeros(max_iter)\n fx = np.zeros(max_iter)\n fpx = np.zeros(max_iter)\n fppx = np.zeros(max_iter)\n \n # iterate\n x[0] = x0 \n i = 0 \n while True:\n \n # step 2: evaluate function and derivatives\n fx[i] = f(x[i])\n fpx[i] = fp(x[i])\n if method == 'halley':\n fppx[i] = fpp(x[i])\n \n # step 3: check convergence\n if abs(fx[i]) < tol or i >= max_iter:\n break\n \n # step 4: update x\n if method == 'newton':\n x[i+1] = x[i] - fx[i]/fpx[i]\n elif method == 'halley':\n a = fx[i]/fpx[i]\n b = a*fppx[i]/(2*fpx[i])\n x[i+1] = x[i] - a/(1-b)\n \n # step 5: increment counter\n i += 1\n \n # return\n if full_info:\n return x,i,fx,fpx,fppx\n else:\n return x[i],i",
"_____no_output_____"
]
],
[
[
"**Note:** The cell below contains a function for plotting the convergence.",
"_____no_output_____"
]
],
[
[
"def plot_find_root(x0,f,fp,fpp=None,method='newton',xmin=-8,xmax=8,xn=100):\n \n # a. find root and return all information \n x,max_iter,fx,fpx,fppx = find_root(x0,f,fp,fpp=fpp,method=method,full_info=True)\n \n # b. compute function on grid\n xvec = np.linspace(xmin,xmax,xn)\n fxvec = f(xvec)\n \n # c. figure\n def _figure(i):\n \n # i. approximation\n if method == 'newton':\n fapprox = fx[i] + fpx[i]*(xvec-x[i])\n elif method == 'halley':\n fapprox = fx[i] + fpx[i]*(xvec-x[i]) + fppx[i]/2*(xvec-x[i])**2 \n \n # ii. figure\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n \n ax.plot(xvec,fxvec,label='function') # on grid\n ax.plot(x[i],fx[i],'o',color='black',label='current') # now \n ax.plot(xvec,fapprox,label='approximation') # approximation\n ax.axvline(x[i+1],ls='--',lw=1,color='black') # cross zero\n ax.plot(x[i+1],fx[i+1],'o',color='black',mfc='none',label='next')# next\n \n ax.legend(loc='lower right',facecolor='white',frameon=True)\n ax.set_ylim([fxvec[0],fxvec[-1]])\n \n widgets.interact(_figure,\n i=widgets.IntSlider(description=\"iterations\", min=0, max=max_iter-1, step=1, value=0)\n );",
"_____no_output_____"
]
],
[
[
"## 3.3 Example",
"_____no_output_____"
]
],
[
[
"f = lambda x: 10*x**3-x**2-1\nfp = lambda x: 30*x**2-2*x\nfpp = lambda x: 60*x-2",
"_____no_output_____"
],
[
"x,i = find_root(-5,f,fp,method='newton')\nprint(i,x,f(x))",
"17 0.5000000000000073 4.773959005888173e-14\n"
],
[
"plot_find_root(-5,f,fp,method='newton')",
"_____no_output_____"
],
[
"x,i = find_root(-5,f,fp,fpp,method='halley')\nprint(i,x,f(x))",
"12 0.4999999999675154 -2.1114998638438465e-10\n"
],
[
"plot_find_root(-5,f,fp,fpp,method='halley')",
"_____no_output_____"
]
],
[
[
"## 3.4 Numerical derivative",
"_____no_output_____"
],
[
"Sometimes, you might not have the **analytical derivative**. Then, you can instead use the **numerical derivative**.",
"_____no_output_____"
]
],
[
[
"# a. function\nf = lambda x: 10*x**3 - x**2 -1\n\n# b. numerical derivative (forward)\nstepsize = 1e-8\nfp_approx = lambda x: (f(x+stepsize)-f(x))/stepsize\n\n# b. find root\nx0 = -5\nx,i = find_root(x0,f,fp_approx,method='newton')\nprint(i,x,f(x))",
"17 0.5000000000000091 5.928590951498336e-14\n"
]
],
[
[
"**Question:** What happens if you increase the stepsize?",
"_____no_output_____"
],
[
"## 3.5 Another example",
"_____no_output_____"
]
],
[
[
"g = lambda x: np.sin(x)\ngp = lambda x: np.cos(x)\ngpp = lambda x: -np.sin(x)\n\nx0 = -4.0\nplot_find_root(x0,g,gp,gpp,method='newton')",
"_____no_output_____"
]
],
[
[
"**Question:** Is the initial value important?",
"_____no_output_____"
],
[
"**Sympy** can actually tell us that there are many solutions:",
"_____no_output_____"
]
],
[
[
"x = sm.symbols('x')\nsm.solveset(sm.sin(x),)",
"_____no_output_____"
]
],
[
[
"## 3.6 Derivative free methods: Bisection",
"_____no_output_____"
],
[
"**Algorithm:** `bisection()`\n\n1. Set $a_0 = a$ and $b_0 = b$ where $f(a)$ and $f(b)$ has oposite sign, $f(a_0)f(b_0)<0$\n2. Compute $f(m_0)$ where $m_0 = (a_0 + b_0)/2$ is the midpoint.\n3. Determine the next sub-interval $[a_1,b_1]$:\n * If $f(a_0)f(m_0) < 0$ (different signs) then $a_1 = a_0$ and $b_1 = m_0$ (i.e. focus on the range $[a_0,m_0]$).\n * If $f(m_0)f(b_0) < 0$ (different signs) then $a_1 = m_0$ and $b_1 = b_0$ (i.e. focus on the range $[m_0,b_0]$).\n4. Repeat step 2 and step 3 until $f(m_n) < \\epsilon$.",
"_____no_output_____"
]
],
[
[
"def bisection(f,a,b,max_iter=500,tol=1e-6,full_info=False):\n \"\"\" bisection\n \n Solve equation f(x) = 0 for a <= x <= b.\n \n Args:\n \n f (callable): function\n a (float): left bound\n b (float): right bound\n max_iter (int): maximum number of iterations\n tol (float): tolerance on solution\n full_info (bool): controls information returned\n \n Returns:\n \n m (float/ndarray): root (if full_info, all x tried)\n i (int): number of iterations used\n a (ndarray): left bounds used\n b (ndarray): right bounds used\n fm (ndarray): funciton values at midpoints\n \n \"\"\"\n \n # test inputs\n if f(a)*f(b) >= 0:\n print(\"bisection method fails.\")\n return None\n \n # step 1: initialize\n _a = a\n _b = b\n a = np.zeros(max_iter)\n b = np.zeros(max_iter)\n m = np.zeros(max_iter)\n fm = np.zeros(max_iter)\n a[0] = _a\n b[0] = _b\n \n # step 2-4: main\n i = 0\n while i < max_iter:\n \n # step 2: midpoint and associated value\n m[i] = (a[i]+b[i])/2\n fm[i] = f(m[i])\n \n # step 3: determine sub-interval\n if abs(fm[i]) < tol:\n break \n elif f(a[i])*fm[i] < 0:\n a[i+1] = a[i]\n b[i+1] = m[i]\n elif f(b[i])*fm[i] < 0:\n a[i+1] = m[i]\n b[i+1] = b[i]\n else:\n print(\"bisection method fails.\")\n return None\n \n i += 1\n \n if full_info:\n return m,i,a,b,fm\n else:\n return m[i],i",
"_____no_output_____"
]
],
[
[
"**Same result** as before, but **trade-off** between more iterations and no evaluation of derivatives.",
"_____no_output_____"
]
],
[
[
"m,i = bisection(f,-8,7)\nprint(i,m,f(m))",
"23 0.4999999403953552 -3.8743014130204756e-07\n"
]
],
[
[
"**Note:** The cell below contains a function for plotting the convergence.",
"_____no_output_____"
]
],
[
[
"def plot_bisection(f,a,b,xmin=-8,xmax=8,xn=100):\n \n # a. find root and return all information \n res = bisection(f,a,b,full_info=True)\n if res == None:\n return\n else:\n m,max_iter,a,b,fm = res\n \n # b. compute function on grid\n xvec = np.linspace(xmin,xmax,xn)\n fxvec = f(xvec)\n \n # c. figure\n def _figure(i):\n \n # ii. figure\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n \n ax.plot(xvec,fxvec) # on grid\n ax.plot(m[i],fm[i],'o',color='black',label='current') # mid\n ax.plot([a[i],b[i]],[fm[i],fm[i]],'--',color='black',label='range') # range\n ax.axvline(a[i],ls='--',color='black')\n ax.axvline(b[i],ls='--',color='black') \n \n ax.legend(loc='lower right',facecolor='white',frameon=True)\n ax.set_ylim([fxvec[0],fxvec[-1]])\n \n widgets.interact(_figure,\n i=widgets.IntSlider(description=\"iterations\", min=0, max=max_iter-1, step=1, value=0)\n );\n\nplot_bisection(f,-8,3)",
"_____no_output_____"
]
],
[
[
"**Note:** Bisection is not good at the final convergence steps. Generally true for methods not using derivatives.",
"_____no_output_____"
],
[
"## 3.7 Scipy",
"_____no_output_____"
],
[
"Scipy, naturally, has better implementations of the above algorithms.",
"_____no_output_____"
],
[
"**Newton:**",
"_____no_output_____"
]
],
[
[
"result = optimize.root_scalar(f,x0=-4,fprime=fp,method='newton')\nprint(result)",
" converged: True\n flag: 'converged'\n function_calls: 30\n iterations: 15\n root: 0.5\n"
]
],
[
[
"**Halley:**",
"_____no_output_____"
]
],
[
[
"result = optimize.root_scalar(f,x0=-4,fprime=fp,fprime2=fpp,method='halley')\nprint(result)",
" converged: True\n flag: 'converged'\n function_calls: 27\n iterations: 9\n root: 0.5\n"
]
],
[
[
"**Bisect:**",
"_____no_output_____"
]
],
[
[
"result = optimize.root_scalar(f,bracket=[-8,7],method='bisect')\nprint(result)",
" converged: True\n flag: 'converged'\n function_calls: 45\n iterations: 43\n root: 0.5000000000007958\n"
]
],
[
[
"The **best choice** is the more advanced **Brent-method**:",
"_____no_output_____"
]
],
[
[
"result = optimize.root_scalar(f,bracket=[-8,7],method='brentq')\nprint(result)",
" converged: True\n flag: 'converged'\n function_calls: 16\n iterations: 15\n root: 0.5000000000002526\n"
]
],
[
[
"<a id=\"Solving-non-linear-equations-(multi-dimensional)\"></a>\n\n# 4. Solving non-linear equations (multi-dimensional)",
"_____no_output_____"
],
[
"## 4.1 Introduction",
"_____no_output_____"
],
[
"We consider **solving non-linear equations** on the form,\n\n$$ \nf(\\boldsymbol{x}) = f(x_1,x_2,\\dots,x_k) = \\boldsymbol{0}, \\boldsymbol{x} \\in \\mathbb{R}^k\n$$",
"_____no_output_____"
],
[
"A specific **example** is:\n\n$$ \nh(\\boldsymbol{x})=h(x_{1,}x_{2})=\\begin{bmatrix}h_{1}(x_{1},x_{2})\\\\\nh_{2}(x_{1},x_{2})\n\\end{bmatrix}=\\begin{bmatrix}x_{1}+0.5(x_{1}-x_{2})^{3}-1\\\\\nx_{2}+0.5(x_{1}-x_{2})^{3}\n\\end{bmatrix}\\in\\mathbb{R}^{2} \n$$\n\nwhere the **Jacobian** is\n\n$$ \n\\nabla h(\\boldsymbol{x})=\\begin{bmatrix}\\frac{\\partial h_{1}}{\\partial x_{1}} & \\frac{\\partial h_{1}}{\\partial x_{2}}\\\\\n\\frac{\\partial h_{2}}{\\partial x_{1}} & \\frac{\\partial h_{2}}{\\partial x_{2}}\n\\end{bmatrix}=\\begin{bmatrix}1+1.5(x_{1}-x_{2})^{2} & -1.5(x_{1}-x_{2})^{2}\\\\\n-1.5(x_{2}-x_{1})^{2} & 1+1.5(x_{2}-x_{1})^{2}\n\\end{bmatrix}\n$$",
"_____no_output_____"
]
],
[
[
"def h(x):\n y = np.zeros(2)\n y[0] = x[0]+0.5*(x[0]-x[1])**3-1.0\n y[1] = x[1]+0.5*(x[1]-x[0])**3\n return y\n\ndef hp(x):\n y = np.zeros((2,2))\n y[0,0] = 1+1.5*(x[0]-x[1])**2\n y[0,1] = -1.5*(x[0]-x[1])**2\n y[1,0] = -1.5*(x[1]-x[0])**2\n y[1,1] = 1+1.5*(x[1]-x[0])**2\n return y",
"_____no_output_____"
]
],
[
[
"## 4.2 Newton's method",
"_____no_output_____"
],
[
"Same as Newton's method in one dimension, but with the following **update step**:\n\n$$ \n\\boldsymbol{x}_{n+1} = \\boldsymbol{x_n} - [ \\nabla h(\\boldsymbol{x_n})]^{-1} f(\\boldsymbol{x_n})\n$$",
"_____no_output_____"
]
],
[
[
"def find_root_multidim(x0,f,fp,max_iter=500,tol=1e-8):\n \"\"\" find root\n \n Args:\n \n x0 (float): initial value\n f (callable): function\n fp (callable): derivative\n max_iter (int): maximum number of iterations\n tol (float): tolerance\n \n Returns:\n \n x (float): root\n i (int): number of iterations used\n \n \"\"\"\n \n # initialize\n x = x0\n i = 0\n \n # iterate\n while i < max_iter:\n \n # step 2: function and derivatives\n fx = f(x)\n fpx = fp(x)\n \n # step 3: check convergence\n if max(abs(fx)) < tol:\n break\n \n # step 4: update x\n fpx_inv = linalg.inv(fpx) \n x = x - fpx_inv@fx\n \n # step 5: increment counter\n i += 1\n \n return x,i",
"_____no_output_____"
]
],
[
[
"**Test algorithm:**",
"_____no_output_____"
]
],
[
[
"x0 = np.array([0,0])\nx,i = find_root_multidim(x0,h,hp)\nprint(i,x,h(x))",
"5 [0.8411639 0.1588361] [ 1.41997525e-10 -1.41997469e-10]\n"
]
],
[
[
"## 4.3 Scipy",
"_____no_output_____"
],
[
"There exist a lot of efficient algorithms for finding roots in multiple dimensions. The default scipy choice is something called *hybr*.",
"_____no_output_____"
],
[
"**With the Jacobian:**",
"_____no_output_____"
]
],
[
[
"result = optimize.root(h,x0,jac=hp)\nprint(result)\nprint('\\nx =',result.x,', h(x) =',h(result.x))",
" fjac: array([[ 0.89914291, -0.43765515],\n [ 0.43765515, 0.89914291]])\n fun: array([-1.11022302e-16, 0.00000000e+00])\n message: 'The solution converged.'\n nfev: 10\n njev: 1\n qtf: array([-1.19565972e-11, 4.12770392e-12])\n r: array([ 2.16690469, -1.03701789, 1.10605417])\n status: 1\n success: True\n x: array([0.8411639, 0.1588361])\n\nx = [0.8411639 0.1588361] , h(x) = [-1.11022302e-16 0.00000000e+00]\n"
]
],
[
[
"**Without the Jacobian:**",
"_____no_output_____"
]
],
[
[
"result = optimize.root(h,x0)\nprint(result)\nprint('\\nx =',result.x,', h(x) =',h(result.x))",
" fjac: array([[-0.89914291, 0.43765515],\n [-0.43765515, -0.89914291]])\n fun: array([-1.11022302e-16, 0.00000000e+00])\n message: 'The solution converged.'\n nfev: 12\n qtf: array([ 1.19565972e-11, -4.12770392e-12])\n r: array([-2.16690469, 1.03701789, -1.10605417])\n status: 1\n success: True\n x: array([0.8411639, 0.1588361])\n\nx = [0.8411639 0.1588361] , h(x) = [-1.11022302e-16 0.00000000e+00]\n"
]
],
[
[
"<a id=\"Summary\"></a>\n\n# 5. Summary",
"_____no_output_____"
],
[
"**This lecture:**\n\n1. Solving matrix equations (directly, decomposition, iterative)\n2. Symbollic solutions (substitution, derivative, solution)\n3. Root-finding (one dimension, multiple dimensions, Newton's method, biscetion)",
"_____no_output_____"
],
[
"**Your work:** Play around with the code in this notebook before solving the problem set. Especially, try out the various scipy functions used.",
"_____no_output_____"
],
[
"**Next lecture:** Numerical optimization.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7b2ca8300454b68f63906ac8b0ecd4d3e15cd34 | 57,180 | ipynb | Jupyter Notebook | Sam_Kumar_LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb | sampath11/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling-OLD | e00b8631b9c51098ae2f2132d63959e238ffe480 | [
"MIT"
] | 1 | 2020-05-09T01:25:35.000Z | 2020-05-09T01:25:35.000Z | Sam_Kumar_LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb | sampath11/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling-OLD | e00b8631b9c51098ae2f2132d63959e238ffe480 | [
"MIT"
] | null | null | null | Sam_Kumar_LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb | sampath11/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling-OLD | e00b8631b9c51098ae2f2132d63959e238ffe480 | [
"MIT"
] | null | null | null | 106.282528 | 10,802 | 0.816177 | [
[
[
"<a href=\"https://colab.research.google.com/github/sampath11/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling/blob/master/Sam_Kumar_LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# ASSIGNMENT\n\n### 1) Replicate the lesson code. I recommend that you [do not copy-paste](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit).\n\nGet caught up to where we got our example in class and then try and take things further. How close to \"pixel perfect\" can you make the lecture graph?\n\nOnce you have something that you're proud of, share your graph in the cohort channel and move on to the second exercise.\n\n### 2) Reproduce another example from [FiveThityEight's shared data repository](https://data.fivethirtyeight.com/).\n\n**WARNING**: There are a lot of very custom graphs and tables at the above link. I **highly** recommend not trying to reproduce any that look like a table of values or something really different from the graph types that we are already familiar with. Search through the posts until you find a graph type that you are more or less familiar with: histogram, bar chart, stacked bar chart, line chart, [seaborn relplot](https://seaborn.pydata.org/generated/seaborn.relplot.html), etc. Recreating some of the graphics that 538 uses would be a lot easier in Adobe photoshop/illustrator than with matplotlib. \n\n- If you put in some time to find a graph that looks \"easy\" to replicate you'll probably find that it's not as easy as you thought. \n\n- If you start with a graph that looks hard to replicate you'll probably run up against a brick wall and be disappointed with your afternoon.\n\n\n\n\n\n\n\n\n\n\n",
"_____no_output_____"
]
],
[
[
"# Your Work Here\n\nfrom IPython.display import display, Image\n\nurl = 'https://fivethirtyeight.com/wp-content/uploads/2017/09/mehtahickey-inconvenient-0830-1.png'\nexample = Image(url=url, width=400)\n\n\ndisplay (example)",
"_____no_output_____"
],
[
"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as num\nimport pandas as pd\n\nplt.style.use('fivethirtyeight')\n\nfake = pd.Series ([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], index=range(1,11))\n\n\nfake.plot.bar (color ='#ed713a', width = 0.9);\n",
"_____no_output_____"
],
[
"style_list = ['default', 'classic'] + sorted (style for style in plt.style.available if style != 'classic')\n\nstyle_list",
"_____no_output_____"
],
[
"fake2 = pd.Series (\n [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,1,\n 2, 2, 2,\n 3, 3, 3,\n 4, 4, \n 5, 5, 5,\n 6, 6, 6, 6, \n 7, 7, 7, 7, 7, \n 8, 8, 8, 8,\n 9, 9, 9, 9, \n 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n ])\n\n\nfake2.head()",
"_____no_output_____"
],
[
"plt.style.use('fivethirtyeight')\n\nfake2.value_counts().sort_index().plot.bar (color='#ed713a', width=0.9)\n",
"_____no_output_____"
],
[
"display (example)",
"_____no_output_____"
],
[
"fig = plt.figure(facecolor = 'black')\n\nax = fake2.value_counts().sort_index().plot.bar (color = '#ed713a', width=0.9)\nax.set(facecolor='black')\n\nplt.xlabel('Rating', color='white')\n\nplt.ylabel ('Percent of total votes', color='white')",
"_____no_output_____"
],
[
"display(example)",
"_____no_output_____"
],
[
"list (range (0,50,10))",
"_____no_output_____"
],
[
"fig = plt.figure(facecolor ='white',figsize=(5,4) )\n\nax = fake.plot.bar (color ='#fc7703', width=0.9)\nax.set (facecolor ='white')",
"_____no_output_____"
]
],
[
[
"# STRETCH OPTIONS\n\n### 1) Reproduce one of the following using the matplotlib or seaborn libraries:\n\n- [thanksgiving-2015](https://fivethirtyeight.com/features/heres-what-your-part-of-america-eats-on-thanksgiving/) \n- [candy-power-ranking](https://fivethirtyeight.com/features/the-ultimate-halloween-candy-power-ranking/) \n- or another example of your choice!\n\n### 2) Make more charts!\n\nChoose a chart you want to make, from [Visual Vocabulary - Vega Edition](http://ft.com/vocabulary).\n\nFind the chart in an example gallery of a Python data visualization library:\n- [Seaborn](http://seaborn.pydata.org/examples/index.html)\n- [Altair](https://altair-viz.github.io/gallery/index.html)\n- [Matplotlib](https://matplotlib.org/gallery.html)\n- [Pandas](https://pandas.pydata.org/pandas-docs/stable/visualization.html)\n\nReproduce the chart. [Optionally, try the \"Ben Franklin Method.\"](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit) If you want, experiment and make changes.\n\nTake notes. Consider sharing your work with your cohort!",
"_____no_output_____"
]
],
[
[
"# More Work Here",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b2cba826048a85fe7a9885f27ccd3466c429fa | 4,264 | ipynb | Jupyter Notebook | code/notebooks/examine_dialogues.ipynb | scai-conf/SCAI-QReCC-21 | 7e00409b9bff28f3207d0c026abe4c8b26f211ae | [
"MIT"
] | 15 | 2021-06-02T19:34:44.000Z | 2022-02-25T08:36:40.000Z | code/notebooks/examine_dialogues.ipynb | scai-conf/SCAI-QReCC-21 | 7e00409b9bff28f3207d0c026abe4c8b26f211ae | [
"MIT"
] | null | null | null | code/notebooks/examine_dialogues.ipynb | scai-conf/SCAI-QReCC-21 | 7e00409b9bff28f3207d0c026abe4c8b26f211ae | [
"MIT"
] | null | null | null | 33.3125 | 932 | 0.605535 | [
[
[
"# load dataset\nimport json\n\npath = '../../dataset/qrecc_test.json'\n\nwith open(path) as f: \n data = json.load(f) ",
"_____no_output_____"
],
[
"# show example\nprint(data[0])\nprint(len(data[0]['Answer'].split()), 'words in the answer') # answer length in words",
"{'Context': [], 'Question': \"What is a physician's assistant?\", 'Rewrite': \"What is a physician's assistant?\", 'Answer': 'physician assistants are medical providers who are licensed to diagnose and treat illness and disease and to prescribe medication for patients', 'Answer_URL': 'https://explorehealthcareers.org/career/medicine/physician-assistant/', 'Conversation_no': 1, 'Turn_no': 1}\n21 words in the answer\n"
],
[
"import numpy as np\n\n# examine pages\nconv2pages = {}\nanswer_lens = []\nfor sample in data:\n conv_id = sample['Conversation_no']\n page = sample['Answer_URL']\n if conv_id not in conv2pages:\n conv2pages[conv_id] = []\n if page not in conv2pages[conv_id]:\n conv2pages[conv_id].append(page)\n answer_lens.append(len(sample['Answer'].split()))\n# print(conv2pages)\nprint(len(conv2pages), 'conversations in total')\nconversations_across_several_pages = [v for c, v in conv2pages.items() if len(v) > 1]\nprint(conversations_across_several_pages[0])\nprint(len(conversations_across_several_pages), 'of them span across several pages')\nprint(\"average answer length: %.0f words\" % np.mean(answer_lens))",
"2775 conversations in total\n['https://explorehealthcareers.org/career/medicine/physician-assistant/', 'https://www.geteducated.com/careers/how-to-become-a-physician-assistant', 'https://www.thepalife.com/how-much-does-it-cost-to-go-to-physician-assistant-pa-school/', 'https://www.prospects.ac.uk/job-profiles/physician-associate', 'https://www.payscale.com/research/US/Job=Physician_Assistant_(PA)/Salary/539a2580/Entry-Level', 'http://www.collegequest.com/how-to-become-an-rn.aspx', 'https://www.gapmedics.com/blog/2015/07/23/weighing-becoming-physician-assistant-nurse/', 'https://www.nursepractitionerschools.com/faq/np-vs-physician-assistant/', 'https://www.registerednursing.org/answers/salary-difference-between-nurse-practitioner-physician-assistant/', 'https://www.physicianassistantedu.org/pa-vs-np/', 'https://www.learnhowtobecome.org/nurse/nurse-practitioner/', 'https://work.chron.com/can-nurse-practitioners-become-doctors-16505.html']\n1990 of them span across several pages\naverage answer length: 18 words\n"
],
[
"# count empty answers\nn_empty_answers = 0 \nfor sample in data:\n if not sample['Answer']:\n n_empty_answers += 1\nprint(n_empty_answers, 'questions without answers')",
"5556 questions without answers\n"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code"
]
] |
e7b2d3b346fe9de4dd38ce2907e7afeb41023a04 | 43,846 | ipynb | Jupyter Notebook | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION | 5d0a5691f746623c24e3133229eaae681cf91891 | [
"MIT"
] | 1 | 2021-12-06T10:00:39.000Z | 2021-12-06T10:00:39.000Z | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION | 5d0a5691f746623c24e3133229eaae681cf91891 | [
"MIT"
] | null | null | null | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION | 5d0a5691f746623c24e3133229eaae681cf91891 | [
"MIT"
] | null | null | null | 96.790287 | 6,768 | 0.877138 | [
[
[
"# Basic Operations on Images",
"_____no_output_____"
]
],
[
[
"Drawing on Images",
"_____no_output_____"
],
[
"import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport cv2",
"_____no_output_____"
]
],
[
[
"Create a black image which will act as a template.",
"_____no_output_____"
]
],
[
[
"image_blank = np.zeros(shape=(512,512,3),dtype=np.int16)",
"_____no_output_____"
]
],
[
[
"image_blank",
"_____no_output_____"
],
[
" Display the black image.",
"_____no_output_____"
]
],
[
[
"plt.imshow(image_blank)",
"_____no_output_____"
]
],
[
[
"Function & Attributes",
"_____no_output_____"
],
[
"#### The generalised function for drawing shapes on images is:",
"_____no_output_____"
],
[
"cv2.shape(line, rectangle etc)(image,Pt1,Pt2,color,thickness)",
"_____no_output_____"
],
[
"\nThere are some common arguments which are passed in function to draw shapes on images:\n\n* Image on which shapes are to be drawn\n* co-ordinates of the shape to be drawn from Pt1(top left) to Pt2(bottom right)\n* Color: The color of the shape that is to be drawn. It is passed as a tuple, eg: (255,0,0). \n* For grayscale, it will be the scale of brightness.\n* The thickness of the geometrical figure.",
"_____no_output_____"
],
[
"## 1. Straight Line",
"_____no_output_____"
],
[
"Drawing a straight line across an image requires specifying the points, through which the line will pass.",
"_____no_output_____"
]
],
[
[
"# Draw a diagonal red line with thickness of 5 px\nline_red = cv2.line(image_blank,(0,0),(500,500),(255,0,255),10)\nplt.imshow(line_red)",
"_____no_output_____"
],
[
"# Draw a diagonal green line with thickness of 5 px\nline_green = cv2.line(image_blank,(0,0),(511,511),(0,255,0),5)\nplt.imshow(line_green)",
"_____no_output_____"
],
[
"# Draw a diagonal green line with thickness of 5 px\nline_green = cv2.line(image_blank,(0,0),(511,511),(0,255,0),10)\nplt.imshow(line_green)",
"_____no_output_____"
]
],
[
[
"## 2. Rectangle",
"_____no_output_____"
],
[
"#### For a rectangle, we need to specify the top left and the bottom right coordinates.",
"_____no_output_____"
]
],
[
[
"#Draw a blue rectangle with a thickness of 5 px\n\nrectangle= cv2.rectangle(image_blank,(0,0),(510,128),(0,255,0),25)\nplt.imshow(rectangle)",
"_____no_output_____"
]
],
[
[
"# 3. Circle",
"_____no_output_____"
]
],
[
[
"For a circle, we need to pass its center coordinates and radius value. Let us draw a circle inside the rectangle drawn above",
"_____no_output_____"
],
[
"img1 = cv2.circle(image_blank,(447,0), 250, (255,0,0), 50) # -1 corresponds to a filled circle\nplt.imshow(img1)",
"_____no_output_____"
]
],
[
[
"Writing on Images",
"_____no_output_____"
],
[
"Adding text to images is also similar to drawing shapes on them. But you need to specify certain arguments before doing so:\n\n* Text to be written\n* coordinates of the text. The text on an image begins from the bottom left direction.\n* Font type and scale.\n* Other attributes like color, thickness and line type. Normally the line type that is used is lineType = cv2.LINE_AA.",
"_____no_output_____"
]
],
[
[
"font = cv2.FONT_HERSHEY_SIMPLEX\ntext = cv2.putText(img1,'Alok',(10,500), font, 4,(255,255,255),2)\nplt.imshow(text)",
"_____no_output_____"
],
[
"These were the minor operations that can be done on images using OpenCV. Feel free to experiment with the shapes and text.",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
e7b2de4ded25ffb7cade56699940746571486d52 | 4,354 | ipynb | Jupyter Notebook | Jupyter_Lab_Colab.ipynb | debparth/Colab_tips_tricks | 13ec062a303257810a53307a9c1dfb65c79002e7 | [
"MIT"
] | null | null | null | Jupyter_Lab_Colab.ipynb | debparth/Colab_tips_tricks | 13ec062a303257810a53307a9c1dfb65c79002e7 | [
"MIT"
] | null | null | null | Jupyter_Lab_Colab.ipynb | debparth/Colab_tips_tricks | 13ec062a303257810a53307a9c1dfb65c79002e7 | [
"MIT"
] | null | null | null | 35.983471 | 240 | 0.56339 | [
[
[
"<a href=\"https://colab.research.google.com/github/debparth/Colab_tips_tricks/blob/main/Jupyter_Lab_Colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"- Install the Colab Code package which will let you run jupyter lab in colab using ngrok tunnel",
"_____no_output_____"
]
],
[
[
"!pip install colabcode",
"Collecting colabcode\n Downloading https://files.pythonhosted.org/packages/5d/d5/4f9db2a4fe80f507c9c44c2cd4fd614234c1fe0d77e8f1101329997a19cd/colabcode-0.0.9-py3-none-any.whl\nCollecting pyngrok>=5.0.0\n Downloading https://files.pythonhosted.org/packages/ea/63/e086f165125e9bf2e71c0db2955911baaaa0af8947ab5c7b3771bdf4d4d5/pyngrok-5.0.0.tar.gz\nRequirement already satisfied: PyYAML in /usr/local/lib/python3.6/dist-packages (from pyngrok>=5.0.0->colabcode) (3.13)\nBuilding wheels for collected packages: pyngrok\n Building wheel for pyngrok (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for pyngrok: filename=pyngrok-5.0.0-cp36-none-any.whl size=18780 sha256=07ed17d9fab927c3428ea36d27ae42e2178a40a5a99a8cf46b800921362b6394\n Stored in directory: /root/.cache/pip/wheels/95/df/23/af8dde08c3fcdc7b966adcacef48ab29aa3b0b1860df5d2b79\nSuccessfully built pyngrok\nInstalling collected packages: pyngrok, colabcode\nSuccessfully installed colabcode-0.0.9 pyngrok-5.0.0\n"
]
],
[
[
"- Paste your **Authorization Code** below in **authtoken** after signing up from [**here**](https://dashboard.ngrok.com/signup)",
"_____no_output_____"
],
[
"- Click on the **XXXXXXXXX.ngrok.io** link below after running the cell",
"_____no_output_____"
]
],
[
[
"from colabcode import ColabCode\n\nColabCode(authtoken=\"\", mount_drive=True, lab=True)",
"Code Server can be accessed on: NgrokTunnel: \"http://9998767f9579.ngrok.io\" -> \"http://localhost:10000\"\n[2020-10-28T19:04:23.315Z] info Using user-data-dir ~/.local/share/code-server\n[2020-10-28T19:04:23.321Z] info code-server 3.6.1 62735da69466a444561ab9b1115dc7c4d496d455\n[2020-10-28T19:04:23.322Z] info Using config file ~/.config/code-server/config.yaml\n[2020-10-28T19:04:23.327Z] info HTTP server listening on http://127.0.0.1:10000\n[2020-10-28T19:04:23.327Z] info - No authentication\n[2020-10-28T19:04:23.327Z] info - Not serving HTTPS\n"
]
]
] | [
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
e7b2ea63d76081a4aa88c51e37219d194fe51de1 | 23,487 | ipynb | Jupyter Notebook | scratch/Untitled2.ipynb | kingjml/tvc-site-selection | c0e35b7511606e204c80342ac2b1015101a56d60 | [
"MIT"
] | null | null | null | scratch/Untitled2.ipynb | kingjml/tvc-site-selection | c0e35b7511606e204c80342ac2b1015101a56d60 | [
"MIT"
] | null | null | null | scratch/Untitled2.ipynb | kingjml/tvc-site-selection | c0e35b7511606e204c80342ac2b1015101a56d60 | [
"MIT"
] | 1 | 2018-10-30T14:10:44.000Z | 2018-10-30T14:10:44.000Z | 114.570732 | 9,596 | 0.878231 | [
[
[
"import rasterio\nimport scipy.interpolate as interpolate\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"path = \"./data/rasters/new/SikSik_Snow.tif\"\nsrc = rasterio.open(path)",
"_____no_output_____"
],
[
"snow_depths = src.read()\nsnow_depths = snow_depths[0]\nsnow_depths = snow_depths[snow_depths > 0]\nsnow_max = np.round(snow_depths.max()+0.5)\nsnow_min = 0.1\nsnow_step = 0.01",
"_____no_output_____"
],
[
"bsnow = np.arange(snow_min,snow_max,snow_step)\nn_samples = 200\nhist, bin_edges = np.histogram(snow_depths, bins=bsnow, density=True)\ncum_values = np.zeros(bin_edges.shape)\ncum_values[1:] = np.cumsum(hist*np.diff(bin_edges))\ninv_cdf = interpolate.interp1d(cum_values, bin_edges, fill_value=\"extrapolate\")\nr = np.random.rand(n_samples)",
"_____no_output_____"
],
[
"inv_cdf(r)",
"_____no_output_____"
],
[
"plt.bar(bin_edges[:-1],hist,width=1)\n\nplt.show()",
"_____no_output_____"
],
[
"samps= inv_cdf(r)\nplt.plot(hist)\nplt.hist(samps)",
"_____no_output_____"
],
[
"plt.hist(samps)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b2f8e574d123b7ed85851eebeadd159326c53b | 12,730 | ipynb | Jupyter Notebook | Day03.ipynb | oddrationale/AdventOfCode2021FSharp | ab9e58ec25cf2c45f059bf6349ccc1142c856eea | [
"MIT"
] | 6 | 2021-12-10T17:31:54.000Z | 2022-01-02T20:33:05.000Z | Day03.ipynb | oddrationale/AdventOfCode2021FSharp | ab9e58ec25cf2c45f059bf6349ccc1142c856eea | [
"MIT"
] | null | null | null | Day03.ipynb | oddrationale/AdventOfCode2021FSharp | ab9e58ec25cf2c45f059bf6349ccc1142c856eea | [
"MIT"
] | 1 | 2022-02-20T05:04:57.000Z | 2022-02-20T05:04:57.000Z | 46.290909 | 451 | 0.604792 | [
[
[
"<h2>--- Day 3: Binary Diagnostic ---</h2>",
"_____no_output_____"
],
[
"[](https://mybinder.org/v2/gh/oddrationale/AdventOfCode2021FSharp/main?urlpath=lab%2Ftree%2FDay03.ipynb)",
"_____no_output_____"
],
[
"<p>The submarine has been making some <span title=\"Turns out oceans are heavy.\">odd creaking noises</span>, so you ask it to produce a diagnostic report just in case.</p>\n<p>The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the <em>power consumption</em>.</p>\n<p>You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the <em>gamma rate</em> and the <em>epsilon rate</em>). The power consumption can then be found by multiplying the gamma rate by the epsilon rate.</p>\n<p>Each bit in the gamma rate can be determined by finding the <em>most common bit in the corresponding position</em> of all numbers in the diagnostic report. For example, given the following diagnostic report:</p>\n<pre><code>00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010\n</code></pre>\n<p>Considering only the first bit of each number, there are five <code>0</code> bits and seven <code>1</code> bits. Since the most common bit is <code>1</code>, the first bit of the gamma rate is <code>1</code>.</p>\n<p>The most common second bit of the numbers in the diagnostic report is <code>0</code>, so the second bit of the gamma rate is <code>0</code>.</p>\n<p>The most common value of the third, fourth, and fifth bits are <code>1</code>, <code>1</code>, and <code>0</code>, respectively, and so the final three bits of the gamma rate are <code>110</code>.</p>\n<p>So, the gamma rate is the binary number <code>10110</code>, or <code><em>22</em></code> in decimal.</p>\n<p>The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is <code>01001</code>, or <code><em>9</em></code> in decimal. Multiplying the gamma rate (<code>22</code>) by the epsilon rate (<code>9</code>) produces the power consumption, <code><em>198</em></code>.</p>\n<p>Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. <em>What is the power consumption of the submarine?</em> (Be sure to represent your answer in decimal, not binary.)</p>",
"_____no_output_____"
]
],
[
[
"let input = File.ReadAllLines @\"input/03.txt\"",
"_____no_output_____"
],
[
"#!time\ninput\n|> Seq.map (fun line -> line.ToCharArray() |> Seq.map (fun char -> char |> string |> int))\n|> Seq.transpose\n|> Seq.map (fun bits -> if (bits |> Seq.sum) * 2 > input.Length then (1, 0) else (0, 1))\n|> Seq.fold (fun (gamma, epsilon) (g, e) -> gamma + string g, epsilon + string e) (String.Empty, String.Empty)\n|> fun (gamma, epsilon) -> Convert.ToInt32(gamma, 2) * Convert.ToInt32(epsilon, 2)",
"_____no_output_____"
]
],
[
[
"<h2 id=\"part2\">--- Part Two ---</h2>",
"_____no_output_____"
],
[
"<p>Next, you should verify the <em>life support rating</em>, which can be determined by multiplying the <em>oxygen generator rating</em> by the <em>CO2 scrubber rating</em>.</p>\n<p>Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and <em>consider just the first bit</em> of those numbers. Then:</p>\n<ul>\n<li>Keep only numbers selected by the <em>bit criteria</em> for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria.</li>\n<li>If you only have one number left, stop; this is the rating value for which you are searching.</li>\n<li>Otherwise, repeat the process, considering the next bit to the right.</li>\n</ul>\n<p>The <em>bit criteria</em> depends on which type of rating value you want to find:</p>\n<ul>\n<li>To find <em>oxygen generator rating</em>, determine the <em>most common</em> value (<code>0</code> or <code>1</code>) in the current bit position, and keep only numbers with that bit in that position. If <code>0</code> and <code>1</code> are equally common, keep values with a <code><em>1</em></code> in the position being considered.</li>\n<li>To find <em>CO2 scrubber rating</em>, determine the <em>least common</em> value (<code>0</code> or <code>1</code>) in the current bit position, and keep only numbers with that bit in that position. If <code>0</code> and <code>1</code> are equally common, keep values with a <code><em>0</em></code> in the position being considered.</li>\n</ul>\n<p>For example, to determine the <em>oxygen generator rating</em> value using the same example diagnostic report from above:</p>\n<ul>\n<li>Start with all 12 numbers and consider only the first bit of each number. There are more <code>1</code> bits (7) than <code>0</code> bits (5), so keep only the 7 numbers with a <code>1</code> in the first position: <code>11110</code>, <code>10110</code>, <code>10111</code>, <code>10101</code>, <code>11100</code>, <code>10000</code>, and <code>11001</code>.</li>\n<li>Then, consider the second bit of the 7 remaining numbers: there are more <code>0</code> bits (4) than <code>1</code> bits (3), so keep only the 4 numbers with a <code>0</code> in the second position: <code>10110</code>, <code>10111</code>, <code>10101</code>, and <code>10000</code>.</li>\n<li>In the third position, three of the four numbers have a <code>1</code>, so keep those three: <code>10110</code>, <code>10111</code>, and <code>10101</code>.</li>\n<li>In the fourth position, two of the three numbers have a <code>1</code>, so keep those two: <code>10110</code> and <code>10111</code>.</li>\n<li>In the fifth position, there are an equal number of <code>0</code> bits and <code>1</code> bits (one each). So, to find the <em>oxygen generator rating</em>, keep the number with a <code>1</code> in that position: <code>10111</code>.</li>\n<li>As there is only one number left, stop; the <em>oxygen generator rating</em> is <code>10111</code>, or <code><em>23</em></code> in decimal.</li>\n</ul>\n<p>Then, to determine the <em>CO2 scrubber rating</em> value from the same example above:</p>\n<ul>\n<li>Start again with all 12 numbers and consider only the first bit of each number. There are fewer <code>0</code> bits (5) than <code>1</code> bits (7), so keep only the 5 numbers with a <code>0</code> in the first position: <code>00100</code>, <code>01111</code>, <code>00111</code>, <code>00010</code>, and <code>01010</code>.</li>\n<li>Then, consider the second bit of the 5 remaining numbers: there are fewer <code>1</code> bits (2) than <code>0</code> bits (3), so keep only the 2 numbers with a <code>1</code> in the second position: <code>01111</code> and <code>01010</code>.</li>\n<li>In the third position, there are an equal number of <code>0</code> bits and <code>1</code> bits (one each). So, to find the <em>CO2 scrubber rating</em>, keep the number with a <code>0</code> in that position: <code>01010</code>.</li>\n<li>As there is only one number left, stop; the <em>CO2 scrubber rating</em> is <code>01010</code>, or <code><em>10</em></code> in decimal.</li>\n</ul>\n<p>Finally, to find the life support rating, multiply the oxygen generator rating (<code>23</code>) by the CO2 scrubber rating (<code>10</code>) to get <code><em>230</em></code>.</p>\n<p>Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. <em>What is the life support rating of the submarine?</em> (Be sure to represent your answer in decimal, not binary.)</p>",
"_____no_output_____"
]
],
[
[
"let mostCommonBit bits = \n match (bits |> Seq.sum) with\n | sum when sum * 2 >= (bits |> Seq.length) -> 1\n | _ -> 0\n\nlet leastCommonBit bits = \n match (bits |> Seq.sum) with\n | sum when sum * 2 >= (bits |> Seq.length) -> 0\n | _ -> 1",
"_____no_output_____"
],
[
"let filter bitCriteria pos (input: seq<string>) = \n let column = \n input\n |> Seq.map (fun line -> line.ToCharArray() |> Seq.map (fun char -> char |> string |> int))\n |> Seq.transpose\n |> Seq.item pos\n |> Seq.cache\n \n let filterBit = \n column \n |> bitCriteria\n \n let criteria = \n column\n |> Seq.map (fun bit -> bit = filterBit)\n \n if input |> Seq.length = 1 then\n input\n else\n input\n |> Seq.zip criteria\n |> Seq.filter (fun (c, _) -> c)\n |> Seq.map (fun (_, line) -> line)",
"_____no_output_____"
],
[
"#!time\nlet oxygenGeneratorRating = \n [0..input.[0].Length-1]\n |> Seq.fold (fun acc pos -> filter mostCommonBit pos acc) input\n |> fun result -> Convert.ToInt32(result |> Seq.exactlyOne, 2)\n\nlet co2ScrubbingRating = \n [0..input.[0].Length-1]\n |> Seq.fold (fun acc pos -> filter leastCommonBit pos acc) input\n |> fun result -> Convert.ToInt32(result |> Seq.exactlyOne, 2)\n\noxygenGeneratorRating * co2ScrubbingRating",
"_____no_output_____"
]
],
[
[
"[Prev](Day02.ipynb) | [Next](Day04.ipynb)",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
e7b327f03243f02ca31daa498c3ef7bf8a959e18 | 11,832 | ipynb | Jupyter Notebook | Making Predictions/Python/Getting Predictions and Prediction Explanations.ipynb | hcchengithub/examples-for-data-scientists | 3523fe0cbdb86a1050b07555f004bac5d9cd3efb | [
"Apache-2.0"
] | null | null | null | Making Predictions/Python/Getting Predictions and Prediction Explanations.ipynb | hcchengithub/examples-for-data-scientists | 3523fe0cbdb86a1050b07555f004bac5d9cd3efb | [
"Apache-2.0"
] | null | null | null | Making Predictions/Python/Getting Predictions and Prediction Explanations.ipynb | hcchengithub/examples-for-data-scientists | 3523fe0cbdb86a1050b07555f004bac5d9cd3efb | [
"Apache-2.0"
] | null | null | null | 41.083333 | 573 | 0.591785 | [
[
[
"## Getting Predictions and Prediction Explanations\n\n**Author**: Thodoris Petropoulos\n\n**Label**: Model Deployment\n### Scope\n\nThe scope of this notebook is to provide instructions on how to get predictions and prediction explanations out of a trained model using the Python API.\n\n### Background\n\nThe main ways you can get predictions out of DataRobot using Python would be the modeling API and the prediction API.\n\n**Modeling API**: You can use the modelling API if you use Python or R and there are multiple ways you can interact with it.\n\n**Prediction API**: Any project can be called with the Prediction API if you have prediction servers. This is a simple REST API. Click on a model in the UI, then \"Deploy Model\" and \"Activate now\". You'll have access to a Python code snippet to help you interact with it. You can also deploy the model through the python API.\n\n\nFor the purposes of this tutorial, we will focus on the Modeling API. Note that this particular method of scoring utilizes modeling workers. This means that if someone is using these workers for modeling, your prediction is going to have to wait. This method of scoring is good for testing but not for deployment. For actual deployment, please deploy the model as a REST API through DataRobot's UI or through the API.\n\n### Requirements\n\n- Python version 3.7.3\n- DataRobot API version 2.19.0. \nSmall adjustments might be needed depending on the Python version and DataRobot API version you are using.\n\nFull documentation of the Python package can be found here: https://datarobot-public-api-client.readthedocs-hosted.com\n\nIt is assumed you already have a DataRobot <code>Project</code> object and a DataRobot <code>Model </code> object.",
"_____no_output_____"
],
[
"#### Import Libraries",
"_____no_output_____"
]
],
[
[
"import datarobot as dr",
"_____no_output_____"
]
],
[
[
"#### Requesting Predictions\n\nBefore actually requesting predictions, you should upload the dataset you wish to predict via <code>Project.upload_dataset</code>. Previously uploaded datasets can be seen under <code>Project.get_datasets</code>. When uploading the dataset you can provide the path to a local file, a file object, raw file content, a pandas.DataFrame object, or the url to a publicly available dataset.",
"_____no_output_____"
]
],
[
[
"#Uploading prediction dataset\ndataset_from_path = project.upload_dataset('path/file')\n\n#Request predictions\npredict_job = model.request_predictions(dataset_from_path.id)\n\n#Waiting for prediction calculations\npredictions = predict_job.get_result_when_complete()\n\npredictions.head()",
"_____no_output_____"
]
],
[
[
"#### Requesting Prediction Explanations\nIn order to create PredictionExplanations for a particular model and dataset, you must first Compute feature impact for the model via <code>dr.Model.get_or_request_feature_impact()</code>",
"_____no_output_____"
]
],
[
[
"model.get_or_request_feature_impact()\n\npei = dr.PredictionExplanationsInitialization.create(project.id, model.id)\n\n#Wait for results of Prediction Explanations\npei.get_result_when_complete()\n\npe_job = dr.PredictionExplanations.create(project.id, model.id, dataset_from_path.id)\n\n#Waiting for Job to Complete\npe = pe_job.get_result_when_complete()\n\ndf_pe = pe.get_all_as_dataframe()\ndf_pe.head()",
"_____no_output_____"
]
],
[
[
"#### Time Series Projects Caveats\nPrediction datasets are uploaded as normal predictions. However, when uploading a prediction dataset, a new parameter forecastPoint can be specified. The forecast point of a prediction dataset identifies the point in time relative which predictions should be generated, and if one is not specified when uploading a dataset, the server will choose the most recent possible forecast point. The forecast window specified when setting the partitioning options for the project determines how far into the future from the forecast point predictions should be calculated.\n\n**Important Note**:\nWhen uploading a dataset for Time Series projects scoring, you need to include the actual values from previous dates depending on the feature derivation setup. For example, if feature derivation window is -10 to -1 days and you want to forecast sales for the next 3 days, your dataset would look like this:\n\n| date | sales | Known_in_advance_feature |\n|------------|-------|--------------------------|\n| 01/01/2019 | 130 | AAA |\n| 02/01/2019 | 123 | VVV |\n| 03/01/2019 | 412 | BBB |\n| 04/01/2019 | 321 | DDD |\n| 05/01/2019 | 512 | DDD |\n| 06/01/2019 | 623 | VVV |\n| 07/01/2019 | 356 | CCC |\n| 08/01/2019 | 133 | AAA |\n| 09/01/2019 | 356 | CCC |\n| 10/01/2019 | 654 | DDD |\n| 11/01/2019 | | BBB |\n| 12/01/2019 | | CCC |\n| 13/01/2019 | | DDD |\n\nDataRobot will detect your forecast point as 10/01/2019 and then it will calculate lag features and make predictions for the missing dates.",
"_____no_output_____"
],
[
"#### Getting Predictions from a DataRobot Deployment\nIf you have used MLOps to deploy a model (DataRobot or Custom), you will have access to an API which you can call using an API Client. Below is a python script of an API Client. You can create your own API Client in the language of your choice!",
"_____no_output_____"
]
],
[
[
"\"\"\"\nUsage:\n python datarobot-predict.py <input-file.csv>\n \nThis example uses the requests library which you can install with:\n pip install requests\nWe highly recommend that you update SSL certificates with:\n pip install -U urllib3[secure] certifi\n\"\"\"\nimport sys\nimport json\nimport requests\n \nAPI_URL = 'Find this in Deployment -> Overview -> Summary -> Endpoint'\nAPI_KEY = 'YOUR_API_KEY'\nDATAROBOT_KEY = 'Find this in Deployment -> Predictions -> Prediction API -> Single mode -> on top of the code sample'\n \nDEPLOYMENT_ID = 'YOUR_DEPLOYMENT_ID'\nMAX_PREDICTION_FILE_SIZE_BYTES = 52428800 # 50 MB\n \n \nclass DataRobotPredictionError(Exception):\n \"\"\"Raised if there are issues getting predictions from DataRobot\"\"\"\n \n \ndef make_datarobot_deployment_predictions(data, deployment_id):\n \"\"\"\n Make predictions on data provided using DataRobot deployment_id provided.\n See docs for details:\n https://app.eu.datarobot.com/docs/users-guide/predictions/api/new-prediction-api.html\n \n Parameters\n ----------\n data : str\n Feature1,Feature2\n numeric_value,string\n deployment_id : str\n The ID of the deployment to make predictions with.\n \n Returns\n -------\n Response schema:\n https://app.eu.datarobot.com/docs/users-guide/predictions/api/new-prediction-api.html#response-schema\n \n Raises\n ------\n DataRobotPredictionError if there are issues getting predictions from DataRobot\n \"\"\"\n # Set HTTP headers. The charset should match the contents of the file.\n headers = {\n 'Content-Type': 'text/plain; charset=UTF-8',\n 'Authorization': 'Bearer {}'.format(API_KEY),\n 'DataRobot-Key': DATAROBOT_KEY,\n }\n \n url = API_URL.format(deployment_id=deployment_id)\n # Make API request for predictions\n predictions_response = requests.post(\n url,\n data=data,\n headers=headers,\n )\n _raise_dataroboterror_for_status(predictions_response)\n # Return a Python dict following the schema in the documentation\n return predictions_response.json()\n \n \ndef _raise_dataroboterror_for_status(response):\n \"\"\"Raise DataRobotPredictionError if the request fails along with the response returned\"\"\"\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError:\n err_msg = '{code} Error: {msg}'.format(\n code=response.status_code, msg=response.text)\n raise DataRobotPredictionError(err_msg)\n \n \ndef main(filename, deployment_id):\n \"\"\"\n Return an exit code on script completion or error. Codes > 0 are errors to the shell.\n Also useful as a usage demonstration of\n `make_datarobot_deployment_predictions(data, deployment_id)`\n \"\"\"\n if not filename:\n print(\n 'Input file is required argument. '\n 'Usage: python datarobot-predict.py <input-file.csv>')\n return 1\n data = open(filename, 'rb').read()\n data_size = sys.getsizeof(data)\n if data_size >= MAX_PREDICTION_FILE_SIZE_BYTES:\n print(\n 'Input file is too large: {} bytes. '\n 'Max allowed size is: {} bytes.'\n ).format(data_size, MAX_PREDICTION_FILE_SIZE_BYTES)\n return 1\n try:\n predictions = make_datarobot_deployment_predictions(data, deployment_id)\n except DataRobotPredictionError as exc:\n print(exc)\n return 1\n print(json.dumps(predictions, indent=4))\n return 0\n \n \nif __name__ == \"__main__\":\n filename = sys.argv[1]\n sys.exit(main(filename, DEPLOYMENT_ID))\n ",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
]
] |
e7b336693c351e432e07f43c595ffa16ea09d239 | 207,036 | ipynb | Jupyter Notebook | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML | 6e7b107e1f8a7a5922489eb81143db8656ff01af | [
"BSD-3-Clause"
] | 1 | 2021-02-08T22:58:39.000Z | 2021-02-08T22:58:39.000Z | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML | 6e7b107e1f8a7a5922489eb81143db8656ff01af | [
"BSD-3-Clause"
] | null | null | null | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML | 6e7b107e1f8a7a5922489eb81143db8656ff01af | [
"BSD-3-Clause"
] | 1 | 2021-08-20T09:06:42.000Z | 2021-08-20T09:06:42.000Z | 279.778378 | 81,697 | 0.918212 | [
[
[
"<table border=\"0\">\n <tr>\n <td>\n <img src=\"https://ictd2016.files.wordpress.com/2016/04/microsoft-research-logo-copy.jpg\" style=\"width 30px;\" />\n </td>\n <td>\n <img src=\"https://www.microsoft.com/en-us/research/wp-content/uploads/2016/12/MSR-ALICE-HeaderGraphic-1920x720_1-800x550.jpg\" style=\"width 100px;\"/></td>\n </tr>\n</table>",
"_____no_output_____"
],
[
"# Double Machine Learning: Summarized Data and Interpretability\n\nDouble Machine Learning (DML) is an algorithm that applies arbitrary machine learning methods\nto fit the treatment and response, then uses a linear model to predict the response residuals\nfrom the treatment residuals.",
"_____no_output_____"
]
],
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"# Helper imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n%matplotlib inline\n\nimport seaborn as sns",
"_____no_output_____"
]
],
[
[
"# Generating Raw Data",
"_____no_output_____"
]
],
[
[
"import scipy.special\n\nnp.random.seed(123)\nn=10000 # number of raw samples\nd=10 # number of binary features + 1\n\n# Generating random segments aka binary features. We will use features 1,...,4 for heterogeneity.\n# The rest for controls. Just as an example.\nX = np.random.binomial(1, .5, size=(n, d))\n# The first column of X is the treatment. Generating an imbalanced A/B test\nX[:, 0] = np.random.binomial(1, scipy.special.expit(X[:, 1]))\n# Generating an outcome with treatment effect heterogeneity. The first binary feature creates heterogeneity\n# We also have confounding on the first variable. We also have heteroskedastic errors.\ny = (-1 + 2 * X[:, 1]) * X[:, 0] + X[:, 1] + (1*X[:, 1] + 1)*np.random.normal(0, 1, size=(n,))",
"_____no_output_____"
]
],
[
[
"# Creating Summarized Data\n\nFor each segment, we split the data in two and create one summarized copy for each split. The summarized copy contains the number of samples that were summarized and the variance of the observations for the summarized copies. Optimally we would want two copies per segment, as I'm creating here, but with many segments, the approach would work ok even with a single copy per segment.",
"_____no_output_____"
]
],
[
[
"from econml.tests.test_statsmodels import _summarize\n\nX_sum = np.unique(X, axis=0)\nn_sum = np.zeros(X_sum.shape[0])\n# The _summarize function performs the summary operation and returns the summarized data\n# For each segment we have two copies.\nX1, X2, y1, y2, X1_sum, X2_sum, y1_sum, y2_sum, n1_sum, n2_sum, var1_sum, var2_sum = _summarize(X, y)\n\n# We concatenate the two copies data\nX_sum = np.vstack([X1_sum, X2_sum]) # first coordinate is treatment, the rest are features\ny_sum = np.concatenate((y1_sum, y2_sum)) # outcome\nn_sum = np.concatenate((n1_sum, n2_sum)) # number of summarized points\nvar_sum = np.concatenate((var1_sum, var2_sum)) # variance of the summarized points\nsplits = (np.arange(len(y1_sum)), np.arange(len(y1_sum), len(y_sum))) # indices of the two summarized copies",
"_____no_output_____"
]
],
[
[
"# Applying the LinearDML",
"_____no_output_____"
]
],
[
[
"from econml.sklearn_extensions.linear_model import WeightedLassoCV\nfrom econml.dml import LinearDML\nfrom sklearn.linear_model import LogisticRegressionCV\n\n# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly\n# as long as it accepts the sample_weight keyword argument at fit time.\nest = LinearDML(model_y=WeightedLassoCV(cv=3),\n model_t=LogisticRegressionCV(cv=3),\n discrete_treatment=True)\nest.fit(y_sum, X_sum[:, 0], X=X_sum[:, 1:5], W=X_sum[:, 5:],\n sample_weight=n_sum, sample_var=var_sum)",
"_____no_output_____"
],
[
"# Treatment Effect of particular segments\nest.effect(np.array([[1, 0, 0, 0]])) # effect of segment with features [1, 0, 0, 0]",
"_____no_output_____"
],
[
"# Confidence interval for effect\nest.effect_interval(np.array([[1, 0, 0, 0]]), alpha=.05) # effect of segment with features [1, 0, 0, 0]",
"_____no_output_____"
],
[
"# Getting the coefficients of the linear CATE model together with the corresponding feature names\nprint(np.array(list(zip(est.cate_feature_names(['A', 'B', 'C', 'D']), est.coef_))))",
"[['A' '2.0151755553187574']\n ['B' '0.07589941486626034']\n ['C' '-0.026742049958516114']\n ['D' '-0.12871399676275952']]\n"
]
],
[
[
"## Non-Linear CATE Models with Polynomial Features",
"_____no_output_____"
]
],
[
[
"from econml.sklearn_extensions.linear_model import WeightedLassoCV\nfrom econml.dml import LinearDML\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom sklearn.preprocessing import PolynomialFeatures\n\n# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly\n# as long as it accepts the sample_weight keyword argument at fit time.\nest = LinearDML(model_y=WeightedLassoCV(cv=3),\n model_t=LogisticRegressionCV(cv=3),\n featurizer=PolynomialFeatures(degree=2, interaction_only=True, include_bias=False),\n discrete_treatment=True)\nest.fit(y_sum, X_sum[:, 0], X=X_sum[:, 1:5], W=X_sum[:, 5:],\n sample_weight=n_sum, sample_var=var_sum)",
"_____no_output_____"
],
[
"# Getting the confidence intervals of the coefficients and the intercept of the CATE model\n# together with the corresponding feature names.\nfeat_names = est.cate_feature_names(['A', 'B', 'C', 'D'])\npoint_int = est.intercept_\npoint = est.coef_\nlower_int, upper_int = est.intercept__interval(alpha=0.01)\nlower, upper = est.coef__interval(alpha=0.01)\nyerr = np.zeros((2, point.shape[0]))\nyerr[0, :] = point - lower\nyerr[1, :] = upper - point\n\nwith sns.axes_style('darkgrid'):\n fig, ax = plt.subplots(1,1)\n x = np.arange(1, 1 + len(point))\n plt.errorbar(np.concatenate(([0], x)), np.concatenate(([point_int], point)),\n np.hstack([np.array([[point_int-lower_int], [upper_int - point_int]]), yerr]), fmt='o')\n ax.set_xticks(np.concatenate(([0], x)))\n ax.set_xticklabels([1] + list(feat_names), rotation='vertical', fontsize=18)\n ax.set_ylabel('coef')\n plt.show()",
"_____no_output_____"
],
[
"import itertools\n# Getting the confidence intervals of the CATE(x) for different x vectors\nfnames = np.array(['A', 'B', 'C', 'D'])\n\nlst = list(itertools.product([0, 1], repeat=4))\npoint = []\nlower = []\nupper = []\nfeat_names = []\nfor x in lst:\n feat_names.append(\" \".join(fnames[np.array(x)>0]))\n x = np.array(x).reshape((1, -1))\n point.append(est.effect(x)[0])\n lb, ub = est.effect_interval(x, alpha=.01)\n lower.append(lb[0])\n upper.append(ub[0])\n\nfeat_names = np.array(feat_names)\npoint = np.array(point)\nlower = np.array(lower)\nupper = np.array(upper)\nyerr = np.zeros((2, point.shape[0]))\nyerr[0, :] = point - lower\nyerr[1, :] = upper - point\n\nwith sns.axes_style('darkgrid'):\n fig, ax = plt.subplots(1,1, figsize=(20, 5)) \n x = np.arange(len(point))\n stat_sig = (lower>0) | (upper<0)\n plt.errorbar(x[stat_sig], point[stat_sig], yerr[:, stat_sig], fmt='o', label='stat_sig')\n plt.errorbar(x[~stat_sig], point[~stat_sig], yerr[:, ~stat_sig], fmt='o', color='red', label='insig')\n ax.set_xticks(x)\n ax.set_xticklabels(feat_names, rotation='vertical', fontsize=18)\n ax.set_ylabel('coef')\n plt.legend()\n plt.show()",
"_____no_output_____"
]
],
[
[
"# Non-Linear CATE Models with Forests",
"_____no_output_____"
]
],
[
[
"from econml.dml import CausalForestDML\nfrom sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier\n\n# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly\n# as long as it accepts the sample_weight keyword argument at fit time.\nest = CausalForestDML(model_y=GradientBoostingRegressor(n_estimators=30, min_samples_leaf=30),\n model_t=GradientBoostingClassifier(n_estimators=30, min_samples_leaf=30),\n discrete_treatment=True,\n n_estimators=1000,\n min_samples_leaf=2,\n min_impurity_decrease=0.001,\n verbose=0, min_weight_fraction_leaf=.03)\nest.fit(y_sum, X_sum[:, 0], X=X_sum[:, 1:5], W=X_sum[:, 5:],\n sample_weight=n_sum, sample_var=None)",
"_____no_output_____"
],
[
"import itertools\n# Getting the confidence intervals of the CATE(x) for different x vectors\nfnames = np.array(['A', 'B', 'C', 'D'])\n\nlst = list(itertools.product([0, 1], repeat=4))\npoint = []\nlower = []\nupper = []\nfeat_names = []\nfor x in lst:\n feat_names.append(\" \".join(fnames[np.array(x)>0]))\n x = np.array(x).reshape((1, -1))\n point.append(est.effect(x)[0])\n lb, ub = est.effect_interval(x, alpha=.01)\n lower.append(lb[0])\n upper.append(ub[0])\n\nfeat_names = np.array(feat_names)\npoint = np.array(point)\nlower = np.array(lower)\nupper = np.array(upper)\nyerr = np.zeros((2, point.shape[0]))\nyerr[0, :] = point - lower\nyerr[1, :] = upper - point\n\nwith sns.axes_style('darkgrid'):\n fig, ax = plt.subplots(1,1, figsize=(20, 5)) \n x = np.arange(len(point))\n stat_sig = (lower>0) | (upper<0)\n plt.errorbar(x[stat_sig], point[stat_sig], yerr[:, stat_sig], fmt='o', label='stat_sig')\n plt.errorbar(x[~stat_sig], point[~stat_sig], yerr[:, ~stat_sig], fmt='o', color='red', label='insig')\n ax.set_xticks(x)\n ax.set_xticklabels(feat_names, rotation='vertical', fontsize=18)\n ax.set_ylabel('coef')\n plt.legend()\n plt.show()",
"_____no_output_____"
]
],
[
[
"# Tree Interpretation of the CATE Model",
"_____no_output_____"
]
],
[
[
"from econml.cate_interpreter import SingleTreeCateInterpreter",
"_____no_output_____"
],
[
"intrp = SingleTreeCateInterpreter(include_model_uncertainty=True, max_depth=2, min_samples_leaf=1)\n# We interpret the CATE models behavior on the distribution of heterogeneity features\nintrp.interpret(est, X_sum[:, 1:5])",
"_____no_output_____"
],
[
"# exporting to a dot file\nintrp.export_graphviz(out_file='cate_tree.dot', feature_names=['A', 'B', 'C', 'D'])",
"_____no_output_____"
],
[
"# or we can directly render. Requires the graphviz python library\nintrp.render(out_file='cate_tree', format='pdf', view=True, feature_names=['A', 'B', 'C', 'D'])",
"_____no_output_____"
],
[
"# or we can also plot inline with matplotlib. a bit uglier\nplt.figure(figsize=(25, 5))\nintrp.plot(feature_names=['A', 'B', 'C', 'D'], fontsize=12)\nplt.show()",
"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:4: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.\n after removing the cwd from sys.path.\n"
]
],
[
[
"# Tree Based Treatment Policy Based on CATE Model",
"_____no_output_____"
]
],
[
[
"from econml.cate_interpreter import SingleTreePolicyInterpreter",
"_____no_output_____"
],
[
"intrp = SingleTreePolicyInterpreter(risk_level=0.05, max_depth=3, min_samples_leaf=1, min_impurity_decrease=.001)\n# We find a tree based treatment policy based on the CATE model\n# sample_treatment_costs is the cost of treatment. Policy will treat if effect is above this cost.\n# It can also be an array that has a different cost for each sample. In case treating different segments\n# has different cost.\nintrp.interpret(est, X_sum[:, 1:5],\n sample_treatment_costs=0)",
"_____no_output_____"
],
[
"# exporting to a dot file\nintrp.export_graphviz(out_file='cate_tree.dot', feature_names=['A', 'B', 'C', 'D'])",
"_____no_output_____"
],
[
"# or we can directly render. Requires the graphviz python library\nintrp.render(out_file='policy_tree', format='pdf', view=True, feature_names=['A', 'B', 'C', 'D'])",
"_____no_output_____"
],
[
"# or we can also plot inline with matplotlib. a bit uglier\nplt.figure(figsize=(25, 5))\nintrp.plot(feature_names=['A', 'B', 'C', 'D'], fontsize=14)\nplt.show()",
"C:\\ProgramData\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:4: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.\n after removing the cwd from sys.path.\n"
]
],
[
[
"# Appendix: Amendment\n\nTo make estimation even more precise one should simply choose the two splits used during the crossfit part of Double Machine Learning so that each summaried copy of a segment ends up in a separate split. We can do this as follows: ",
"_____no_output_____"
]
],
[
[
"from econml.sklearn_extensions.linear_model import WeightedLassoCV\nfrom econml.dml import LinearDML\nfrom sklearn.linear_model import LogisticRegressionCV\n\n# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly\n# as long as it accepts the sample_weight keyword argument at fit time.\nest = LinearDML(model_y=WeightedLassoCV(cv=3),\n model_t=LogisticRegressionCV(cv=3),\n discrete_treatment=True,\n cv=[(splits[0], splits[1]), (splits[1], splits[0])]) # we input custom fold structure\nest.fit(y_sum, X_sum[:, 0], X=X_sum[:, 1:5], W=X_sum[:, 5:],\n sample_weight=n_sum, sample_var=var_sum)",
"_____no_output_____"
],
[
"# Treatment Effect of particular segments\nest.effect(np.array([[1, 0, 0, 0]])) # effect of segment with features [1, 0, 0, 0]",
"_____no_output_____"
],
[
"# Confidence interval for effect\nest.effect_interval(np.array([[1, 0, 0, 0]])) # effect of segment with features [1, 0, 0, 0]",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7b33d05ef7862348a15a9ac08a71a82d6b526de | 9,340 | ipynb | Jupyter Notebook | notebooks/ModelPredict.ipynb | AdamBarnhard/bike_classifier_whisk_0_1_21 | 46c09d164853a5207861454e21a905d4e401608d | [
"MIT"
] | 1 | 2021-11-12T03:41:36.000Z | 2021-11-12T03:41:36.000Z | notebooks/ModelPredict.ipynb | AdamBarnhard/bike_classifier_whisk_0_1_21 | 46c09d164853a5207861454e21a905d4e401608d | [
"MIT"
] | 8 | 2020-05-12T22:27:31.000Z | 2022-03-12T00:29:34.000Z | notebooks/ModelPredict.ipynb | AdamBarnhard/bike_classifier_whisk_0_1_21 | 46c09d164853a5207861454e21a905d4e401608d | [
"MIT"
] | null | null | null | 43.44186 | 1,495 | 0.632013 | [
[
[
"# Load the \"autoreload\" extension. Prior to executing code, modules are reloaded. \n# There's no need to restart jupyter notebook if you modify code in the `src` directory.\n# https://ipython.org/ipython-doc/3/config/extensions/autoreload.html\n%load_ext autoreload\n\n# OPTIONAL: always reload modules so that as you change code in src, it gets loaded\n%autoreload 2\n",
"_____no_output_____"
],
[
"# import Model\nfrom bike_classifier_whisk_0_1_21.models.model import Model\n\n# import data_dir\nimport bike_classifier_whisk_0_1_21\nimport json",
"_____no_output_____"
],
[
"from bike_classifier_whisk_0_1_21 import project",
"_____no_output_____"
],
[
"Model().predict(project.data_dir / 'raw/Examples/full_2020_grail-al-7-0_2370_sr-bk_P5.png')",
"_____no_output_____"
],
[
"Model().predict(bike_classifier_whisk_0_1_21.project.data_dir / 'raw/Examples/full_2020_strive-cf-7-0_2239_tm_P5.png')",
"_____no_output_____"
],
[
"Model().predict(bike_classifier_whisk_0_1_21.project.data_dir / 'raw/Examples/Marin-Nicasio-plus-outside.jpg')",
"_____no_output_____"
],
[
"Model().predict(bike_classifier_whisk_0_1_21.project.data_dir / 'raw/Examples/PUBLIC-R24-Road-Bike-Cream_010_720x.jpg')",
"_____no_output_____"
],
[
"Model().predict(bike_classifier_whisk_0_1_21.project.data_dir / 'raw/Examples/Marlin5_19_23134_A_Primary.jpeg')",
"_____no_output_____"
],
[
"Model().predict('https://whisk-examples.s3.amazonaws.com/bike-images/full_2020_strive-cf-7-0_2239_tm_P5.png')",
"_____no_output_____"
],
[
"json.loads(\"[test]\")",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b34ac9320cea7af187960778555bb792453e33 | 46,601 | ipynb | Jupyter Notebook | notebooks/Experimental/Ishan/ADP Demo/Old Versions/Final Demo DataScientist.ipynb | Noob-can-Compile/PySyft | 156cf93489b16dd0205b0058d4d23d56b3a91ab8 | [
"Apache-2.0"
] | null | null | null | notebooks/Experimental/Ishan/ADP Demo/Old Versions/Final Demo DataScientist.ipynb | Noob-can-Compile/PySyft | 156cf93489b16dd0205b0058d4d23d56b3a91ab8 | [
"Apache-2.0"
] | null | null | null | notebooks/Experimental/Ishan/ADP Demo/Old Versions/Final Demo DataScientist.ipynb | Noob-can-Compile/PySyft | 156cf93489b16dd0205b0058d4d23d56b3a91ab8 | [
"Apache-2.0"
] | null | null | null | 69.553731 | 1,392 | 0.674471 | [
[
[
"import syft as sy\nimport numpy as np\nfrom syft.core.adp.entity import DataSubject",
"_____no_output_____"
],
[
"domain_node = sy.login(email=\"[email protected]\", password=\"please_work\", port=8081)",
"Connecting to http://localhost:8081... done! \t Logging into adp... done!\n"
],
[
"# See what's on the Domain Node\ndomain_node.store.pandas",
"_____no_output_____"
],
[
"# Get a pointer for the last entry, which is a dataset\nprivate_dataset_ptr = domain_node.store[\"db0a433c93484a9ca2a8d4f5d691f139\"]",
"_____no_output_____"
],
[
"private_dataset_ptr",
"_____no_output_____"
],
[
"private_dataset_ptr.request(reason=\"Need to access the dataset\")",
"_____no_output_____"
]
],
[
[
"# Working with remote analysis\n\n## Columns in remote dataset:\nClassification\nYear\nPeriod\nPeriod Desc.\nAggregate Level\nIs Leaf Code\n\nTrade Flow Code\nTrade Flow\nReporter Code\nReporter\nReporter ISO\nPartner Code\nPartner\nPartner ISO\nCommodity Code\nCommodity\nQty Unit Code\nQty Unit\nQty\nNetweight (kg)\nTrade Value (US$)\nFlag\n\n",
"_____no_output_____"
]
],
[
[
"# Our request was denied, we will get an error\nprivate_dataset_ptr.get()",
"[2021-08-11T11:35:46.003018-0400][CRITICAL][logger]][26891] You do not have permission to .get() Object with ID: <UID: db0a433c93484a9ca2a8d4f5d691f139>Please submit a request.\n"
],
[
"total_sum = 0\nfor row in private_dataset_ptr:\n if row[6] == 1: # Trade Flow Code 1 == Import\n print(\"This row was imported\")\n total_sum += row[-2]\nprint(f'The total value of all Canadian Imports in this dataset amounts to USD${total_sum}')",
"{'request_block': True, 'timeout_secs': 25, 'delete_obj': False}\n"
],
[
"for i in private_dataset_ptr:\n print(i)",
"<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11160>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x10454d5e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb5b0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5ee0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeba00>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc81c0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeba00>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeba00>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x10454d5e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb130>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5cd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e2289a0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11160>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11dc0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc81c0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x10454d5e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb130>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5cd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddebb80>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddebfd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de112e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11220>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb5b0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x10454d5e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb130>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb5b0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e2289a0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc81c0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5ee0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e2289a0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e2289a0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5cd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb5b0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13db56160>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x10454d5e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5cd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb130>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5cd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeba00>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc81c0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddebb80>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13db56160>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5ee0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11dc0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddebfd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13db56160>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc81c0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeba00>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x10454d5e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11310>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13db56160>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeba00>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5ee0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5ee0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb130>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddebfd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeba00>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5cd0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb130>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f5ee0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e2289a0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13db56160>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13d7f84f0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e2289a0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddebb80>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc82e0>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb130>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13dbc8340>\n<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca790>\n"
]
]
] | [
"code",
"markdown",
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7b3535558141460cf21b5ae5161ce69cd23bf22 | 5,754 | ipynb | Jupyter Notebook | Titanic TPOT.ipynb | DiegoHueltes/aml-bigdataspain | d778272a8286a70f69c612f3bb456d3693d3c729 | [
"MIT"
] | 1 | 2019-05-19T02:48:48.000Z | 2019-05-19T02:48:48.000Z | Titanic TPOT.ipynb | DiegoHueltes/aml-bigdataspain | d778272a8286a70f69c612f3bb456d3693d3c729 | [
"MIT"
] | null | null | null | Titanic TPOT.ipynb | DiegoHueltes/aml-bigdataspain | d778272a8286a70f69c612f3bb456d3693d3c729 | [
"MIT"
] | null | null | null | 29.96875 | 284 | 0.528328 | [
[
[
"from tpot import TPOTClassifier\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"def load_and_labelize_titanic(filename, encoders=None):\n \"\"\"Read csv and perform basic labeling encoding\"\"\"\n \n df = pd.read_csv(filename)\n if not encoders:\n encoders = {'Sex': LabelEncoder(), \n 'Cabin': LabelEncoder(), \n 'Embarked': LabelEncoder()}\n for column, encoder in encoders.items():\n encoder.fit(list(df[column].astype(str)) + ['UnknownLabel'])\n df[column] = encoder.transform(df[column].astype(str))\n else:\n for column, encoder in encoders.items():\n df.loc[~df[column].isin(encoder.classes_), column] = 'UnknownLabel'\n df[column] = encoder.transform(df[column].astype(str))\n \n df = df.fillna(-999)\n passenger_ids = df['PassengerId']\n df = df.drop(['PassengerId', 'Name', 'Ticket'], axis=1)\n return df, encoders, passenger_ids",
"_____no_output_____"
],
[
"train, encoders, _ = load_and_labelize_titanic('titanic/train.csv')",
"_____no_output_____"
],
[
"tpot = TPOTClassifier(generations=5, population_size=50, verbosity=2, \n n_jobs=1, scoring='accuracy')\ntpot.fit(train.drop('Survived', axis=1).values, train['Survived'])",
"Optimization Progress: 33%|███▎ | 100/300 [00:57<01:29, 2.24pipeline/s]"
],
[
"test, _, passenger_ids = load_and_labelize_titanic('titanic/test.csv', encoders)\nresults = tpot.predict(test)\nresults_df = pd.DataFrame({'PassengerId': passenger_ids, 'Survived': results})\nresults_df.to_csv('titanic/predictions.csv', index=False)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code"
]
] |
e7b35554fc08ff945fdbab8e18d67ba1ebdfc863 | 18,324 | ipynb | Jupyter Notebook | CLIP Algorithm research/Image Scraper.ipynb | drkkgy/CLIP_ALGO_PROJECT | a94d483a8f282eefe8adb9f497dec1d7661bf783 | [
"MIT"
] | 1 | 2021-09-27T16:07:51.000Z | 2021-09-27T16:07:51.000Z | CLIP Algorithm research/Image Scraper.ipynb | drkkgy/CLIP_ALGO_PROJECT | a94d483a8f282eefe8adb9f497dec1d7661bf783 | [
"MIT"
] | null | null | null | CLIP Algorithm research/Image Scraper.ipynb | drkkgy/CLIP_ALGO_PROJECT | a94d483a8f282eefe8adb9f497dec1d7661bf783 | [
"MIT"
] | null | null | null | 61.08 | 450 | 0.676872 | [
[
[
"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport os\nimport time\nimport io\nfrom PIL import Image\nimport PIL\nimport hashlib\n\n",
"_____no_output_____"
],
[
"import selenium\nfrom selenium import webdriver\n# This is the path I use\n# DRIVER_PATH = '.../Desktop/Scraping/chromedriver 2'\n# Put the path for your ChromeDriver here\nDRIVER_PATH = 'D:\\Adelaide Study Details\\Sem-1\\Research\\CLIP Algorithm research\\chromedriver'\nwd = webdriver.Chrome(executable_path=DRIVER_PATH)",
"_____no_output_____"
],
[
"def fetch_image_urls(query:str, max_links_to_fetch:int, wd:webdriver, sleep_between_interactions:int=1):\n def scroll_to_end(wd):\n wd.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(sleep_between_interactions) \n \n # build the google query\n search_url = \"https://www.google.com/search?safe=off&site=&tbm=isch&source=hp&q={q}&oq={q}&gs_l=img\"\n\n # load the page\n wd.get(search_url.format(q=query))\n\n image_urls = set()\n image_name = set()\n image_count = 0\n results_start = 0\n while image_count < max_links_to_fetch:\n scroll_to_end(wd)\n\n # get all image thumbnail results\n thumbnail_results = wd.find_elements_by_css_selector(\"img.Q4LuWd\")\n number_results = len(thumbnail_results)\n \n print(f\"Found: {number_results} search results. Extracting links from {results_start}:{number_results}\")\n \n for img in thumbnail_results[results_start:number_results]:\n # try to click every thumbnail such that we can get the real image behind it\n try:\n img.click()\n time.sleep(sleep_between_interactions)\n except Exception:\n continue\n\n # extract image urls \n actual_images = wd.find_elements_by_css_selector('img.n3VNCb')\n for actual_image in actual_images:\n if actual_image.get_attribute('src') and 'http' in actual_image.get_attribute('src'):\n image_urls.add(actual_image.get_attribute('src'))\n image_name.add(actual_image.get_attribute('alt'))\n\n image_count = len(image_urls)\n\n if len(image_urls) >= max_links_to_fetch:\n print(f\"Found: {len(image_urls)} image links, done!\")\n break\n else:\n print(\"Found:\", len(image_urls), \"image links, looking for more ...\")\n time.sleep(30)\n return\n load_more_button = wd.find_element_by_css_selector(\".mye4qd\")\n if load_more_button:\n wd.execute_script(\"document.querySelector('.mye4qd').click();\")\n\n # move the result startpoint further down\n results_start = len(thumbnail_results)\n\n return image_urls,image_name",
"_____no_output_____"
],
[
"def persist_image(folder_path:str,url:str,img_name:str):\n try:\n image_content = requests.get(url).content\n\n except Exception as e:\n print(f\"ERROR - Could not download {url} - {e}\")\n\n try:\n image_file = io.BytesIO(image_content)\n image = Image.open(image_file).convert('RGB')\n #file_path = os.path.join(folder_path,img_name + '.jpg')\n file_path = os.path.join(folder_path,hashlib.sha1(image_content).hexdigest()[:10].replace(\n hashlib.sha1(image_content).hexdigest()[:10], img_name) + '.jpg')\n with open(file_path, 'wb') as f:\n image.save(f, \"JPEG\", quality=85)\n print(f\"SUCCESS - saved {url} - as {file_path}\")\n except Exception as e:\n print(f\"ERROR - Could not save {url} - {e}\")\n \n",
"_____no_output_____"
],
[
"def search_and_download(search_term:str,driver_path:str,target_path='./images',number_images=5):\n target_folder = os.path.join(target_path,'_'.join(search_term.lower().split(' ')))\n\n if not os.path.exists(target_folder):\n os.makedirs(target_folder)\n\n with webdriver.Chrome(executable_path=driver_path) as wd:\n res,name = fetch_image_urls(search_term, number_images, wd=wd, sleep_between_interactions=1)\n \n for elem,name1 in zip(res,name):\n persist_image(target_folder,elem,name1.replace(\" \", \"_\"))\n return \"Scraping completed\"",
"_____no_output_____"
],
[
"search_term_dog = ['dog','dog in house','small dog','big dog','furry dog','cute dog','happy dog','sitting dog','dancing dog',\n 'good dog']\n\nfor search_term in search_term_dog:\n\n search_and_download(search_term=search_term,driver_path=DRIVER_PATH,number_images = 1)\n\n",
"Found: 100 search results. Extracting links from 0:100\nFound: 25 image links, done!\nERROR - Could not save https://akm-img-a-in.tosshub.com/indiatoday/images/story/202108/international_dog_day_2021_4_r_1200x768.jpeg?mhENil.rEsB2Wju30UDroUYKmJ4NfkX4&size=770:433 - [Errno 22] Invalid argument: './images\\\\dog\\\\Planning_on_bringing_home_a_dog?_Make_sure_you_pick_the_right_one_|__Lifestyle_News,The_Indian_Express.jpg'\nSUCCESS - saved https://post.medicalnewstoday.com/wp-content/uploads/sites/3/2020/02/322868_1100-800x825.jpg - as ./images\\dog\\12_Common_Dog_Breeds_and_Their_Health_Issues.jpg\nSUCCESS - saved https://www.cdc.gov/healthypets/images/pets/cute-dog-headshot.jpg?_=42445 - as ./images\\dog\\Dogs.jpg\nSUCCESS - saved https://www.cdc.gov/healthypets/images/pets/angry-dog.jpg?_=03873 - as ./images\\dog\\How_canines_capture_your_heart:_scientists_explain_puppy_dog_eyes_|_Animal__behaviour_|_The_Guardian.jpg\nSUCCESS - saved https://i.natgeofe.com/n/4f5aaece-3300-41a4-b2a8-ed2708a0a27c/domestic-dog_thumb_4x3.jpg - as ./images\\dog\\How_dogs_contribute_to_your_health_and_happiness.jpg\nERROR - Could not save https://www.gannett-cdn.com/media/2021/06/03/USATODAY/usatsports/imageForEntry18-8on.jpg?width=2560 - [Errno 22] Invalid argument: './images\\\\dog\\\\Dogs_|_Healthy_Pets,_Healthy_People_|_CDC.jpg'\nERROR - Could not save https://i.insider.com/5484d9d1eab8ea3017b17e29?width=600&format=jpeg&auto=webp - [Errno 22] Invalid argument: './images\\\\dog\\\\The_Best_Dogs_of_BBC_Earth_|_Top_5_|_BBC_Earth_-_YouTube.jpg'\nSUCCESS - saved https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSfMrZwXNHTlMVE-SymlzpcIL7mEBNV0ML9lw&usqp=CAU - as ./images\\dog\\A_German_shepherd_is_first_dog_in_the_U.S._to_test_positive_for_the__coronavirus.jpg\nSUCCESS - saved https://ggsc.s3.amazonaws.com/images/uploads/The_Science-Backed_Benefits_of_Being_a_Dog_Owner.jpg - as ./images\\dog\\Dog_breeds:_Most_popular_in_America.jpg\nSUCCESS - saved https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTop31TFo1k5vRkHWnmq6ujs6lJe0LJyMLbZg&usqp=CAU - as ./images\\dog\\Dog_Breeds_Banned_By_Home_Insurance_Companies_–_Forbes_Advisor.jpg\nSUCCESS - saved https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRlfjz8jGVsfPpSxI00bmHe9dm1InvBQQJTPw&usqp=CAU - as ./images\\dog\\Best_Friends:_You_and_Your_Dog_-_HelpGuide.org.jpg\nSUCCESS - saved https://images.indianexpress.com/2021/07/dog-2785074_1280.jpg - as ./images\\dog\\Dogs_caught_coronavirus_from_their_owners,_genetic_analysis_suggests.jpg\nSUCCESS - saved https://i.ytimg.com/vi/MPV2METPeJU/maxresdefault.jpg - as ./images\\dog\\The_25_Cutest_Dog_Breeds_-_Most_Adorable_Dogs_and_Puppies.jpg\nSUCCESS - saved https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=1200:* - as ./images\\dog\\Parvo_in_Dogs_and_Puppies:_Causes_and_Treatment_for_Canine_Parvovirus_|__PetMD.jpg\nERROR - Could not save https://i.natgeofe.com/n/187b3223-0b45-4aa5-ae5c-24793dd2d6cb/01-german-shepherd-coronavirus-bwtkdt_3x4.jpg - [Errno 22] Invalid argument: './images\\\\dog\\\\What_animal_welfare_problems_are_associated_with_dog_breeding?_–_RSPCA__Knowledgebase.jpg'\nSUCCESS - saved https://media.nature.com/lw800/magazine-assets/d41586-020-01430-5/d41586-020-01430-5_17977552.jpg - as ./images\\dog\\Dog,_facts_and_photos.jpg\nSUCCESS - saved https://post.healthline.com/wp-content/uploads/2020/08/3180-Pug_green_grass-732x549-thumbnail-732x549.jpg - as ./images\\dog\\Hong_Kong_dog_causes_panic_–_but_here's_why_you_needn't_worry_about_pets__spreading_COVID-19.jpg\nERROR - Could not save https://s3-us-west-2.amazonaws.com/uw-s3-cdn/wp-content/uploads/sites/6/2019/10/08113321/Dog-behavior-Kasper-Luijsterburg.jpg - [Errno 22] Invalid argument: './images\\\\dog\\\\Genes_contribute_to_dog_breeds'_iconic_traits_|_UW_News.jpg'\nSUCCESS - saved https://www.helpguide.org/wp-content/uploads/king-charles-spaniel-resting-head-768.jpg - as ./images\\dog\\International_Dog_Day_2021:_History,_significance,_celebrations,_images_and__quotes|_Everything_you_need_to_know_-_Information_News.jpg\nSUCCESS - saved https://i.guim.co.uk/img/media/fe1e34da640c5c56ed16f76ce6f994fa9343d09d/0_174_3408_2046/master/3408.jpg?width=1200&height=900&quality=85&auto=format&fit=crop&s=0d3f33fb6aa6e0154b7713a00454c83d - as ./images\\dog\\9_Reasons_to_Own_a_Dog.jpg\nSUCCESS - saved https://kb.rspca.org.au/wp-content/uploads/2018/11/golder-retriever-puppy.jpeg - as ./images\\dog\\The_Science-Backed_Benefits_of_Being_a_Dog_Owner.jpg\nFound: 100 search results. Extracting links from 0:100\nFound: 25 image links, done!\nERROR - Could not save https://5.imimg.com/data5/OE/FL/MY-47770095/dog-house-500x500.jpg - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\PetNest_Wooden_Water_Proof_Dog_House_Outdoor_Ideal_for_Large_Size_Dogs__Labrador_and_German_Shepherd_:_Amazon.in:_Pet_Supplies.jpg'\nSUCCESS - saved https://static.toiimg.com/thumb/msid-74774056,width-1200,height-900,resizemode-4/.jpg - as ./images\\dog_in_house\\Living_in_the_Dog_House:_The_Emotional_Benefit_of_Dogs_–_Michal_Agus_Fox.jpg\nSUCCESS - saved https://nationaltoday.com/wp-content/uploads/2021/06/shutterstock_695423926-min.jpg - as ./images\\dog_in_house\\DIY_Insulated_Dog_House_Build_-_YouTube.jpg\nSUCCESS - saved https://static.thebark.com/sites/default/files/content/blog/full/dog-proofing-your-home-room-guide.jpg - as ./images\\dog_in_house\\Snow_Dog_House,_Amer_Road_-_Pet_Shops_in_Jaipur_-_Justdial.jpg\nERROR - Could not save https://image.shutterstock.com/image-photo/dog-sitting-pet-booth-cozy-260nw-1622196817.jpg - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\Who's_The_Alpha_Dog_In_Your_Multi-Dog_House?_-_Little_Dog_Tips.jpg'\nERROR - Could not save https://cdn.shopclues.com/images/thumbnails/38717/320/320/IMG20160428WA00301465280735.jpg - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\AmazonBasics_Elevated_Portable_Pet_House_-_Medium,_Black_:_Amazon.in:_Pet__Supplies.jpg'\nERROR - Could not save https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR0I5XxjLPXMVYm43lKxehxa2_eBfOjn65GhA&usqp=CAU - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\DOG_HOUSE_REPAIR_MONTH_-_July_1,_2022_|_National_Today.jpg'\nERROR - Could not save https://media.architecturaldigest.com/photos/5b5f3f9c2acdbe14ff211b6d/master/pass/%22Bow%20Wow%20Haus%22%20by%20Robert%20Young%20of%20Robert%20Young%20Architecture,%20built%20by%20Fountainhead%20Construction,%20with%20former%20ARFan%20Tara.%20%20Photo%20by%20Tria%20Giovan%20-1321.jpg - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\Dog_Inside_House_Images,_Stock_Photos_&_Vectors_|_Shutterstock.jpg'\nERROR - Could not save https://michalagusfox.files.wordpress.com/2019/01/add24c14-8598-4798-b3fb-4d68c8e77f9c.jpg?w=1100 - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\Does_My_Dog_Need_a_Dog_House?_|_PetMD.jpg'\nERROR - Could not save https://image.shutterstock.com/image-photo/beautiful-woman-hugging-her-adorable-260nw-1539127433.jpg - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\How_to_Stop_Dog_from_Peeing_in_the_House_|_Four_Paws.jpg'\nSUCCESS - saved https://media.istockphoto.com/photos/dogs-house-and-small-dog-picture-id495353836 - as ./images\\dog_in_house\\Buy_Dog_house_Online_-_Get_44%_Off.jpg\nSUCCESS - saved https://media.istockphoto.com/photos/funny-pug-dog-in-the-dog-house-picture-id516461357?k=20&m=516461357&s=612x612&w=0&h=kQzKEbQkQ4AdGGkHzi4vjgRVbskI4yGVoqnmI2B329o= - as ./images\\dog_in_house\\Dogs_House_And_Small_Dog_Stock_Photo_-_Download_Image_Now_-_iStock.jpg\nERROR - Could not save https://m.media-amazon.com/images/I/81FuMKwXu+L._SY355_.jpg - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\Brown_Plastic_Dog_Houses_at_Rs_900/piece_|_Rampuram_|_Kanpur|_ID:__22203893862.jpg'\nERROR - Could not save https://m.media-amazon.com/images/S/aplus-media/sota/32d098b1-73ab-4f6b-ae29-23865819c487.__CR0,0,970,600_PT0_SX970_V1___.jpg - [Errno 22] Invalid argument: './images\\\\dog_in_house\\\\This_Dog_House_Plan_Is_Exactly_What_Your_Pet_Needs_|_Southern_Living.jpg'\nSUCCESS - saved https://www.fourpaws.com/-/media/Images/fourpawsnew%20NA/US/articles/potty-time-and-training/how-to-stop-a-dog-from-peeing-in-the-house/dogs-and-house-soiling-article-new-final.jpg - as ./images\\dog_in_house\\Dog_House:_Beautiful_&_durable_options_that_are_great_for_your_pet_|_Most__Searched_Products_-_Times_of_India.jpg\nSUCCESS - saved https://imagesvc.meredithcorp.io/v3/jumpstartpure/image?url=https://cf-images.us-east-1.prod.boltdns.net/v1/static/474428695/90e22acb-74f6-4335-bb53-8c667b146c79/e128ac24-5353-4b71-b43d-1440315b4557/1280x720/match/image.jpg&w=1280&h=720&q=90&c=cc - as ./images\\dog_in_house\\24,565_Dog_House_Stock_Photos,_Pictures_&_Royalty-Free_Images_-_iStock.jpg\nSUCCESS - saved https://5.imimg.com/data5/ZK/UG/DI/SELLER-49409162/plastic-pet-house-500x500.png - as ./images\\dog_in_house\\Ways_to_Keep_Your_House_Clean_with_a_Messy_Dog.jpg\n"
],
[
"search_term_cat = ['cat','cat in house','small cat','big cat','furry cat','cute cat','happy cat','sitting cat','dancing cat',\n 'good cat']\n\nfor search_term in search_term_cat:\n search_and_download(search_term=search_term,driver_path=DRIVER_PATH,number_images = 2\n )",
"_____no_output_____"
]
],
[
[
"## Images data\n* Dog Images - 3000\n* Cat Images - 3000",
"_____no_output_____"
],
[
"### Source code reference :- https://towardsdatascience.com/image-scraping-with-python-a96feda8af2d",
"_____no_output_____"
],
[
"**Note:** Still working to correct the algorithm as it crashes after scraping around 50 images",
"_____no_output_____"
]
]
] | [
"code",
"markdown"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
e7b3581bfbe4488d12405ae96584d3c53036aa12 | 5,692 | ipynb | Jupyter Notebook | tutorial_github.ipynb | pete88b/nbdev_colab_helper | 03dbdb9e6136138c95a9166b1490c807989048f9 | [
"Apache-2.0"
] | 5 | 2021-01-17T02:22:01.000Z | 2021-08-11T07:02:31.000Z | tutorial_github.ipynb | pete88b/nbdev_colab_helper | 03dbdb9e6136138c95a9166b1490c807989048f9 | [
"Apache-2.0"
] | 3 | 2021-01-20T08:42:23.000Z | 2022-02-26T10:13:27.000Z | tutorial_github.ipynb | pete88b/nbdev_colab_helper | 03dbdb9e6136138c95a9166b1490c807989048f9 | [
"Apache-2.0"
] | 2 | 2020-09-06T04:52:52.000Z | 2021-01-17T02:22:16.000Z | 26.351852 | 180 | 0.571152 | [
[
[
"# github workflow with colab tutorial\n\n> A step by step guide",
"_____no_output_____"
],
[
"In this tutorial, we'll show how you can work with branches using only github and colab.",
"_____no_output_____"
],
[
"## Prerequisites",
"_____no_output_____"
],
[
"To complete this tutorial, you'll need a google account (with access to a google drive) and a github account.\n\nYou'll also need an `nbdev` project in github. If you don't, please take a look at this `tutorial`.",
"_____no_output_____"
],
[
"## github workflow with colab workflow",
"_____no_output_____"
],
[
"### Create a new branch in github",
"_____no_output_____"
],
[
"- Navigate to your project in github,\n- click the \"Switch branches\" button,\n- enter a new branch name and\n- click \"Create branch\"\n\n<img alt=\"new branch\" width=\"900\" src=\"images/create-new-branch.png\"/>",
"_____no_output_____"
],
[
"### Clone the new branch in colab",
"_____no_output_____"
],
[
"#### Add a section to nbdev_colab_projects.ini for your new branch\n\nHere's an example `nbdev_colab_projects.ini` that uses the project name \"nbdev_colab_helper_wip\" for the new branch \"change-dflt-branch-instructions2\":\n \n```\n[DEFAULT]\nproject_parent = /content/drive/My Drive/Colab Notebooks/github\n \ngit_user_name = **changeme**\ngit_user_email = **changeme**@gmail.com\ngit_user_password = **changeme**\n \n[nbdev_colab_helper]\ngit_url = https://github.com/pete88b/nbdev_colab_helper.git\ngit_branch = master\n \n[nbdev_colab_helper_wip]\ngit_url = https://github.com/pete88b/nbdev_colab_helper.git\ngit_branch = change-dflt-branch-instructions2\n```\n\n#### Run `setup_project`\n\nRun [these setup steps](https://pete88b.github.io/nbdev_colab_helper/tutorial.html#Colab-setup) in colab (feel free to use an existing colab helper notebook if you have one).",
"_____no_output_____"
],
[
"### Make some changes",
"_____no_output_____"
],
[
"Using the above config, I can find the new branch in google drive: /content/drive/My Drive/Colab Notebooks/github/nbdev_colab_helper_wip.\n\nYou can now edit files and (using your colab helper notebook) build your library, run tests etc.",
"_____no_output_____"
],
[
"### Push changes to github",
"_____no_output_____"
],
[
"When your ready to push to github, it's a good idea to check what has changed by running:\n\n```\n!git status\n```\n```\nOn branch change-dflt-branch-instructions2\nYour branch is up to date with 'origin/change-dflt-branch-instructions2'.\n\nChanges not staged for commit:\n (use \"git add <file>...\" to update what will be committed)\n (use \"git checkout -- <file>...\" to discard changes in working directory)\n\n\tmodified: 00_core.ipynb\n\tmodified: docs/tutorial.html\n\tmodified: tutorial.ipynb\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n```\n\nif you want to push all changes, you can:\n\n```\ncommit_message = 'minor changes to tutorial'\ngit_push(project_config['git_branch'], commit_message)\n```\n\nor you can push changes to just 2 files with something like:\n\n```\n!nbdev_install_git_hooks\n!git add docs/tutorial.html\n!git add tutorial.ipynb\ngit_branch = project_config['git_branch']\n!git commit -m \"minor changes to tutorial\"\n!git push origin $git_branch\n```",
"_____no_output_____"
],
[
"### Create pull request in github",
"_____no_output_____"
],
[
"You should now be able to go back to github and create a pull request.\n\n<img alt=\"new PR\" width=\"900\" src=\"images/create-pull.png\"/>",
"_____no_output_____"
],
[
"### Cleanup",
"_____no_output_____"
],
[
"Once you have finished working with your new branch in colab, it might make sense to delete it from your google drive to\n- save a little space on your drive and\n- make it possible to use the same project name again\n\nI'll probably use the \"nbdev_colab_helper_wip\" project name for whatever branch I'm currently working on.",
"_____no_output_____"
]
]
] | [
"markdown"
] | [
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
]
] |
e7b3587329fb6553ced02165c08766bfc4fc7202 | 12,971 | ipynb | Jupyter Notebook | notebooks/TF_Pub_Analysis.ipynb | alliance-genome/ontobio | 0ec3aa6fea9d4492a9873a4b9b394c4866f741b6 | [
"BSD-3-Clause"
] | 101 | 2017-04-19T20:54:49.000Z | 2022-03-14T02:32:11.000Z | notebooks/TF_Pub_Analysis.ipynb | valearna/ontobio | 460915df0beb0d4fbcd414cf4157769b08954857 | [
"BSD-3-Clause"
] | 402 | 2017-04-24T19:53:12.000Z | 2022-03-31T20:27:59.000Z | notebooks/TF_Pub_Analysis.ipynb | valearna/ontobio | 460915df0beb0d4fbcd414cf4157769b08954857 | [
"BSD-3-Clause"
] | 30 | 2017-04-20T17:59:12.000Z | 2022-02-25T22:26:08.000Z | 48.040741 | 7,064 | 0.749441 | [
[
[
"## Distribution of publication count for Dmel TF genes\n\nFor each TF gene, count the number of *curated* publications, using data from GO and Monarch",
"_____no_output_____"
]
],
[
[
"import ontobio.golr.golr_associations as ga",
"_____no_output_____"
],
[
"# Fetch all Dmel TF genes\nDNA_BINDING_TF = 'GO:0003700'\nDMEL = 'NCBITaxon:7227'\ntf_genes = ga.get_subjects_for_object(object=DNA_BINDING_TF, subject_taxon=DMEL)\nlen(tf_genes)",
"_____no_output_____"
],
[
"# Routine to go to GO and Monarch to fetch all annotations for a gene\ndef get_pubs_for_gene(g):\n \n # Monarch\n r = ga.search_associations(subject=g, rows=-1)\n pubs = set()\n for a in r['associations']:\n pl = a['publications']\n if pl is not None:\n pubs.update([p['id'] for p in pl if p['id'].startswith('PMID')])\n \n # GO\n r = ga.search_associations(subject=g, rows=-1, object_category='function')\n for a in r['associations']:\n pl = a['reference']\n if pl is not None:\n pubs.update([p for p in pl if p.startswith('PMID')])\n \n return pubs\n \nlen(get_pubs_for_gene(tf_genes[0]))",
"_____no_output_____"
],
[
"# find all gene,numberOfPub pairs\npairs = []\nfor g in tf_genes:\n np = len(get_pubs_for_gene(g))\n pairs.append((g,np))\n ",
"_____no_output_____"
],
[
"# Check\nvals = [np for _,np in pairs]\nvals[0:5]",
"_____no_output_____"
],
[
"# Check\ntf_genes_with_no_pubs = [g for g,np in pairs if np==0]\ntf_genes_with_no_pubs",
"_____no_output_____"
],
[
"# genes with fewer than 5 pubs\n[g for g,np in pairs if np < 5]",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\n%matplotlib inline\n",
"_____no_output_____"
],
[
"# Histogram\nplt.hist(vals, bins=40)\nplt.ylabel('No of genes')\nplt.xlabel('No of pubs')\nplt.show()",
"_____no_output_____"
],
[
"# Save results\nimport csv\nwith open('gene-pubs.csv', 'w', newline='') as csvfile:\n w = csv.writer(csvfile, delimiter=',')\n for g,np in pairs:\n w.writerow([g,np])\n ",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b35bd99d06cf8410500343ff2a5b1c8bcf6724 | 5,999 | ipynb | Jupyter Notebook | .ipynb_checkpoints/Arrays in Python-checkpoint.ipynb | kcdenman/pythonudemy | e035cc652cfc276c678fe8d9238830be4f7efc1c | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Arrays in Python-checkpoint.ipynb | kcdenman/pythonudemy | e035cc652cfc276c678fe8d9238830be4f7efc1c | [
"MIT"
] | null | null | null | .ipynb_checkpoints/Arrays in Python-checkpoint.ipynb | kcdenman/pythonudemy | e035cc652cfc276c678fe8d9238830be4f7efc1c | [
"MIT"
] | null | null | null | 16.946328 | 89 | 0.447241 | [
[
[
"l = [23245, 27, 546, 215, -1234]",
"_____no_output_____"
],
[
"l",
"_____no_output_____"
],
[
"#two types of arrays. 'arrayarrays are python. better version in numpy",
"_____no_output_____"
],
[
"import numpy as np",
"_____no_output_____"
],
[
"np.array(l)",
"_____no_output_____"
],
[
"a = np.array(l)",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"b = np.array([12, 455, 63.3, True,'abc'])",
"_____no_output_____"
],
[
"b #note that arrays have to all have the same datatype",
"_____no_output_____"
],
[
"print(b)",
"['12' '455' '63.3' 'True' 'abc']\n"
],
[
"l.pop",
"_____no_output_____"
],
[
"l.pop()",
"_____no_output_____"
],
[
"l",
"_____no_output_____"
],
[
"a.mean()",
"_____no_output_____"
],
[
"#do it myself",
"_____no_output_____"
],
[
"#create a few different arrays for a business intelligence problem\n#dim1: years between 2010 and 2018\n#mea1: sales figures\n",
"_____no_output_____"
],
[
"years = np.array(['2010', '2011','2012','2013','2014','2015','2016','2017','2018'])",
"_____no_output_____"
],
[
"years",
"_____no_output_____"
],
[
"sales = np.array([100,105,110,120,140,175,225,250,300])",
"_____no_output_____"
],
[
"len(years)",
"_____no_output_____"
],
[
"len(sales)",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b37a1d69bd59b9ecdf6e081169610ef7b402b0 | 10,938 | ipynb | Jupyter Notebook | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode | a3f49db90469ad70b63ba65967fdf0ce6c16201e | [
"MIT"
] | null | null | null | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode | a3f49db90469ad70b63ba65967fdf0ce6c16201e | [
"MIT"
] | null | null | null | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode | a3f49db90469ad70b63ba65967fdf0ce6c16201e | [
"MIT"
] | null | null | null | 32.945783 | 636 | 0.553575 | [
[
[
"# 1-5.1 Python Intro \n## conditionals, type, and mathematics extended \n- **conditionals: `elif`**\n- **casting** \n- basic math operators \n\n-----\n\n><font size=\"5\" color=\"#00A0B2\" face=\"verdana\"> <B>Student will be able to</B></font> \n- **code more than two choices using `elif`** \n- **gather numeric input using type casting** \n- perform subtraction, multiplication and division operations in code \n",
"_____no_output_____"
],
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Concepts</B></font>\n## conditional `elif`\n\n[]( http://edxinteractivepage.blob.core.windows.net/edxpages/f7cff1a7-5601-48a1-95a6-fd1fdfabd20e.html?details=[{\"src\":\"http://jupyternootbookwams.streaming.mediaservices.windows.net/a2ac5f4b-0400-4a60-91d5-d350c3cc0515/Unit1_Section5.1-elif.ism/manifest\",\"type\":\"application/vnd.ms-sstr+xml\"}],[{\"src\":\"http://jupyternootbookwams.streaming.mediaservices.windows.net/a2ac5f4b-0400-4a60-91d5-d350c3cc0515/Unit1_Section5.1-elif.vtt\",\"srclang\":\"en\",\"kind\":\"subtitles\",\"label\":\"english\"}])\n### a little review \n- **`if`** means \"**if** a condition exists then do some task.\" **`if`** is usually followed by **`else`** \n- **`else`** means \"**or else** after we have tested **if**, then do an alternative task\" \n\nWhen there is a need to test for multiple conditions there is **`elif`**\n- **`elif`** statement follows **`if`**, and means **\"else, if \"** another condition exists do something else\n- **`elif`** can be used many times\n- **`else`** is used after the last test condition (**`if`** or **`elif`**)\n\n#### in psuedo code \n**If** it is raining bring an umbrella \nor **Else If** (`elif`) it is snowing bring a warm coat \nor **Else** go as usual \n\nLike **`else`**, the **`elif`** only executes when the previous conditional is False",
"_____no_output_____"
],
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Examples</B></font>",
"_____no_output_____"
]
],
[
[
"# [ ] review the code then run testing different inputs\n# WHAT TO WEAR\nweather = input(\"Enter weather (sunny, rainy, snowy): \") \n\nif weather.lower() == \"sunny\":\n print(\"Wear a t-shirt\")\nelif weather.lower() == \"rainy\":\n print(\"Bring an umbrella and boots\")\nelif weather.lower() == \"snowy\":\n print(\"Wear a warm coat and hat\")\nelse:\n print(\"Sorry, not sure what to suggest for\", weather)",
"_____no_output_____"
],
[
"# [ ] review the code then run testing different inputs\n# SECRET NUMBER GUESS\nsecret_num = \"2\"\n\nguess = input(\"Enter a guess for the secret number (1-3): \")\n\nif guess.isdigit() == False:\n print(\"Invalid: guess should only use digits\")\nelif guess == \"1\":\n print(\"Guess is too low\")\nelif guess == secret_num:\n print(\"Guess is right\")\nelif guess == \"3\":\n print(\"Guess is too high\")\nelse:\n print(guess, \"is not a valid guess (1-3)\")",
"_____no_output_____"
]
],
[
[
"# \n<font size=\"6\" color=\"#B24C00\" face=\"verdana\"> <B>Task 1</B></font>\n\n## Program: Shirt Sale\n### Complete program using `if, elif, else`\n- Get user input for variable size (S, M, L)\n- reply with each shirt size and price (Small = \\$ 6, Medium = \\$ 7, Large = \\$ 8)\n- if the reply is other than S, M, L, give a message for not available\n- *optional*: add additional sizes",
"_____no_output_____"
]
],
[
[
"# [ ] code and test SHIRT SALE\n\n",
"_____no_output_____"
]
],
[
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Concepts</B></font>\n## casting\nCasting is the conversion from one data type to another Such as converting from **`str`** to **`int`**.\n[]( http://edxinteractivepage.blob.core.windows.net/edxpages/f7cff1a7-5601-48a1-95a6-fd1fdfabd20e.html?details=[{\"src\":\"http://jupyternootbookwams.streaming.mediaservices.windows.net/4cbf7f96-9ddd-4962-88a8-71081d7d5ef6/Unit1_Section5.1-casting-input.ism/manifest\",\"type\":\"application/vnd.ms-sstr+xml\"}],[{\"src\":\"http://jupyternootbookwams.streaming.mediaservices.windows.net/4cbf7f96-9ddd-4962-88a8-71081d7d5ef6/Unit1_Section5.1-casting-input.vtt\",\"srclang\":\"en\",\"kind\":\"subtitles\",\"label\":\"english\"}])\n### `int()`\nthe **`int()`** function can convert stings that represent whole counting numbers into integers and strip decimals to convert float numbers to integers\n- `int(\"1\") = 1` the string representing the integer character `\"1\"`, cast to a number \n- `int(5.1) = 5` the decimal (float), `5.1`, truncated into a non-decimal (integer) \n- `int(\"5.1\") = ValueError` `\"5.1\"` isn't a string representation of integer, `int()` can cast only strings representing integer values \n",
"_____no_output_____"
],
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Example</B></font>",
"_____no_output_____"
]
],
[
[
"weight1 = '60' # a string\nweight2 = 170 # an integer\n# add 2 integers\ntotal_weight = int(weight1) + weight2\nprint(total_weight)",
"230\n"
]
],
[
[
"# \n<font size=\"6\" color=\"#B24C00\" face=\"verdana\"> <B>Task 2</B></font>\n## casting with `int()` & `str()`",
"_____no_output_____"
]
],
[
[
"str_num_1 = \"11\"\nstr_num_2 = \"15\"\nint_num_3 = 10\n# [ ] Add the 3 numbers as integers and print the result\n\n",
"_____no_output_____"
],
[
"str_num_1 = \"11\"\nstr_num_2 = \"15\"\nint_num_3 = 10\n# [ ] Add the 3 numbers as test strings and print the result\n\n",
"_____no_output_____"
]
],
[
[
"<font size=\"4\" color=\"#B24C00\" face=\"verdana\"> <B>Task 2 cont...</B></font>\n### Program: adding using `int` casting\n- **[ ]** initialize **`str_integer`** variable to a **string containing characters of an integer** (quotes) \n- **[ ]** initialize **`int_number`** variable with an **integer value** (no quotes)\n- **[ ]** initialize **`number_total`** variable and **add int_number + str_integer** using **`int`** casting\n- **[ ]** print the sum (**`number_total`**)",
"_____no_output_____"
]
],
[
[
"# [ ] code and test: adding using int casting\nstr_integer = \"2\"\nint_number = 10\nnumber_total = int(str_integer) + int_number\nprint(number_total)\n",
"_____no_output_____"
]
],
[
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Concepts</B></font>\n## `input()` strings that represent numbers can be \"cast\" to integer values\n",
"_____no_output_____"
],
[
"# \n<font size=\"6\" color=\"#00A0B2\" face=\"verdana\"> <B>Example</B></font>",
"_____no_output_____"
]
],
[
[
"# [ ] review and run code\nstudent_age = input('enter student age (integer): ')\nage_next_year = int(student_age) + 1\nprint('Next year student will be',age_next_year)",
"_____no_output_____"
],
[
"# [ ] review and run code\n# cast to int at input\nstudent_age = int(input('enter student age (integer): '))\n\nage_in_decade = student_age + 10\n\nprint('In a decade the student will be', age_in_decade)",
"_____no_output_____"
]
],
[
[
"# \n<font size=\"6\" color=\"#B24C00\" face=\"verdana\"> <B>Task 3</B></font>\n## Program: adding calculator\n- get input of 2 **integer** numbers \n- cast the input and print the input followed by the result\n - Output Example: **`9 + 13 = 22`** \n\nOptional: check if input .isdigit() before trying integer addition to avoid errors in casting invalid inputs",
"_____no_output_____"
]
],
[
[
"# [ ] code and test the adding calculator\n\n",
"_____no_output_____"
]
],
[
[
"[Terms of use](http://go.microsoft.com/fwlink/?LinkID=206977) [Privacy & cookies](https://go.microsoft.com/fwlink/?LinkId=521839) © 2017 Microsoft",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] | [
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
e7b38b9d8c2255e60258f06da2b2cb99b23eccc4 | 3,652 | ipynb | Jupyter Notebook | 30_Top_Down.ipynb | Dzeiberg/multiinstance | 95b70e066610b1935cda9086d8fb8609809e7d15 | [
"Apache-2.0"
] | null | null | null | 30_Top_Down.ipynb | Dzeiberg/multiinstance | 95b70e066610b1935cda9086d8fb8609809e7d15 | [
"Apache-2.0"
] | null | null | null | 30_Top_Down.ipynb | Dzeiberg/multiinstance | 95b70e066610b1935cda9086d8fb8609809e7d15 | [
"Apache-2.0"
] | null | null | null | 29.451613 | 122 | 0.545728 | [
[
[
"from multiinstance.data.realData import buildDataset as buildReal\nfrom multiinstance.utils import *\n\nfrom multiinstance.ward_clustering import WardClustering\n\nimport matplotlib.pyplot as plt\n\nfrom glob import glob\nfrom tqdm.notebook import tqdm\n\nimport numpy as np",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"ds= buildReal(\"/data/dzeiberg/ClassPriorEstimation/rawDatasets/abalone.mat\", 4)\nds = addTransformScores(ds)\nds.alphaHats, ds.curves = getBagAlphaHats(ds,numbootstraps=100)\nward = WardClustering(ds,randomPairing=True,numbootstraps=ds.alphaHats.shape[1])\nward.cluster()",
"_____no_output_____"
],
[
"def moralize(row, clusterAssignment, alphaHatMat,numU):\n # cluster j was merged into cluster i at this iteration\n j = clusterAssignment[row-1,np.argmax(np.abs(clusterAssignment[row] - clusterAssignment[row - 1]))]\n i = clusterAssignment[row-1,np.argmin(np.abs(clusterAssignment[row] - clusterAssignment[row - 1]))]\n ai = alphaHatMat[row - 1, i].mean()\n aj = alphaHatMat[row - 1, j].mean()\n aij = alphaHatMat[row, i].mean()\n inI = np.where(clusterAssignment[row - 1] == i)[0]\n inJ = np.where(clusterAssignment[row - 1] == j)[0]\n ni = numU[inI].sum()\n nj = numU[inJ].sum()\n wi = ni / (ni + nj)\n ajHat = aij / (1 - wi) - wi / (1 - wi) * ai\n aiHat = (aij / wi) - ((1 - wi) / wi * aj)\n varI = alphaHatMat[row - 1,i].var()\n varJ = alphaHatMat[row - 1,j].var()\n if varI < varJ:\n #print(wi*ai+(1-wi)*aj,aij)\n print(\"update {j} from {aj:.3f} to {ajHat:.3f}\".format(j=j,aj=alphaHatMat[row-1,j].mean(),ajHat=ajHat))\n# print(aij, wi*ai + (1-wi)*ajHat)\n print(ai, aiHat, aj, ajHat)\n alphaHatMat[row - 1,inJ] = ajHat\n else:\n print(\"update {i} from {ai:.3f} to {aiHat:.3f}\".format(i=i,ai=alphaHatMat[row-1,i].mean(),aiHat=aiHat))\n alphaHatMat[row - 1,inI] = aiHat\n return alphaHatMat",
"_____no_output_____"
],
[
"ahmat = np.copy(ward.alphaHatMat)\nfor row in range(ward.clusterAssignment.shape[0]-1,0,-1):\n ahmat = moralize(row, ward.clusterAssignment.astype(int), ahmat, ds.numU)",
"_____no_output_____"
],
[
"ward.clusterAssignment",
"_____no_output_____"
],
[
"plt.plot([np.mean(np.abs(ds.trueAlphas.flatten() - ahmat[i].mean(1))) for i in range(ahmat.shape[0]-1,-1,-1)])",
"_____no_output_____"
]
]
] | [
"code"
] | [
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
e7b392ae03b31a40981d08552107caffb67bf3e2 | 162,975 | ipynb | Jupyter Notebook | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction | ea569ca159be74f7416d96c1ef2bf739f57dbf68 | [
"MIT"
] | 4 | 2017-09-04T22:28:23.000Z | 2018-03-09T01:07:57.000Z | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction | ea569ca159be74f7416d96c1ef2bf739f57dbf68 | [
"MIT"
] | null | null | null | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction | ea569ca159be74f7416d96c1ef2bf739f57dbf68 | [
"MIT"
] | null | null | null | 95.58651 | 103,824 | 0.732591 | [
[
[
"import pandas as pd\nimport ujson as json\n\n%load_ext autoreload\n%autoreload 2\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'",
"_____no_output_____"
]
],
[
[
"# Read Data\n\nWe run into memory issues using the code block below:\n\n```python\ndata = pd.read_json('../data/17.04_association_data.json',\n orient='records',\n typ='frame',\n lines=True,\n numpy=True)\n```\n\nThus, I have turned to another library to iteratively load the JSON file into memory.",
"_____no_output_____"
]
],
[
[
"# Convert the JSON data to a list of strings. I can then parse the strings\n# using usjon later.\nfilename = '../data/17.04_association_data.json'\nwith open(filename, 'r+') as f:\n data = f.readlines()\ndata = [x.rstrip() for x in data]",
"_____no_output_____"
],
[
"len(data)",
"_____no_output_____"
],
[
"from pprint import pprint\npprint(json.loads(data[0]))",
"{'association_score': {'datasources': {'cancer_gene_census': 0.90830650599492,\n 'chembl': 0.825695006743774,\n 'europepmc': 0.30565916633482804,\n 'eva': 0.905780555555555,\n 'eva_somatic': 0.0,\n 'expression_atlas': 0.190300397794741,\n 'gene2phenotype': 1.0,\n 'gwas_catalog': 0.0,\n 'intogen': 0.0,\n 'phenodigm': 0.14626161111111102,\n 'reactome': 1,\n 'uniprot': 1,\n 'uniprot_literature': 1},\n 'datatypes': {'affected_pathway': 1.0,\n 'animal_model': 0.14626161111111102,\n 'genetic_association': 1.0,\n 'known_drug': 0.825695006743774,\n 'literature': 0.30565916633482804,\n 'rna_expression': 0.190300397794741,\n 'somatic_mutation': 0.90830650599492},\n 'overall': 1.0},\n 'disease': {'efo_info': {'label': 'neoplasm',\n 'path': [['EFO_0000616']],\n 'therapeutic_area': {'codes': [], 'labels': []}},\n 'id': 'EFO_0000616'},\n 'evidence_count': {'datasources': {'cancer_gene_census': 159.0,\n 'chembl': 91.0,\n 'europepmc': 4551.0,\n 'eva': 6.0,\n 'eva_somatic': 27.0,\n 'expression_atlas': 12.0,\n 'gene2phenotype': 1.0,\n 'gwas_catalog': 0.0,\n 'intogen': 19.0,\n 'phenodigm': 5.0,\n 'reactome': 26.0,\n 'uniprot': 37.0,\n 'uniprot_literature': 9.0},\n 'datatypes': {'affected_pathway': 26.0,\n 'animal_model': 5.0,\n 'genetic_association': 53.0,\n 'known_drug': 91.0,\n 'literature': 4551.0,\n 'rna_expression': 12.0,\n 'somatic_mutation': 205.0},\n 'total': 4943.0},\n 'id': 'ENSG00000121879-EFO_0000616',\n 'is_direct': True,\n 'target': {'gene_info': {'name': 'phosphatidylinositol-4,5-bisphosphate '\n '3-kinase catalytic subunit alpha',\n 'symbol': 'PIK3CA'},\n 'id': 'ENSG00000121879'}}\n"
]
],
[
[
"From observation, I'm seeing that the `datatypes` key-value dictionary under the `association_score` data dictionary looks like the thing that is used for data analysis. On the other hand, there's an `evidence_count` thing as well - I think that one is the so-called \"raw data\". What was used in the paper should be the `association_score -> datatypes` dictionary.\n\n",
"_____no_output_____"
]
],
[
[
"from tqdm import tqdm\nrecords = []\nfor d in tqdm(data):\n # Get the datatype out.\n d = json.loads(d)\n record = d['association_score']['datatypes']\n # Add the target symbol to the record.\n record['target'] = d['target']['gene_info']['symbol']\n record['target_id'] = d['target']['id']\n # Add the disease ID to the record.\n record['disease'] = d['disease']['id']\n record['disease_efo_label'] = d['disease']['efo_info']['label']\n records.append(record)",
"100%|██████████| 2673321/2673321 [00:44<00:00, 60570.96it/s]\n"
]
],
[
[
"Let's write this to the \"feather\" format - it'll let us load the dataframe really quickly in other notebooks.",
"_____no_output_____"
]
],
[
[
"pd.DataFrame(records).to_feather('../data/association_score_data_types.feather')",
"_____no_output_____"
]
],
[
[
"Just to test, let's reload the dataframe.",
"_____no_output_____"
]
],
[
[
"df = pd.read_feather('../data/association_score_data_types.feather')",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
]
],
[
[
"Great! Sanity check passed :).\n\n# Exploratory Analysis\n\nLet's go on to some exploratory analysis of the data.\n\nI'd like to first see how many of each target type is represented in the dataset.\n\nIn the paper, for each target, the GSK research group used a simple \"mean\" of all evidence strengths across all diseases for a given target. I wasn't very satisfied with this, as I'm concerned about variability across diseases. Thus, to start, I will begin with a \"coefficient of variation\" computation, which will give us a good measure of the spread relative to the mean.\n\nIf the spread (measured by standard deviation) is greater than the mean, we should see CV > 1. Intuitively, I think this may indicate problems with using a simple mean.\n\nTo ensure that we don't get any `NaN` values after the computation, I will replace all zero-valued data with an infinitesimally small number, $ 10^{-6} $.",
"_____no_output_____"
]
],
[
[
"df_cv = df.replace(0, 1E-6).groupby('target').std() / df.replace(0, 1E-6).groupby('target').mean()\ndf_cv.sample(10)",
"_____no_output_____"
]
],
[
[
"How many target-disease pairs represented?",
"_____no_output_____"
]
],
[
[
"len(df)",
"_____no_output_____"
]
],
[
[
"How many unique targets are there?",
"_____no_output_____"
]
],
[
[
"len(df_cv)",
"_____no_output_____"
]
],
[
[
"And how many unique diseases are represented?",
"_____no_output_____"
]
],
[
[
"len(df.groupby('disease').mean())",
"_____no_output_____"
],
[
"# Theoretical number of target-disease pairs\nlen(df_cv) * len(df.groupby('disease').mean())",
"_____no_output_____"
]
],
[
[
"If densely populated, there should be $ 31051 \\times 8891 \\approx 270 million $ unique combinations. However, we only have $ 2673321 \\approx 2.6 million $ target-disease pairs represented. That means a very sparse dataset.",
"_____no_output_____"
],
[
"Let's now do a simple count of the cells here:\n\n- How many have non-zero values?\n- Of those that have non-zero values:\n - How many have CV < 1?\n - How many have CV = 1?\n - How many have CV > 1?",
"_____no_output_____"
]
],
[
[
"# This is the number of cells that have nonzero values.\ndf_cv[df_cv != 0].isnull()",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport numpy as np\ndef ecdf(data):\n x, y = np.sort(data), np.arange(1, len(data)+1) / len(data)\n return x, y",
"_____no_output_____"
]
],
[
[
"Let's make an ECDF scatter plot of the non-zero data. We're still only interested in the coefficient of variation (CV). In the following plots, I will plot the ECDF of log10-transformed CV scores for each target. Recall that CV < 1 means that variation is less than the mean; CV approx. 1 indicates variation close to magnitude of mean, and CV > 1 indicates variation greater than mean. I would like to see what proportion of CV scores are greater than 1.",
"_____no_output_____"
]
],
[
[
"from matplotlib.gridspec import GridSpec\nfrom scipy.stats import percentileofscore as pos\n\ndf_cv_nonzero = df_cv[df_cv != 0]\n\ngs = GridSpec(2, 4)\nfig = plt.figure(figsize=(12, 6))\n\nfor i, col in enumerate(df_cv.columns):\n x, y = ecdf(df_cv_nonzero[col].dropna())\n x = np.log10(x)\n ax = fig.add_subplot(gs[i])\n ax.scatter(x, y)\n \n # What percentile is the value 0\n zero_pos = pos(x, 0)\n ax.set_title(f'{col}, {100 - np.round(zero_pos, 2)}%')\n ax.vlines(x=0, ymin=0, ymax=1)\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"**Figure:** Distribution of log10-transformed CV scores for each variable of interest in the dataset. Vertical line at zero indicates $log10(CV) = 0$, which means $CV = 1$. Percentage of datapoints with CV > 1 is indicated in each subplot's title.",
"_____no_output_____"
],
[
"Comment: I'm not surprised, then, that the animal model and RNA expression scores were most predictive...",
"_____no_output_____"
],
[
"In the next notebook, I will explore whether I can reproduce the findings of the OpenTargets paper.",
"_____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",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
e7b392c8d5c7205d7f54fa492c68d350d4ee0d0d | 72,309 | ipynb | Jupyter Notebook | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End | 45301d45d53242ab52d1cc1866fbb7ffbdfd6290 | [
"MIT"
] | null | null | null | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End | 45301d45d53242ab52d1cc1866fbb7ffbdfd6290 | [
"MIT"
] | null | null | null | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End | 45301d45d53242ab52d1cc1866fbb7ffbdfd6290 | [
"MIT"
] | null | null | null | 38.441786 | 194 | 0.409935 | [
[
[
"# Segmentação de Clientes",
"_____no_output_____"
],
[
"Nesse Notebooks, vamos fazer segmetação de Clie",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom matplotlib import style\nimport plotly\nimport matplotlib.dates as mdates\nfrom datetime import datetime, timedelta\nimport plotly.offline as pyoff\nimport plotly.graph_objs as go\n#initiate visualization library for jupyter notebook \nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\npyoff.init_notebook_mode(connected=True)\n\n\nsns.set(style=\"ticks\")\n%matplotlib inline\n\nimport gc\nimport itertools\nfrom datetime import datetime\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nwarnings.simplefilter(\"ignore\")\nnp.random.seed(157)\n\n\n\nimport os,sys\nsys.path.append(\"../src/\")\n\nfrom plot_functions import *",
"_____no_output_____"
],
[
"customers_ = pd.read_csv(\"../files/olist_data/olist_customers_dataset.csv\")\norder_items_ = pd.read_csv(\"../files/olist_data/olist_order_items_dataset.csv\")\norder_payments_ = pd.read_csv(\"../files/olist_data/olist_order_payments_dataset.csv\")\norders_ = pd.read_csv(\"../files/olist_data/olist_orders_dataset.csv\")\nproducts = pd.read_csv(\"../files/olist_data/olist_products_dataset.csv\")\nsellers = pd.read_csv(\"../files/olist_data/olist_sellers_dataset.csv\")\ngeoloc = pd.read_csv(\"../files/olist_data/olist_geolocation_dataset.csv\")",
"_____no_output_____"
],
[
"geoloc[geoloc[['geolocation_zip_code_prefix', 'geolocation_city', 'geolocation_state']].duplicated()]",
"_____no_output_____"
],
[
"# creating master dataframe \norder_payments_.head()\ndf1 = order_payments_.merge(order_items_, on='order_id')\ndf2 = df1.merge(orders_, on='order_id')\ndf3 = df2.merge(products,on ='product_id')\ndf4 = df3.merge(sellers,on = 'seller_id')\ndf5 = df4.merge(geoloc,left_on = 'seller_zip_code_prefix',right_on='geolocation_zip_code_prefix')\ndf5.drop('seller_zip_code_prefix',axis = 1 ,inplace = True)\ndf = df5.merge(customers_, on='customer_id')\nprint(df.shape)\n\ndel customers_,order_items_,order_payments_,orders_,products,sellers,geoloc\ndel df1,df2,df3,df4,df5 # realasee memory",
"(16968656, 37)\n"
],
[
"df.head()",
"_____no_output_____"
],
[
"df.info()",
"<class 'pandas.core.frame.DataFrame'>\nInt64Index: 16968656 entries, 0 to 16968655\nData columns (total 37 columns):\n # Column Dtype \n--- ------ ----- \n 0 order_id object \n 1 payment_sequential int64 \n 2 payment_type object \n 3 payment_installments int64 \n 4 payment_value float64\n 5 order_item_id int64 \n 6 product_id object \n 7 seller_id object \n 8 shipping_limit_date object \n 9 price float64\n 10 freight_value float64\n 11 customer_id object \n 12 order_status object \n 13 order_purchase_timestamp object \n 14 order_approved_at object \n 15 order_delivered_carrier_date object \n 16 order_delivered_customer_date object \n 17 order_estimated_delivery_date object \n 18 product_category_name object \n 19 product_name_lenght float64\n 20 product_description_lenght float64\n 21 product_photos_qty float64\n 22 product_weight_g float64\n 23 product_length_cm float64\n 24 product_height_cm float64\n 25 product_width_cm float64\n 26 seller_city object \n 27 seller_state object \n 28 geolocation_zip_code_prefix int64 \n 29 geolocation_lat float64\n 30 geolocation_lng float64\n 31 geolocation_city object \n 32 geolocation_state object \n 33 customer_unique_id object \n 34 customer_zip_code_prefix int64 \n 35 customer_city object \n 36 customer_state object \ndtypes: float64(12), int64(5), object(20)\nmemory usage: 4.8+ GB\n"
],
[
"df.describe()",
"_____no_output_____"
]
],
[
[
"## Limpeza dos dados",
"_____no_output_____"
]
],
[
[
"# converting date columns to datetime\ndate_columns = ['shipping_limit_date', 'order_purchase_timestamp', 'order_approved_at', 'order_delivered_carrier_date', 'order_delivered_customer_date', 'order_estimated_delivery_date']\nfor col in date_columns:\n df[col] = pd.to_datetime(df[col], format='%Y-%m-%d %H:%M:%S')",
"_____no_output_____"
],
[
"# cleaning up name columns\ndf['customer_city'] = df['customer_city'].str.title()\ndf['payment_type'] = df['payment_type'].str.replace('_', ' ').str.title()\n# engineering new/essential columns\ndf['delivery_against_estimated'] = (df['order_estimated_delivery_date'] - df['order_delivered_customer_date']).dt.days\ndf['order_purchase_year'] = df.order_purchase_timestamp.apply(lambda x: x.year)\ndf['order_purchase_month'] = df.order_purchase_timestamp.apply(lambda x: x.month)\ndf['order_purchase_dayofweek'] = df.order_purchase_timestamp.apply(lambda x: x.dayofweek)\ndf['order_purchase_hour'] = df.order_purchase_timestamp.apply(lambda x: x.hour)\ndf['order_purchase_day'] = df['order_purchase_dayofweek'].map({0:'Mon',1:'Tue',2:'Wed',3:'Thu',4:'Fri',5:'Sat',6:'Sun'})\ndf['order_purchase_mon'] = df.order_purchase_timestamp.apply(lambda x: x.month).map({1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'Jul',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'})\n# Changing the month attribute for correct ordenation\ndf['month_year'] = df['order_purchase_month'].astype(str).apply(lambda x: '0' + x if len(x) == 1 else x)\ndf['month_year'] = df['order_purchase_year'].astype(str) + '-' + df['month_year'].astype(str)\n#creating year month column\ndf['month_y'] = df['order_purchase_timestamp'].map(lambda date: 100*date.year + date.month)",
"_____no_output_____"
],
[
"# displaying summary staticstics of columns\ndf.describe(include='all')",
"_____no_output_____"
],
[
"# displaying missing value counts and corresponding percentage against total observations\nmissing_values = df.isnull().sum().sort_values(ascending = False)\npercentage = (df.isnull().sum()/df.isnull().count()*100).sort_values(ascending = False)\npd.concat([missing_values, percentage], axis=1, keys=['Values', 'Percentage']).transpose()",
"_____no_output_____"
],
[
"# dropping missing values\ndf.dropna(inplace=True)\ndf.isnull().values.any()",
"_____no_output_____"
]
],
[
[
"## Análise exploratória de dados",
"_____no_output_____"
]
],
[
[
"n_customers = df['customer_unique_id'].nunique()\nprint('Unique customers: {}'.format(n_customers))\nn_cities = df['customer_city'].nunique()\nprint('Unique cities: {}'.format(n_cities))",
"_____no_output_____"
],
[
"# City disctribution\ndf['customer_city'].value_counts().sort_values(ascending=False)",
"_____no_output_____"
],
[
"cities = df['customer_city'].value_counts().sort_values(ascending=False).head(50).to_frame()\nplt.figure(figsize=(15,5))\nsns.barplot(x = cities.index.values.flatten() ,y = cities.values.flatten())\nplt.tight_layout()\nplt.xticks(rotation = 90)\nplt.title('Top 50 cidades')\nplt.ylabel('Quantidade de Clientes');",
"_____no_output_____"
],
[
"# How many states are the customers from?\ndf['customer_state'].nunique()",
"_____no_output_____"
],
[
"cities = df['customer_city'].value_counts().sort_values(ascending=False).head(50).to_frame()\n",
"_____no_output_____"
],
[
"states = df['customer_state'].value_counts().sort_values(ascending=False)\nplt.figure(figsize=(15,5))\nsns.barplot(x = states.index.values.flatten() ,y = states.values.flatten())\nplt.tight_layout()\nplt.xticks(rotation = 90)\nplt.title('Top Estados')\nplt.ylabel('Quantidade de Clientes');",
"_____no_output_____"
],
[
"df_customer_dly = df.groupby(\n 'customer_unique_id',\n as_index=False).agg({\n 'order_purchase_timestamp': 'min'\n })",
"_____no_output_____"
],
[
"df_customer_dly.groupby('order_purchase_timestamp').count().cumsum().plot(figsize=(15,5))\nplt.title('Customers cumulative')\nplt.xlabel('Timeline')\nplt.ylabel('Customer count cumulative');",
"_____no_output_____"
],
[
"\n# New customers count by day\nax = df_customer_dly.groupby('order_purchase_timestamp').count().head(10).plot(kind='bar', figsize=(15,5))\n# set monthly locator\nax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))\n# set font and rotation for date tick labels\nplt.gcf().autofmt_xdate()\nplt.title('Customers cumulative')\nplt.xlabel('Timeline')\nplt.ylabel('Customer count');",
"_____no_output_____"
]
],
[
[
"**Crescimento Mensal**",
"_____no_output_____"
]
],
[
[
"#calculate Revenue for each row and create a new dataframe with YearMonth - Revenue columns\ndf_revenue = df.groupby(['month_year'])['payment_value'].sum().reset_index()\ndf_revenue",
"_____no_output_____"
],
[
"#calculating for monthly revenie growth rate\n# using pct_change() function to see monthly percentage change\ndf_revenue['MonthlyGrowth'] = df_revenue['payment_value'].pct_change()\n\ndf_revenue",
"_____no_output_____"
],
[
"#creating monthly active customers dataframe by counting unique Customer IDs\ndf_monthly_active = df.groupby('month_year')['customer_unique_id'].nunique().reset_index()\n\nfig, ax = plt.subplots(figsize=(12, 6))\nsns.set(palette='muted', color_codes=True, style='whitegrid')\nbar_plot(x='month_year', y='customer_unique_id', df=df_monthly_active, value=True)\nax.tick_params(axis='x', labelrotation=90)\n",
"_____no_output_____"
],
[
"#creating monthly active customers dataframe by counting unique Customer IDs\ndf_monthly_sales = df.groupby('month_year')['order_status'].count().reset_index()\n\nfig, ax = plt.subplots(figsize=(12, 6))\nsns.set(palette='muted', color_codes=True, style='whitegrid')\nbar_plot(x='month_year', y='order_status', df=df_monthly_sales, value=True)\nax.tick_params(axis='x', labelrotation=90)\n",
"_____no_output_____"
]
],
[
[
"**Média de por compra de clientes**",
"_____no_output_____"
]
],
[
[
"# create a new dataframe for average revenue by taking the mean of it\ndf_monthly_order_avg = df.groupby('month_year')['payment_value'].mean().reset_index()\n\nfig, ax = plt.subplots(figsize=(12, 6))\nsns.set(palette='muted', color_codes=True, style='whitegrid')\nbar_plot(x='month_year', y='payment_value', df=df_monthly_order_avg, value=True)\nax.tick_params(axis='x', labelrotation=90)",
"_____no_output_____"
]
],
[
[
"## Segmentação de Clientes",
"_____no_output_____"
],
[
"A segmetação irá classificar clionets baseado na frequencia de compra, quantidade de comprar e dinheiro gasto.\n\n* Como os clientes são segmentados de acordo com tempo gasto na comaprar, quantidade na comprar e o número de pedidos?",
"_____no_output_____"
]
],
[
[
"df['order_status'].value_counts()",
"_____no_output_____"
],
[
"df_customer = df[df['order_status']=='delivered']",
"_____no_output_____"
],
[
"# Setting reference day\ndf_customer['today'] = df_customer['order_purchase_timestamp'].max()\n# Date deltas\ndf_customer['recency'] = df_customer['today'] - df['order_purchase_timestamp']",
"_____no_output_____"
]
]
] | [
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
]
] |
e7b394c8936c923efb2ad979bebf0fb42e730e09 | 4,222 | ipynb | Jupyter Notebook | code/postprocess/Sample Postprocessing.ipynb | miniminisu/dcgan-code-cu-foam-3D | 9b7e4b184da33fa259ab42f28d9d3d77fe28bd3e | [
"MIT"
] | 1 | 2021-07-29T07:41:46.000Z | 2021-07-29T07:41:46.000Z | code/postprocess/Sample Postprocessing.ipynb | miniminisu/dcgan-code-cu-foam-3D | 9b7e4b184da33fa259ab42f28d9d3d77fe28bd3e | [
"MIT"
] | 1 | 2021-09-28T16:25:04.000Z | 2021-09-28T16:25:04.000Z | code/postprocess/Sample Postprocessing.ipynb | miniminisu/dcgan-code-cu-foam-3D | 9b7e4b184da33fa259ab42f28d9d3d77fe28bd3e | [
"MIT"
] | null | null | null | 24.404624 | 116 | 0.542397 | [
[
[
"import numpy as np\nimport h5py\nimport tifffile\nfrom scipy.ndimage.filters import median_filter\nfrom skimage.filters import threshold_otsu\nfrom collections import Counter\nimport os",
"_____no_output_____"
]
],
[
[
"## Processing of a single image",
"_____no_output_____"
],
[
"## Loading the HDF5 file and converting to tiff",
"_____no_output_____"
]
],
[
[
"root_hdf5 = '../../pytorch/fake_images_TI/hdf5'\nroot_tiff = '../../pytorch/fake_images_TI/tiff'\nroot_postprocess_tiff = '../../pytorch/fake_images_TI/postprocess_tiff'\nfiles_name = os.listdir(root_hdf5)\nprint(files_name)\n",
"['fake_TI_1001.hdf5', 'fake_TI_10736.hdf5', 'fake_TI_3036.hdf5', 'fake_TI_5071.hdf5', 'fake_TI_7216.hdf5']\n"
],
[
"for file_name in files_name:\n file_path = os.path.join(root_hdf5, file_name)\n f = h5py.File(file_path,'r')\n my_array = f['data'][()]\n img = my_array[0, 0, :, :, :].astype(np.float32)\n file_name = file_name.split('.')[0]+\".tiff\"\n # print(name)\n file_path = os.path.join(root_tiff, file_name)\n tifffile.imsave(file_path, img)\n # print(img.shape)",
"_____no_output_____"
]
],
[
[
"## Denoising and thresholding",
"_____no_output_____"
]
],
[
[
"files_name = os.listdir(root_tiff)\nfor file_name in files_name:\n file_path = os.path.join(root_tiff, file_name)\n im_in = tifffile.imread(file_path)\n\n #apply single pixel denoising\n im_in = median_filter(im_in, size=(3, 3, 3))\n\n #cutaway outer noise area\n #im_in = im_in[40:240, 40:240, 40:240]\n\n #Normalize to range zero and one\n im_in = im_in/255.\n\n #Threshhold Image\n threshold_global_otsu = threshold_otsu(im_in)\n segmented_image = (im_in >= threshold_global_otsu).astype(np.int32)\n\n #Store as postprocessed image\n file_path = os.path.join(root_postprocess_tiff, file_name.split('.')[0]+'.tiff')\n\n tifffile.imsave(file_path, segmented_image.astype(np.int32))",
"_____no_output_____"
]
],
[
[
"## Compute porosity",
"_____no_output_____"
]
],
[
[
"segmented_image = tifffile.imread(\"postprocessed_example.tiff\")\nporc = Counter(segmented_image.flatten())\nprint(porc)\nporosity = porc[0]/float(porc[0]+porc[1])\nprint(\"Porosity of the sample: \", porosity)",
"Counter({1: 6425472, 0: 1574528})\nPorosity of the sample: 0.196816\n"
]
]
] | [
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] | [
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
e7b3a847891cdc2f0a111dee2ff9c24d27caf910 | 3,835 | ipynb | Jupyter Notebook | Exercises-with-open-data/Other/barometer_col_de_la_fausille.ipynb | trongnghia00/cms | 7b60a4ffb306cf19f686224bb8b812cdc916373b | [
"CC-BY-4.0"
] | 15 | 2017-10-13T18:39:44.000Z | 2021-11-27T05:15:19.000Z | Exercises-with-open-data/Other/barometer_col_de_la_fausille.ipynb | trongnghia00/cms | 7b60a4ffb306cf19f686224bb8b812cdc916373b | [
"CC-BY-4.0"
] | 1 | 2017-07-19T13:27:25.000Z | 2017-07-19T13:27:25.000Z | Exercises-with-open-data/Other/barometer_col_de_la_fausille.ipynb | trongnghia00/cms | 7b60a4ffb306cf19f686224bb8b812cdc916373b | [
"CC-BY-4.0"
] | 22 | 2017-07-19T12:24:56.000Z | 2022-03-06T16:44:59.000Z | 26.631944 | 322 | 0.537679 | [
[
[
"# Measuring atmospheric pressure",
"_____no_output_____"
],
[
"In this exercise we used a Sony XPeria phone's sensors with the [PhyPhox](https://phyphox.org/) application to measure ambient air pressure on a sunny summer day in southern France. We begin our descent from the Jura mountains at Col de la Fausille and end down at a parking lot at CERN's Meyrin site in Switzerland.",
"_____no_output_____"
]
],
[
[
"# Let's load the relevant python modules.\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n%matplotlib inline",
"_____no_output_____"
],
[
"# Load the relevant data.\n\nbaro = pd.read_csv(\"../../Data/barometri_fausille.csv\")",
"_____no_output_____"
],
[
"# Take a look at the data.\n\nbaro.head()",
"_____no_output_____"
],
[
"# Since the data has only time and pressure, we'll calculate the height difference from known formulas\n# and add the values in the dataframe.\n\nmaxp = max(baro[\"Pressure (hPa)\"])\ndp = list(maxp-baro[\"Pressure (hPa)\"].copy())\nbaro[\"Height (m)\"] = np.ones(len(baro))\n\n# Since we know our destination is elevated about 440 m from the sea level:\n\nfor i in range(0, len(dp)):\n baro[\"Height (m)\"][i] = dp[i]*(10/1.2) + 440",
"_____no_output_____"
],
[
"# Here's the plot vs. time. Can you tell where our car stood still?\n\nfig, ax1 = plt.subplots()\n\nfig.set_figwidth(20)\nfig.set_figheight(5)\n\neka, = plt.plot(baro[\"Time (s)\"],baro[\"Pressure (hPa)\"], c = 'r', label = 'Pressure')\nplt.title(\"Air pressure on the way down from Col de la Fausille \\n\", fontsize = 15)\nplt.xlabel(\"Time (s)\", fontsize = 15)\nplt.ylabel(\"Pressure (hPa) \\n\", fontsize = 15)\n\nax2 = ax1.twinx()\nax2.set_ylabel('Height (m) \\n', fontsize = 15)\n\ntoka, = plt.plot(baro[\"Time (s)\"], baro[\"Height (m)\"], c = 'b', label = 'Height')\n\naxes=fig.gca()\naxes.set_ylim(0,1500)\n\nplt.legend([eka, toka],['Pressure', 'Height'], loc = 'lower right')\nplt.show()",
"_____no_output_____"
],
[
"# Since time isn't physically very interesting here, let's try the height instead.\n\nplt.figure(figsize = (20,5))\n\nplt.plot(baro[\"Height (m)\"], baro[\"Pressure (hPa)\"])\nplt.title(\"Air pressure \\n\", fontsize = 15)\nplt.xlabel(\"Height (m)\", fontsize = 15)\nplt.ylabel(\"Pressure (hPa) \\n\", fontsize = 15)\n\nplt.show()",
"_____no_output_____"
]
]
] | [
"markdown",
"code"
] | [
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.