hexsha
stringlengths 40
40
| size
int64 6
14.9M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 6
260
| max_stars_repo_name
stringlengths 6
119
| max_stars_repo_head_hexsha
stringlengths 40
41
| max_stars_repo_licenses
list | max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 6
260
| max_issues_repo_name
stringlengths 6
119
| max_issues_repo_head_hexsha
stringlengths 40
41
| max_issues_repo_licenses
list | max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 6
260
| max_forks_repo_name
stringlengths 6
119
| max_forks_repo_head_hexsha
stringlengths 40
41
| max_forks_repo_licenses
list | max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2
1.04M
| max_line_length
int64 2
11.2M
| alphanum_fraction
float64 0
1
| cells
list | cell_types
list | cell_type_groups
list |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cbafcfc725e7e399fdd3562e275fe08ef1f43446
| 20,977 |
ipynb
|
Jupyter Notebook
|
scripts/d21-en/pytorch/chapter_natural-language-processing-pretraining/bert-dataset.ipynb
|
lucmertins/CapDeepLearningBook
|
e5959b552c8716e7fc65a21ae9c13c58509544c1
|
[
"MIT"
] | null | null | null |
scripts/d21-en/pytorch/chapter_natural-language-processing-pretraining/bert-dataset.ipynb
|
lucmertins/CapDeepLearningBook
|
e5959b552c8716e7fc65a21ae9c13c58509544c1
|
[
"MIT"
] | null | null | null |
scripts/d21-en/pytorch/chapter_natural-language-processing-pretraining/bert-dataset.ipynb
|
lucmertins/CapDeepLearningBook
|
e5959b552c8716e7fc65a21ae9c13c58509544c1
|
[
"MIT"
] | null | null | null | 36.996473 | 544 | 0.59017 |
[
[
[
"# The Dataset for Pretraining BERT\n:label:`sec_bert-dataset`\n\nTo pretrain the BERT model as implemented in :numref:`sec_bert`,\nwe need to generate the dataset in the ideal format to facilitate\nthe two pretraining tasks:\nmasked language modeling and next sentence prediction.\nOn one hand,\nthe original BERT model is pretrained on the concatenation of\ntwo huge corpora BookCorpus and English Wikipedia (see :numref:`subsec_bert_pretraining_tasks`),\nmaking it hard to run for most readers of this book.\nOn the other hand,\nthe off-the-shelf pretrained BERT model\nmay not fit for applications from specific domains like medicine.\nThus, it is getting popular to pretrain BERT on a customized dataset.\nTo facilitate the demonstration of BERT pretraining,\nwe use a smaller corpus WikiText-2 :cite:`Merity.Xiong.Bradbury.ea.2016`.\n\nComparing with the PTB dataset used for pretraining word2vec in :numref:`sec_word2vec_data`,\nWikiText-2 i) retains the original punctuation, making it suitable for next sentence prediction; ii) retains the original case and numbers; iii) is over twice larger.\n",
"_____no_output_____"
]
],
[
[
"import os\nimport random\nimport torch\nfrom d2l import torch as d2l",
"_____no_output_____"
]
],
[
[
"In the WikiText-2 dataset,\neach line represents a paragraph where\nspace is inserted between any punctuation and its preceding token.\nParagraphs with at least two sentences are retained.\nTo split sentences, we only use the period as the delimiter for simplicity.\nWe leave discussions of more complex sentence splitting techniques in the exercises\nat the end of this section.\n",
"_____no_output_____"
]
],
[
[
"#@save\nd2l.DATA_HUB['wikitext-2'] = (\n 'https://s3.amazonaws.com/research.metamind.io/wikitext/'\n 'wikitext-2-v1.zip', '3c914d17d80b1459be871a5039ac23e752a53cbe')\n\n#@save\ndef _read_wiki(data_dir):\n file_name = os.path.join(data_dir, 'wiki.train.tokens')\n with open(file_name, 'r') as f:\n lines = f.readlines()\n # Uppercase letters are converted to lowercase ones\n paragraphs = [\n line.strip().lower().split(' . ') for line in lines\n if len(line.split(' . ')) >= 2]\n random.shuffle(paragraphs)\n return paragraphs",
"_____no_output_____"
]
],
[
[
"## Defining Helper Functions for Pretraining Tasks\n\nIn the following,\nwe begin by implementing helper functions for the two BERT pretraining tasks:\nnext sentence prediction and masked language modeling.\nThese helper functions will be invoked later\nwhen transforming the raw text corpus\ninto the dataset of the ideal format to pretrain BERT.\n\n### Generating the Next Sentence Prediction Task\n\nAccording to descriptions of :numref:`subsec_nsp`,\nthe `_get_next_sentence` function generates a training example\nfor the binary classification task.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef _get_next_sentence(sentence, next_sentence, paragraphs):\n if random.random() < 0.5:\n is_next = True\n else:\n # `paragraphs` is a list of lists of lists\n next_sentence = random.choice(random.choice(paragraphs))\n is_next = False\n return sentence, next_sentence, is_next",
"_____no_output_____"
]
],
[
[
"The following function generates training examples for next sentence prediction\nfrom the input `paragraph` by invoking the `_get_next_sentence` function.\nHere `paragraph` is a list of sentences, where each sentence is a list of tokens.\nThe argument `max_len` specifies the maximum length of a BERT input sequence during pretraining.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef _get_nsp_data_from_paragraph(paragraph, paragraphs, vocab, max_len):\n nsp_data_from_paragraph = []\n for i in range(len(paragraph) - 1):\n tokens_a, tokens_b, is_next = _get_next_sentence(\n paragraph[i], paragraph[i + 1], paragraphs)\n # Consider 1 '<cls>' token and 2 '<sep>' tokens\n if len(tokens_a) + len(tokens_b) + 3 > max_len:\n continue\n tokens, segments = d2l.get_tokens_and_segments(tokens_a, tokens_b)\n nsp_data_from_paragraph.append((tokens, segments, is_next))\n return nsp_data_from_paragraph",
"_____no_output_____"
]
],
[
[
"### Generating the Masked Language Modeling Task\n:label:`subsec_prepare_mlm_data`\n\nIn order to generate training examples\nfor the masked language modeling task\nfrom a BERT input sequence,\nwe define the following `_replace_mlm_tokens` function.\nIn its inputs, `tokens` is a list of tokens representing a BERT input sequence,\n`candidate_pred_positions` is a list of token indices of the BERT input sequence\nexcluding those of special tokens (special tokens are not predicted in the masked language modeling task),\nand `num_mlm_preds` indicates the number of predictions (recall 15% random tokens to predict).\nFollowing the definition of the masked language modeling task in :numref:`subsec_mlm`,\nat each prediction position, the input may be replaced by\na special “<mask>” token or a random token, or remain unchanged.\nIn the end, the function returns the input tokens after possible replacement,\nthe token indices where predictions take place and labels for these predictions.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef _replace_mlm_tokens(tokens, candidate_pred_positions, num_mlm_preds,\n vocab):\n # Make a new copy of tokens for the input of a masked language model,\n # where the input may contain replaced '<mask>' or random tokens\n mlm_input_tokens = [token for token in tokens]\n pred_positions_and_labels = []\n # Shuffle for getting 15% random tokens for prediction in the masked\n # language modeling task\n random.shuffle(candidate_pred_positions)\n for mlm_pred_position in candidate_pred_positions:\n if len(pred_positions_and_labels) >= num_mlm_preds:\n break\n masked_token = None\n # 80% of the time: replace the word with the '<mask>' token\n if random.random() < 0.8:\n masked_token = '<mask>'\n else:\n # 10% of the time: keep the word unchanged\n if random.random() < 0.5:\n masked_token = tokens[mlm_pred_position]\n # 10% of the time: replace the word with a random word\n else:\n masked_token = random.randint(0, len(vocab) - 1)\n mlm_input_tokens[mlm_pred_position] = masked_token\n pred_positions_and_labels.append(\n (mlm_pred_position, tokens[mlm_pred_position]))\n return mlm_input_tokens, pred_positions_and_labels",
"_____no_output_____"
]
],
[
[
"By invoking the aforementioned `_replace_mlm_tokens` function,\nthe following function takes a BERT input sequence (`tokens`)\nas an input and returns indices of the input tokens\n(after possible token replacement as described in :numref:`subsec_mlm`),\nthe token indices where predictions take place,\nand label indices for these predictions.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef _get_mlm_data_from_tokens(tokens, vocab):\n candidate_pred_positions = []\n # `tokens` is a list of strings\n for i, token in enumerate(tokens):\n # Special tokens are not predicted in the masked language modeling\n # task\n if token in ['<cls>', '<sep>']:\n continue\n candidate_pred_positions.append(i)\n # 15% of random tokens are predicted in the masked language modeling task\n num_mlm_preds = max(1, round(len(tokens) * 0.15))\n mlm_input_tokens, pred_positions_and_labels = _replace_mlm_tokens(\n tokens, candidate_pred_positions, num_mlm_preds, vocab)\n pred_positions_and_labels = sorted(pred_positions_and_labels,\n key=lambda x: x[0])\n pred_positions = [v[0] for v in pred_positions_and_labels]\n mlm_pred_labels = [v[1] for v in pred_positions_and_labels]\n return vocab[mlm_input_tokens], pred_positions, vocab[mlm_pred_labels]",
"_____no_output_____"
]
],
[
[
"## Transforming Text into the Pretraining Dataset\n\nNow we are almost ready to customize a `Dataset` class for pretraining BERT.\nBefore that, \nwe still need to define a helper function `_pad_bert_inputs`\nto append the special “<mask>” tokens to the inputs.\nIts argument `examples` contain the outputs from the helper functions `_get_nsp_data_from_paragraph` and `_get_mlm_data_from_tokens` for the two pretraining tasks.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef _pad_bert_inputs(examples, max_len, vocab):\n max_num_mlm_preds = round(max_len * 0.15)\n all_token_ids, all_segments, valid_lens, = [], [], []\n all_pred_positions, all_mlm_weights, all_mlm_labels = [], [], []\n nsp_labels = []\n for (token_ids, pred_positions, mlm_pred_label_ids, segments,\n is_next) in examples:\n all_token_ids.append(\n torch.tensor(\n token_ids + [vocab['<pad>']] * (max_len - len(token_ids)),\n dtype=torch.long))\n all_segments.append(\n torch.tensor(segments + [0] * (max_len - len(segments)),\n dtype=torch.long))\n # `valid_lens` excludes count of '<pad>' tokens\n valid_lens.append(torch.tensor(len(token_ids), dtype=torch.float32))\n all_pred_positions.append(\n torch.tensor(\n pred_positions + [0] *\n (max_num_mlm_preds - len(pred_positions)), dtype=torch.long))\n # Predictions of padded tokens will be filtered out in the loss via\n # multiplication of 0 weights\n all_mlm_weights.append(\n torch.tensor([1.0] * len(mlm_pred_label_ids) + [0.0] *\n (max_num_mlm_preds - len(pred_positions)),\n dtype=torch.float32))\n all_mlm_labels.append(\n torch.tensor(\n mlm_pred_label_ids + [0] *\n (max_num_mlm_preds - len(mlm_pred_label_ids)),\n dtype=torch.long))\n nsp_labels.append(torch.tensor(is_next, dtype=torch.long))\n return (all_token_ids, all_segments, valid_lens, all_pred_positions,\n all_mlm_weights, all_mlm_labels, nsp_labels)",
"_____no_output_____"
]
],
[
[
"Putting the helper functions for\ngenerating training examples of the two pretraining tasks,\nand the helper function for padding inputs together,\nwe customize the following `_WikiTextDataset` class as the WikiText-2 dataset for pretraining BERT.\nBy implementing the `__getitem__ `function,\nwe can arbitrarily access the pretraining (masked language modeling and next sentence prediction) examples \ngenerated from a pair of sentences from the WikiText-2 corpus.\n\nThe original BERT model uses WordPiece embeddings whose vocabulary size is 30,000 :cite:`Wu.Schuster.Chen.ea.2016`.\nThe tokenization method of WordPiece is a slight modification of\nthe original byte pair encoding algorithm in :numref:`subsec_Byte_Pair_Encoding`.\nFor simplicity, we use the `d2l.tokenize` function for tokenization.\nInfrequent tokens that appear less than five times are filtered out.\n",
"_____no_output_____"
]
],
[
[
"#@save\nclass _WikiTextDataset(torch.utils.data.Dataset):\n def __init__(self, paragraphs, max_len):\n # Input `paragraphs[i]` is a list of sentence strings representing a\n # paragraph; while output `paragraphs[i]` is a list of sentences\n # representing a paragraph, where each sentence is a list of tokens\n paragraphs = [\n d2l.tokenize(paragraph, token='word') for paragraph in paragraphs]\n sentences = [\n sentence for paragraph in paragraphs for sentence in paragraph]\n self.vocab = d2l.Vocab(\n sentences, min_freq=5,\n reserved_tokens=['<pad>', '<mask>', '<cls>', '<sep>'])\n # Get data for the next sentence prediction task\n examples = []\n for paragraph in paragraphs:\n examples.extend(\n _get_nsp_data_from_paragraph(paragraph, paragraphs,\n self.vocab, max_len))\n # Get data for the masked language model task\n examples = [(_get_mlm_data_from_tokens(tokens, self.vocab) +\n (segments, is_next))\n for tokens, segments, is_next in examples]\n # Pad inputs\n (self.all_token_ids, self.all_segments, self.valid_lens,\n self.all_pred_positions, self.all_mlm_weights, self.all_mlm_labels,\n self.nsp_labels) = _pad_bert_inputs(examples, max_len, self.vocab)\n\n def __getitem__(self, idx):\n return (self.all_token_ids[idx], self.all_segments[idx],\n self.valid_lens[idx], self.all_pred_positions[idx],\n self.all_mlm_weights[idx], self.all_mlm_labels[idx],\n self.nsp_labels[idx])\n\n def __len__(self):\n return len(self.all_token_ids)",
"_____no_output_____"
]
],
[
[
"By using the `_read_wiki` function and the `_WikiTextDataset` class,\nwe define the following `load_data_wiki` to download and WikiText-2 dataset\nand generate pretraining examples from it.\n",
"_____no_output_____"
]
],
[
[
"#@save\ndef load_data_wiki(batch_size, max_len):\n num_workers = d2l.get_dataloader_workers()\n data_dir = d2l.download_extract('wikitext-2', 'wikitext-2')\n paragraphs = _read_wiki(data_dir)\n train_set = _WikiTextDataset(paragraphs, max_len)\n train_iter = torch.utils.data.DataLoader(train_set, batch_size,\n shuffle=True,\n num_workers=num_workers)\n return train_iter, train_set.vocab",
"_____no_output_____"
]
],
[
[
"Setting the batch size to 512 and the maximum length of a BERT input sequence to be 64,\nwe print out the shapes of a minibatch of BERT pretraining examples.\nNote that in each BERT input sequence,\n$10$ ($64 \\times 0.15$) positions are predicted for the masked language modeling task.\n",
"_____no_output_____"
]
],
[
[
"batch_size, max_len = 512, 64\ntrain_iter, vocab = load_data_wiki(batch_size, max_len)\n\nfor (tokens_X, segments_X, valid_lens_x, pred_positions_X, mlm_weights_X,\n mlm_Y, nsp_y) in train_iter:\n print(tokens_X.shape, segments_X.shape, valid_lens_x.shape,\n pred_positions_X.shape, mlm_weights_X.shape, mlm_Y.shape,\n nsp_y.shape)\n break",
"torch.Size([512, 64]) torch.Size([512, 64]) torch.Size([512]) torch.Size([512, 10]) torch.Size([512, 10]) torch.Size([512, 10]) torch.Size([512])\n"
]
],
[
[
"In the end, let us take a look at the vocabulary size.\nEven after filtering out infrequent tokens,\nit is still over twice larger than that of the PTB dataset.\n",
"_____no_output_____"
]
],
[
[
"len(vocab)",
"_____no_output_____"
]
],
[
[
"## Summary\n\n* Comparing with the PTB dataset, the WikiText-2 dateset retains the original punctuation, case and numbers, and is over twice larger.\n* We can arbitrarily access the pretraining (masked language modeling and next sentence prediction) examples generated from a pair of sentences from the WikiText-2 corpus.\n\n\n## Exercises\n\n1. For simplicity, the period is used as the only delimiter for splitting sentences. Try other sentence splitting techniques, such as the spaCy and NLTK. Take NLTK as an example. You need to install NLTK first: `pip install nltk`. In the code, first `import nltk`. Then, download the Punkt sentence tokenizer: `nltk.download('punkt')`. To split sentences such as `sentences = 'This is great ! Why not ?'`, invoking `nltk.tokenize.sent_tokenize(sentences)` will return a list of two sentence strings: `['This is great !', 'Why not ?']`.\n1. What is the vocabulary size if we do not filter out any infrequent token?\n",
"_____no_output_____"
],
[
"[Discussions](https://discuss.d2l.ai/t/1496)\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbafd69a0f1f0bc770cd9365c0a5157a08602089
| 871 |
ipynb
|
Jupyter Notebook
|
Index.ipynb
|
r351574nc3/Notebooks
|
cb52f466a92aa96917ee0e6aed8d8ed9c5169a80
|
[
"Apache-2.0"
] | null | null | null |
Index.ipynb
|
r351574nc3/Notebooks
|
cb52f466a92aa96917ee0e6aed8d8ed9c5169a80
|
[
"Apache-2.0"
] | null | null | null |
Index.ipynb
|
r351574nc3/Notebooks
|
cb52f466a92aa96917ee0e6aed8d8ed9c5169a80
|
[
"Apache-2.0"
] | null | null | null | 17.078431 | 34 | 0.482204 |
[
[
[
"# Notebooks\n## Test Cells",
"_____no_output_____"
]
],
[
[
"print('Everything is ok')",
"blah"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
]
] |
cbafebb2339bc02c5b0cebd54e876682098e17a5
| 2,150 |
ipynb
|
Jupyter Notebook
|
Tree/Review/617. Merge Two Binary Trees.ipynb
|
YuHe0108/Leetcode
|
90d904dde125dd35ee256a7f383961786f1ada5d
|
[
"Apache-2.0"
] | 1 |
2020-08-05T11:47:47.000Z
|
2020-08-05T11:47:47.000Z
|
Tree/Review/617. Merge Two Binary Trees.ipynb
|
YuHe0108/LeetCode
|
b9e5de69b4e4d794aff89497624f558343e362ad
|
[
"Apache-2.0"
] | null | null | null |
Tree/Review/617. Merge Two Binary Trees.ipynb
|
YuHe0108/LeetCode
|
b9e5de69b4e4d794aff89497624f558343e362ad
|
[
"Apache-2.0"
] | null | null | null | 20.283019 | 80 | 0.48186 |
[
[
[
"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:\n # 如果 root1 或者 root2 有一个为空,或者两个都是空,返回\n if not root1 or not root2:\n return root1 or root2\n \n root1.val += root2.val\n root1.left = self.mergeTrees(root1.left, root2.left)\n root1.right = self.mergeTrees(root1.right, root2.right)\n return root1",
"_____no_output_____"
],
[
"a = 0\nb = 0\nif not a or not b:\n print(a or b)",
"0\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cbafed6199a7f0cf741aea66f01025df966e7368
| 49,563 |
ipynb
|
Jupyter Notebook
|
0021_reg_practices/Regular Expression Exercises.ipynb
|
junjiecai/jupyter_demos
|
8aa8a0320545c0ea09e05e94aea82bc8aa537750
|
[
"MIT"
] | 3 |
2019-09-16T10:44:39.000Z
|
2021-09-04T18:55:52.000Z
|
0021_reg_practices/Regular Expression Exercises.ipynb
|
junjiecai/jupyter_demos
|
8aa8a0320545c0ea09e05e94aea82bc8aa537750
|
[
"MIT"
] | null | null | null |
0021_reg_practices/Regular Expression Exercises.ipynb
|
junjiecai/jupyter_demos
|
8aa8a0320545c0ea09e05e94aea82bc8aa537750
|
[
"MIT"
] | 2 |
2020-10-24T16:19:29.000Z
|
2021-09-04T18:55:57.000Z
| 39.273376 | 2,413 | 0.565482 |
[
[
[
"from regular_expression_visualization.visualize_reg import search_pattern",
"_____no_output_____"
]
],
[
[
"search_pattern is a helper function that cross matches several regular expressions against several strings. It visulizes the result by surrounding the matched substring in red border. Only the first matched substring is bordered.",
"_____no_output_____"
],
[
"## Simple pattern",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'ee', # exactly ee\n 'ea', # exactly ea\n 'ai',\n 'aa'\n]\nstrings = ['tee', 'tea', 'bail']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"## One of the pattern",
"_____no_output_____"
],
[
"Use ```|``` to seperate several pattern",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'ee|ea|ai', # ee or ea or ai\n]\nstrings = ['tee', 'tea', 'bail']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"Pattern order matters",
"_____no_output_____"
]
],
[
[
" patterns = [\n 'oo|ooo', # oo is tried first\n 'ooo|oo', # ooo is tried first\n]\nstrings = ['loong', 'looong', 'long']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"When \"one of pattern\" is followed by or following other regular expressions, use () to seperate to seperate from them",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'b(ea|ee)', # b + (ea or ee)\n 'bea|ee' # bea or ee\n]\nstrings = ['bead', 'bee']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"## Qualifiers",
"_____no_output_____"
],
[
"### appear m to n times",
"_____no_output_____"
],
[
"Use ```{m,n}```",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'ooo', # o, three times\n 'o{3}', # o, three times\n 'o{2,3}', # o, 2~3 time\n 'o{2, 3}', # o, Not working! Don't put in the blank! \n 'o{2,}', # o, more than 2 times\n 'lo{,3}', # l + o, o appears 0 to 3 times\n 'o{,3}', # seems not working alone \n]\nstrings = ['looong', 'long', 'loong']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### appear at least once",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'o+n', # o, at least 1 time\n 'o{1,}n'# same as above\n]\nstrings = ['looong', 'long', 'bug']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### appear zero or more times",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'lo*ng', # long, o appears zero or more time\n 'lo{0,}ng' # same as above\n]\nstrings = ['long', 'lng', 'loong', 'leong']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### appear zero or one time",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'apples?', # apple, ending s may not appear\n 'apples{0,1}' # same as above\n]\nstrings = ['apple', 'apples']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"## Sub expression",
"_____no_output_____"
],
[
"use ```()```",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'ba(na){2}', # b + na, na appears two times\n 'banana', # same as above\n 'bana{2}', # ban + a, a appear 2 times,\n 'banaa', # same as above\n \n]\nstrings = ['banana', 'banaa']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
],
[
"patterns = [\n '(a+_+){2}', # two consecutive pattern which match a+_+, they are not necessarily the same string\n 'a+_+a+_+', # same as above\n 'a+_+'\n]\nstrings = ['aa_a__', 'a_', 'a__a_a_']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"## Character Set",
"_____no_output_____"
],
[
"### Any character\n```.``` stands for any character",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'b.d', # b + any character + d\n 'be..' # b + e + any character + any character\n]\nstrings = ['bed', 'bid','bee', 'benign', 'beed']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any character in a set\nUse ```[...]```",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'b[ei]d', # b + e or i + d\n 'bed|bid' # same as above\n] \nstrings = ['bed', 'bid', 'bee', 'bud']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"Use ```-``` for character range",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'id_[0-5]', # id_ + any number in 0 to 5\n 'id_[012345]' # same as above\n]\nstrings = ['id_1', 'id_6']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
],
[
"patterns = [\n 'type_[a-ex]', # type_ + any character in range a to e and x,\n 'type_[abcdex]', # same as above\n 'type_[a-zA-Z]' # any letter\n] \nstrings = ['type_a', 'type_b', 'type_x', 'type_Z']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any character not in set",
"_____no_output_____"
],
[
"Use ```[^...]```",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'type_[^a-z]' # type_ + any character not in a to z\n] \nstrings = ['type_1', 'type_a', 'type_c']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any number",
"_____no_output_____"
],
[
"Use ```\\d```",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'id_\\d\\d', # id_ + any number character + any number character\n 'id_[0-9][0-9]' # same as above\n]\nstrings = ['id_12', 'id_0', 'id']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any non-number character",
"_____no_output_____"
],
[
"Use ```\\D```",
"_____no_output_____"
]
],
[
[
"patterns = [\n 'e\\D', # e + any character which is not number character\n 'e[^0-9]' # same as above\n]\nstrings = ['bee', 'tel', 'te1']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any word charcters",
"_____no_output_____"
],
[
"Use ```\\w```, word character means a-z, A-Z, 0-9 and _",
"_____no_output_____"
]
],
[
[
"patterns = [\n '\\w+', # any word character, more than one time\n '[a-zA-Z0-9_]+' # same as above\n]\nstrings = [':id_1.']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any non-word characters",
"_____no_output_____"
],
[
"Use ```\\W```",
"_____no_output_____"
]
],
[
[
"patterns = [\n '\\W+', # any non-word character, more than one time\n '[^a-zA-Z0-9_]+'# same as above\n]\nstrings = ['id_1 + id_2']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any space",
"_____no_output_____"
],
[
"Use ```\\s```",
"_____no_output_____"
]
],
[
[
"patterns = [\n '\\s.*\\s', # blank + any string + blank\n '[\\t\\n\\f\\r ].*[\\t\\n\\f\\r ]' # same as above\n]\nstrings = ['Monkey D Luffy']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Any Non Space",
"_____no_output_____"
]
],
[
[
"patterns = [\n '\\S.+\\S', # any character except space + any string + any character except space\n '[^\\t\\n\\f\\r ].*[^\\t\\n\\f\\r ]' # same as above\n]\nstrings = ['on the\\ntree']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"## Escaping",
"_____no_output_____"
],
[
"As you see, many characters like ```(```,```.```,```+``` have special means in regular expression. If you want to disable these and search for these characters, add ```\\``` before them",
"_____no_output_____"
]
],
[
[
"patterns = [\n '($\\d+.\\d+)', # $ . + are not treated as characters\n '\\(\\$\\d+\\.\\d+\\)' # $ . + are treated as characters\n]\nstrings = ['apple ($3.25)']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"## Anchor",
"_____no_output_____"
],
[
"Anchor are searched but won't be part be of the matching result",
"_____no_output_____"
],
[
"### followed by",
"_____no_output_____"
],
[
"Use ```(?=...)```",
"_____no_output_____"
]
],
[
[
"patterns = [\n '\\w+(?=\\.)', # word character string, followed by comma. the comma is not returned in the matching result\n '\\w+\\.' # comma is returned in the matching result\n]\nstrings = ['Apple juice.']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Not followed by",
"_____no_output_____"
],
[
"Use ```(?!...)```",
"_____no_output_____"
]
],
[
[
"patterns = [\n '\\w+(?!\\.)', # word character string, not followed by comma\n '\\w+[^\\.]' # word character string, followed by any character which is not comma\n]\nstrings = ['Apple juice.']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### Following",
"_____no_output_____"
],
[
"Use ```(?<=...)```",
"_____no_output_____"
]
],
[
[
"patterns = [\n '(?<=:)\\d+', # number character string, following :\n ':\\d+' # : + number character string\n]\nstrings = ['apple:10']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### not following",
"_____no_output_____"
],
[
"Use ```(?<!)```",
"_____no_output_____"
]
],
[
[
"patterns = [\n '(?<!A)\\d+', # number character string, not followed by A\n '[^A]\\d+' # any character expect A + number character string\n]\nstrings = ['A123 123']\n\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"### border of word",
"_____no_output_____"
]
],
[
[
"patterns = [\n r'\\beat\\b', # eat surrounded by border of word, (whole word searching)\n 'eat' #\n]\nstrings = ['I eat food', 'beat']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"Why use ```r``` in ```r'\\beat\\b'```? ```\\b``` in python has special meaning (like ```+``` has special meaning in regular expression), it represents a back space character [(see here)](https://stackoverflow.com/questions/25065608/what-does-backward-slash-b-do-in-python) \n\nTo disable this behaviour, add ```r``` in front of the string. (Like we add ```\\``` before ```+``` in regular expression)",
"_____no_output_____"
],
[
"### not border of word",
"_____no_output_____"
]
],
[
[
"patterns = [\n r'\\Beat\\B', # eat, not following or followed by word border, (appear within a word)\n 'eat'\n]\nstrings = ['I eat food', 'beats']\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
],
[
[
"## Exercises\nTry to search valid email address",
"_____no_output_____"
]
],
[
[
"patterns = [\n '^[^\\d@][\\w+\\.]+@\\w+(\\.com)?\\.(cn|com|org)',\n]\n\nstrings = [\n '[email protected]',\n 'fredness7@@hotmail.com',\n 'frendess7@htcom',\n '[email protected]',\n '@ht.com.cn',\n '[email protected]', \n '@[email protected]', \n]\n\nsearch_pattern(patterns, strings)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb008cb62327d774403a9f60f7091a6925fbb6e
| 20,740 |
ipynb
|
Jupyter Notebook
|
trial/.ipynb_checkpoints/dateScraper-checkpoint.ipynb
|
sahiltshah98/greyhound
|
7e0d42b8bd15484557a81995cb2e03e4f9605dec
|
[
"Apache-2.0"
] | null | null | null |
trial/.ipynb_checkpoints/dateScraper-checkpoint.ipynb
|
sahiltshah98/greyhound
|
7e0d42b8bd15484557a81995cb2e03e4f9605dec
|
[
"Apache-2.0"
] | null | null | null |
trial/.ipynb_checkpoints/dateScraper-checkpoint.ipynb
|
sahiltshah98/greyhound
|
7e0d42b8bd15484557a81995cb2e03e4f9605dec
|
[
"Apache-2.0"
] | 1 |
2020-04-20T20:16:43.000Z
|
2020-04-20T20:16:43.000Z
| 28.489011 | 84 | 0.539875 |
[
[
[
"from requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\nfrom datetime import timedelta, date\nimport sys",
"_____no_output_____"
]
],
[
[
"## All library invoke(s) ",
"_____no_output_____"
]
],
[
[
"base_link = \"https://thegreyhoundrecorder.com.au/results/search/\"\n\n#html_file_name = link_date + \".html\"",
"_____no_output_____"
],
[
"links=list()",
"_____no_output_____"
]
],
[
[
"## URL connection functions ",
"_____no_output_____"
]
],
[
[
"def simple_get(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None.\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n\n except RequestException as e:\n log_error('Error during requests to {0} : {1}'.format(url, str(e)))\n return None\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns True if the response seems to be HTML, False otherwise.\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 \n and content_type is not None \n and content_type.find('html') > -1)\n\n\ndef log_error(e):\n \"\"\"\n It is always a good idea to log errors. \n This function just prints them, but you can\n make it do anything.\n \"\"\"\n print(e)",
"_____no_output_____"
]
],
[
[
"## Function for each Date. The link-date is a global variable ",
"_____no_output_____"
]
],
[
[
"def date_execute():\n \n link = base_link+link_date+'/' #Creation of link\n raw_html = simple_get(link) #Connection complete\n \n \n html = BeautifulSoup(raw_html, 'html.parser')\n \n \n race_date = html.find('h2').decode_contents()\n \n print(race_date) #Progress tracking output statements\n print(len(raw_html))\n print(len(html))\n \n \n \n result_div = html.findAll(\"div\", {\"class\": \"resultsTblWrap\"})\n #print(result_div)\n anchors = result_div[0].findAll('a') #selecting all the race hyperlinks\n\n i=0\n links.append(link_date)\n while (i < len(anchors)):\n #print((anchors[i]['href']))\n s=anchors[i]['href']\n links.append(s) #adding them to a global list\n i=i+1\n \n \n \n ",
"_____no_output_____"
]
],
[
[
"## library function to traverse through all possible dates ",
"_____no_output_____"
]
],
[
[
"\n\ndef daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)):\n yield start_date + timedelta(n)\n\nstart_date = date(2016, 1, 1)\nend_date = date(2016, 2, 1) # Feb 1 2016 is the sop-date\nfor single_date in daterange(start_date, end_date):\n link_date=single_date.strftime(\"%Y-%m-%d\")\n #print(link_date)\n date_execute() #Calling day-wise function to execute",
"Friday January 01, 2016\n51728\n44\nSaturday January 02, 2016\n52872\n44\nSunday January 03, 2016\n47594\n44\nMonday January 04, 2016\n52836\n44\nTuesday January 05, 2016\n52811\n44\nWednesday January 06, 2016\n52885\n44\nThursday January 07, 2016\n51804\n44\nFriday January 08, 2016\n53850\n44\nSaturday January 09, 2016\n52862\n44\nSunday January 10, 2016\n47580\n44\nMonday January 11, 2016\n49674\n44\nTuesday January 12, 2016\n53877\n44\nWednesday January 13, 2016\n48669\n44\nThursday January 14, 2016\n53906\n44\nFriday January 15, 2016\n53820\n44\nSaturday January 16, 2016\n51790\n44\nSunday January 17, 2016\n49710\n44\nMonday January 18, 2016\n52836\n44\nTuesday January 19, 2016\n50727\n44\nWednesday January 20, 2016\n52887\n44\nThursday January 21, 2016\n50770\n44\nFriday January 22, 2016\n52806\n44\nSaturday January 23, 2016\n54948\n44\nSunday January 24, 2016\n46534\n44\nMonday January 25, 2016\n52846\n44\nTuesday January 26, 2016\n51757\n44\nWednesday January 27, 2016\n52881\n44\nThursday January 28, 2016\n53918\n44\nFriday January 29, 2016\n52782\n44\nSaturday January 30, 2016\n54976\n44\nSunday January 31, 2016\n48656\n44\n"
]
],
[
[
"## Check out the outcome ",
"_____no_output_____"
]
],
[
[
"print(\"\\n\".join(links))",
"2016-01-01\n/results/bulli/2033\n/results/cambridge/2035\n/results/darwin/2032\n/results/dubbo/2031\n/results/geelong/2025\n/results/gosford/2027\n/results/ipswich/2029\n/results/mandurah/2034\n/results/strathalbyn/2030\n/results/traralgon/2026\n/results/wagga/2028\n2016-01-02\n/results/addington/2020\n/results/bundaberg/2022\n/results/ipswich/2023\n/results/mandurah/2016\n/results/richmond/2015\n/results/tamworth/2017\n/results/the-gardens/2014\n/results/the-meadows/2012\n/results/warrnambool/2013\n/results/wauchope/2021\n/results/wentworth-park/2018\n/results/young/2019\n2016-01-03\n/results/albion-park/2011\n/results/cairns/2009\n/results/gawler/2010\n/results/healesville/2005\n/results/mount-gambier/2007\n/results/sale/2004\n/results/sandown-park/2006\n2016-01-04\n/results/albion-park/1998\n/results/angle-park/2002\n/results/ballarat/1992\n/results/bathurst/2001\n/results/cranbourne/1994\n/results/grafton/1997\n/results/launceston/1995\n/results/manawatu/1996\n/results/mandurah/1999\n/results/manukau/2003\n/results/nowra/2000\n/results/traralgon/1993\n2016-01-05\n/results/ascot-park/1989\n/results/devonport/1982\n/results/gawler/1983\n/results/geelong/1980\n/results/horsham/1981\n/results/ipswich/1988\n/results/lismore/1986\n/results/mandurah/1984\n/results/mandurah/1991\n/results/sale/1979\n/results/townsville/1987\n/results/warragul/1978\n2016-01-06\n/results/albion-park/1974\n/results/angle-park/1972\n/results/ballarat/1966\n/results/bendigo/1968\n/results/gawler/1977\n/results/hatrick/1975\n/results/northam/1971\n/results/richmond/1970\n/results/rockhampton/1973\n/results/the-meadows/1969\n/results/warrnambool/1967\n/results/wentworth-park/1976\n2016-01-07\n/results/addington/1959\n/results/albion-park/1962\n/results/angle-park/1963\n/results/dapto/1960\n/results/hobart/1964\n/results/mandurah/1965\n/results/manukau/1958\n/results/sandown-park/1954\n/results/shepparton/1957\n/results/warragul/1956\n/results/warrnambool/1955\n2016-01-08\n/results/addington/1952\n/results/bendigo/1941\n/results/bulli/1948\n/results/darwin/1947\n/results/dubbo/1944\n/results/geelong/1942\n/results/hatrick/1951\n/results/ipswich/1945\n/results/mandurah/1950\n/results/mount-gambier/1946\n/results/nowra/1949\n/results/strathalbyn/1953\n/results/traralgon/1943\n2016-01-09\n/results/bundaberg/1937\n/results/cowra/1938\n/results/cranbourne/1930\n/results/gosford/1933\n/results/ipswich/1934\n/results/mandurah/1936\n/results/port-augusta/1935\n/results/richmond/1931\n/results/tamworth/1932\n/results/the-meadows/1929\n/results/wauchope/1940\n/results/wentworth-park/1939\n2016-01-10\n/results/albion-park/1926\n/results/canberra/1928\n/results/gawler/1925\n/results/healesville/1922\n/results/manukau/1927\n/results/sale/1923\n/results/sandown-park/1924\n2016-01-11\n/results/albion-park/1916\n/results/angle-park/1920\n/results/ballarat/1912\n/results/bulli/1918\n/results/dubbo/1919\n/results/launceston/1915\n/results/manawatu/1917\n/results/mandurah/1921\n/results/traralgon/1914\n2016-01-12\n/results/addington/1906\n/results/devonport/1902\n/results/forbury-park/1907\n/results/gawler/1904\n/results/geelong/1900\n/results/gosford/1908\n/results/horsham/1901\n/results/ipswich/1909\n/results/lismore/1910\n/results/mandurah/1905\n/results/mandurah/1911\n/results/townsville/1903\n/results/warragul/1899\n2016-01-13\n/results/albion-park/1898\n/results/angle-park/1896\n/results/hatrick/1893\n/results/northam/1891\n/results/northam/1892\n/results/richmond/1894\n/results/rockhampton/1895\n/results/wentworth-park/1897\n2016-01-14\n/results/addington/1882\n/results/albion-park/1884\n/results/angle-park/1883\n/results/cambridge/1881\n/results/dapto/1879\n/results/dubbo/1886\n/results/hobart/1878\n/results/mandurah/1880\n/results/mandurah/1885\n/results/sandown-park/1875\n/results/shepparton/1877\n/results/warragul/1874\n/results/warrnambool/1876\n2016-01-15\n/results/addington/1871\n/results/bathurst/1867\n/results/bendigo/1843\n/results/casino/1869\n/results/darwin/1873\n/results/gawler/1870\n/results/geelong/1844\n/results/gosford/1866\n/results/hatrick/1847\n/results/hobart/1872\n/results/ipswich/1846\n/results/mandurah/1868\n/results/traralgon/1845\n2016-01-16\n/results/gosford/1837\n/results/gunnedah/1841\n/results/ipswich/1842\n/results/mandurah/1839\n/results/richmond/1840\n/results/taree/1836\n/results/temora/1838\n/results/the-meadows/1832\n/results/tweed-heads/1835\n/results/warragul/1833\n/results/wentworth-park/1834\n2016-01-17\n/results/albion-park/1826\n/results/cairns/1831\n/results/canberra/1830\n/results/healesville/1823\n/results/manukau/1829\n/results/mount-gambier/1828\n/results/sale/1824\n/results/sandown-park/1825\n/results/strathalbyn/1827\n2016-01-18\n/results/addington/1822\n/results/albion-park/1819\n/results/angle-park/1818\n/results/ballarat/1813\n/results/bathurst/1815\n/results/grafton/1821\n/results/launceston/1816\n/results/manawatu/1814\n/results/mandurah/1820\n/results/nowra/1817\n/results/traralgon/1811\n/results/warragul/1812\n2016-01-19\n/results/devonport/1802\n/results/forbury-park/1803\n/results/gawler/1807\n/results/geelong/1801\n/results/gosford/1806\n/results/ipswich/1809\n/results/lismore/1808\n/results/mandurah/1804\n/results/mandurah/1810\n/results/townsville/1805\n2016-01-20\n/results/albion-park/1796\n/results/angle-park/1797\n/results/ballarat/1787\n/results/cranbourne/1788\n/results/gawler/1798\n/results/hatrick/1790\n/results/northam/1793\n/results/northam/1795\n/results/richmond/1794\n/results/rockhampton/1791\n/results/the-meadows/1789\n/results/wentworth-park/1792\n2016-01-21\n/results/albion-park/1780\n/results/angle-park/1781\n/results/cambridge/1785\n/results/hobart/1783\n/results/maitland/1784\n/results/mandurah/1782\n/results/sandown-park/1776\n/results/shepparton/1778\n/results/warragul/1775\n/results/warrnambool/1777\n2016-01-22\n/results/addington/1774\n/results/bendigo/1762\n/results/bulli/1767\n/results/casino/1765\n/results/darwin/1771\n/results/geelong/1764\n/results/hatrick/1766\n/results/ipswich/1769\n/results/mandurah/1768\n/results/mount-gambier/1770\n/results/the-gardens/1773\n/results/warragul/1763\n2016-01-23\n/results/bundaberg/1760\n/results/cairns/1761\n/results/cowra/1757\n/results/gunnedah/1754\n/results/ipswich/1753\n/results/mandurah/1755\n/results/manukau/1759\n/results/richmond/1752\n/results/taree/1758\n/results/the-gardens/1750\n/results/the-meadows/1749\n/results/traralgon/1748\n/results/tweed-heads/1756\n/results/wentworth-park/1751\n2016-01-24\n/results/albion-park/1746\n/results/canberra/1747\n/results/gawler/1745\n/results/healesville/1742\n/results/sale/1743\n/results/sandown-park/1744\n2016-01-25\n/results/albion-park/1735\n/results/angle-park/1740\n/results/ballarat/1730\n/results/bathurst/1737\n/results/grafton/1739\n/results/launceston/1733\n/results/manawatu/1734\n/results/mandurah/1736\n/results/mandurah/1741\n/results/nowra/1738\n/results/shepparton/1732\n/results/traralgon/1731\n2016-01-26\n/results/ascot-park/1726\n/results/devonport/1722\n/results/gawler/1724\n/results/geelong/1719\n/results/gosford/1723\n/results/horsham/1720\n/results/ipswich/1728\n/results/kempsey/1721\n/results/lismore/1727\n/results/townsville/1725\n/results/warragul/1718\n2016-01-27\n/results/albion-park/1715\n/results/angle-park/1712\n/results/ballarat/1706\n/results/bendigo/1709\n/results/cranbourne/1707\n/results/gawler/1716\n/results/hatrick/1710\n/results/northam/1714\n/results/richmond/1711\n/results/rockhampton/1713\n/results/the-meadows/1708\n/results/wentworth-park/1717\n2016-01-28\n/results/addington/1702\n/results/albion-park/1704\n/results/angle-park/1699\n/results/cambridge/1701\n/results/dapto/1703\n/results/hobart/1697\n/results/maitland/1698\n/results/mandurah/1700\n/results/mandurah/1705\n/results/sandown-park/1693\n/results/shepparton/1695\n/results/warragul/1696\n/results/warrnambool/1694\n2016-01-29\n/results/addington/1691\n/results/bendigo/1681\n/results/bulli/1686\n/results/casino/1689\n/results/darwin/1687\n/results/geelong/1682\n/results/hatrick/1685\n/results/ipswich/1690\n/results/mandurah/1688\n/results/sale/1683\n/results/strathalbyn/1684\n/results/the-gardens/1692\n2016-01-30\n/results/armidale/1674\n/results/ballarat/1669\n/results/bundaberg/1676\n/results/hatrick/1678\n/results/ipswich/1680\n/results/kempsey/1671\n/results/mandurah/1677\n/results/richmond/1679\n/results/temora/1675\n/results/the-gardens/1670\n/results/the-meadows/1668\n/results/traralgon/1667\n/results/tweed-heads/1672\n/results/wentworth-park/1673\n2016-01-31\n/results/addington/1666\n/results/albion-park/1665\n/results/canberra/1663\n/results/gawler/1664\n/results/healesville/1659\n/results/mount-gambier/1662\n/results/sale/1660\n/results/sandown-park/1661\n"
]
],
[
[
"## storing the entire list into a file",
"_____no_output_____"
]
],
[
[
"with open('datefile.txt', 'w') as filehandle:\n filehandle.writelines(\"%s\\n\" % place for place in links)",
"_____no_output_____"
]
],
[
[
"### ignore | code snippet to redirect system-output to text file ",
"_____no_output_____"
]
],
[
[
"import sys\n\norig_stdout = sys.stdout\nf = open(html_file_name, 'w')\nsys.stdout = f\n\nprint(html)\n\nsys.stdout = orig_stdout\nf.close()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"raw"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"raw"
]
] |
cbb012c46f9d5ca69f9250c5a1374aa993757ec2
| 4,949 |
ipynb
|
Jupyter Notebook
|
notebooks/Tutorial-backend-pre_requisitos.ipynb
|
DS4a5CTeam90/tutorials
|
9277d8fafc37ce3dd7382b32623c0a7d285d10b2
|
[
"MIT"
] | 1 |
2021-09-12T01:46:35.000Z
|
2021-09-12T01:46:35.000Z
|
notebooks/Tutorial-backend-pre_requisitos.ipynb
|
DS4a5CTeam90/tutorials
|
9277d8fafc37ce3dd7382b32623c0a7d285d10b2
|
[
"MIT"
] | null | null | null |
notebooks/Tutorial-backend-pre_requisitos.ipynb
|
DS4a5CTeam90/tutorials
|
9277d8fafc37ce3dd7382b32623c0a7d285d10b2
|
[
"MIT"
] | null | null | null | 27.803371 | 205 | 0.576884 |
[
[
[
"# Tutorial sobre desarrollo de aplicaciones (BACKEND)",
"_____no_output_____"
],
[
"## Pre-requisitos\n\n1. Cuenta en Github\n2. Instalación de Git en sus maquinas de desarrollo\n3. Configuración de la llave SSH-Key (para descargar y subir codigo)\n4. Cuenta en Heroku\n\n-----------\n\n1. Cuenta en Github: \n\nVisitar el sitio web: https://github.com/ y seguir los pasos para registrarse. Todos ustedes ya lo han hecho, asi que estamos bien por este lado.\n\n2. Instalación de Git en sus maquinas de desarrollo\n\n#### Modo 1\n\nPor simplicidad, vamos a hacerlo desde el Workspace de DS4A, en donde ya está instalado Git.\n\n#### Modo 2\n\nDirigirse al siguiente sitio web y descargar el ejecutable de instalación (según el sistema operativo que tengan):\n\nhttps://git-scm.com/book/en/v2/Getting-Started-Installing-Git\n\nPor ejemplo, para Windows:\n\nhttps://git-scm.com/download/win\n\n3. Configuración de la llave SSH-Key\n\nSuperando 1 - es un registro estandard, como en cualquier otro servicio Web - y el 2, que consiste en instalar un ejecutable, el punto importante es el de la configuracion de la SSH-Key.\n\nPara esto, vamos a seguir las instrucciones sugeridas en el siguiente sitio:\n\nhttps://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent\n",
"_____no_output_____"
]
],
[
[
"from IPython.display import Video\nVideo(\"video_ssh.mp4\")",
"_____no_output_____"
]
],
[
[
"Ese paso el paso # 1. Ahora necesitamos adicionar esa llave SSH (SSH-KEY) a Github para que nos autorice nuestra maquina de desarrollo. Seguiremos las instrucciones que el mismo Github nos ofrece:\n\nhttps://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account\n\nLa guia de Github sugiere instalar xclip. Vamos en cambio hacer el siguiente procedimiento más simple:\n",
"_____no_output_____"
]
],
[
[
"Video(\"video_add_key_01.mp4\")",
"_____no_output_____"
],
[
"Video(\"video_add_key_02.mp4\")",
"_____no_output_____"
]
],
[
[
"Muy bien, ya tenemos lo necesario para autenticarnos y realizar parte del tutorial.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cbb028f09dd1ee962c881e40cf5e3018b8643ace
| 36,241 |
ipynb
|
Jupyter Notebook
|
models/NPSpeciesScraper_Selenium_GetParkNamesOnly.ipynb
|
sdutta3/wildlifewatch
|
45b82254ae248024f67842b5ca5f988bb64896ec
|
[
"MIT"
] | null | null | null |
models/NPSpeciesScraper_Selenium_GetParkNamesOnly.ipynb
|
sdutta3/wildlifewatch
|
45b82254ae248024f67842b5ca5f988bb64896ec
|
[
"MIT"
] | null | null | null |
models/NPSpeciesScraper_Selenium_GetParkNamesOnly.ipynb
|
sdutta3/wildlifewatch
|
45b82254ae248024f67842b5ca5f988bb64896ec
|
[
"MIT"
] | null | null | null | 49.850069 | 168 | 0.604178 |
[
[
[
"import numpy as np\nimport pandas as pd\nimport urllib\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys",
"_____no_output_____"
],
[
"np_list = []\npark_chosen = 'Acadia National Park (ACAD)'",
"_____no_output_____"
],
[
"chrome_options = webdriver.chrome.options.Options()\n#chrome_options.add_argument('--headless')\n#chrome_options.add_argument('--no-sandbox')\n#chrome_options.add_argument('--disable-dev-shm-usage')\nchrome_path = r'C:\\Users\\Sumit\\Anaconda3\\pkgs\\python-chromedriver-binary-77.0.3865.40.0-py36_0\\Lib\\site-packages\\chromedriver_binary\\chromedriver.exe'\ndriver = webdriver.Chrome(chrome_path, options=chrome_options)\n# req = urllib.request.urlopen(\"https://irma.nps.gov/NPSpecies/Search/SpeciesList\")\ndriver.get(\"https://irma.nps.gov/NPSpecies/Search/SpeciesList\")\n# assert 'NPSpecies' in driver.title\nprint(driver.title)\nelem1 = driver.find_element_by_id(\"ext-gen1047\").click()\nelem9 = driver.find_element_by_id(\"ext-gen1048\").click()\nelem2 = driver.find_element_by_id(\"boundlist-1145-listEl\") # boundlist-1145-listEl\nelem3 = elem2.find_element_by_class_name('x-list-plain')\n# elem11 = elem2.find_elements_by_css_selector(\"*\")\n# for elem in elem11:\n# print(elem.get_attribute('class'))\nelem4 = elem3.find_elements_by_tag_name(\"li\")\nfor park in elem4:\n np_list.append(park.text)\nelem8 = driver.find_element_by_id('nps-npspecies-ux-filterparkcombobox-1011-inputEl')\ndriver.execute_script(\"arguments[0].value = '\"+park_chosen+\"';\", elem8)\nelem5 = driver.find_element_by_id('radiofield-1017-inputEl').click() # Click Full list with details\nelem6 = driver.find_element_by_id('button-1021-btnIconEl').click() # Click Submit\ndriver.implicitly_wait(10)\n# elem7 = driver.find_element_by_id('button-1142-btnIconEl').click() # this is the Download button\n# elem10 = driver.find_element_by_id('button-1142-btnInnerEl').click()\n# elem13 = driver.find_element_by_css_selector(\"a[role='button']\")\nelem12 = driver.find_element_by_id('button-1142').click()\n# elem14 = driver.find_element_by_xpath('//a[. = \"Download\"]').click() # '//button[. = \"Download\"]'\ndriver.close()",
"NPSpecies- Search for a Park Species List\n"
],
[
"driver",
"_____no_output_____"
],
[
"np_list",
"_____no_output_____"
],
[
"len(np_list)",
"_____no_output_____"
],
[
"bsobj = BeautifulSoup(req.read())",
"_____no_output_____"
],
[
"bs_div = bsobj.find(\"div\", {'id': 'boundlist-1145-listEl'})\nprint(bs_div)",
"None\n"
],
[
"# ul class x-list-plain has list of parks",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb02bada8c3a8306966bf806227ec9c127b3908
| 3,986 |
ipynb
|
Jupyter Notebook
|
2/1-3/recursion/Last-index-recursion.ipynb
|
ZacksAmber/Udacity-Data-Structure-Algorithms
|
b5e008ab111b6bc9765acd58d7e1771852eb1d30
|
[
"MIT"
] | 1 |
2021-09-27T10:18:14.000Z
|
2021-09-27T10:18:14.000Z
|
2/1-3/recursion/Last-index-recursion.ipynb
|
ZacksAmber/Udacity-Data-Structure-Algorithms
|
b5e008ab111b6bc9765acd58d7e1771852eb1d30
|
[
"MIT"
] | null | null | null |
2/1-3/recursion/Last-index-recursion.ipynb
|
ZacksAmber/Udacity-Data-Structure-Algorithms
|
b5e008ab111b6bc9765acd58d7e1771852eb1d30
|
[
"MIT"
] | null | null | null | 20.978947 | 181 | 0.48846 |
[
[
[
"## Problem statement\n\nGiven an array `arr` and a target element `target`, find the last index of occurence of `target` in `arr` using recursion. If `target` is not present in `arr`, return `-1`.\n\nFor example:\n\n1. For `arr = [1, 2, 5, 5, 1, 2, 5, 4]` and `target = 5`, `output = 6`\n\n2. For `arr = [1, 2, 5, 5, 1, 2, 5, 4]` and `target = 7`, `output = -1`",
"_____no_output_____"
]
],
[
[
"def last_index(arr, target):\n \"\"\"\n :param: arr - input array\n :param: target - integer element\n return: int - last index of target in arr\n TODO: complete this method to find the last index of target in arr\n \"\"\"\n pass",
"_____no_output_____"
]
],
[
[
"<span class=\"graffiti-highlight graffiti-id_vwcsmcw-id_flmfhqn\"><i></i><button>Show Solution</button></span>",
"_____no_output_____"
]
],
[
[
"def test_function(test_case):\n arr = test_case[0]\n target = test_case[1]\n solution = test_case[2]\n output = last_index(arr, target)\n if output == solution:\n print(\"Pass\")\n else:\n print(\"FAIL: Expected\", solution, \", but you've got:\", output)",
"_____no_output_____"
],
[
"arr = [1, 2, 5, 5, 4]\ntarget = 5\nsolution = 3\n\ntest_case = [arr, target, solution]\ntest_function(test_case)",
"Pass\n"
],
[
"arr = [1, 2, 5, 5, 4]\ntarget = 7\nsolution = -1\n\ntest_case = [arr, target, solution]\ntest_function(test_case)",
"Pass\n"
],
[
"arr = [91, 19, 3, 8, 9]\ntarget = 91\nsolution = 0\n\ntest_case = [arr, target, solution]\ntest_function(test_case)",
"Pass\n"
],
[
"arr = [1, 1, 1, 1, 1, 1]\ntarget = 1\nsolution = 5\n\ntest_case = [arr, target, solution]\ntest_function(test_case)",
"Pass\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbb04f23a0bae910e71787fc0e9f7c2eb2d2457b
| 41,396 |
ipynb
|
Jupyter Notebook
|
SSDF_Simuipynb.ipynb
|
dgod1028/SBass_Project
|
cdfd13a6876ef54621c3486ac89ad3bd50f23158
|
[
"MIT"
] | null | null | null |
SSDF_Simuipynb.ipynb
|
dgod1028/SBass_Project
|
cdfd13a6876ef54621c3486ac89ad3bd50f23158
|
[
"MIT"
] | null | null | null |
SSDF_Simuipynb.ipynb
|
dgod1028/SBass_Project
|
cdfd13a6876ef54621c3486ac89ad3bd50f23158
|
[
"MIT"
] | null | null | null | 37.735643 | 135 | 0.401681 |
[
[
[
"# !/usr/bin/python3\n\n\n### 1. Data import\n\nimport sys ## system\nimport numpy as np ## Matrix Calculate\nimport glob ## global variable\nimport random ## random sample\nfrom math import exp, gamma, log, sqrt ## exp,log,sqrt cal\nimport scipy.stats as ss\nimport time\nfrom copy import deepcopy as dc\nimport time\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport logging\nfrom Utils.Utils import *\nimport csv\nimport os\nimport pandas as pd\nimport numpy as np\nfrom scipy.linalg import cholesky\n\n# path_psig, path_gamg, path_fg, path_ gg, path_bhg, path_ghg C path_deltag, path_llg\n\n\n###### Important Options\nnp.random.seed(1028)\nUPDATE = False # <- update from last MCMC\nFIX = True # <- if FIX, then fix the sigma.a, omega.b (sigma, delta) as 1.\nVV = 1\n# Total Iteration = burnin + mcmc\nburnin = 0\nmcmc = 200000\ntarget_mh = 0.25\n\nSIG = 1\n\nif sys.argv[1] == \"soda\":\n PATH = \"carb/\"\nelse:\n PATH = \"yogurt/\"\nff = sys.argv[1]\n\nif sys.argv[2] == '0': MODEL = MODEL + '_FIX'\nMODEL = \"SSDF_Simu\"\n\nPATH = \"sims6/s%i/\" % int(sys.argv[2]) # <- Simulation\nff = \"sims6\"\n\nif UPDATE:\n FN = PATH + MODEL + \"_update.npz\"\n LOGFILE = \"Logs/%s_%s_update.log\" % (MODEL, ff)\nelse:\n FN = PATH + MODEL + \".npz\"\n LOGFILE = \"Logs/sims6/%s_%s_%s.log\" % (MODEL, ff, sys.argv[2])\n\nlogging.basicConfig(level=logging.INFO,\n filename=LOGFILE,\n format=\"%(asctime)s %(levelname)-7s %(message)s\")\nwith open(LOGFILE, \"w\"):\n pass\n\nif not os.path.isdir(PATH + MODEL):\n os.mkdir(PATH + MODEL)\nif not os.path.isdir(PATH + MODEL + '/MCMC'):\n os.mkdir(PATH + MODEL + '/MCMC')\nif not os.path.isdir('Logs'):\n os.mkdir('Logs')\n\nPATH_PSIG = PATH + MODEL + '/MCMC/psig.csv'\nPATH_GAMG = PATH + MODEL + '/MCMC/gamg.csv'\nPATH_FG = PATH + MODEL + '/MCMC/fg.csv'\nPATH_GG = PATH + MODEL + '/MCMC/gg.csv'\nPATH_BHG = PATH + MODEL + '/MCMC/bhg.csv'\nPATH_GHG = PATH + MODEL + '/MCMC/ghg.csv'\nPATH_DELTAG = PATH + MODEL + '/MCMC/deltag.csv'\nPATH_SIGMAG = PATH + MODEL + '/MCMC/sigmag.csv'\nPATH_LLG = PATH + MODEL + '/MCMC/llg.csv'\nPATH_PHIG = PATH + MODEL + '/MCMC/phig.csv'\nPATH_VBG = PATH + MODEL + '/MCMC/vbg.csv'\n\nPATH_VBG = PATH + MODEL + '/MCMC/vbg.csv'\nPATH_VGAM = PATH + MODEL + '/MCMC/vgam.csv'\nPATH_GAMMU = PATH + MODEL + '/MCMC/gammu.csv'\nPATH_GAMMUH = PATH + MODEL + '/MCMC/gammuh.csv'\nPATH_VPSI = PATH + MODEL + '/MCMC/vpsi.csv'\nPATH_PSIMU = PATH + MODEL + '/MCMC/psimu.csv'\nPATH_PSIMUH = PATH + MODEL + '/MCMC/psimuh.csv'\n\nPATH_BETAG = PATH + MODEL + '/MCMC/betag.csv'\nPATH_KG = PATH + MODEL + '/MCMC/kg.csv'\n\nwith open(PATH_PSIG, 'w') as f:\n pass\nwith open(PATH_GAMG, 'w') as f:\n pass\nwith open(PATH_FG, 'w') as f:\n pass\nwith open(PATH_GG, 'w') as f:\n pass\nwith open(PATH_BHG, 'w') as f:\n pass\nwith open(PATH_GHG, 'w') as f:\n pass\nwith open(PATH_DELTAG, 'w') as f:\n pass\nwith open(PATH_SIGMAG, 'w') as f:\n pass\nwith open(PATH_LLG, 'w') as f:\n pass\nwith open(PATH_PHIG, 'w') as f:\n pass\nwith open(PATH_VBG, 'w') as f:\n pass\n\nwith open(PATH_VGAM, 'w') as f:\n pass\nwith open(PATH_GAMMU, 'w') as f:\n pass\nwith open(PATH_GAMMUH, 'w') as f:\n pass\nwith open(PATH_VPSI, 'w') as f:\n pass\nwith open(PATH_PSIMU, 'w') as f:\n pass\nwith open(PATH_PSIMUH, 'w') as f:\n pass\n\nwith open(PATH_KG, 'w') as f:\n pass\nwith open(PATH_BETAG, 'w') as f:\n pass\n\nlist_of_files = sorted(glob.glob(PATH + 'demand/*.csv'))\nlist_of_files2 = sorted(glob.glob(PATH + 'prices/*.csv'))\n# C = pd.read_csv(PATH + \"c.csv\").iloc[:, 2:]\n\n## Remove last one day\ndemand = [np.loadtxt(f, skiprows=1, delimiter=\",\") for f in list_of_files]\nprices = [np.loadtxt(f, skiprows=1, delimiter=\",\") for f in list_of_files2]\n\n# demand = [np.loadtxt(f, skiprows=1, delimiter=\",\") for f in list_of_files[:50]]\n# prices = [np.loadtxt(f, skiprows=1, delimiter=\",\") for f in list_of_files2[:50]]\n\ndemand = [d[:, :] for d in demand]\nprices = [p[:, :] for p in prices]\n\n\n# demand = [d[:-1, :] for d in demand]\n# prices = [p[:-1, :] for p in prices]\n\n\n##################### 2. Fucntions\n###prior : 0 = pu0 , 1 = pv0, 2 = gu0 , 3 = gv0 , 4 = tpp , 5 = tpg\n\n\ndef rwmh(de, pr, x, ll, alpha, f, psi, g, kt, r, betai, zphi, bh, gh, abh, sigma, delta, vbi, tpa, tpp,\n llb1, sdm, gammu, vgam, gamm, psimu, vpsi, psim, household):\n ## alpha <- gamma ## a <- alpha\n\n k = de.shape[1] ###\n kp = k - 1\n\n af = f.dot(gh.T) # <- gh.T like t(gh) in R\n bg = g.dot(bh.T)\n\n af2 = af + gammu\n bg2 = bg + psimu\n\n n = psi.shape[0]\n\n ite = np.zeros((n, 2)) ### num of mcmc iteration\n ## sampling psi,gamma\n\n #\"\"\"\n for i in range(n):\n\n ## -------------\n ## M-H Sampling\n\n rpsi = psi[i:(i + 1)].dot(C.T).reshape(-1)\n rpsi[-1] = 0\n rnalpha = alpha[i:(i + 1)].dot(C.T).reshape(-1)\n\n\n llb = ll[i] + logpdf(alpha[i, :], af2[i, :], sigma)\n nalpha = alpha[i] + mvn(np.identity(ck) * tpa[i])\n rnalpha = nalpha.reshape(1, -1).dot(C.T).reshape(-1)\n\n nll = mdcev(rpsi, rnalpha, de[i, :], pr[i, :], SIG)\n nllb = nll + logpdf(nalpha, af2[i, :], sigma )\n\n if nllb - llb > np.log(random.uniform(0, 1)):\n alpha[i] = nalpha\n ll[i] = nll\n llb1[i] = nllb\n ite[i, 0] += 1\n else:\n rnalpha = alpha[i:(i + 1)].dot(C.T).reshape(-1)\n\n llb = ll[i] + logpdf(psi[i], bg2[i], delta)\n\n npsi = psi[i] + mvn(np.identity(ck) * tpp[i])\n rnpsi = npsi.reshape(1, -1).dot(C.T).reshape(-1)\n rnpsi[-1] = 0\n nll = mdcev(rnpsi, rnalpha, de[i, :], pr[i, :], SIG)\n nllb = nll + logpdf(npsi, bg2[i, :], delta)\n\n if nllb - llb > np.log(random.uniform(0, 1)):\n psi[i] = npsi.transpose()\n ll[i] = nll\n llb1[i] = nllb\n ite[i, 1] += 1\n #\"\"\"\n\n # gammu\n y = alpha - af\n y2 = psi - bg\n\n for i in range(1, ck):\n gammu[i] = bmreg1(y[:, i:(i + 1)], np.ones((n, 1)), None, 1, gamm[i], vgam[i, i], e=False)\n for i in range(ck):\n psimu[i] = bmreg1(y2[:, i:(i + 1)], np.ones((n, 1)), None, 1, psim[i], vpsi[i, i], e=False)\n\n #psimu[:] = 0\n #gammu[:] = 0\n\n ### f & g\n gmat = np.zeros((kl, kl))\n gmat[0, 0] = 1\n gmat[1:, 0] = betai\n #gmat = np.eye(3)\n\n w = np.identity(3) #* (0.01 ** 2)\n \n r = 0\n if ck == 12:\n theta, kt = FFBS(np.concatenate([alpha - gammu, psi - psimu], axis=1), abh, sdm , gmat, w, m0, c0, kt, r)\n else:\n theta, kt = FFBS(np.concatenate([alpha - gammu, (psi - psimu)[:,:-1]], axis=1), abh, sdm, gmat, w, m0, c0, kt, r)\n\n f = theta[:, 0:(1)]\n g = theta[:, 1:(1 + 2)]\n\n ## delta_ht\n \n xf = f[:-1][kt[1:] == 1] # Collect f_h(t-1) when f_h(t-1) > 0\n for j in range(2):\n # yg = g[kt == 1, j]\n yg = g[1:][kt[1:] == 1, j] # collect g_h(t) when f_h(t-1) > 0\n\n if yg.shape[0] > 0:\n bs = np.linalg.inv(vbi[j, j] + xf.T.dot(xf) / vg[j, j]) \n bm = bs.dot(vbi[j, j] * zphi[j] + (xf.T.dot(yg)) / vg[j, j])\n\n else: # when all f_h(t) < 0, then sample from delta_bar\n bs = [1 / (vbi[j, j])]\n bm = zphi[j]\n\n betai[j] = bm + mvn([bs])\n \n\n return [alpha, f, psi, g, ll, ite, kt, betai, gammu, psimu, llb1]\n\n\ndef FFBS(data, F, V, G, W, m0, c0, kt, r):\n # W system var\n # F True_t = F * True_t-1 + u +G * w\n t = data.shape[0]\n m = data.shape[1]\n p = F.shape[1]\n m = int(p * (p + 1) / 2)\n mt = np.zeros((t, p))\n ct = np.zeros((t, m))\n\n m_t = m0.copy()\n Ct = c0.copy()\n k_t = 1\n kt = kt.reshape(kt.shape[0])\n Ft = F.copy()\n atrow = np.zeros((t, p, 1))\n rtrow = np.zeros((t, p, p))\n gtrow = np.zeros((t, p, p))\n ctrow = np.zeros((t, p, p))\n wtrow = np.zeros((t, p, p))\n rtmat = np.zeros((t, p, p))\n theta = np.zeros((t, p))\n\n ## Forward Filtering\n\n for i in range(t):\n\n kt[i] = k_t\n if k_t == 1:\n Gt = G.copy()\n Wt = W.copy()\n rtrow[i] = np.eye(3)\n\n\n else:\n Gt = np.identity(3)\n #Gt[0, 0] = 0\n Wt = W.copy()\n #Gt = G.copy()\n Wt[1:,1:] = np.eye(2) * 0\n if i == 0:\n Gt = np.identity(3) #* 0\n ######################################################\n ### predict theta t|y-1\n at = Gt.dot(m_t)\n Rt = Gt.dot(Ct).dot(Gt.T) + Wt\n\n sft = Ft.dot(at)\n Qt = Ft.dot(Rt).dot(Ft.T) + V\n Qti = np.linalg.inv(Qt)\n KGt = Rt.dot(Ft.T).dot(Qti)\n m_t = at + KGt.dot(data[i].reshape((cmn, 1)) - sft)\n\n atrow[i] = at.copy()\n rtrow[i] = Rt.copy()\n gtrow[i] = Gt.copy()\n # Ct = Rt - KGt.dot(Ft).dot(Rt)\n Ct = np.round(Rt - KGt.dot(Ft).dot(Rt), 10)\n mt[i] = m_t.transpose()\n\n ctrow[i] = Ct.copy()\n wtrow[i] = Wt.copy()\n\n if m_t[0] > r:\n k_t = 1\n else:\n k_t = 0\n \"\"\"\n try:\n if Ct[1, 1] == 0:\n theta[i] = m_t.reshape(-1)\n theta[i, 0] += mvn([[Ct[0, 0]]]) # cholesky([H_t[0,0]], lower=True).dot(np.random.rand(1))\n else:\n theta[i] = m_t.reshape(-1) + mvn(\n Ct) # + cholesky(H_t, lower=True).dot(np.random.rand(p))#rtrow[i].dot()\n except:\n print(H_t, kt[i], i)\n 1 + \"a\"\n \"\"\"\n\n ## Back_Sampling\n H_t = ctrow[-1]\n h_t = mt[-1]\n for i in range(t - 1, -1, -1):\n\n try:\n if H_t[1, 1] == 0:\n theta[i] = h_t.reshape(-1)\n theta[i, 0] += mvn([[H_t[0, 0]]]) # cholesky([H_t[0,0]], lower=True).dot(np.random.rand(1))\n else:\n theta[i] = h_t.reshape(-1) + mvn(\n H_t) # + cholesky(H_t, lower=True).dot(np.random.rand(p))#rtrow[i].dot()\n except:\n print(H_t, kt[i], i)\n 1 + \"a\"\n if i != 0:\n Gt = gtrow[i]\n a_t = atrow[i]\n m_t = mt[i - 1]\n C_t = ctrow[i - 1]\n R_tp1 = rtrow[(i)]\n\n CGRi = C_t.dot(Gt.T).dot(np.linalg.inv(R_tp1))\n h_t = m_t.reshape(p, 1) + CGRi.dot(theta[i].reshape(p, 1) - a_t.reshape(p, 1))\n H_t = C_t - CGRi.dot(Gt).dot(C_t)\n H_t = np.round(H_t, 10)\n \n\n\n\n return theta, kt\n\n\n# Form a shared array and a lock, to protect access to shared memory.\n\nk = demand[1].shape[1]\nkp = k - 1\n# ck = C.shape[1]\nh = len(demand)\n\nif k == 35:\n try:\n C = np.array(pd.read_csv(PATH + \"c.csv\").iloc[:, 2:])\n except:\n C = np.array(pd.read_csv(\"sims6/c.csv\").iloc[:, 2:])\nelse:\n C = np.eye(k)\n\nck = C.shape[1]\nckp = ck - 1\n\npsia = np.zeros((h, ck))\npsid = {}\nglist = list()\nstart = 0\nind = np.zeros((h, 2)) # np.array([0] * h * 2).reshape((h, 2))\npsih = []\ngamh = []\n\nfor i in range(h):\n # psid[i] = np.zeros((demand[i].shape[0], ck))\n ind[i, 0] = start\n ind[i, 1] = start + demand[i].shape[0]\n glist.append(range(start, start + demand[i].shape[0]))\n start = start + demand[i].shape[0]\n# print(glist)\n# print(ind)\n# psi = shared_array((t,k))\n# psi = np.zeros((t,k))#np.concatenate([psid[x] for x in sorted(psid)], 0) #+ 0.01\n\ndems = demand[0]\npris = prices[0]\n\ncg = np.eye(ck)\n\nfor i in range(1, h):\n dems = np.vstack((dems, demand[i]))\n pris = np.vstack((pris, prices[i]))\n\ndems = np.array(dems).reshape((-1, k))\npris = np.array(pris).reshape((-1, k))\n\nt = dems.shape[0]\npsi = np.zeros((t, ck)) # np.concatenate([psid[x] for x in sorted(psid)], 0) #+ 0.01\n\nif len(sys.argv) > 2:\n c = int(sys.argv[2])\nelse:\n c = 4\n\nthin = 1\nnmcmc = burnin + thin * mcmc\n\n### 3. Prior Setting\n\nm_psi = 0\ntau_psi = 1\n\nm_gamma = 0\ntau_gamma = 1\n\n### 4. Initial Value\n\nzdata = np.array([1.] * h).reshape((h, 1))\nrankz = zdata.shape[1]\n\ngu0 = np.zeros((ck, 1)) + 0.01\nfor i0 in range(1):\n gu0[i0, i0] = 1\ngv0 = np.diag([100.] * 1)\ngv0i = np.linalg.inv(gv0)\nss0 = 2\nsr0 = 2\nsrn = sr0 + t\n\nbu0 = np.zeros((ck, 2)) + 0.01\nfor i in range(2):\n bu0[i, i] = 1\nbv0 = np.diag([100.] * 2)\nbv0i = np.linalg.inv(bv0)\n\nds0 = 2\ndr0 = 2\ndrn = dr0 + t\n\npu0 = np.zeros((1, 1))\npv0 = np.diag([100.] * 1)\n\npv0i = np.linalg.inv(pv0)\npv0iu0 = pv0i.dot(pu0)\n\n##############vb\nf0 = 1 + 2\nf0n = f0 + h\ng0 = np.diag([f0]) * 100\n\ntpa = np.zeros(t) + 0.05\ntpp = np.zeros(t) + 0.05\n# tpa = np.diag([0.1] * k)\n# tpp = np.diag([0.1] * kp)\n\ngama = np.zeros((t, ck))\ngamm = np.zeros((t, ck))\ngams = np.zeros((t, ck))\n\ngh = dc(gu0)\n\nfa = np.zeros((t, 1))\nfm = np.zeros((t, 1))\nfs = np.zeros((t, 1))\n\nsigma = np.diag([1.] * ck)\nsigmai = np.linalg.inv(sigma)\n\n### baseline\npsia = np.zeros((t, ck))\npsim = np.zeros((t, ck))\npsis = np.zeros((t, ck))\n\nbh = dc(bu0)\n\nga = np.zeros((t, 2))\ngm = np.zeros((t, 2))\ngs = np.zeros((t, 2))\n\nvg = np.identity(2) #* 0.01\n\ndelta = np.diag([1.] * ck)\ndeltai = np.linalg.inv(delta)\n\nbetaa = np.zeros((h, 2)) + 0.01\nbetam = np.zeros((h, 2))\nbetas = np.zeros((h, 2))\n\nphi = np.zeros((1, 2))\n\nvb = np.diag([1.] * 2) #* 0.01\nvbi = np.linalg.inv(vb)\n\nm = prices[0].shape[0]\nmn = m - 1\n\nif ck!= 12:\n cmn = ck * 2 - 1\nelse:\n cmn = ck * 2\nkl = 1 + 2\n\nm0 = np.zeros((kl, 1))\nc0 = np.identity(kl) # * 100\n\n# print(\"c0\",c0)\nabh = np.zeros((cmn, kl))\nsdm = np.diag([1.] * cmn)\nkt = np.ones(t)\n# kt = np.array([1.]*t).reshape((t,1))\nktm = np.zeros(t)\nkts = dc(kt)\n\nr = np.zeros((h, 1))\n\nlla = np.zeros((t, 1))\nllb = np.zeros((t, 1))\n\nrpsi = psi.dot(C.T)\nrgama = gama.dot(C.T)\n\nfor i in range(t):\n lla[i] = mdcev(rpsi[i], rgama[i], dems[i], pris[i], SIG)\nart = np.zeros((t, 2))\n\nitea = np.array([0] * h * 2).reshape((h, 2))\n\n# v = np.diag([0.1] * ck)\n# iv = np.linalg.inv(v)\n\n## psi_mu, gam_mu\ngammu = np.zeros((h, ck))\ngammum = np.zeros((h, ck))\ngammus = np.zeros((h, ck))\n\ngamhmu = np.zeros(ck)\ngamhmum = np.zeros(ck)\ngamhmus = np.zeros(ck)\n\npsimu = np.zeros((h, ck))\npsimum = np.zeros((h, ck))\npsimus = np.zeros((h, ck))\n\npsihmu = np.zeros(ck)\npsihmum = np.zeros(ck)\npsihmus = np.zeros(ck)\n\nvgam = np.identity(ck)\nvpsi = np.identity(ck)\n\nexecutor = ProcessPoolExecutor()\nstart = time.time()\n\npsilogm = np.zeros((t, ck))\ngamlogm = np.zeros((t, ck))\npsilogs = np.zeros((t, ck))\ngamlogs = np.zeros((t, ck))\n\nimport pandas as pd\n\nif __name__ == '__main__':\n\n # betaa = np.array(pd.read_csv(PATH + \"betas.csv\"))[:, 1:]\n init = True\n #psi = np.array(pd.read_csv(PATH + \"psis.csv\"))[:, 1:] # + np.random.normal(()) # Remove Index\n #gama = np.array(pd.read_csv(PATH + \"gams.csv\"))[:, 1:]\n\n # init = False\n if init:\n try:\n psi = np.array(pd.read_csv(PATH + \"psis.csv\"))[:, 1:] # + np.random.normal(()) # Remove Index\n gama = np.array(pd.read_csv(PATH + \"gams.csv\"))[:, 1:]\n betaa = np.array(pd.read_csv(PATH + \"betas.csv\"))[:, 1:]\n fa = np.array(pd.read_csv(PATH + \"f.csv\"))\n ga = np.array(pd.read_csv(PATH + \"g.csv\"))\n gh = np.array(pd.read_csv(PATH + \"a.csv\"))[:, 1:] # Remove Index\n bh = np.array(pd.read_csv(PATH + \"b.csv\"))[:, 1:] # Remove Index\n phi = np.array([[-0.5, 0.5]])\n except:\n psi = np.array(pd.read_csv('sims6/' + \"psis.csv\"))[:, 1:] # Remove Index\n gama = np.array(pd.read_csv('sims6/' + \"gams.csv\"))[:, 1:]\n betaa = np.array(pd.read_csv('sims6/' + \"betas.csv\"))[:, 1:]\n fa = np.array(pd.read_csv('sims6/' + \"f.csv\"))\n ga = np.array(pd.read_csv('sims6/' + \"g.csv\"))\n gh = np.array(pd.read_csv('sims6/' + \"a.csv\"))[:, 1:] # Remove Index\n bh = np.array(pd.read_csv('sims6/' + \"b.csv\"))[:, 1:] # Remove Index\n\n tgh = gh.copy()\n tbh = bh.copy()\n for imcmc in range(nmcmc):\n if imcmc % 10 == 0: # print(imcmc); print(bh); print(phi); print(vb)\n print(\"Iter: %i, LML: %.1f\" % (imcmc, lla.sum()))\n print(\"spend time:\", time.time() - start)\n print('abh', abh)\n print('fa', np.concatenate([fa, ga], 1)[:40])\n # print(\"psim\",phi,\"\\n\",betaa)\n # print(\"simga\",np.diag(sigma), \"delta\", np.diag(delta))\n # print(\"Iter: %i, POS: %.1f\" % (imcmc, llb.sum()))\n if imcmc % 100 == 0:\n logging.info(\"Iter: %i\" % imcmc)\n logging.info(\"spend time: %.3f\" % (time.time() - start))\n logging.info(\"lml:%.3f\" % lla.sum())\n logging.info(phi)\n logging.info(abh)\n logging.info(psihmu)\n logging.info(gamhmu)\n\n start = time.time()\n itea = np.zeros((t, 2))\n zphi = zdata.dot(phi)\n futures = []\n\n for i in range(h):\n futures.append(\n executor.submit(rwmh, demand[i], prices[i], 1, lla[glist[i]], gama[glist[i], :], fa[glist[i], :],\n psi[glist[i], :], ga[glist[i], :], kt[glist[i]], r[i], betaa[i, :].transpose(),\n zphi[i, :].transpose(), bh, gh, abh, sigma, delta, vbi, tpa[glist[i]], tpp[glist[i]],\n llb[glist[i]], sdm, gammu[i, :], vgam, gamhmu, psimu[i, :], vpsi, psihmu, i))\n\n for i in range(h):\n # alpha,f,psi,g,ll,ite,kt,betai.T,p,a\n gama[glist[i], :], fa[glist[i], :], psi[glist[i], :], ga[glist[i], :], lla[glist[i]], itea[glist[i], :], kt[\n glist[i]], betaa[i, :], gammu[i, :], psimu[i, :], llb[glist[i]] = futures[i].result()\n\n art += itea\n\n gamab = gama.copy()\n psib = psi.copy()\n for i in range(h):\n gamab[glist[i]] -= gammu[i]\n psib[glist[i]] -= psimu[i]\n\n # gamab = gama - np.vstack( [np.repeat(gammu[i], len(gg), 0) for i,gg in enumerate(glist)])\n # psib = psi - np.vstack( [ [np.repeat(psimu[i], len(gg), 0) for i,gg in enumerate(glist)], np.zeros((t, 1))])\n\n for i in range(ck):\n if i == 0:\n res1 = psib[:, i:(i + 1)] - ga.dot(bh[i:(i + 1), :].T)\n delta[i, i] = ss.invgamma(a=(0.5 + t) / 2, scale=(0.5 + res1.T.dot(res1)) / 2).rvs()\n res2 = gamab[:, i:(i + 1)] - fa.dot(gh[i:(i + 1), :].T)\n sigma[i, i] = ss.invgamma(a=(0.5 + t) / 2, scale=(0.5 + res2.T.dot(res2)) / 2).rvs()\n elif i == 1:\n bh[i, 0], delta[i, i] = bmreg1(psib[:, i:(i + 1)] - ga[:, 1:2], ga[:, 0:1], None,\n delta[i, i])\n gh[i], sigma[i, i] = bmreg1(gamab[:, i:(i + 1)], fa, None, sigma[i, i])\n else:\n # if i != k - 1:\n # bh[i, 0], delta[i, i] = bmreg1(psib[:, i:(i + 1)] - ga[:, 1:2], ga[:, 0:1], None,delta[i, i])\n if i != k - 1:\n bh[i], delta[i, i] = bmreg1(psib[:, i:(i + 1)], ga, None, delta[i, i],)\n gh[i], sigma[i, i] = bmreg1(gamab[:, i:(i + 1)], fa, None, sigma[i, i])\n #bh[:,0] = tbh[:,0].copy()\n\n \"\"\" Fix to 0.01\n for i in range(ck):\n if i == 0:\n res1 = psib[:, i:(i + 1)] - ga.dot(bh[i:(i + 1), :].T)\n delta[i, i] = ss.invgamma(a=(0.5 + t) / 2, scale=(0.5 + res1.T.dot(res1)) / 2).rvs()\n res2 = gamab[:, i:(i + 1)] - fa.dot(gh[i:(i + 1), :].T)\n sigma[i, i] = ss.invgamma(a=(0.5 + t) / 2, scale=(0.5 + res2.T.dot(res2)) / 2).rvs()\n elif i == 1:\n bh[i, 0], delta[i, i] = bmreg1(psib[:, i:(i + 1)] - ga[:, 1:2], ga[:, 0:1], None,\n 0.01)\n gh[i], sigma[i, i] = bmreg1(gamab[:, i:(i + 1)], fa, None, 0.01)\n else:\n if i != k - 1:\n bh[i], delta[i, i] = bmreg(psib[:, i:(i + 1)], ga, None, 0.01)\n gh[i], sigma[i, i] = bmreg(gamab[:, i:(i + 1)], fa, None, 0.01)\n\n \"\"\"\n \"\"\" Fix prior to True Value\n for i in range(ck):\n if i == 0:\n res1 = psib[:, i:(i + 1)] - ga.dot(bh[i:(i + 1), :].T)\n delta[i, i] = ss.invgamma(a=(0.5 + t) / 2, scale=(0.5 + res1.T.dot(res1)) / 2).rvs()\n res2 = gamab[:, i:(i + 1)] - fa.dot(gh[i:(i + 1), :].T)\n sigma[i, i] = ss.invgamma(a=(0.5 + t) / 2, scale=(0.5 + res2.T.dot(res2)) / 2).rvs()\n elif i == 1:\n bh[i, 0], delta[i, i] = bmreg1(psib[:, i:(i + 1)] - ga[:, 1:2], ga[:, 0:1], None,\n delta[i, i], tbh[i, 0].reshape(1,1), np.eye(1) *0.01)\n gh[i], sigma[i, i] = bmreg1(gamab[:, i:(i + 1)], fa, None, sigma[i, i], tgh[i].reshape(1,1), np.eye(1) *0.01 )\n else:\n # if i != k - 1:\n bh[i], delta[i, i] = bmreg(psib[:, i:(i + 1)], ga, None, delta[i, i], tbh[i].reshape(2,1), np.eye(2) * 0.01)\n gh[i], sigma[i, i] = bmreg(gamab[:, i:(i + 1)], fa, None, sigma[i, i],tgh[i].reshape(1,1), np.eye(1) *0.01)\n \"\"\"\n\n\n\n if FIX:\n sigma = np.identity(ck) * VV # * 0.1\n delta = np.identity(ck) * VV # * 0.1\n\n for i in range(1, ck):\n gamhmu[i], vgam[i, i] = bmreg1(gammu[:, i:(i + 1)], np.ones((h, 1)), None, vgam[i, i])\n\n # ************\n #for i in range(ck ):\n for i in range(ck-1):\n psihmu[i], vpsi[i, i] = bmreg1(psimu[:, i:(i + 1)], np.ones((h, 1)), None, vpsi[i, i])\n\n #gamhmu[:] = 0\n #psihmu[:] = 0\n\n # print(np.diag(sigma))\n # print(np.diag(delta))\n if ck == 12:\n sdm = np.zeros((ck * 2, ck * 2))\n sdm[:ck, :ck] = sigma.copy()\n sdm[ck:, ck:] = delta.copy()\n\n abh[0:(ck), 0] = gh.reshape((ck))\n abh[ck:(ck * 2), 1:(1 + 2)] = bh[0:ck, :]\n else:\n sdm = np.zeros((ck * 2 - 1, ck * 2 - 1))\n sdm[:(ck-1), :(ck-1)] = sigma[:-1,:-1].copy()\n sdm[(ck-1):, (ck-1):] = delta.copy()\n\n abh[0:(ck), 0] = gh.reshape((ck))\n abh[ck:, 1:] = bh[0:(ck-1), :]\n\n ## phi & vb\n \n for j in range(2):\n phi[0, j], vb[j, j] = bmreg1(betaa[:, j].reshape((h, 1)), zdata, phi, vb[j,j])#vb[j,j])\n #phi = np.array([[-0.5, 0.5]])\n #vb = np.identity(2) * 0.1\n vbi = np.linalg.inv(vb)\n\n # Update Shock\n\n\n if imcmc < burnin and imcmc % 10 == 0:\n t_a = art[:, 0] / 10\n t_p = art[:, 1] / 10\n tpa = tpa * np.sqrt(1 + (t_a - target_mh))\n tpp = tpp * np.sqrt(1 + (t_p - target_mh))\n art = np.zeros((t, 2))\n # print(tpp,tpa)\n\n if imcmc >= burnin: #Save\n jmcmc = int((imcmc - burnin) / thin)\n lmcmc = jmcmc - int((mcmc / 2))\n\n if lmcmc >= 0:\n psilogm += psi.copy()\n psilogs += psi ** 2\n gamlogm += gama.copy()\n gamlogs += gama ** 2\n\n gamm += gama.copy()\n gams += gama ** 2\n\n fm += fa.copy()\n fs += fa ** 2\n\n ## baseline\n psim += psi.copy()\n psis += psi ** 2\n\n gm += ga\n gs += ga ** 2\n\n betam += betaa.copy()\n betas += betaa ** 2\n\n ktm += kt\n\n gammum += gammu.copy()\n gammus += gammu ** 2\n\n psimum += psimu\n psimus += psimu ** 2\n\n with open(PATH_PSIG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(np.mean(psi, axis=0))\n with open(PATH_GAMG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(np.mean(gama, axis=0))\n\n # with open(PATH_FG, 'a', newline='') as f:\n # writer = csv.writer(f)\n # writer.writerow(fa.reshape(-1))\n\n # with open(PATH_GG, 'a', newline='') as f:\n # writer = csv.writer(f)\n # writer.writerow(ga.reshape(-1))\n with open(PATH_BHG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(bh.reshape(-1))\n with open(PATH_GHG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(gh.reshape(-1))\n with open(PATH_SIGMAG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(np.diag(sigma))\n with open(PATH_DELTAG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(np.diag(delta))\n with open(PATH_VBG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(vb.reshape(-1))\n\n # with open(PATH_LLG, 'a', newline='') as f:\n # writer = csv.writer(f)\n # writer.writerow(lla.reshape(-1))\n with open(PATH_PHIG, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(phi.reshape(-1))\n\n with open(PATH_VGAM, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(np.diag(vgam))\n\n with open(PATH_GAMMU, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(gamhmu)\n\n # with open(PATH_GAMMUH, 'a', newline='') as f:\n # writer = csv.writer(f)\n # writer.writerow(gammu.reshape(-1))\n\n with open(PATH_VPSI, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(np.diag(vpsi))\n\n with open(PATH_PSIMU, 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(psihmu)\n\n # with open(PATH_PSIMUH, 'a', newline='') as f:\n # writer = csv.writer(f)\n # writer.writerow(psimu.reshape(-1))\n\n # with open(PATH_BETAG, 'a', newline='') as f:\n # writer = csv.writer(f)\n # writer.writerow(betaa.reshape(-1))\n\n # with open(PATH_KG, 'a', newline='') as f:\n # writer = csv.writer(f)\n # writer.writerow(kt.reshape(-1))\n\n if jmcmc % 100 == 0:\n np.savez(FN, psim=psim, psis=psis, ktm=ktm, fm=fm, fs=fs, gm=gm, gs=gs,\n gamm=gamm, gams=gams, mcmc=mcmc,\n betam=betam, betas=betas, glist=glist, dems=dems, pris=pris, ind=ind, gammum=gammum,\n gammus=gammus, psimum=psimum, psimus=psimus, fa=fa, ga=ga, kt=kt, psi=psi, gamma=gama,\n betaa=betaa,\n bh=bh, gh=gh)\n\n # print(\"spend time:\", time.time() - start)\n\n np.savez(FN, psim=psim, psis=psis, ktm=ktm, fm=fm, fs=fs, gm=gm, gs=gs,\n gamm=gamm, gams=gams, mcmc=mcmc,\n betam=betam, betas=betas, glist=glist, dems=dems, pris=pris, ind=ind, gammum=gammum, gammus=gammus,\n psimum=psimum, psimus=psimus, psilogm=psilogm, psilogs=psilogs, gamlogm=gamlogm, gamlogs=gamlogs, fa=fa,\n ga=ga)\n '''\n\n res = rmultireg(y=psia[:,0:kp],x=zdata,bbar=tu0,a=tv0,nu=pf0,v=pg0,n=1)\n print(\"B:\",res[\"B\"])\n print(\"Sigma:\", res[\"Sigma\"][0])\n print( xpnd(np.array([1,2,3,4,5,6]) ) )\n print(rwishart(nu=pf0,v=pg0))\n '''\n\n",
"_____no_output_____"
],
[
"# Functions\nimport numpy as np\nfrom math import gamma, sqrt\nfrom scipy.stats import invgamma\n## Common Functions\n\n# Likelihood\n\ndef mdcev(psid, gamd, dem, pri, sigma=1):\n x = np.array(dem)\n p = np.array(pri)\n k = x.shape[0]\n n = 1\n expgam = np.array(np.exp(gamd))\n temp = psid\n temp2 = expgam\n\n v = temp - np.log(x * temp2 + 1) - np.log(p)\n xp = x > 0\n\n vi = np.copy(v)\n xi = np.copy(x)\n mv = xp.sum() ## 0 = col 1 = row\n\n lli = (vi[xp]/sigma).sum() - mv * np.log(np.exp(vi/sigma).sum()) + np.log(gamma(mv)) - np.log(sigma ** (mv-1))\n\n gamj = expgam[xp]\n pij = p[xp]\n xij = xi[xp]\n jacv = 1 / (xij + 1/gamj) ##jacobian\n ll = lli + np.log(jacv).sum() + np.log((pij / jacv).sum())\n # print(\"sumll\",sumll)\n return ll\n\n\n\ndef h2t(x, l):\n res = None\n for h, i in zip(x, l):\n if res is None:\n res = np.tile(h, (i, 1))\n else:\n res = np.concatenate([res, np.tile(h, (i, 1))], axis=0)\n return res\n\n\n# Fast sampling random value from multivariate-normal distribution\ndef mvn(cov):\n L = np.linalg.cholesky(cov)\n z = np.random.standard_normal(len(cov))\n return np.dot(L, z)\n\n# Fast Logpdf from MVN\ndef logpdf(x, mean, cov):\n # `eigh` assumes the matrix is Hermitian.\n vals, vecs = np.linalg.eigh(cov)\n logdet = np.sum(np.log(vals))\n valsinv = np.array([1./v for v in vals])\n # `vecs` is R times D while `vals` is a R-vector where R is the matrix\n # rank. The asterisk performs element-wise multiplication.\n U = vecs * np.sqrt(valsinv)\n rank = len(vals)\n dev = x - mean\n # \"maha\" for \"Mahalanobis distance\".\n maha = np.square(np.dot(dev, U)).sum()\n log2pi = np.log(2 * np.pi)\n return -0.5 * (rank * log2pi + maha + logdet)\n\n#cholesky\ndef chol(x):\n if (x.shape[1] == 1 and x.shape[0] == 1):\n x = np.array(np.sqrt(x)).reshape((1, 1))\n else:\n x = np.linalg.cholesky(x)\n return x\n\n# xpnd function in R\ndef xpnd(x):\n dim = int((-1 + sqrt(1 + 8 * len(x))) / 2)\n new = np.zeros((dim, dim))\n\n inds = np.tril_indices_from(new)\n new[inds] = x\n new[(inds[1], inds[0])] = x\n return new\n\n# Bayes Reg\n\ndef bmreg(y, x, theta=None, Lambda=None, u0=None, v0=None, f0=None, g0=None):\n n = y.shape[0]\n m = y.shape[1]\n k = x.shape[1]\n l = m * k\n if u0 is None: u0 = np.zeros((k, m))\n if v0 is None: v0 = np.eye(k) * 100\n if f0 is None: f0 = k\n if g0 is None: g0 = np.eye(m)\n\n try:\n lambdai = np.linalg.inv(Lambda)\n except:\n lambdai = 1 / Lambda\n\n v0i = np.linalg.inv(v0)\n var = np.linalg.inv(x.transpose().dot(x) * lambdai + v0i)\n mean = var.dot((x.transpose() * lambdai).dot(y) + v0i.dot(u0)).reshape(k)\n s_theta = (mean + mvn(var)).reshape(k,m)\n\n ## generate lambda\n res = y - x.dot(s_theta)\n s_lambda = invgamma(a=1 + n/2, scale=1 + (res.T.dot(res)) / 2).rvs()\n\n return [s_theta.reshape(k), s_lambda]\n\n#\ndef bmreg1(y, x, theta=None, Lambda=None, u0=None, v0=None, e=True):\n n = y.shape[0]\n m = y.shape[1]\n k = x.shape[1]\n l = m * k\n if u0 is None: u0 = np.zeros((k, m))\n if v0 is None: v0 = 100\n lambdai = 1 / Lambda\n\n v0i = 1/ v0\n var = np.linalg.inv(x.T.dot(x) * lambdai + v0i)\n mean = var.dot((x.T * lambdai).dot(y) + u0*v0i).reshape(k)\n\n ## generate lambda\n if e:\n s_theta = (mean + mvn(var)).reshape(k, m)\n res = y - x.dot(s_theta)\n s_lambda = invgamma(a=0.5 + n/2, scale=0.5 + (res.T.dot(res)) / 2).rvs()\n\n return [s_theta.reshape(k), s_lambda]\n else:\n return mean + mvn(var)\n\n# For multiple core\ndef divide_work(h, coren):\n part = []\n rest = h % coren\n o = int((h - rest) / coren)\n temp = 0\n for i in range(coren):\n if i == (coren - 1):\n temp = rest\n part.append(range(i * o, i * o + o + temp))\n return part",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cbb05dca0c3f29cbef82850c2a2aa0c5212e0a50
| 7,159 |
ipynb
|
Jupyter Notebook
|
Google_ColabNB/ML_SelfStudy_RF.ipynb
|
Pradyumna1312/ML_SelfStudy
|
0827d6c23bfbfdca7064536c639be120cd2e76db
|
[
"MIT"
] | null | null | null |
Google_ColabNB/ML_SelfStudy_RF.ipynb
|
Pradyumna1312/ML_SelfStudy
|
0827d6c23bfbfdca7064536c639be120cd2e76db
|
[
"MIT"
] | null | null | null |
Google_ColabNB/ML_SelfStudy_RF.ipynb
|
Pradyumna1312/ML_SelfStudy
|
0827d6c23bfbfdca7064536c639be120cd2e76db
|
[
"MIT"
] | null | null | null | 29.460905 | 238 | 0.507892 |
[
[
[
"<a href=\"https://colab.research.google.com/github/Pradyumna1312/ML_SelfStudy/blob/main/ML_SelfStudy_RF.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"Using the iris flower dataset, create a Random Forest model in Python to categorise the type\nof flower. It includes the sepal length, sepal breadth, petal length, petal width, and floral type.\nSetosa, versicolor, and virginia are the three species or classes. You may find the dataset in the\nScikit-learn package or get it from the UCI Machine Learning Repository.\n\nImplement **Random Forest Algorithm** in Python",
"_____no_output_____"
],
[
"* Import the datasets",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.datasets import load_iris\nimport sklearn.metrics as metrics\n",
"_____no_output_____"
]
],
[
[
"* Print the labels and feature names\n\n",
"_____no_output_____"
]
],
[
[
"iris_data=load_iris()\niris=pd.DataFrame(iris_data.data)\nprint(\"IRIS Target names\", iris_data.target_names)\nprint(\"IRIS Features name\", iris_data.feature_names)\n\n",
"IRIS Target names ['setosa' 'versicolor' 'virginica']\nIRIS Features name ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']\n"
]
],
[
[
"* Separate the columns into dependent and independent variables",
"_____no_output_____"
]
],
[
[
"X=iris.values\nY=iris_data.target",
"_____no_output_____"
]
],
[
[
"* Split those variables into a training and test set (70% and 30% respectively)\n* Train the model on the training set.\n* Perform predictions on the test set.\n* Predict the accuracy of the model\n* Make a prediction for the input sample: sepal length = 4, sepal width = 3, petal length =\n5, petal width = 1.5",
"_____no_output_____"
]
],
[
[
"X_train, X_test, Y_train, Y_test= train_test_split(X,Y,test_size=0.3, random_state=0) # Splitting\nclf=RandomForestClassifier(random_state=0) \nclf.fit(X_train, Y_train) # Training\nY_pred=clf.predict(X_test) # Predicting\nprint(\"Accuracy of the model: \",metrics.accuracy_score(Y_test, Y_pred)) # Accuracy\nprint(\"Prediction through Random Forest =\",clf.predict([[4,3,5,1.5]])) # Prediction for the given \n",
"Accuracy of the model: 0.9777777777777777\nPrediction through Random Forest = [2]\n"
]
],
[
[
"Repeat the above steps by reducing each iris species to 25 samples and comment on the class\nprediction accuracy.",
"_____no_output_____"
]
],
[
[
"x1=X[0:25]\nx2=X[50:75]\nx3=X[100:125]\ny1=Y[0:25]\ny2=Y[50:75]\ny3=Y[100:125]\nX1=[0]*75\nY1=[0]*75\nfor i in range(25):\n X1[i]=x1[i]\n Y1[i]=y1[i]\nfor i in range(25):\n X1[i+25]=x2[i]\n Y1[i+25]=y2[i]\nfor i in range(25):\n X1[i+50]=x3[i]\n Y1[i+50]=y3[i]\nX2=np.array(X1)\nY2=np.array(Y1)\n",
"_____no_output_____"
],
[
"X_train, X_test, Y_train, Y_test= train_test_split(X2,Y2,test_size=0.3, random_state=0) # Splitting\nclf=RandomForestClassifier(random_state=0) \nclf.fit(X_train, Y_train) # Training\nY_pred=clf.predict(X_test) # Predicting\nprint(\"Accuracy of the model: \",metrics.accuracy_score(Y_test, Y_pred)) # Accuracy\nprint(\"Prediction through Random Forest =\",clf.predict([[4,3,5,1.5]])) # Prediction for the given ",
"Accuracy of the model: 0.9565217391304348\nPrediction through Random Forest = [2]\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbb05ff7aacf5c9886d1ff373267a51ae8ed7789
| 58,330 |
ipynb
|
Jupyter Notebook
|
Ch4/11_SpamClassification.ipynb
|
prashant3286/practical-nlp
|
9eefbaad7b07ad97c00698dc0fcce2df84086198
|
[
"MIT"
] | null | null | null |
Ch4/11_SpamClassification.ipynb
|
prashant3286/practical-nlp
|
9eefbaad7b07ad97c00698dc0fcce2df84086198
|
[
"MIT"
] | null | null | null |
Ch4/11_SpamClassification.ipynb
|
prashant3286/practical-nlp
|
9eefbaad7b07ad97c00698dc0fcce2df84086198
|
[
"MIT"
] | 2 |
2021-06-29T13:52:08.000Z
|
2022-02-01T01:44:00.000Z
| 56.962891 | 14,702 | 0.584073 |
[
[
[
"## Spam Classification\nIn this notebook we demonstrate how to classify if an image is SPAM or HAM using the SMS Spam Collection Dataset which can be found [here](https://www.kaggle.com/uciml/sms-spam-collection-dataset#spam.csv)\n",
"_____no_output_____"
]
],
[
[
"!pip install fastai==1.0.60",
"Collecting fastai==1.0.60\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/f5/e4/a7025bf28f303dbda0f862c09a7f957476fa92c9271643b4061a81bb595f/fastai-1.0.60-py3-none-any.whl (237kB)\n\r\u001b[K |█▍ | 10kB 17.3MB/s eta 0:00:01\r\u001b[K |██▊ | 20kB 22.9MB/s eta 0:00:01\r\u001b[K |████▏ | 30kB 11.5MB/s eta 0:00:01\r\u001b[K |█████▌ | 40kB 8.9MB/s eta 0:00:01\r\u001b[K |███████ | 51kB 4.3MB/s eta 0:00:01\r\u001b[K |████████▎ | 61kB 5.0MB/s eta 0:00:01\r\u001b[K |█████████▋ | 71kB 5.6MB/s eta 0:00:01\r\u001b[K |███████████ | 81kB 6.3MB/s eta 0:00:01\r\u001b[K |████████████▍ | 92kB 5.8MB/s eta 0:00:01\r\u001b[K |█████████████▉ | 102kB 5.1MB/s eta 0:00:01\r\u001b[K |███████████████▏ | 112kB 5.1MB/s eta 0:00:01\r\u001b[K |████████████████▋ | 122kB 5.1MB/s eta 0:00:01\r\u001b[K |██████████████████ | 133kB 5.1MB/s eta 0:00:01\r\u001b[K |███████████████████▎ | 143kB 5.1MB/s eta 0:00:01\r\u001b[K |████████████████████▊ | 153kB 5.1MB/s eta 0:00:01\r\u001b[K |██████████████████████ | 163kB 5.1MB/s eta 0:00:01\r\u001b[K |███████████████████████▌ | 174kB 5.1MB/s eta 0:00:01\r\u001b[K |████████████████████████▉ | 184kB 5.1MB/s eta 0:00:01\r\u001b[K |██████████████████████████▎ | 194kB 5.1MB/s eta 0:00:01\r\u001b[K |███████████████████████████▋ | 204kB 5.1MB/s eta 0:00:01\r\u001b[K |█████████████████████████████ | 215kB 5.1MB/s eta 0:00:01\r\u001b[K |██████████████████████████████▍ | 225kB 5.1MB/s eta 0:00:01\r\u001b[K |███████████████████████████████▊| 235kB 5.1MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 245kB 5.1MB/s \n\u001b[?25hRequirement already satisfied: numexpr in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (2.7.3)\nRequirement already satisfied: fastprogress>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (1.0.0)\nRequirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (1.19.5)\nRequirement already satisfied: bottleneck in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (1.3.2)\nRequirement already satisfied: torchvision in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (0.9.1+cu101)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (3.2.2)\nRequirement already satisfied: nvidia-ml-py3 in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (7.352.0)\nRequirement already satisfied: pyyaml in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (3.13)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (2.23.0)\nRequirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (7.1.2)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (1.4.1)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (1.1.5)\nRequirement already satisfied: torch>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (1.8.1+cu101)\nRequirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (4.6.3)\nRequirement already satisfied: spacy>=2.0.18 in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (2.2.4)\nRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from fastai==1.0.60) (20.9)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai==1.0.60) (2.8.1)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai==1.0.60) (2.4.7)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai==1.0.60) (1.3.1)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->fastai==1.0.60) (0.10.0)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->fastai==1.0.60) (1.24.3)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->fastai==1.0.60) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->fastai==1.0.60) (2020.12.5)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->fastai==1.0.60) (3.0.4)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->fastai==1.0.60) (2018.9)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.0.0->fastai==1.0.60) (3.7.4.3)\nRequirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (1.0.0)\nRequirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (7.4.0)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (2.0.5)\nRequirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (4.41.1)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (3.0.5)\nRequirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (0.4.1)\nRequirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (1.0.5)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (1.0.5)\nRequirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (0.8.2)\nRequirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (1.1.3)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from spacy>=2.0.18->fastai==1.0.60) (57.0.0)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.1->matplotlib->fastai==1.0.60) (1.15.0)\nRequirement already satisfied: importlib-metadata>=0.20; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy>=2.0.18->fastai==1.0.60) (4.0.1)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=0.20; python_version < \"3.8\"->catalogue<1.1.0,>=0.0.7->spacy>=2.0.18->fastai==1.0.60) (3.4.1)\nInstalling collected packages: fastai\n Found existing installation: fastai 1.0.61\n Uninstalling fastai-1.0.61:\n Successfully uninstalled fastai-1.0.61\nSuccessfully installed fastai-1.0.60\n"
],
[
"!pip install wget",
"Collecting wget\n Downloading https://files.pythonhosted.org/packages/47/6a/62e288da7bcda82b935ff0c6cfe542970f04e29c756b0e147251b2fb251f/wget-3.2.zip\nBuilding wheels for collected packages: wget\n Building wheel for wget (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for wget: filename=wget-3.2-cp37-none-any.whl size=9675 sha256=d7ab8a16d1666c059ec7f19af012864902772bdfab299f582dfb6f2eff9aa6a1\n Stored in directory: /root/.cache/pip/wheels/40/15/30/7d8f7cea2902b4db79e3fea550d7d7b85ecb27ef992b618f3f\nSuccessfully built wget\nInstalling collected packages: wget\nSuccessfully installed wget-3.2\n"
],
[
"import pandas as pd\nimport wget\nimport os\nfrom zipfile import ZipFile",
"_____no_output_____"
],
[
"try :\n from google.colab import files \n !wget https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip\n !unzip smsspamcollection.zip\n df = pd.read_csv('SMSSpamCollection', sep='\\t', header=None, names=['target', 'text'])\nexcept ModuleNotFoundError :\n url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip'\n path = os.getcwd()+'\\Data'\n wget.download(url,path)\n temp=path+'\\smsspamcollection.zip' \n file = ZipFile(temp) \n file.extractall(path) \n file.close()\n df = pd.read_csv(path + '\\SMSSpamCollection', sep='\\t', header=None, names=['target', 'text'])",
"--2021-06-04 06:42:34-- https://archive.ics.uci.edu/ml/machine-learning-databases/00228/smsspamcollection.zip\nResolving archive.ics.uci.edu (archive.ics.uci.edu)... 128.195.10.252\nConnecting to archive.ics.uci.edu (archive.ics.uci.edu)|128.195.10.252|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 203415 (199K) [application/x-httpd-php]\nSaving to: ‘smsspamcollection.zip’\n\nsmsspamcollection.z 100%[===================>] 198.65K 774KB/s in 0.3s \n\n2021-06-04 06:42:35 (774 KB/s) - ‘smsspamcollection.zip’ saved [203415/203415]\n\nArchive: smsspamcollection.zip\n inflating: SMSSpamCollection \n inflating: readme \n"
],
[
"import fastai\nfrom fastai import *\nfrom fastai.text import *\nimport pandas as pd\nimport numpy as np\nfrom functools import partial\nimport io\nimport os",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"display(df.shape) #Number of rows (instances) and columns in the dataset\ndf[\"target\"].value_counts()/df.shape[0] #Class distribution in the dataset",
"_____no_output_____"
],
[
"from sklearn.model_selection import train_test_split\n\n# split data into training and validation set\ndf_train, df_test = train_test_split(df,stratify = df['target'], test_size = 0.2, random_state = 2020)",
"_____no_output_____"
],
[
"df_train.shape,df_test.shape",
"_____no_output_____"
],
[
"# Language model data \ndata_lm = TextLMDataBunch.from_df(train_df = df_train, valid_df = df_test, path = \"\") \n\n# Classifier model data \ndata_class = TextClasDataBunch.from_df(path = \"\", train_df = df_train, valid_df = df_test, vocab=data_lm.train_ds.vocab, bs=32)",
"_____no_output_____"
],
[
"df_test",
"_____no_output_____"
]
],
[
[
"TextLMDataBunch applies some text preprocessing tasks to help the algorithm perform better. Altough we commonly remove stoopwords and punctuations, here we do not do it. This model can handle semantics, deleting such information might do more harm than good with respect to accuracy\n\nNow lets look at our training data\n",
"_____no_output_____"
]
],
[
[
"data_lm.show_batch()",
"_____no_output_____"
]
],
[
[
"Those 'xxmaj','xxbos', 'xxup' etc are all special tokens for the NN. xxbos stands for begin of sentence, xxmaj indicates that the first letter of the next word is in capital letter, 'xxup' is used to indicate the entire next word is in captital letters. You can view the entire set of tokens [here.](https://docs.fast.ai/text.transform.html)",
"_____no_output_____"
]
],
[
[
"model = language_model_learner(data_lm, arch = AWD_LSTM, pretrained = True, drop_mult=0.5)",
"Downloading https://s3.amazonaws.com/fast-ai-modelzoo/wt103-fwd\n"
]
],
[
[
"We will use a pretrained model. You can learn more about it [here.](https://docs.fast.ai/text.models.html#Language-model-modules)\n\nNow lets test our language model. Its is giving sensible outputs as it is pre trained on wiki corpus. \n",
"_____no_output_____"
]
],
[
[
"for i in range(10):\n print(model.predict(\"The food is\", n_words=15))",
"The food is taken by the British language , which would become the English word \"\nThe food is not a food source . In February 2005 , the Drunk\nThe food is filled in , as Ok Food has been in supply . Following\nThe food is cool even in the night ( 150 seconds the first hour ) , people who\nThe food is drinking from the food market , and drinks you through a good - eating meal\nThe food is a food drink for India 's white Indians . The food is\nThe food is released from its food as a food source to the public . This is\nThe food is still eaten in its original place including one in London , one in\nThe food is usually a food chain or food must be prepared for food , that is ,\nThe food is the world 's only silent work , and the world 's greatest food source .\n"
]
],
[
[
"We will now need to fine tune our model for our particular task. <br>",
"_____no_output_____"
]
],
[
[
"model.lr_find() # you can find more details about this at https://docs.fast.ai/basic_train.html\nmodel.recorder.plot(suggestion=True)",
"_____no_output_____"
],
[
"model.fit_one_cycle(4, max_lr= 5e-02)#you can freeze and unfreeze different layers and by doing so we can have different lr for each layer\n#for freezing and unfreezing code you can refer https://docs.fast.ai/text.html\n",
"_____no_output_____"
],
[
"for i in range(10):\n print(model.predict(\"The food is\", n_words=15))",
"The food is eyes into the paper by an bath water cup of coffee animation plus a coffee\nThe food is not a word . Its not wylie , but it is used .\nThe food is true timing . Since it means terms and conditions are true , the world\nThe food is going to search evening - home 4 you ? xxbos This day xxbos\nThe food is waiting for you south calling ! Lots of unlimited n cost 10p from a\nThe food is very simple . The law are a simple pay . Life is not\nThe food is done ! The food are pleased to miss the latest mobiles . You\nThe food is very simple . Aight it is a fantastic day . So xxbos\nThe food is cooking times per night flip the receipts can be used . Last sign is\nThe food is high quickly that give us all the same ice needs . Ice cream phones\n"
]
],
[
[
"Note that now the model is predicting ':)' and other such characters which can generally be seen in SMS messages. With further more fine tuning and running it for more cyles you can get the model to predict more characters which are found in SMS messages.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
cbb0608a7b0ac2e71c1dd75d6eb7fda654ffad34
| 3,066 |
ipynb
|
Jupyter Notebook
|
homework3.ipynb
|
zeynepsakli/GlobalAIHub_IntroToPython
|
812835e00a8ecd865af12187aa0b5bbc7cfcb64b
|
[
"MIT"
] | null | null | null |
homework3.ipynb
|
zeynepsakli/GlobalAIHub_IntroToPython
|
812835e00a8ecd865af12187aa0b5bbc7cfcb64b
|
[
"MIT"
] | null | null | null |
homework3.ipynb
|
zeynepsakli/GlobalAIHub_IntroToPython
|
812835e00a8ecd865af12187aa0b5bbc7cfcb64b
|
[
"MIT"
] | null | null | null | 24.725806 | 128 | 0.510437 |
[
[
[
"#### user login program #######\nusername=\"Zeynep\"\nuserpassword=\"1234\"\nname=str(input(\"please give your name\"))\npassword=input(\"please give your password\")\n\nif (username!=name and userpassword==password):\n print(\"wrong user name ! try again\")\nelif (username==name and userpassword!=password):\n print(\"wrong user password ! try again\")\nelif (username!=name and userpassword!=password):\n print(\"wrong user name and user password ! try again\")\nelse:\n print(\"good job :)\")\n \n",
"please give your nameZeynep\nplease give your password1234\ngood job :)\n"
],
[
"###Second Part",
"{'python': 1, 'course': 2}\n"
],
[
"employees = {\n \"employee1\" : {\n \"namex\": \"Hannah\",\n \"passwordx\": \"1234\"\n }}\nname=str(input(\"please give your name\"))\npassword=input(\"please give your password\")\n\nif (employees.get(\"employee1\").get(\"namex\")!=name and employees.get(\"employee1\").get(\"passwordx\")==password):\n print(\"wrong user name ! try again\")\nelif (employees.get(\"employee1\").get(\"namex\")==name and employees.get(\"employee1\").get(\"passwordx\")!=password):\n print(\"wrong user password ! try again\")\nelif (employees.get(\"employee1\").get(\"namex\")!=name and employees.get(\"employee1\").get(\"passwordx\")!=password):\n print(\"wrong user name and user password ! try again\")\nelse:\n print(\"good job :)\")\n",
"please give your nameHannah\nplease give your password1234\ngood job :)\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
cbb0647741e6c86dc329f5772420428660ebbccf
| 221,380 |
ipynb
|
Jupyter Notebook
|
TugasPemrograman_Proyek3B_Kelompok2_MATH1042.ipynb
|
yosiafarianto78/Tugas_pemrograman_proyek2b
|
7c6c4d1ba1a07d2181e49a6e881a068ea03af35a
|
[
"MIT"
] | null | null | null |
TugasPemrograman_Proyek3B_Kelompok2_MATH1042.ipynb
|
yosiafarianto78/Tugas_pemrograman_proyek2b
|
7c6c4d1ba1a07d2181e49a6e881a068ea03af35a
|
[
"MIT"
] | null | null | null |
TugasPemrograman_Proyek3B_Kelompok2_MATH1042.ipynb
|
yosiafarianto78/Tugas_pemrograman_proyek2b
|
7c6c4d1ba1a07d2181e49a6e881a068ea03af35a
|
[
"MIT"
] | null | null | null | 233.031579 | 34,274 | 0.870413 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbb06c523ea3ab79ff2e173aa1ac7b27b4764872
| 30,485 |
ipynb
|
Jupyter Notebook
|
using_invert_etas.ipynb
|
amandasyamsul/SLIM
|
1a6af8b24cc926e8cc13a716cd52985eee8180c1
|
[
"MIT"
] | null | null | null |
using_invert_etas.ipynb
|
amandasyamsul/SLIM
|
1a6af8b24cc926e8cc13a716cd52985eee8180c1
|
[
"MIT"
] | null | null | null |
using_invert_etas.ipynb
|
amandasyamsul/SLIM
|
1a6af8b24cc926e8cc13a716cd52985eee8180c1
|
[
"MIT"
] | null | null | null | 32.956757 | 282 | 0.500246 |
[
[
[
"import numpy as np\nimport datetime as dt\n\nfrom inversion import invert_etas_params\n\nif __name__ == '__main__':\n theta_0 = {\n 'log10_mu': -5.8,\n 'log10_k0': -2.6,\n 'a': 1.8,\n 'log10_c': -2.5,\n 'omega': -0.02,\n 'log10_tau': 3.5,\n 'log10_d': -0.85,\n 'gamma': 1.3,\n 'rho': 0.66\n }\n\n inversion_meta = {\n \"fn_catalog\": \"19970101-20220116_mini.csv\",\n \"data_path\": \"\",\n \"auxiliary_start\": dt.datetime(1997, 1, 1),\n \"timewindow_start\": dt.datetime(2002, 4, 16),\n \"timewindow_end\": dt.datetime(2022, 1, 16),\n \"theta_0\": theta_0,\n \"mc\": 5.4,\n \"delta_m\": 0.1,\n \"coppersmith_multiplier\": 100,\n }\n\n parameters = invert_etas_params(\n inversion_meta,\n globe=True\n )",
"PREPARING METADATA...\n\n using catalog: 19970101-20220116_mini.csv\n Data will be stored in /home/amand4/notebooks/surface-load-quakes/etas\n Time Window: 1997-01-01 00:00:00 (aux) - 2002-04-16 00:00:00 (start) - 2022-01-16 00:00:00 (end)\n m_ref is 5.4 and delta_m is 0.1\n coppersmith multiplier is 100\n Region has 511201962.31054497 square km\n\n\nINITIALIZING\n\n reading data..\n\n 15766 out of 15766 events lie within target region.\n 15764 events are within time window\n\n\n calculating distances..\n\n beta is 2.3629393184057337 \n\n number of sources: 15764\n number of targets: 12573\n\n took 0:01:41.371130 to prepare the data\n\n preparing source and target events..\n\n beta of primary catalog is 2.3629393184057337\n using input initial values for theta\n\n\n\nSTART INVERSION!\n\niteration 0\n\n expectation\n\n calculating gij\n calculating Pij\n"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
cbb06f7d6c9085f00e27d1693406c1e788b5cc1e
| 16,857 |
ipynb
|
Jupyter Notebook
|
01_Getting_&_Knowing_Your_Data/Chipotle/My_Exercises.ipynb
|
edenni/pandas_exercises
|
68f0ee92e9c62cf0c4b97b0423fe7b8b93cfc90e
|
[
"BSD-3-Clause"
] | null | null | null |
01_Getting_&_Knowing_Your_Data/Chipotle/My_Exercises.ipynb
|
edenni/pandas_exercises
|
68f0ee92e9c62cf0c4b97b0423fe7b8b93cfc90e
|
[
"BSD-3-Clause"
] | null | null | null |
01_Getting_&_Knowing_Your_Data/Chipotle/My_Exercises.ipynb
|
edenni/pandas_exercises
|
68f0ee92e9c62cf0c4b97b0423fe7b8b93cfc90e
|
[
"BSD-3-Clause"
] | null | null | null | 21.528736 | 135 | 0.425699 |
[
[
[
"# Ex2 - Getting and Knowing your Data",
"_____no_output_____"
],
[
"This time we are going to pull data directly from the internet.\nSpecial thanks to: https://github.com/justmarkham for sharing the dataset and materials.\n\n### Step 1. Import the necessary libraries",
"_____no_output_____"
]
],
[
[
"import pandas as pd",
"_____no_output_____"
]
],
[
[
"### Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv). ",
"_____no_output_____"
],
[
"### Step 3. Assign it to a variable called chipo.",
"_____no_output_____"
]
],
[
[
"chipo = pd.read_csv('https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv', sep='\\t')",
"_____no_output_____"
]
],
[
[
"### Step 4. See the first 10 entries",
"_____no_output_____"
]
],
[
[
"chipo.head(10)",
"_____no_output_____"
]
],
[
[
"### Step 5. What is the number of observations in the dataset?",
"_____no_output_____"
]
],
[
[
"# Solution 1\n\nchipo.shape[0]",
"_____no_output_____"
],
[
"# Solution 2\n\n",
"_____no_output_____"
]
],
[
[
"### Step 6. What is the number of columns in the dataset?",
"_____no_output_____"
]
],
[
[
"chipo.shape[1]",
"_____no_output_____"
]
],
[
[
"### Step 7. Print the name of all the columns.",
"_____no_output_____"
]
],
[
[
"chipo.columns",
"_____no_output_____"
]
],
[
[
"### Step 8. How is the dataset indexed?",
"_____no_output_____"
]
],
[
[
"chipo.index",
"_____no_output_____"
]
],
[
[
"### Step 9. Which was the most-ordered item? ",
"_____no_output_____"
]
],
[
[
"chipo.groupby('item_name').sum().sort_values('quantity', ascending=False).iloc[0]",
"_____no_output_____"
]
],
[
[
"### Step 10. For the most-ordered item, how many items were ordered?",
"_____no_output_____"
],
[
"### Step 11. What was the most ordered item in the choice_description column?",
"_____no_output_____"
]
],
[
[
"chipo.groupby(['choice_description']).sum().sort_values('quantity', ascending=False).iloc[0]",
"_____no_output_____"
]
],
[
[
"### Step 12. How many items were orderd in total?",
"_____no_output_____"
]
],
[
[
"chipo['quantity'].sum()",
"_____no_output_____"
]
],
[
[
"### Step 13. Turn the item price into a float",
"_____no_output_____"
],
[
"#### Step 13.a. Check the item price type",
"_____no_output_____"
]
],
[
[
"chipo['item_price'].head(5)",
"_____no_output_____"
]
],
[
[
"#### Step 13.b. Create a lambda function and change the type of item price",
"_____no_output_____"
]
],
[
[
"chipo['item_price'] = chipo['item_price'].transform(lambda x: float(x[1:]))",
"_____no_output_____"
]
],
[
[
"#### Step 13.c. Check the item price type",
"_____no_output_____"
]
],
[
[
"chipo.item_price.dtype",
"_____no_output_____"
]
],
[
[
"### Step 14. How much was the revenue for the period in the dataset?",
"_____no_output_____"
]
],
[
[
"revenue = (chipo.quantity * chipo.item_price).sum()\nrevenue",
"_____no_output_____"
]
],
[
[
"### Step 15. How many orders were made in the period?",
"_____no_output_____"
]
],
[
[
"n_order = len(chipo.order_id.unique())\nn_order",
"_____no_output_____"
],
[
"chipo.order_id.value_counts().count()",
"_____no_output_____"
]
],
[
[
"### Step 16. What is the average revenue amount per order?",
"_____no_output_____"
]
],
[
[
"# Solution 1\n\nrevenue / n_order",
"_____no_output_____"
],
[
"# Solution 2\n\n",
"_____no_output_____"
]
],
[
[
"### Step 17. How many different items are sold?",
"_____no_output_____"
]
],
[
[
"len(chipo.item_name.unique())",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb07db1e9091d3c97deb444605a7b4a7d8c8ec5
| 18,128 |
ipynb
|
Jupyter Notebook
|
temp_analysis_bonus_1_starter.ipynb
|
Zone6Mars/sqlalchemy-challenge
|
a2ba1d97d7c2fa985604e6d4ac722a6cf43ced19
|
[
"ADSL"
] | null | null | null |
temp_analysis_bonus_1_starter.ipynb
|
Zone6Mars/sqlalchemy-challenge
|
a2ba1d97d7c2fa985604e6d4ac722a6cf43ced19
|
[
"ADSL"
] | null | null | null |
temp_analysis_bonus_1_starter.ipynb
|
Zone6Mars/sqlalchemy-challenge
|
a2ba1d97d7c2fa985604e6d4ac722a6cf43ced19
|
[
"ADSL"
] | null | null | null | 26.008608 | 178 | 0.384488 |
[
[
[
"# Bonus: Temperature Analysis I",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nfrom datetime import datetime as dt",
"_____no_output_____"
],
[
"# \"tobs\" is \"temperature observations\"\ndf = pd.read_csv('Resources/hawaii_measurements.csv')\ndf.head()",
"_____no_output_____"
],
[
"# Convert the date column format from string to datetime\n#Converting the date column format from string to datetime\n\ndf.date = pd.to_datetime(df.date, infer_datetime_format=True)",
"_____no_output_____"
],
[
"# Set the date column as the DataFrame index\\\ndf = df.set_index(df['date'])\ndf.head()",
"_____no_output_____"
],
[
"# Drop the date column\ndf = df.drop(columns='date')\ndf.head()",
"_____no_output_____"
]
],
[
[
"### Compare June and December data across all years ",
"_____no_output_____"
]
],
[
[
"from scipy import stats",
"_____no_output_____"
],
[
"# Filter data for desired months (June)\nHI_June = df[df.index.month == 6]\nHI_June.head()",
"_____no_output_____"
],
[
"# Filter data for desired months (Decemeber)\nHI_December = df[df.index.month == 12]\nHI_December.head()",
"_____no_output_____"
],
[
"# Identify the average temperature for June\nHI_June.mean()",
"_____no_output_____"
],
[
"# Identify the average temperature for December\nHI_December.mean()",
"_____no_output_____"
],
[
"# Create collections of temperature data\nHI_June_TempsObs = HI_June.tobs\nHI_June_TempsObs",
"_____no_output_____"
],
[
"# Create collections of temperature data\nHI_December_TempsObs = HI_December.tobs\nHI_December_TempsObs",
"_____no_output_____"
],
[
"# Run paired t-test\nstats.ttest_ind(HI_June_TempsObs,HI_December_TempsObs)",
"_____no_output_____"
]
],
[
[
"### Analysis",
"_____no_output_____"
]
],
[
[
"#The mean temperature difference between the June and December is approximately 4 degrees Fahrenheit. \n# This is slightly a difference. The t-test has a low p-value that indicates it is a 39% change that probability that the results from an experiment happened by chance. \n# Also means that there's a 61% chance that Hawaii has 71 to 75 degree weather year round.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb0867d303f40be0a743c438aa6cc2078caffeb
| 12,926 |
ipynb
|
Jupyter Notebook
|
python/notebooks/Untitled.ipynb
|
tjhunter/karps
|
7c74c3bf5b566264d6fed6e17fb1716216467a50
|
[
"Apache-2.0"
] | 5 |
2017-10-25T10:53:47.000Z
|
2019-01-12T19:32:36.000Z
|
python/notebooks/Untitled.ipynb
|
tjhunter/karps
|
7c74c3bf5b566264d6fed6e17fb1716216467a50
|
[
"Apache-2.0"
] | 15 |
2017-06-22T20:53:50.000Z
|
2017-10-22T00:47:00.000Z
|
python/notebooks/Untitled.ipynb
|
tjhunter/karps
|
7c74c3bf5b566264d6fed6e17fb1716216467a50
|
[
"Apache-2.0"
] | 1 |
2018-08-23T04:25:57.000Z
|
2018-08-23T04:25:57.000Z
| 45.836879 | 1,381 | 0.629893 |
[
[
[
"import logging\nimport importlib\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nimportlib.reload(logging)\nlogging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%I:%M:%S')\n",
"_____no_output_____"
],
[
"def f(x): return x\nf.__qualname__",
"_____no_output_____"
],
[
"import grpc\n\nfrom karps.proto import interface_pb2_grpc\nfrom karps.proto import interface_pb2\nfrom karps.proto.computation_pb2 import SessionId",
"_____no_output_____"
],
[
"import karps as ks\nimport karps.functions as f\nfrom karps.display import show_phase\n",
"_____no_output_____"
],
[
"df = ks.dataframe([(1,)], schema=\"ee\")\nprint(df)\nct = f.collect(df)\nprint(ct)\n\nprint(df.ee)\n",
"/[email protected]:{ee:int}\n/collect_list_1!org.spark.StructuredReduce:[{ee:int}]\nee:int<-/[email protected]:{ee:int}\n"
],
[
"f.max(df.ee)",
"_____no_output_____"
],
[
"ct = f.collect(df)\nct",
"_____no_output_____"
],
[
"s = ks.session(\"test\")",
"_____no_output_____"
],
[
"comp = s.compute(ct)",
"_____no_output_____"
],
[
"\ndf.ee + df.ee\n",
"_____no_output_____"
],
[
"show_phase(comp, \"initial\")",
"_____no_output_____"
],
[
"show_phase(comp, \"final\")",
"_____no_output_____"
],
[
"comp.values()",
"_____no_output_____"
],
[
"f.inv(df.ee)",
"_____no_output_____"
],
[
"id(1)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb0a04621c1d37276a38cbb6b2bc21b6e634baa
| 20,242 |
ipynb
|
Jupyter Notebook
|
notebooks/gridworldnav-user-study.ipynb
|
rddy/ASE
|
c804c490e27c2b9c4bff79d01375c496223d21ea
|
[
"MIT"
] | 7 |
2020-08-10T00:41:29.000Z
|
2022-01-04T23:27:31.000Z
|
notebooks/gridworldnav-user-study.ipynb
|
rddy/ASE
|
c804c490e27c2b9c4bff79d01375c496223d21ea
|
[
"MIT"
] | null | null | null |
notebooks/gridworldnav-user-study.ipynb
|
rddy/ASE
|
c804c490e27c2b9c4bff79d01375c496223d21ea
|
[
"MIT"
] | null | null | null | 34.720412 | 322 | 0.565112 |
[
[
[
"%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
],
[
"from __future__ import division\n\nimport pickle\nimport os\nfrom collections import defaultdict\nimport types\n\nimport numpy as np\nimport pandas as pd\nfrom statsmodels.stats.anova import AnovaRM\nimport statsmodels.api as sm\n\nfrom sensei.envs import GridWorldNavEnv, GuideEnv\nfrom sensei import utils\nfrom sensei import ase\nfrom sensei.gw_user_study import HumanGridWorldUser\nfrom sensei.guide_models import GridWorldGuide",
"_____no_output_____"
],
[
"from matplotlib import pyplot as plt\nimport matplotlib as mpl\n%matplotlib inline\n\nmpl.rcParams.update({'font.size': 18})",
"_____no_output_____"
],
[
"data_dir = utils.gw_human_data_dir\nfig_dir = os.path.join(data_dir, 'figures')\nif not os.path.exists(fig_dir):\n os.makedirs(fig_dir)\nuser_ids = [str(i) for i in range(12) if str(i) in os.listdir(data_dir)]",
"_____no_output_____"
],
[
"baseline_guide_evals_of_user = {}\ntrain_logs_of_user = {}\nfor user_id in user_ids:\n user_data_dir = os.path.join(data_dir, user_id)\n \n baselines_eval_path = os.path.join(user_data_dir, 'guide_evals.pkl')\n with open(baselines_eval_path, 'rb') as f:\n baseline_guide_evals = pickle.load(f)\n \n train_logs_path = os.path.join(user_data_dir, 'train_logs.pkl')\n with open(train_logs_path, 'rb') as f:\n train_logs = pickle.load(f)\n \n baseline_guide_evals_of_user[user_id] = baseline_guide_evals\n train_logs_of_user[user_data_dir] = train_logs",
"_____no_output_____"
],
[
"perf_of_guide = {}\nrollouts_of_guide = defaultdict(list)\nfor user_id, baseline_guide_evals in baseline_guide_evals_of_user.items():\n for guide_name, guide_eval in baseline_guide_evals.items():\n rollouts = guide_eval['rollouts']\n rollouts_of_guide[guide_name].extend(rollouts)\n\nfor guide_name, guide_eval_rollouts in rollouts_of_guide.items():\n perf = utils.compute_perf_metrics(guide_eval_rollouts, None, max_ep_len=25)\n perf_of_guide[guide_name] = perf",
"_____no_output_____"
],
[
"plt.xlabel('Time')\nplt.ylabel('Distance to Goal')\nplt.title('2D Navigation')\nfor guide_name in ['iden', 'naive', 'learned']:\n perf = perf_of_guide[guide_name]\n tilts = perf['dist_to_goal_t']\n tilt_stderrs = perf['dist_to_goal_stderr_t']\n label = utils.label_of_guide[guide_name]\n color = utils.color_of_guide[guide_name]\n xs = np.arange(0, len(tilts), 1)\n ys = np.array(tilts)\n yerrs = np.array(tilt_stderrs)\n y_mins = ys - yerrs\n y_maxs = ys + yerrs\n plt.fill_between(\n xs,\n y_mins,\n y_maxs,\n where=y_maxs >= y_mins,\n interpolate=False,\n label=label,\n color=color,\n alpha=0.5)\n plt.plot(xs, ys, color=color)\nplt.legend(loc='upper right', prop={'size': 18})\nplt.savefig(os.path.join(fig_dir, 'gw-user-study.pdf'), bbox_inches='tight')\nplt.show()",
"_____no_output_____"
],
[
"n_users = len(baseline_guide_evals_of_user)\ndepvar = 'response'\nsubject = 'user_id'\nwithin = 'condition'\nmetrics = ['rollout_len']\nfor metric in metrics:\n rows = []\n for user_id, baseline_guide_evals in baseline_guide_evals_of_user.items():\n rows.append({subject: user_id, depvar: baseline_guide_evals['iden']['perf'][metric], within: 'unassisted'})\n rows.append({subject: user_id, depvar: baseline_guide_evals['learned']['perf'][metric], within: 'assisted'})\n data = pd.DataFrame(rows)\n aovrm = AnovaRM(data=data, depvar=depvar, subject=subject, within=[within])\n res = aovrm.fit()\n print(res)",
"_____no_output_____"
],
[
"questions = [\n 'I was often able to infer my current position and orientation',\n 'I was often able to move toward the goal',\n 'I often found the guidance helpful',\n 'I relied primarily on the most recent guidance to infer my current position and orientation',\n 'I relied primarily on past guidance and recent movements to infer my current position and orientation',\n 'I often forgot which position and orientation I believed was in'\n]",
"_____no_output_____"
],
[
"responses = [\n [[6, 5, 6, 4, 7, 5], [6, 6, 6, 7, 4, 7], [7, 7, 7, 7, 3, 1]],\n [[7, 6, 7, 7, 3, 2], [5, 5, 4, 3, 6, 5], [7, 7, 7, 7, 3, 1]],\n [[5, 6, 6, 6, 4, 4], [6, 6, 6, 6, 5, 3], [7, 7, 7, 6, 5, 1]],\n [[6, 6, 6, 6, 2, 4], [6, 6, 6, 6, 3, 4], [7, 7, 7, 7, 2, 1]],\n [[2, 3, 6, 5, 6, 5], [6, 6, 6, 5, 6, 2], [7, 7, 7, 5, 7, 1]],\n [[5, 5, 7, 6, 6, 3], [6, 6, 6, 6, 6, 1], [7, 7, 7, 7, 6, 1]],\n [[6, 6, 6, 1, 6, 1], [6, 6, 6, 1, 6, 2], [7, 7, 7, 1, 6, 1]],\n [[6, 6, 6, 2, 6, 2], [5, 6, 5, 4, 6, 3], [7, 7, 7, 7, 5, 2]],\n [[5, 4, 4, 3, 6, 3], [4, 4, 3, 2, 6, 3], [6, 6, 7, 4, 6, 2]],\n [[6, 7, 6, 5, 5, 5], [6, 7, 6, 5, 5, 4], [7, 7, 6, 6, 4, 4]],\n [[7, 7, 7, 4, 4, 1], [7, 4, 7, 6, 6, 2], [7, 7, 7, 7, 2, 1]],\n [[5, 5, 5, 4, 4, 3], [5, 5, 5, 4, 5, 3], [6, 6, 7, 6, 3, 1]],\n]",
"_____no_output_____"
],
[
"n_users = len(responses)\nn_phases = len(responses[0])\nresponses_of_q = [[[np.nan for _ in range(n_users)] for _ in questions] for _ in range(n_phases)]\nfor phase_idx in range(n_phases):\n for user_idx, user_responses in enumerate(responses):\n for q_idx, response in enumerate(responses[user_idx][phase_idx]):\n responses_of_q[phase_idx][q_idx][user_idx] = response",
"_____no_output_____"
],
[
"# one-way repeated measures ANOVA with the presence of assistance as a factor influencing responses\nn_users = len(responses)\ndepvar = 'response'\nsubject = 'user_id'\nwithin = 'condition'\nassistant_labels = [\n '\\\\multirow{4}{*}{\\\\rotatebox[origin=c]{90}{Naive ASE}}',\n '\\\\multirow{4}{*}{\\\\rotatebox[origin=c]{90}{ASE}}'\n]\nfor assisted_phase in [1, 2]:\n for i, q in enumerate(questions):\n if i == 0:\n assistant_label = assistant_labels[assisted_phase-1]\n else:\n assistant_label = ''\n rows = []\n for user_id in user_ids:\n user_id = int(user_id)\n rows.append({subject: user_id, depvar: responses_of_q[0][i][user_id], within: 'unassisted'})\n rows.append({subject: user_id, depvar: responses_of_q[assisted_phase][i][user_id], within: 'assisted'})\n data = pd.DataFrame(rows)\n aovrm = AnovaRM(data=data, depvar=depvar, subject=subject, within=[within])\n res = aovrm.fit()\n p = res.anova_table['Pr > F'].values[0]\n print('%s & %s & $%s%s%s$ & %0.2f & %s%0.2f%s \\\\\\\\' % (assistant_label, q, '\\\\mathbf{' if p < 0.05 else '', utils.discretize_p_value(p), '}' if p < 0.05 else '', np.nanmean(responses_of_q[0][i]), '\\\\textbf{' if p < 0.05 else '', np.nanmean(responses_of_q[assisted_phase][i]), '}' if p < 0.05 else ''))\n if assisted_phase == 1:\n print('\\midrule')",
"_____no_output_____"
],
[
"guide_names = ['prac', 'iden', 'learned']\nn_rollouts_of_guide = {\n 'prac': 3,\n 'iden': 5,\n 'learned': 5\n}\nperfs_of_guide = {guide_name: [[] for _ in range(n_rollouts)] for guide_name, n_rollouts in n_rollouts_of_guide.items()}\nfor guide_name, n_rollouts in n_rollouts_of_guide.items():\n for i in range(n_rollouts):\n for baseline_guide_evals in baseline_guide_evals_of_user.values():\n rollouts = [baseline_guide_evals[guide_name]['rollouts'][i]]\n if guide_name == 'iden':\n rollouts.append(baseline_guide_evals['naive']['rollouts'][i])\n for rollout in rollouts:\n perf = utils.compute_perf_metrics(rollouts, None, max_ep_len=25)\n perfs_of_guide[guide_name][i].append(perf)",
"_____no_output_____"
],
[
"metric = 'rollout_len'\nplt.xlabel('Episode Number')\nplt.ylabel(utils.label_of_perf_met[metric])\nplt.title('2D Navigation')\nguide_names = ['iden', 'learned']\nfor i, guide_name in enumerate(guide_names):\n perfs = perfs_of_guide[guide_name]\n all_perfs = [user_perf[metric] for perf in perfs for user_perf in perf]\n if guide_name == 'learned':\n label = 'ASE (Our Method)'\n elif guide_name == 'iden':\n label = 'Unassisted + Naive ASE (counterbalanced)'\n else:\n label = utils.label_of_guide[guide_name]\n color = utils.color_of_guide[guide_name]\n shift = sum(len(perfs_of_guide[guide_names[j]]) for j in range(i))\n n_users = len(perfs[0])\n xs = np.tile(np.arange(1 + shift, 1 + len(perfs) + shift, 1), n_users)\n ys = np.array(all_perfs)\n plt.scatter(xs, ys, color=color, alpha=0.25)\n \n results = sm.OLS(ys,sm.add_constant(xs - shift - 1)).fit()\n X_plot = np.linspace(1, len(perfs), 100)\n plt.plot(X_plot + shift, X_plot*results.params[1] + results.params[0], label=label, color=color, linestyle='--', linewidth=2)\n \n xs = np.arange(1 + shift, 1 + len(perfs) + shift, 1)\n ys = np.array([np.mean([user_perf[metric] for user_perf in perf]) for perf in perfs])\n stderr = lambda x: np.std(x) / np.sqrt(len(x))\n yerrs = np.array([stderr([user_perf[metric] for user_perf in perf]) for perf in perfs])\n \nplt.legend(loc='upper left', prop={'size': 12}, bbox_to_anchor=(0.025, -0.2))\nplt.savefig(os.path.join(fig_dir, 'gw-user-study-learning-effect.pdf'), bbox_inches='tight')\nplt.show()",
"_____no_output_____"
],
[
"gw_size = 5\nn_goals = gw_size**2\nn_states = 4*gw_size**2\nn_objes_per_set = gw_size**2\nn_obj_instances_of_set = [1, 2, 1]\nn_obj_sets = len(n_obj_instances_of_set)\nn_objes = n_objes_per_set*n_obj_sets\nn_obses = n_objes + n_obj_sets\nground_truth = np.zeros((n_obses, n_states))\nticks = np.arange(0, gw_size, 1)\nposes = utils.enumerate_gw_poses(ticks, ticks)\nposes_of_obs = [[] for _ in range(n_obses)]\nfor obj_set in range(n_obj_sets):\n for obj in range(n_objes_per_set):\n obs = obj_set*(n_objes_per_set+1)+obj\n obj_poses = [poses[obj*4]]\n for i in range(1, n_obj_instances_of_set[obj_set]):\n obj_poses.append(poses[np.random.choice(list(range(n_objes_per_set)))*4])\n poses_of_obs[obs] = obj_poses\n for obj_pos in obj_poses:\n for state, user_pos in enumerate(poses):\n conds = []\n conds.append(obj_pos[0] == user_pos[0] and obj_pos[1] == user_pos[1] + 1 and user_pos[2] == 2)\n conds.append(obj_pos[0] == user_pos[0] and obj_pos[1] == user_pos[1] - 1 and user_pos[2] == 0)\n conds.append(obj_pos[1] == user_pos[1] and obj_pos[0] == user_pos[0] + 1 and user_pos[2] == 3)\n conds.append(obj_pos[1] == user_pos[1] and obj_pos[0] == user_pos[0] - 1 and user_pos[2] == 1)\n if any(conds):\n ground_truth[obs, state] = 1\n\nfor obj_set in range(n_obj_sets):\n obs = obj_set*(n_objes_per_set+1)+n_objes_per_set\n for state, user_pos in enumerate(poses):\n conds = []\n conds.append(user_pos[0] == 0 and user_pos[2] == 1)\n conds.append(user_pos[0] == gw_size - 1 and user_pos[2] == 3)\n conds.append(user_pos[1] == 0 and user_pos[2] == 0)\n conds.append(user_pos[1] == gw_size - 1 and user_pos[2] == 2)\n if any(conds):\n ground_truth[obs, state] = 1\n\nground_truth = utils.smooth_matrix(ground_truth, n_states, eps=1e-6)\nground_truth_obs_model = np.log(ground_truth)\n\nmax_ep_len = gw_size**2\nenv = GridWorldNavEnv(\n gw_size=gw_size,\n n_goals=n_goals,\n max_ep_len=max_ep_len,\n ground_truth_obs_model=ground_truth_obs_model\n)",
"_____no_output_____"
],
[
"env.n_objes_per_set = n_objes_per_set\nenv.n_obj_sets = n_obj_sets\ndef is_obs_informative(self, obs):\n n_uninf_obses = self.n_obses // self.n_obj_sets\n return obs >= n_uninf_obses\nenv.is_obs_informative = types.MethodType(is_obs_informative, env)\n\nenv.practice = False\ndef set_practice_mode(self, mode):\n self.practice = mode\nenv.set_practice_mode = types.MethodType(set_practice_mode, env)",
"_____no_output_____"
],
[
"sess = utils.make_tf_session(gpu_mode=False)",
"_____no_output_____"
],
[
"masked_obses = np.arange(0, env.n_obses // env.n_obj_sets, 1)\ninternal = np.exp(env.ground_truth_obs_model)\nobs_weights = np.ones(env.n_obses)\nfor obs in masked_obses:\n obs_weights[obs] = 1e-6\ninternal = utils.smooth_matrix(internal, env.n_obses, eps=(1-obs_weights[:, np.newaxis]))\ninternal = np.log(internal)\ninternal_obs_model = internal\n\nuser_init_belief_conf = 1e-9\n\nuser_model = HumanGridWorldUser(\n env,\n internal_obs_model,\n env.make_dynamics_model(eps=1e-6),\n q_func=env.Q,\n init_belief_conf=user_init_belief_conf\n)\nguide_env = GuideEnv(env, user_model, n_obs_per_act=1)",
"_____no_output_____"
],
[
"def get_theta_of_user(user_id):\n user_data_dir = os.path.join(utils.gw_human_data_dir, user_id)\n\n init_belief_conf = 1-1e-9\n dynamics_model = env.make_dynamics_model(eps=1e-9)\n internal_dynamics_model = env.make_dynamics_model(eps=0.1)\n\n tabular_obs_model_kwargs = {\n 'scope_file': os.path.join(user_data_dir, 'guide_scope.pkl'),\n 'tf_file': os.path.join(user_data_dir, 'guide.tf'),\n 'user_init_belief_conf': user_init_belief_conf,\n 'obs_params_only': True,\n 'prior_coeff': 0.,\n 'warm_start': False\n }\n\n guide_train_kwargs = {\n 'iterations': 1000,\n 'ftol': 1e-6,\n 'batch_size': 32,\n 'learning_rate': 1e-2,\n 'val_update_freq': 100,\n 'verbose': True,\n 'show_plots': False\n }\n\n guide_model = GridWorldGuide(\n sess,\n env,\n env.ground_truth_obs_model,\n dynamics_model,\n env.Q,\n n_obs_per_act=guide_env.n_obs_per_act,\n prior_internal_obs_model=env.ground_truth_obs_model,\n internal_dynamics_model=internal_dynamics_model,\n tabular_obs_model_kwargs=tabular_obs_model_kwargs,\n learn_internal_obs_model=True,\n init_belief_conf=init_belief_conf,\n user_init_belief_conf=user_init_belief_conf\n )\n\n guide_evals = baseline_guide_evals_of_user[user_id]\n init_train_rollouts = guide_evals['iden']['rollouts']\n guide_optimizer = ase.InteractiveGuideOptimizer(sess, env, guide_env)\n guide_optimizer.run(\n guide_model,\n n_train_batches=0,\n n_rollouts_per_batch=0,\n guide_train_kwargs={'iterations': 0, 'verbose': False},\n verbose=True,\n init_train_rollouts=init_train_rollouts,\n n_eval_rollouts=None\n )\n guide_model.load()\n \n theta = sess.run(guide_model.internal_obs_model.obs_weights)[0, 0, 0]\n return theta",
"_____no_output_____"
],
[
"thetas = [get_theta_of_user(user_id) for user_id in user_ids]",
"_____no_output_____"
],
[
"thetas",
"_____no_output_____"
],
[
"plt.title('2D Navigation')\nplt.xlabel(r'Learned Model of User Bias $\\hat{\\theta}$')\nplt.ylabel('Number of Users')\nplt.hist(thetas, bins=20, color='orange', label='ASE (Our Method)', align='left')\nplt.hist(np.ones(len(thetas)), bins=20, color='teal', label='Naive ASE (Baseline)', align='left')\nplt.axvline(x=0, linestyle='--', color='black', label='Ground Truth')\nplt.xlim([-0.1, 1.1])\nplt.yticks(range(0, 14, 2))\nplt.legend(loc='upper center')\nplt.savefig(os.path.join(fig_dir, 'gw-learned-theta.pdf'), bbox_inches='tight', dpi=500)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb0acc1cb016c7a8bd41e4baabcc24709f74a26
| 1,477 |
ipynb
|
Jupyter Notebook
|
Udemy_200+Exercises_Programming_Python.ipynb
|
kxen42/Learn-Python-Programming-Third-Edition
|
851ddc5e6094fadd44f31a9ad1d3876456b04372
|
[
"MIT"
] | null | null | null |
Udemy_200+Exercises_Programming_Python.ipynb
|
kxen42/Learn-Python-Programming-Third-Edition
|
851ddc5e6094fadd44f31a9ad1d3876456b04372
|
[
"MIT"
] | null | null | null |
Udemy_200+Exercises_Programming_Python.ipynb
|
kxen42/Learn-Python-Programming-Third-Edition
|
851ddc5e6094fadd44f31a9ad1d3876456b04372
|
[
"MIT"
] | null | null | null | 27.867925 | 282 | 0.551794 |
[
[
[
"<a href=\"https://colab.research.google.com/github/kxen42/Learn-Python-Programming-Third-Edition/blob/main/Udemy_200%2BExercises_Programming_Python.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"You can create a notebook from Google Drive > New Notebook\nFile > 'Locate in Drive' to find the file\nYou have to connect to a hosted runtime environment, if not already connected, hit Connecting in the upper RHS. You should see icons for RAM and Disk in the upper RHS.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbb0c2a4d5ecc7223faf9303c301139e237d64f5
| 5,625 |
ipynb
|
Jupyter Notebook
|
arrays/filling_arrays.ipynb
|
uob-ds/cfd2021
|
bbf8dc1a3938def910c8173cf353efd14dca66e5
|
[
"CC-BY-4.0"
] | 1 |
2021-09-01T07:46:49.000Z
|
2021-09-01T07:46:49.000Z
|
arrays/filling_arrays.ipynb
|
uob-ds/cfd2021
|
bbf8dc1a3938def910c8173cf353efd14dca66e5
|
[
"CC-BY-4.0"
] | null | null | null |
arrays/filling_arrays.ipynb
|
uob-ds/cfd2021
|
bbf8dc1a3938def910c8173cf353efd14dca66e5
|
[
"CC-BY-4.0"
] | 1 |
2021-09-28T09:09:29.000Z
|
2021-09-28T09:09:29.000Z
| 21.146617 | 187 | 0.527289 |
[
[
[
"# Making and filling arrays.",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
]
],
[
[
"## Making arrays\n\nYou have seen how to create arrays from a sequence of values:",
"_____no_output_____"
]
],
[
[
"np.array([1, 2, 3])",
"_____no_output_____"
]
],
[
[
"You have also seen how to create arrays that are sequential integers, using `np.arange`:",
"_____no_output_____"
]
],
[
[
"np.arange(5)",
"_____no_output_____"
]
],
[
[
"We often find that we want to create an empty or default array, that we will fill later.\n\nNumpy has routines for that. The main ones we will use are `np.zeros` and `np.ones`.\n\nYou can guess what they do:",
"_____no_output_____"
]
],
[
[
"np.zeros(5)",
"_____no_output_____"
],
[
"np.ones(5)",
"_____no_output_____"
]
],
[
[
"These arrays aren't very useful at the moment; usually, we will want to fill in the elements of these arrays with other values.",
"_____no_output_____"
],
[
"## Filling arrays\n\nWe put values into arrays using *assignment*.",
"_____no_output_____"
],
[
"### A refresher on assignment\n\nRemember the basic assignment statement. We have so far learned that the assignment statement is a *name* followed by `=` followed by an expression (a recipe that returns a value).",
"_____no_output_____"
]
],
[
[
"# An assignment statement\na = 1\na",
"_____no_output_____"
]
],
[
[
"Here the left hand side (LHS) is `a`.\n\nThe right hand side (RHS) is an expression: `1`.\n\nWe can read `a = 1` as \"a gets the value 1.\" We can also read it as: \"Make the location called 'a' point to the value 1.\"",
"_____no_output_____"
],
[
"So far, the left hand side (LHS) has always been a *name*.\n\nIn fact, the LHS can be anything we can *assign* to.",
"_____no_output_____"
],
[
"### A refresher on indexing\n\nRemember too that we can retrieve values from an array by *indexing*.\n\nHere is an example array:",
"_____no_output_____"
]
],
[
[
"my_array = np.arange(1, 11)\nmy_array",
"_____no_output_____"
]
],
[
[
"We can retrieve one or more values by indexing:",
"_____no_output_____"
]
],
[
[
"my_array[1]",
"_____no_output_____"
],
[
"my_array[5:]",
"_____no_output_____"
]
],
[
[
"## Assignment with indexing\n\nIn fact we can use these exact same specifications on the LHS of an assignment statement:",
"_____no_output_____"
]
],
[
[
"my_array[1] = 99\nmy_array",
"_____no_output_____"
],
[
"my_array[5:] = 100\nmy_array",
"_____no_output_____"
]
],
[
[
"When you use array indexing on the LHS, it means *specify the elements to assign*. So:\n\n* `my_array[5]` on the RHS means - get the value at offset 5 in `my_array`\n* `my_array[5]` on the LHS means - use this location to store the data returned from the RHS.\n\nSo we can read `my_array[1] = 99` as \"Make the location 'my_array[5]' point to\nthe value 99.\".\n\nWe will use this kind of assignment to get a little closer to a good solution to the three girl problem, in [leaping ahead](leaping_ahead).",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cbb0c6d8c34cd2b527e7cba3fc8989c01102d48f
| 28,618 |
ipynb
|
Jupyter Notebook
|
sagemaker-distributed-training.ipynb
|
philschmid/transformers-pytorch-text-classification
|
97d195806a2f97dd4fb87af817d20991271129af
|
[
"MIT"
] | 11 |
2022-01-25T17:33:34.000Z
|
2022-02-06T08:15:49.000Z
|
sagemaker-distributed-training.ipynb
|
philschmid/transformers-pytorch-text-classification
|
97d195806a2f97dd4fb87af817d20991271129af
|
[
"MIT"
] | null | null | null |
sagemaker-distributed-training.ipynb
|
philschmid/transformers-pytorch-text-classification
|
97d195806a2f97dd4fb87af817d20991271129af
|
[
"MIT"
] | 2 |
2022-01-20T10:52:24.000Z
|
2022-01-26T15:48:53.000Z
| 51.938294 | 8,214 | 0.724195 |
[
[
[
"# Hugging Face Transformers with `Pytorch` \n### Text Classification Example using vanilla `Pytorch`, `Transformers`, `Datasets`",
"_____no_output_____"
],
[
"# Introduction\n\nWelcome to this end-to-end multilingual Text-Classification example using PyTorch. In this demo, we will use the Hugging Faces `transformers` and `datasets` library together with `Pytorch` to fine-tune a multilingual transformer for text-classification. This example is a derived version of the [text-classificiaton.ipynb](https://github.com/philschmid/transformers-pytorch-text-classification/blob/main/text-classification.ipynb) notebook and uses Amazon SageMaker for distributed training. In the [text-classificiaton.ipynb](https://github.com/philschmid/transformers-pytorch-text-classification/blob/main/text-classification.ipynb) we showed how to fine-tune `distilbert-base-multilingual-cased` on the `amazon_reviews_multi` dataset for `sentiment-analysis`. This dataset has over 1.2 million data points, which is huge. Running training would take on 1x NVIDIA V100 takes around 6,5h for `batch_size` 16, which is quite long.\n\nTo scale and accelerate our training we will use [Amazon SageMaker](https://aws.amazon.com/de/sagemaker/), which provides two strategies for [distributed training](https://huggingface.co/docs/sagemaker/train#distributed-training), [data parallelism](https://huggingface.co/docs/sagemaker/train#data-parallelism) and model parallelism. Data parallelism splits a training set across several GPUs, while [model parallelism](https://huggingface.co/docs/sagemaker/train#model-parallelism) splits a model across several GPUs. We are going to use [SageMaker Data Parallelism](https://aws.amazon.com/blogs/aws/managed-data-parallelism-in-amazon-sagemaker-simplifies-training-on-large-datasets/), which has been built into the [Trainer](https://huggingface.co/transformers/main_classes/trainer.html) API. To be able use data-parallelism we only have to define the `distribution` parameter in our `HuggingFace` estimator.\n\nI moved the \"training\" part of the [text-classificiaton.ipynb](https://github.com/philschmid/transformers-pytorch-text-classification/blob/main/text-classification.ipynb) notebook into a separate training script [train.py](./scripts/train.py), which accepts the same hyperparameter and can be run on Amazon SageMaker using the `HuggingFace` estimator. \n\nOur goal is to decrease the training duration by scaling our global/effective batch size from 16 up to 128, which is 8x bigger than before. For monitoring our training we will use the new Training Metrics support by the [Hugging Face Hub](hf.co/models) ",
"_____no_output_____"
],
[
"### Installation",
"_____no_output_____"
]
],
[
[
"#!pip install sagemaker \n!pip install transformers datasets tensorboard datasets[s3] --upgrade",
"_____no_output_____"
]
],
[
[
"This example will use the [Hugging Face Hub](https://huggingface.co/models) as remote model versioning service. To be able to push our model to the Hub, you need to register on the [Hugging Face](https://huggingface.co/join). \nIf you already have an account you can skip this step. \nAfter you have an account, we will use the `notebook_login` util from the `huggingface_hub` package to log into our account and store our token (access key) on the disk. ",
"_____no_output_____"
]
],
[
[
"from huggingface_hub import notebook_login\n\nnotebook_login()",
"_____no_output_____"
]
],
[
[
"## Setup & Configuration\n\nIn this step we will define global configurations and parameters, which are used across the whole end-to-end fine-tuning proccess, e.g. `tokenizer` and `model` we will use. ",
"_____no_output_____"
]
],
[
[
"import sagemaker\n\nsess = sagemaker.Session()\n# sagemaker session bucket -> used for uploading data, models and logs\n# sagemaker will automatically create this bucket if it not exists\nsagemaker_session_bucket=None\nif sagemaker_session_bucket is None and sess is not None:\n # set to default bucket if a bucket name is not given\n sagemaker_session_bucket = sess.default_bucket()\n\nrole = sagemaker.get_execution_role()\nsess = sagemaker.Session(default_bucket=sagemaker_session_bucket)\n\nprint(f\"sagemaker role arn: {role}\")\nprint(f\"sagemaker bucket: {sess.default_bucket()}\")\nprint(f\"sagemaker session region: {sess.boto_region_name}\")",
"_____no_output_____"
]
],
[
[
"_Note: The execution role is only available when running a notebook within SageMaker (SageMaker Notebook Instances or Studio). If you run `get_execution_role` in a notebook not on SageMaker, expect a region error._\n\nYou can comment in the cell below and provide a an IAM Role name with SageMaker permissions to setup your environment out side of SageMaker.",
"_____no_output_____"
]
],
[
[
"# import sagemaker\n# import boto3\n# import os\n\n# os.environ[\"AWS_DEFAULT_REGION\"]=\"your-region\"\n\n# # This ROLE needs to exists with your associated AWS Credentials and needs permission for SageMaker\n# ROLE_NAME='role-name-of-your-iam-role-with-right-permissions'\n\n# iam_client = boto3.client('iam')\n# role = iam_client.get_role(RoleName=ROLE_NAME)['Role']['Arn']\n# sess = sagemaker.Session()\n\n# print(f\"sagemaker role arn: {role}\")\n# print(f\"sagemaker bucket: {sess.default_bucket()}\")\n# print(f\"sagemaker session region: {sess.boto_region_name}\")",
"sagemaker role arn: arn:aws:iam::558105141721:role/sagemaker_execution_role\nsagemaker bucket: sagemaker-us-east-1-558105141721\nsagemaker session region: us-east-1\n"
]
],
[
[
"In this example are we going to fine-tune the [distilbert-base-multilingual-cased](https://huggingface.co/distilbert-base-multilingual-cased) a multilingual DistilBERT model. ",
"_____no_output_____"
]
],
[
[
"model_id = \"distilbert-base-multilingual-cased\"\n\n# name for our repository on the hub\nmodel_name = model_id.split(\"/\")[-1] if \"/\" in model_id else model_id\nrepo_name = f\"{model_name}-sentiment\"",
"_____no_output_____"
]
],
[
[
"## Dataset & Pre-processing\n\nAs Dataset we will use the [amazon_reviews_multi](https://huggingface.co/datasets/amazon_reviews_multi) a multilingual text-classification. The dataset contains reviews in English, Japanese, German, French, Chinese and Spanish, collected between November 1, 2015 and November 1, 2019. Each record in the dataset contains the review text, the review title, the star rating, an anonymized reviewer ID, an anonymized product ID and the coarse-grained product category (e.g. ‘books’, ‘appliances’, etc.) The corpus is balanced across stars, so each star rating constitutes 20% of the reviews in each language.\n",
"_____no_output_____"
]
],
[
[
"dataset_id=\"amazon_reviews_multi\"\ndataset_config=\"all_languages\"\n\nseed=33",
"_____no_output_____"
]
],
[
[
"To load the `amazon_reviews_multi` dataset, we use the `load_dataset()` method from the 🤗 Datasets library.\n",
"_____no_output_____"
]
],
[
[
"from datasets import load_dataset\n\ndataset = load_dataset(dataset_id,dataset_config)",
"Reusing dataset amazon_reviews_multi (/home/ubuntu/.cache/huggingface/datasets/amazon_reviews_multi/all_languages/1.0.0/724e94f4b0c6c405ce7e476a6c5ef4f87db30799ad49f765094cf9770e0f7609)\n"
]
],
[
[
"### Pre-processing & Tokenization\n\nThe [amazon_reviews_multi](https://huggingface.co/datasets/amazon_reviews_multi) has 5 classes (`stars`) to match those into a `sentiment-analysis` task we will map those star ratings to the following classes `labels`:\n* `[1-2]`: `Negative`\n* `[3]`: `Neutral`\n* `[4-5]`: `Positive`\n\nThose `labels` can be later used to create a user friendly output after we fine-tuned our model. ",
"_____no_output_____"
]
],
[
[
"from datasets import ClassLabel\n\ndef map_start_to_label(review):\n if review[\"stars\"] < 3:\n review[\"stars\"] = 0\n elif review[\"stars\"] == 3:\n review[\"stars\"] = 1\n else: \n review[\"stars\"] = 2\n return review\n\n# convert 1-5 star reviews to 0,1,2\ndataset = dataset.map(map_start_to_label)\n\n# convert feature from Value to ClassLabel\nclass_feature = ClassLabel(names=['negative','neutral', 'positive'])\ndataset = dataset.cast_column(\"stars\", class_feature)\n\n# rename our target column to labels\ndataset = dataset.rename_column(\"stars\",\"labels\")\n\n# drop columns that are not needed\ndataset = dataset.remove_columns(['review_id', 'product_id', 'reviewer_id', 'review_title', 'language', 'product_category'])\n\ndataset[\"train\"].features\n",
"Loading cached processed dataset at /home/ubuntu/.cache/huggingface/datasets/amazon_reviews_multi/all_languages/1.0.0/724e94f4b0c6c405ce7e476a6c5ef4f87db30799ad49f765094cf9770e0f7609/cache-da69b832ccae3902.arrow\nLoading cached processed dataset at /home/ubuntu/.cache/huggingface/datasets/amazon_reviews_multi/all_languages/1.0.0/724e94f4b0c6c405ce7e476a6c5ef4f87db30799ad49f765094cf9770e0f7609/cache-c090e61da6df9ce2.arrow\nLoading cached processed dataset at /home/ubuntu/.cache/huggingface/datasets/amazon_reviews_multi/all_languages/1.0.0/724e94f4b0c6c405ce7e476a6c5ef4f87db30799ad49f765094cf9770e0f7609/cache-e24978bae26959c1.arrow\nLoading cached processed dataset at /home/ubuntu/.cache/huggingface/datasets/amazon_reviews_multi/all_languages/1.0.0/724e94f4b0c6c405ce7e476a6c5ef4f87db30799ad49f765094cf9770e0f7609/cache-3d48141565c7759b.arrow\nLoading cached processed dataset at /home/ubuntu/.cache/huggingface/datasets/amazon_reviews_multi/all_languages/1.0.0/724e94f4b0c6c405ce7e476a6c5ef4f87db30799ad49f765094cf9770e0f7609/cache-4f7e3a2cd4b9babf.arrow\nLoading cached processed dataset at /home/ubuntu/.cache/huggingface/datasets/amazon_reviews_multi/all_languages/1.0.0/724e94f4b0c6c405ce7e476a6c5ef4f87db30799ad49f765094cf9770e0f7609/cache-0d00e718261d5a59.arrow\n"
]
],
[
[
"Before we prepare the dataset for training. Lets take a quick look at the class distribution of the dataset.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\n\ndf = dataset[\"train\"].to_pandas()\n\ndf.hist()",
"_____no_output_____"
]
],
[
[
"The Distribution is not perfect, but lets give it a try and improve on this later.",
"_____no_output_____"
],
[
"To train our model we need to convert our \"Natural Language\" to token IDs. This is done by a 🤗 Transformers Tokenizer which will tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary). If you are not sure what this means check out [chapter 6](https://huggingface.co/course/chapter6/1?fw=tf) of the Hugging Face Course.\n",
"_____no_output_____"
]
],
[
[
"from transformers import AutoTokenizer\n\ntokenizer = AutoTokenizer.from_pretrained(model_id)",
"_____no_output_____"
]
],
[
[
"Additionally we add the `truncation=True` and `max_length=512` to align the length and truncate texts that are bigger than the maximum size allowed by the model. ",
"_____no_output_____"
]
],
[
[
"def process(examples):\n tokenized_inputs = tokenizer(\n examples[\"review_body\"], truncation=True, max_length=512\n )\n return tokenized_inputs\n\ntokenized_datasets = dataset.map(process, batched=True)\ntokenized_datasets[\"train\"].features",
"_____no_output_____"
]
],
[
[
"Before we can start our distributed Training, we need to upload our already pre-processed dataset to Amazon S3. Therefore we will use the built-in utils of `datasets`",
"_____no_output_____"
]
],
[
[
"import botocore\nfrom datasets.filesystems import S3FileSystem\n\ns3 = S3FileSystem() \n\n# save train_dataset to s3\ntraining_input_path = f's3://{sess.default_bucket()}/{dataset_id}/train'\ntokenized_datasets[\"train\"].save_to_disk(training_input_path, fs=s3)\n\n# save validation_dataset to s3\neval_input_path = f's3://{sess.default_bucket()}/{dataset_id}/test'\ntokenized_datasets[\"validation\"].save_to_disk(eval_input_path, fs=s3)",
"_____no_output_____"
]
],
[
[
"## Creating an Estimator and start a training job\n\n\nLast step before we can start our managed training is to define our Hyperparameters, create our sagemaker `HuggingFace` estimator and configure distributed training.",
"_____no_output_____"
]
],
[
[
"from sagemaker.huggingface import HuggingFace\nfrom huggingface_hub import HfFolder\n\n# hyperparameters, which are passed into the training job\nhyperparameters={\n 'model_id':'distilbert-base-multilingual-cased', \n 'epochs': 3, \n 'per_device_train_batch_size': 16, \n 'per_device_eval_batch_size': 16, \n 'learning_rate': 3e-5*8, \n 'fp16': True, \n # logging & evaluation strategie\n 'strategy':'steps',\n 'steps':5_000,\n 'save_total_limit':2,\n 'load_best_model_at_end':True,\n 'metric_for_best_model':\"f1\",\n # push to hub config\n 'push_to_hub': True, \n 'hub_model_id': 'distilbert-base-multilingual-cased-sentiment-2', \n 'hub_token': HfFolder.get_token() \n}\n\n# configuration for running training on smdistributed Data Parallel\ndistribution = {'smdistributed':{'dataparallel':{ 'enabled': True }}}\n\n# create the Estimator\nhuggingface_estimator = HuggingFace(\n entry_point = 'train.py', \n source_dir = './scripts', \n instance_type = 'ml.p3.16xlarge', \n instance_count = 1, \n role = role, \n transformers_version = '4.12', \n pytorch_version = '1.9', \n py_version = 'py38', \n hyperparameters = hyperparameters, \n distribution = distribution\n)",
"_____no_output_____"
]
],
[
[
"Since, we are using SageMaker Data Parallelism our total_batch_size will be per_device_train_batch_size * n_gpus.\n\n",
"_____no_output_____"
]
],
[
[
"# define a data input dictonary with our uploaded s3 uris\ndata = {\n 'train': training_input_path,\n 'eval': eval_input_path\n}\n\n# starting the train job with our uploaded datasets as input\n# setting wait to False to not expose the HF Token\nhuggingface_estimator.fit(data,wait=False)",
"_____no_output_____"
]
],
[
[
"Since we are using the Hugging Face Hub intergration with Tensorboard we can inspect our progress directly on the hub, as well as testing checkpoints during the training.",
"_____no_output_____"
]
],
[
[
"from huggingface_hub import HfApi\n\nwhoami = HfApi().whoami()\nusername = whoami['name']\n\nprint(f\"https://huggingface.co/{username}/{hyperparameters['hub_model_id']}\")",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"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"
]
] |
cbb0d8b11e71c814b7656920692f7cd28f7091ac
| 147,578 |
ipynb
|
Jupyter Notebook
|
basics/Quantum Teleportation.ipynb
|
mentesniker/quantum-computer-science
|
a305a91df486a1a87d8d641bc18c57e078eccdb7
|
[
"MIT"
] | 1 |
2021-01-31T16:21:58.000Z
|
2021-01-31T16:21:58.000Z
|
basics/Quantum Teleportation.ipynb
|
mentesniker/quantum-computer-science
|
a305a91df486a1a87d8d641bc18c57e078eccdb7
|
[
"MIT"
] | null | null | null |
basics/Quantum Teleportation.ipynb
|
mentesniker/quantum-computer-science
|
a305a91df486a1a87d8d641bc18c57e078eccdb7
|
[
"MIT"
] | null | null | null | 587.960159 | 119,968 | 0.950806 |
[
[
[
"# Quantum teleportation",
"_____no_output_____"
],
[
"By the end of this post, we will teleport the quantum state \n$$\\sqrt{0.70}\\vert0\\rangle + \\sqrt{0.30}\\vert1\\rangle$$ from Alice's qubit to Bob's qubit. \n\nRecall that the teleportation algorithm consists of four major components:\n\n1. Initializing the state to be teleported. We will do this on Alice's qubit `q0`.\n2. Creating entanglement between two qubits. We will use qubits `q1` and `q2` for this. Recall that Alice owns `q1`, and Bob owns `q2`.\n3. Applying a Bell measurement on Alice's qubits `q0` and `q1`.\n4. Applying classically controlled operations on Bob's qubit `q2` depending on the outcomes of the Bell measurement on Alice's qubits.\n\nThis exercise guides you through each of these steps.",
"_____no_output_____"
],
[
"### Initializing the state to be teleported",
"_____no_output_____"
],
[
"First, we create a quantum circuit that has the state $$\\sqrt{0.70}\\vert0\\rangle + \\sqrt{0.30}\\vert1\\rangle$$ We can do this by using `Qiskit`'s `initialize` function.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport math\ndef initialize_qubit(given_circuit, qubit_index):\n \n ### WRITE YOUR CODE BETWEEN THESE LINES - START\n desired_vector = [math.sqrt(0.70),math.sqrt(0.30)]\n given_circuit.initialize(desired_vector, [all_qubits_Alice[qubit_index]])\n ### WRITE YOUR CODE BETWEEN THESE LINES - END\n \n return given_circuit",
"_____no_output_____"
]
],
[
[
"Next, we need to create entanglement between Alice's and Bob's qubits.",
"_____no_output_____"
]
],
[
[
"def entangle_qubits(given_circuit, qubit_Alice, qubit_Bob):\n \n ### WRITE YOUR CODE BETWEEN THESE LINES - START\n given_circuit.h(qubit_Alice)\n given_circuit.cx(qubit_Alice,qubit_Bob)\n mycircuit.barrier()\n given_circuit.cx(0,1)\n given_circuit.h(0)\n \n ### WRITE YOUR CODE BETWEEN THESE LINES - END\n \n return given_circuit",
"_____no_output_____"
]
],
[
[
"Next, we need to do a Bell measurement of Alice's qubits.",
"_____no_output_____"
]
],
[
[
"def bell_meas_Alice_qubits(given_circuit, qubit1_Alice, qubit2_Alice, clbit1_Alice, clbit2_Alice):\n \n ### WRITE YOUR CODE BETWEEN THESE LINES - START\n given_circuit.measure([0,1], [0,1])\n ### WRITE YOUR CODE BETWEEN THESE LINES - END\n\n return given_circuit",
"_____no_output_____"
]
],
[
[
"Finally, we apply controlled operations on Bob's qubit. Recall that the controlled operations are applied in this order:\n\n- an $X$ gate is applied on Bob's qubit if the measurement coutcome of Alice's second qubit, `clbit2_Alice`, is `1`.\n- a $Z$ gate is applied on Bob's qubit if the measurement coutcome of Alice's first qubit, `clbit1_Alice`, is `1`.",
"_____no_output_____"
]
],
[
[
"def controlled_ops_Bob_qubit(given_circuit, qubit_Bob, clbit1_Alice, clbit2_Alice):\n ### WRITE YOUR CODE BETWEEN THESE LINES - START\n given_circuit.x(qubit_Bob).c_if(clbit2_Alice, 1)\n given_circuit.z(qubit_Bob).c_if(clbit1_Alice, 1)\n ### WRITE YOUR CODE BETWEEN THESE LINES - END\n \n return given_circuit",
"_____no_output_____"
]
],
[
[
"The next lines of code put everything together. ",
"_____no_output_____"
]
],
[
[
"### imports\nfrom qiskit import QuantumRegister, ClassicalRegister\n\n### set up the qubits and classical bits\nall_qubits_Alice = QuantumRegister(2)\nall_qubits_Bob = QuantumRegister(1)\ncreg1_Alice = ClassicalRegister(1)\ncreg2_Alice = ClassicalRegister(1)\n\n### quantum teleportation circuit here\n# Initialize\nmycircuit = QuantumCircuit(all_qubits_Alice, all_qubits_Bob, creg1_Alice, creg2_Alice)\ninitialize_qubit(mycircuit, 0)\nmycircuit.barrier()\n# Entangle\nentangle_qubits(mycircuit, 1, 2)\nmycircuit.barrier()\n# Do a Bell measurement\nbell_meas_Alice_qubits(mycircuit, all_qubits_Alice[0], all_qubits_Alice[1], creg1_Alice, creg2_Alice)\nmycircuit.barrier()\n\n# Apply classically controlled quantum gates\ncontrolled_ops_Bob_qubit(mycircuit, all_qubits_Bob[0], creg1_Alice, creg2_Alice)\n\n### Look at the complete circuit\nmycircuit.draw()",
"_____no_output_____"
],
[
"from qiskit import BasicAer\nfrom qiskit.visualization import plot_histogram, plot_bloch_multivector\nbackend = BasicAer.get_backend('statevector_simulator')\nout_vector = execute(mycircuit, backend).result().get_statevector()\nplot_bloch_multivector(out_vector)",
"_____no_output_____"
]
],
[
[
"As you can see, the state from the qubit 1 is teleported to the qubit 2. However, please note something, in the teleportation process the original qubit state was destroyed when we did the measurements of Alice's qubits.",
"_____no_output_____"
],
[
"## References:\n\nThe original lab can be found in the link: https://qiskit.org/learn/intro-qc-qh/\nHere is just my solution to the original lab file. I made some modifications to fit the style of the blog as well.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cbb0eb338acc6b3d2fe9ad05d98e4daf9f676883
| 58,892 |
ipynb
|
Jupyter Notebook
|
11. Facets.ipynb
|
chikoungoun/R-Tuto
|
28e15ccb37796000888c2abc0c1fd217f8ba7b44
|
[
"MIT"
] | null | null | null |
11. Facets.ipynb
|
chikoungoun/R-Tuto
|
28e15ccb37796000888c2abc0c1fd217f8ba7b44
|
[
"MIT"
] | null | null | null |
11. Facets.ipynb
|
chikoungoun/R-Tuto
|
28e15ccb37796000888c2abc0c1fd217f8ba7b44
|
[
"MIT"
] | null | null | null | 392.613333 | 22,296 | 0.941673 |
[
[
[
"library(ggplot2)\nlibrary(palmerpenguins)",
"_____no_output_____"
]
],
[
[
"**facet_wrap() :** to facet the plot by a single variable",
"_____no_output_____"
]
],
[
[
"ggplot(data = penguins, aes(x=flipper_length_mm, y=body_mass_g))+\ngeom_point(aes(color=species))+\nfacet_wrap(~species)",
"Warning message:\n\"Removed 2 rows containing missing values (geom_point).\"\n"
],
[
"ggplot(data = diamonds)+\ngeom_bar(aes(x=color, fill=cut))+\nfacet_wrap(~cut)",
"_____no_output_____"
]
],
[
[
"**facet_grid() :** facet the plot with 2 variables",
"_____no_output_____"
]
],
[
[
"ggplot(data = penguins, aes(x=flipper_length_mm, y=body_mass_g))+\ngeom_point(aes(color=species))+\nfacet_grid(sex~species)",
"Warning message:\n\"Removed 2 rows containing missing values (geom_point).\"\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb0f7ad8c7bd4b6e113b365750aa2c6168f0534
| 10,946 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/Spotify's recommendation engine-checkpoint.ipynb
|
umar-khayam/Data-Science
|
f86092a7144a696b3b81701795a50c5cd505fae3
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Spotify's recommendation engine-checkpoint.ipynb
|
umar-khayam/Data-Science
|
f86092a7144a696b3b81701795a50c5cd505fae3
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Spotify's recommendation engine-checkpoint.ipynb
|
umar-khayam/Data-Science
|
f86092a7144a696b3b81701795a50c5cd505fae3
|
[
"MIT"
] | null | null | null | 76.545455 | 1,530 | 0.639138 |
[
[
[
"import pandas as pd\nfrom sklearn.cluster import KMeans",
"_____no_output_____"
],
[
"class Spotify_recommendation(object):\n def __init__(self):\n self.df=pd.read_csv('top50.csv')\n self.numarical_df=None\n self.results=dict()\n def columns_renaming(self):\n self.df.columns=[i.lower().replace(',','') for i in self.df]\n \n def cleaning_str_columns(self):\n for i in ['trackname','artistname','genre']:\n self.df[i]=self.df[i].str.lower()\n \n def remove_column(self):\n self.df.drop(columns=['Unamed: 0'],axis=1,inplace=True)\n\n def normalization_algo(self, col):\n max_d=self.df[col].max()\n min_d=self.df[col].min()\n return (self.df[col]-min_d)/(max_d-min_d)\n \n def normalizing_col(self):\n df_numarical=self.df.select_dtypes(include=['int64'])\n self.numarical_df=df_numarical\n for i in self.numarical.columns:\n self.df[i]=self.normalization_algo(i)\n \n def cluster_creation(self):\n kn=KMeans(n_clusters=10)\n pred=kn.fit_predict(self.numarical_df)\n self.df['cluster_val']=pred\n \n def fit(self):\n total_songs =list(self.df['trackname'].unique())\n for i in total_songs:\n distance=[]\n song_res=self.df(self.df['trackname']==i).head(1).values[0]\n rem_data=self.df[self.df['trackname']!=i]\n \n for r_song in rem_data.values:\n dist=0\n for idx, col in enumerate(rem_data.columns):\n if not col in ['trackname','artistname','genre']:\n dist=dist + np.absolute(float(song_res[idx]-float(r_song[idx])))\n distance.append(dist)\n rem_data['distance']=distance\n rem_data=rem_data.sort_values('disance')\n temp=rem_data.to_dict(orient='records')\n \n self.results[i]=temp\n \n def predict(self, song_name,top_songs=5):\n return self.result[song_name][0:top_songs]\n ",
"_____no_output_____"
],
[
"s=Spotify_recommendation()\ns.columns_renaming()\ns.cleaning_str_columns()\ns.normalizing_col()",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code"
]
] |
cbb0f8d96be5c524926845d45b5744f1e3d81614
| 216,051 |
ipynb
|
Jupyter Notebook
|
plot-counts.ipynb
|
harrisonized/mta
|
1185b0b43911acfa78bf1f25dcb9c2350e05d61b
|
[
"MIT"
] | 1 |
2019-07-03T03:20:44.000Z
|
2019-07-03T03:20:44.000Z
|
plot-counts.ipynb
|
harrisonized/MTA
|
1185b0b43911acfa78bf1f25dcb9c2350e05d61b
|
[
"MIT"
] | null | null | null |
plot-counts.ipynb
|
harrisonized/MTA
|
1185b0b43911acfa78bf1f25dcb9c2350e05d61b
|
[
"MIT"
] | null | null | null | 1,341.931677 | 181,504 | 0.955673 |
[
[
[
"import pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"data_dir = \"data\"\nsave = True",
"_____no_output_____"
]
],
[
[
"# Get Data",
"_____no_output_____"
]
],
[
[
"df = pd.read_csv(f'{data_dir}/station-counts.csv', index_col='datetime')",
"_____no_output_____"
]
],
[
[
"# Plot Histogram",
"_____no_output_____"
]
],
[
[
"# get data\nbar_df = pd.DataFrame(df.sum().sort_values(ascending=False)[9:24], columns=['num_people'])\n\nx = bar_df['num_people'][::-1]/52\ny = bar_df.index[::-1]\n\n# plot\nfig, ax = plt.subplots(figsize=(12, 8))\nax.barh(y, x, align='center', capsize=3)\nax.xaxis.grid(True)\nax.set_yticks(y)\nax.set_xlabel('Number of People Per Week', fontsize=12)\nax.set_title('Top 15 Stations by Number of People per Week', fontsize=16)\n\n# save\nif save:\n plt.savefig(\"figures/station-count-week.png\",\n bbox_inches=\"tight\",\n transparent=False,)",
"_____no_output_____"
]
],
[
[
"# Plot Line Chart for One Week",
"_____no_output_____"
]
],
[
[
"df[(df.index >= '2018-03-24 00:00:00')\n & (df.index <= '2018-03-31 00:00:00')][['34 ST-HERALD SQ',\n 'TIMES SQ-42 ST',\n '1 AV',\n 'LEXINGTON AV/63',\n '42 ST-PORT AUTH']].plot(ylim = (0, 3500), figsize=(12, 8))\n\nplt.xticks([0, 6, 12, 18, 24, 30, 36], ['Sat', 'Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri'])\nplt.xlabel('Day of the Week', fontsize=16)\nplt.ylabel('Number of People', fontsize=16)\nplt.title('One Week of Station Traffic for the Top 5 Stations', fontsize=24)\n\nif save:\n plt.savefig(\"figures/day-count-20200324_20200331.png\",\n bbox_inches=\"tight\",)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb109df40052be426914450d8b2c5befd3171cd
| 395,830 |
ipynb
|
Jupyter Notebook
|
NLP_Concepts_06 - RNNs in practice.ipynb
|
AlxndrMlk/nlp-concepts
|
aa4b23e492de53f029bd16ba4162d639efba4705
|
[
"MIT"
] | 2 |
2020-12-17T12:56:55.000Z
|
2020-12-17T12:56:56.000Z
|
NLP_Concepts_06 - RNNs in practice.ipynb
|
AlxndrMlk/nlp-concepts
|
aa4b23e492de53f029bd16ba4162d639efba4705
|
[
"MIT"
] | null | null | null |
NLP_Concepts_06 - RNNs in practice.ipynb
|
AlxndrMlk/nlp-concepts
|
aa4b23e492de53f029bd16ba4162d639efba4705
|
[
"MIT"
] | 1 |
2021-04-15T10:14:49.000Z
|
2021-04-15T10:14:49.000Z
| 389.596457 | 43,392 | 0.934886 |
[
[
[
"import time\n\nimport pandas as pd\nimport numpy as np\n\nimport nltk\nnltk.download('gutenberg')\n\nimport tensorflow as tf\nkeras = tf.keras\n\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import train_test_split\n\nfrom tqdm import tqdm\n\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')",
"[nltk_data] Downloading package gutenberg to\n[nltk_data] C:\\Users\\aleksander.molak\\AppData\\Roaming\\nltk_data...\n[nltk_data] Package gutenberg is already up-to-date!\n"
]
],
[
[
"# NLP Concepts #6 - RNNs in practice",
"_____no_output_____"
],
[
"## Define helpers",
"_____no_output_____"
]
],
[
[
"def get_slices(text, slice_len=100):\n \n text_split = text.split(' ')\n \n n_chunks = int(len(text_split) / slice_len)\n current_start_id = 0\n \n slices = []\n \n for i in range(n_chunks + 1):\n current_slice = text_split[current_start_id:current_start_id + slice_len]\n \n if len(current_slice) > 0:\n slices.append(' '.join(current_slice))\n \n current_start_id += slice_len\n \n return slices",
"_____no_output_____"
]
],
[
[
"## Get and prepare data",
"_____no_output_____"
]
],
[
[
"# Print corpora and their lengths\nfor i in nltk.corpus.gutenberg.fileids():\n src = nltk.corpus.gutenberg.words(i)\n print(i, len(src))",
"austen-emma.txt 192427\nausten-persuasion.txt 98171\nausten-sense.txt 141576\nbible-kjv.txt 1010654\nblake-poems.txt 8354\nbryant-stories.txt 55563\nburgess-busterbrown.txt 18963\ncarroll-alice.txt 34110\nchesterton-ball.txt 96996\nchesterton-brown.txt 86063\nchesterton-thursday.txt 69213\nedgeworth-parents.txt 210663\nmelville-moby_dick.txt 260819\nmilton-paradise.txt 96825\nshakespeare-caesar.txt 25833\nshakespeare-hamlet.txt 37360\nshakespeare-macbeth.txt 23140\nwhitman-leaves.txt 154883\n"
]
],
[
[
"### Join and check lengths",
"_____no_output_____"
]
],
[
[
"# Shakespeare's \"Macbeth\"\nshkspr = nltk.corpus.gutenberg.words('shakespeare-macbeth.txt')\nshkspr_join = ' '.join(shkspr)\n\nlen(shkspr)",
"_____no_output_____"
],
[
"# Carroll's \"Alice's adventures (...)\"\ncarroll = nltk.corpus.gutenberg.words('carroll-alice.txt')[:23140]\ncarroll_join = ' '.join(carroll)\n\nlen(carroll)",
"_____no_output_____"
]
],
[
[
"### Get slices and generate labels",
"_____no_output_____"
]
],
[
[
"# Get slices\nshkspr_slices = get_slices(shkspr_join, 250)\ncarroll_slices = get_slices(carroll_join, 250)",
"_____no_output_____"
],
[
"len(shkspr_slices), len(carroll_slices)",
"_____no_output_____"
],
[
"# Create X\nX = shkspr_slices + carroll_slices\n\n# Create y\ny = np.array([0] * 93 + [1] * 93)",
"_____no_output_____"
]
],
[
[
"### Train test split",
"_____no_output_____"
]
],
[
[
"# Train test split \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)",
"_____no_output_____"
]
],
[
[
"### Tokenize texts",
"_____no_output_____"
]
],
[
[
"# Initialize a tokenizer\nVOCAB_SIZE = 20000\n\ntokenizer = tf.keras.preprocessing.text.Tokenizer(\n num_words=VOCAB_SIZE,\n lower=True, \n oov_token=1\n)",
"_____no_output_____"
],
[
"# Fit the toknizer\ntokenizer.fit_on_texts(X_train)",
"_____no_output_____"
],
[
"# Tokenize\nX_train_tok = tokenizer.texts_to_sequences(X_train) \nX_test_tok = tokenizer.texts_to_sequences(X_test)",
"_____no_output_____"
],
[
"# Plot seq lens\nseq_lens_train = [len(seq) for seq in X_train_tok]\nseq_lens_test = [len(seq) for seq in X_test_tok]\n\nplt.hist(seq_lens_train, density=True, alpha=.7, label='Train')\nplt.hist(seq_lens_test, density=True, alpha=.7, label='Test')\n\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"# Find maxlen\nMAXLEN = max([len(x.split(' ')) for x in X_train])",
"_____no_output_____"
],
[
"# Pad sequences\nX_train_tok_pad = pad_sequences(X_train_tok, maxlen=MAXLEN, padding='post')\nX_test_tok_pad = pad_sequences(X_test_tok, maxlen=MAXLEN, padding='post')",
"_____no_output_____"
]
],
[
[
"## Classification example",
"_____no_output_____"
]
],
[
[
"def train_and_evaluate(model, X_train, y_train, X_val, y_val, epochs=30, lr=1e-4, verbose=2):\n \n # Compile\n model.compile(loss = 'binary_crossentropy',\n optimizer = tf.keras.optimizers.Adam(lr),\n metrics = ['accuracy'])\n \n # Callbacks\n early = keras.callbacks.EarlyStopping(patience=10, restore_best_weights=True)\n \n # Time it\n start = time.time()\n \n # Fit \n history = model.fit(X_train, y_train,\n validation_data = (X_val, y_val),\n callbacks = [early],\n epochs = epochs,\n verbose = verbose)\n \n # Time it\n training_time = time.time() - start\n \n # Plot learning curve\n plt.figure(figsize=(10, 4))\n plt.subplot(121)\n plt.plot(history.history['loss'], label='train')\n plt.plot(history.history['val_loss'], label='val')\n plt.legend()\n plt.title('Loss')\n \n plt.subplot(122)\n plt.plot(history.history['accuracy'], label='train')\n plt.plot(history.history['val_accuracy'], label='val')\n plt.legend()\n plt.title('Accuracy')\n \n plt.show()\n \n # Evaluate\n loss, acc = model.evaluate(X_val, y_val, verbose=0)\n \n print(f'Val. accuracy: {acc}')\n print(f'Training time: {training_time:.02f} seconds')",
"_____no_output_____"
]
],
[
[
"### Build a simple model",
"_____no_output_____"
]
],
[
[
"model = tf.keras.Sequential([\n \n tf.keras.layers.Embedding(\n input_dim = VOCAB_SIZE,\n output_dim = 100,\n mask_zero = True,\n input_length = MAXLEN),\n \n tf.keras.layers.LSTM(64),\n \n tf.keras.layers.Dense(1, activation='sigmoid')\n])",
"_____no_output_____"
],
[
"model.summary()",
"Model: \"sequential_2\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_2 (Embedding) (None, 250, 100) 2000000 \n_________________________________________________________________\nlstm_3 (LSTM) (None, 64) 42240 \n_________________________________________________________________\ndense_2 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 2,042,305\nTrainable params: 2,042,305\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"train_and_evaluate(model, X_train_tok_pad, y_train, X_test_tok_pad, y_test, verbose=0, epochs=30)",
"_____no_output_____"
]
],
[
[
"### Build a deeper model",
"_____no_output_____"
]
],
[
[
"model_2 = tf.keras.Sequential([\n \n tf.keras.layers.Embedding(\n input_dim = VOCAB_SIZE,\n output_dim = 100,\n mask_zero = True,\n input_length = MAXLEN),\n \n tf.keras.layers.LSTM(64, return_sequences=True),\n tf.keras.layers.LSTM(128),\n \n tf.keras.layers.Dense(1, activation='sigmoid')\n])\n",
"_____no_output_____"
],
[
"model_2.summary()",
"Model: \"sequential_3\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_3 (Embedding) (None, 250, 100) 2000000 \n_________________________________________________________________\nlstm_4 (LSTM) (None, 250, 64) 42240 \n_________________________________________________________________\nlstm_5 (LSTM) (None, 128) 98816 \n_________________________________________________________________\ndense_3 (Dense) (None, 1) 129 \n=================================================================\nTotal params: 2,141,185\nTrainable params: 2,141,185\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"train_and_evaluate(model_2, X_train_tok_pad, y_train, X_test_tok_pad, y_test, verbose=0, epochs=30)",
"_____no_output_____"
]
],
[
[
"## Build a bi-directional model",
"_____no_output_____"
]
],
[
[
"model_3 = tf.keras.Sequential([\n \n tf.keras.layers.Embedding(\n input_dim = VOCAB_SIZE,\n output_dim = 100,\n mask_zero = True,\n input_length = MAXLEN),\n \n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),\n \n tf.keras.layers.Dense(1, activation='sigmoid')\n])",
"_____no_output_____"
],
[
"model_3.summary()",
"_____no_output_____"
],
[
"train_and_evaluate(model_3, X_train_tok_pad, y_train, X_test_tok_pad, y_test, verbose=0, epochs=30)",
"_____no_output_____"
]
],
[
[
"## Build a deep bi-directional model",
"_____no_output_____"
]
],
[
[
"model_4 = tf.keras.Sequential([\n \n tf.keras.layers.Embedding(\n input_dim = VOCAB_SIZE,\n output_dim = 100,\n mask_zero = True,\n input_length = MAXLEN),\n \n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(128)),\n \n tf.keras.layers.Dense(1, activation='sigmoid')\n])",
"_____no_output_____"
],
[
"model_4.summary()",
"Model: \"sequential_4\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nembedding_4 (Embedding) (None, 250, 100) 2000000 \n_________________________________________________________________\nbidirectional (Bidirectional (None, 250, 128) 84480 \n_________________________________________________________________\nbidirectional_1 (Bidirection (None, 256) 263168 \n_________________________________________________________________\ndense_4 (Dense) (None, 1) 257 \n=================================================================\nTotal params: 2,347,905\nTrainable params: 2,347,905\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"train_and_evaluate(model_4, X_train_tok_pad, y_train, X_test_tok_pad, y_test, verbose=0, epochs=30)",
"_____no_output_____"
]
],
[
[
"## Long distance dependencies - `SimpleRNN()` and `LSTM()`",
"_____no_output_____"
],
[
"#### Experiment:\n\nWe will put a negative number at the beginnig of a random sequence of positive numbers. We'll manipulate sequence length and check how it affects performance of `SimpleRNN` and `LSTM` in a classification task.\n\n<br>\n\n<img src=\"https://www.hackingwithswift.com/uploads/matrix.jpg\" alt=\"Numbers\" style=\"width: 400px;\"/>\n\n",
"_____no_output_____"
]
],
[
[
"LENGTHS = [10, 20, 50, 200]",
"_____no_output_____"
],
[
"def build_dataset(length, n_examples):\n \n X = []\n y = []\n \n for i in range(n_examples):\n class_ = np.random.choice([0, 1])\n \n if class_ == 1:\n row = np.array([-1] + list(np.random.choice(np.arange(0, 1, .01), length - 1)))\n elif class_ == 0:\n row = np.random.choice(np.arange(0, 1, .01), length)\n \n X.append(row)\n y.append(class_)\n \n return np.array(X)[:, :, np.newaxis], np.array(y)",
"_____no_output_____"
],
[
"def build_model(rnn_type, len_):\n \n if rnn_type == 'rnn':\n rnn_layer = tf.keras.layers.SimpleRNN\n elif rnn_type == 'lstm':\n rnn_layer = tf.keras.layers.LSTM\n \n model = tf.keras.Sequential([\n\n rnn_layer(64, input_shape=(len_, 1), return_sequences=True),\n rnn_layer(128),\n \n tf.keras.layers.Dense(32, activation='tanh'),\n tf.keras.layers.Dropout(.2),\n \n tf.keras.layers.Dense(1, activation='sigmoid')\n ])\n \n return model",
"_____no_output_____"
],
[
"for len_ in LENGTHS:\n \n # Prep data\n print(f'Buidling dataset of length {len_}')\n X, y = build_dataset(len_, 200)\n \n # Train test split \n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)\n \n # Build models\n rnn_model = build_model('rnn', len_)\n lstm_model = build_model('lstm', len_)\n \n # Train and evaluate\n print(f'\\nRNN for {len_}')\n train_and_evaluate(rnn_model, X_train, y_train, X_test, y_test, verbose=0, epochs=30)\n \n print(f'\\nLSTM for {len_}')\n train_and_evaluate(lstm_model, X_train, y_train, X_test, y_test, verbose=0, epochs=30)",
"Buidling dataset of length 10\n\nRNN for 10\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cbb11fe04d3b301fe6f7fd5b53d83c36f060cc17
| 28,157 |
ipynb
|
Jupyter Notebook
|
Credit Risk Evaluator.ipynb
|
psharmausa/Credit_Risk_Analysis-challenge
|
fb606581968215e06c6d7040f12946c7342baf80
|
[
"ADSL"
] | null | null | null |
Credit Risk Evaluator.ipynb
|
psharmausa/Credit_Risk_Analysis-challenge
|
fb606581968215e06c6d7040f12946c7342baf80
|
[
"ADSL"
] | null | null | null |
Credit Risk Evaluator.ipynb
|
psharmausa/Credit_Risk_Analysis-challenge
|
fb606581968215e06c6d7040f12946c7342baf80
|
[
"ADSL"
] | null | null | null | 31.996591 | 397 | 0.356821 |
[
[
[
"import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder\n",
"_____no_output_____"
],
[
"train_df = pd.read_csv(Path('Resources/2019loans.csv'))\ntest_df = pd.read_csv(Path('Resources/2020Q1loans.csv'))\ntrain_df.shape\ntest_df.shape",
"_____no_output_____"
],
[
"# Drop the label to create the X data\ntrain_clean = train_df.drop('target', axis=1)\ntest_clean=test_df.drop('target', axis=1)",
"_____no_output_____"
],
[
"# # Convert categorical data to numeric and separate target feature for training data\nX_train_dummies = pd.get_dummies(train_clean)\nX_test_dummies =pd.get_dummies(test_clean)\n",
"_____no_output_____"
],
[
"# add missing dummy variables to testing set\nset(X_train_dummies)^ set(X_test_dummies)\ndebt_settlement_flag_Y=0\nX_test_dummies[debt_settlement_flag_Y]=debt_settlement_flag_Y\nX_test_dummies\n",
"_____no_output_____"
],
[
"# Train the Logistic Regression model on the unscaled data and print the model score\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression()\nclassifier",
"_____no_output_____"
],
[
"classifier.fit(X_train_dummies,y_train)",
"_____no_output_____"
],
[
"# Convert categorical data to numeric and separate target feature for training data\nprint(f\"Training Data Score: {classifier.score(X_train_dummies, y_train)}\")\nprint(f\"Testing Data Score: {classifier.score(X_test_dummies, y_test)}\")",
"Training Data Score: 0.6485221674876848\nTesting Data Score: 0.5253083794130158\n"
],
[
"# Predict \npredictions = classifier.predict(X_test_dummies)\nprint(f\"The new point was classified as: {predictions}\")",
"The new point was classified as: [1 1 1 ... 1 1 0]\n"
],
[
"predictions=classifier.predict(X_test_dummies)\npd.DataFrame({\"Predication\": predictions,\"Actual\": y_test})\n",
"_____no_output_____"
],
[
"print(f'Actual:\\t\\t{list(y_test[:10])}')\nprint(f'Predicted:\\t{list(classifier.predict(X_test_dummies[:10]))}')",
"Actual:\t\t[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\nPredicted:\t[1, 1, 1, 0, 1, 1, 1, 1, 1, 1]\n"
],
[
"# Train the Logistic Regression model on the unscaled data and print the model score\nfrom sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression()\nclassifier",
"_____no_output_____"
],
[
"classifier.fit(X_train_dummies, y_train)",
"C:\\Users\\19193\\anaconda3\\lib\\site-packages\\sklearn\\linear_model\\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression\n n_iter_i = _check_optimize_result(\n"
],
[
"# Train a Random Forest Classifier model and print the model score\n#Import Random Forest Model\nfrom sklearn.ensemble import RandomForestClassifier\n\n#Create a Gaussian Classifier\nclf=RandomForestClassifier(n_estimators=100)\n\n#Train the model using the training sets y_pred=clf.predict(X_test)\nclf.fit(X_train_dummies,y_train)\n\ny_pred=clf.predict(X_test_dummies)\nprint(f'Training Score: {clf.score(X_train_dummies, y_train)}')\nprint(f'Testing Score: {clf.score(X_test_dummies, y_test)}')",
"Training Score: 1.0\nTesting Score: 0.5950659293917482\n"
],
[
"from sklearn import metrics\n# Model Accuracy, how often is the classifier correct?\nprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))",
"Accuracy: 0.6465333900467886\n"
],
[
"# Scale the data\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler().fit(X_train_dummies)\nX_train_scaled = scaler.transform(X_train_dummies)\nX_test_scaled = scaler.transform(X_test_dummies)",
"_____no_output_____"
],
[
"# Train the Logistic Regression model on the scaled data and print the model score\nclf = LogisticRegression().fit(X_train_scaled, y_train)\nprint(f'Training Score: {clf.score(X_train_scaled, y_train)}')\nprint(f'Testing Score: {clf.score(X_test_scaled, y_test)}')",
"Training Score: 0.713136288998358\nTesting Score: 0.560187154402382\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb12e730fec29946d41f80f6be9f27a46efa083
| 62,279 |
ipynb
|
Jupyter Notebook
|
nbs/00_export.ipynb
|
isabella232/nbdev
|
682ef97d86a451d24ff7ec67d4624ddf1c8c9820
|
[
"Apache-2.0"
] | null | null | null |
nbs/00_export.ipynb
|
isabella232/nbdev
|
682ef97d86a451d24ff7ec67d4624ddf1c8c9820
|
[
"Apache-2.0"
] | 1 |
2021-02-23T22:53:25.000Z
|
2021-02-23T22:53:25.000Z
|
nbs/00_export.ipynb
|
isabella232/nbdev
|
682ef97d86a451d24ff7ec67d4624ddf1c8c9820
|
[
"Apache-2.0"
] | null | null | null | 35.628719 | 490 | 0.552369 |
[
[
[
"#hide\n#default_exp export\n#default_cls_lvl 3\nfrom nbdev.showdoc import show_doc",
"_____no_output_____"
],
[
"#export\nfrom nbdev.imports import *\nfrom fastcore.script import *\nfrom fastcore.foundation import *\nfrom keyword import iskeyword\nimport nbformat",
"_____no_output_____"
]
],
[
[
"# Export to modules\n\n> The functions that transform notebooks in a library",
"_____no_output_____"
],
[
"The most important function defined in this module is `notebooks2script`, so you may want to jump to it before scrolling though the rest, which explain the details behind the scenes of the conversion from notebooks to library. The main things to remember are:\n- put `# export` on each cell you want exported\n- put `# exports` on each cell you want exported with the source code shown in the docs \n- put `# exporti` on each cell you want exported without it being added to `__all__`, and without it showing up in the docs.\n- one cell should contain `# default_exp` followed by the name of the module (with points for submodules and without the py extension) everything should be exported in (if one specific cell needs to be exported in a different module, just indicate it after `#export`: `#export special.module`)\n- all left members of an equality, functions and classes will be exported and variables that are not private will be put in the `__all__` automatically\n- to add something to `__all__` if it's not picked automatically, write an exported cell with something like `#add2all \"my_name\"`",
"_____no_output_____"
],
[
"## Basic foundations",
"_____no_output_____"
],
[
"For bootstrapping `nbdev` we have a few basic foundations defined in <code>imports</code>, which we test a show here. First, a simple config file class, `Config` that read the content of your `settings.ini` file and make it accessible:",
"_____no_output_____"
]
],
[
[
"show_doc(Config, title_level=3)",
"_____no_output_____"
],
[
"create_config(\"github\", \"nbdev\", user='fastai', path='..', tst_flags='tst', cfg_name='test_settings.ini')\ncfg = Config(cfg_name='test_settings.ini')\ntest_eq(cfg.lib_name, 'nbdev')\ntest_eq(cfg.git_url, \"https://github.com/fastai/nbdev/tree/master/\")\n# test_eq(cfg.path(\"lib_path\"), Path.cwd().parent/'nbdev')\n# test_eq(cfg.path(\"nbs_path\"), Path.cwd())\n# test_eq(cfg.path(\"doc_path\"), Path.cwd().parent/'docs')\ntest_eq(cfg.custom_sidebar, 'False')",
"_____no_output_____"
]
],
[
[
"## Reading a notebook",
"_____no_output_____"
],
[
"### What's a notebook?",
"_____no_output_____"
],
[
"A jupyter notebook is a json file behind the scenes. We can just read it with the json module, which will return a nested dictionary of dictionaries/lists of dictionaries, but there are some small differences between reading the json and using the tools from `nbformat` so we'll use this one.",
"_____no_output_____"
]
],
[
[
"#export\ndef read_nb(fname):\n \"Read the notebook in `fname`.\"\n with open(Path(fname),'r', encoding='utf8') as f: return nbformat.reads(f.read(), as_version=4)",
"_____no_output_____"
]
],
[
[
"`fname` can be a string or a pathlib object.",
"_____no_output_____"
]
],
[
[
"test_nb = read_nb('00_export.ipynb')",
"_____no_output_____"
]
],
[
[
"The root has four keys: `cells` contains the cells of the notebook, `metadata` some stuff around the version of python used to execute the notebook, `nbformat` and `nbformat_minor` the version of nbformat. ",
"_____no_output_____"
]
],
[
[
"test_nb.keys()",
"_____no_output_____"
],
[
"test_nb['metadata']",
"_____no_output_____"
],
[
"f\"{test_nb['nbformat']}.{test_nb['nbformat_minor']}\"",
"_____no_output_____"
]
],
[
[
"The cells key then contains a list of cells. Each one is a new dictionary that contains entries like the type (code or markdown), the source (what is written in the cell) and the output (for code cells).",
"_____no_output_____"
]
],
[
[
"test_nb['cells'][0]",
"_____no_output_____"
]
],
[
[
"### Finding patterns",
"_____no_output_____"
],
[
"The following functions are used to catch the flags used in the code cells.",
"_____no_output_____"
]
],
[
[
"#export\ndef check_re(cell, pat, code_only=True):\n \"Check if `cell` contains a line with regex `pat`\"\n if code_only and cell['cell_type'] != 'code': return\n if isinstance(pat, str): pat = re.compile(pat, re.IGNORECASE | re.MULTILINE)\n return pat.search(cell['source'])",
"_____no_output_____"
]
],
[
[
"`pat` can be a string or a compiled regex. If `code_only=True`, this function ignores non-code cells, such as markdown.",
"_____no_output_____"
]
],
[
[
"cell = test_nb['cells'][1].copy()\nassert check_re(cell, '#export') is not None\nassert check_re(cell, re.compile('#export')) is not None\nassert check_re(cell, '# bla') is None\ncell['cell_type'] = 'markdown'\nassert check_re(cell, '#export') is None\nassert check_re(cell, '#export', code_only=False) is not None",
"_____no_output_____"
],
[
"#export\ndef check_re_multi(cell, pats, code_only=True):\n \"Check if `cell` contains a line matching any regex in `pats`, returning the first match found\"\n return L(pats).map_first(partial(check_re, cell, code_only=code_only))",
"_____no_output_____"
],
[
"cell = test_nb['cells'][0].copy()\ncell['source'] = \"a b c\"\nassert check_re(cell, 'a') is not None\nassert check_re(cell, 'd') is None\n# show that searching with patterns ['d','b','a'] will match 'b'\n# i.e. 'd' is not found and we don't search for 'a'\nassert check_re_multi(cell, ['d','b','a']).span() == (2,3)",
"_____no_output_____"
],
[
"#export\ndef _mk_flag_re(body, n_params, comment):\n \"Compiles a regex for finding nbdev flags\"\n assert body!=True, 'magics no longer supported'\n prefix = r\"\\s*\\#\\s*\"\n param_group = \"\"\n if n_params == -1: param_group = r\"[ \\t]+(.+)\"\n if n_params == 1: param_group = r\"[ \\t]+(\\S+)\"\n if n_params == (0,1): param_group = r\"(?:[ \\t]+(\\S+))?\"\n return re.compile(rf\"\"\"\n# {comment}:\n^ # beginning of line (since re.MULTILINE is passed)\n{prefix}\n{body}\n{param_group}\n[ \\t]* # any number of spaces and/or tabs\n$ # end of line (since re.MULTILINE is passed)\n\"\"\", re.MULTILINE | re.VERBOSE)",
"_____no_output_____"
]
],
[
[
"This function returns a regex object that can be used to find nbdev flags in multiline text\n- `body` regex fragment to match one or more flags,\n- `n_params` number of flag parameters to match and catch (-1 for any number of params; `(0,1)` for 0 for 1 params),\n- `comment` explains what the compiled regex should do.",
"_____no_output_____"
]
],
[
[
"#hide\nre_blank_test = _mk_flag_re('export[si]?', 0, \"test\")\nre_mod_test = _mk_flag_re('export[si]?', 1, \"test\")\nre_opt_test = _mk_flag_re('export[si]?', (0,1), \"test\")\nfor f in ['export', 'exports', 'exporti']:\n cell = nbformat.v4.new_code_cell(f'#{f} \\n some code')\n assert check_re(cell, re_blank_test) is not None\n assert check_re(cell, re_mod_test) is None\n assert check_re(cell, re_opt_test) is not None\n test_eq(check_re(cell, re_opt_test).groups()[0], None)\n cell.source = f'#{f} special.module \\n some code'\n assert check_re(cell, re_blank_test) is None\n assert check_re(cell, re_mod_test) is not None\n test_eq(check_re(cell, re_mod_test).groups()[0], 'special.module')\n assert check_re(cell, re_opt_test) is not None\n test_eq(check_re(cell, re_opt_test).groups()[0], 'special.module')",
"_____no_output_____"
],
[
"#export\n_re_blank_export = _mk_flag_re(\"export[si]?\", 0,\n \"Matches any line with #export, #exports or #exporti without any module name\")",
"_____no_output_____"
],
[
"#export\n_re_mod_export = _mk_flag_re(\"export[si]?\", 1,\n \"Matches any line with #export, #exports or #exporti with a module name and catches it in group 1\")",
"_____no_output_____"
],
[
"#export\n_re_internal_export = _mk_flag_re(\"exporti\", (0,1),\n \"Matches any line with #exporti with or without a module name\")",
"_____no_output_____"
],
[
"#exporti\ndef _is_external_export(tst):\n \"Check if a cell is an external or internal export. `tst` is an re match\"\n return _re_internal_export.search(tst.string) is None",
"_____no_output_____"
],
[
"#export\ndef is_export(cell, default):\n \"Check if `cell` is to be exported and returns the name of the module to export it if provided\"\n tst = check_re(cell, _re_blank_export)\n if tst:\n if default is None:\n print(f\"No export destination, ignored:\\n{cell['source']}\")\n return default, _is_external_export(tst)\n tst = check_re(cell, _re_mod_export)\n if tst: return os.path.sep.join(tst.groups()[0].split('.')), _is_external_export(tst)\n else: return None",
"_____no_output_____"
]
],
[
[
"`is_export` returns;\n- a tuple of (\"module name\", \"external boolean\" (`False` for an internal export)) if `cell` is to be exported or \n- `None` if `cell` will not be exported.\n\nThe cells to export are marked with `#export`/`#exporti`/`#exports`, potentially with a module name where we want it exported. The default module is given in a cell of the form `#default_exp bla` inside the notebook (usually at the top), though in this function, it needs the be passed (the final script will read the whole notebook to find it).\n- a cell marked with `#export`/`#exporti`/`#exports` will be exported to the default module\n- an exported cell marked with `special.module` appended will be exported in `special.module` (located in `lib_name/special/module.py`)\n- a cell marked with `#export` will have its signature added to the documentation\n- a cell marked with `#exports` will additionally have its source code added to the documentation\n- a cell marked with `#exporti` will not show up in the documentation, and will also not be added to `__all__`.",
"_____no_output_____"
]
],
[
[
"cell = test_nb['cells'][1].copy()\ntest_eq(is_export(cell, 'export'), ('export', True))\ncell['source'] = \"# exports\"\ntest_eq(is_export(cell, 'export'), ('export', True))\ncell['source'] = \"# exporti\"\ntest_eq(is_export(cell, 'export'), ('export', False))\ncell['source'] = \"# export mod\"\ntest_eq(is_export(cell, 'export'), ('mod', True))",
"_____no_output_____"
],
[
"#hide\ncell['source'] = \"# export mod.file\"\ntest_eq(is_export(cell, 'export'), (f'mod{os.path.sep}file', True))\ncell['source'] = \"# exporti mod.file\"\ntest_eq(is_export(cell, 'export'), (f'mod{os.path.sep}file', False))\ncell['source'] = \"# expt mod.file\"\nassert is_export(cell, 'export') is None\ncell['source'] = \"# exportmod.file\"\nassert is_export(cell, 'export') is None\ncell['source'] = \"# exportsmod.file\"\nassert is_export(cell, 'export') is None\ncell['source'] = \"# exporti mod file\"\nassert is_export(cell, 'export') is None",
"_____no_output_____"
],
[
"#export\n_re_default_exp = _mk_flag_re('default_exp', 1, \"Matches any line with #default_exp with a module name\")",
"_____no_output_____"
],
[
"#export\ndef find_default_export(cells):\n \"Find in `cells` the default export module.\"\n res = L(cells).map_first(check_re, pat=_re_default_exp)\n return res.groups()[0] if res else None",
"_____no_output_____"
]
],
[
[
"Stops at the first cell containing `# default_exp` (if there are several) and returns the value behind. Returns `None` if there are no cell with that code.",
"_____no_output_____"
]
],
[
[
"test_eq(find_default_export(test_nb['cells']), 'export')\nassert find_default_export(test_nb['cells'][2:]) is None",
"_____no_output_____"
],
[
"#hide\nmods = [f'mod{i}' for i in range(3)]\ncells = [{'cell_type': 'code', 'source': f'#default_exp {mod}'} for mod in mods]\nfor i, mod in enumerate(mods): test_eq(mod, find_default_export(cells[i:]))",
"_____no_output_____"
]
],
[
[
"### Listing all exported objects",
"_____no_output_____"
],
[
"The following functions make a list of everything that is exported to prepare a proper `__all__` for our exported module.",
"_____no_output_____"
]
],
[
[
"#export\n_re_patch_func = re.compile(r\"\"\"\n# Catches any function decorated with @patch, its name in group 1 and the patched class in group 2\n@patch # At any place in the cell, something that begins with @patch\n(?:\\s*@.*)* # Any other decorator applied to the function\n\\s*def # Any number of whitespace (including a new line probably) followed by def\n\\s+ # One whitespace or more\n([^\\(\\s]+) # Catch a group composed of anything but whitespace or an opening parenthesis (name of the function)\n\\s*\\( # Any number of whitespace followed by an opening parenthesis\n[^:]* # Any number of character different of : (the name of the first arg that is type-annotated)\n:\\s* # A column followed by any number of whitespace\n(?: # Non-catching group with either\n([^,\\s\\(\\)]*) # a group composed of anything but a comma, a parenthesis or whitespace (name of the class)\n| # or\n(\\([^\\)]*\\))) # a group composed of something between parenthesis (tuple of classes)\n\\s* # Any number of whitespace\n(?:,|\\)) # Non-catching group with either a comma or a closing parenthesis\n\"\"\", re.VERBOSE)",
"_____no_output_____"
],
[
"tst = _re_patch_func.search(\"\"\"\n@patch\n@log_args(a=1)\ndef func(obj:Class):\"\"\")\ntst, tst.groups()",
"_____no_output_____"
],
[
"#hide\ntst = _re_patch_func.search(\"\"\"\n@patch\ndef func(obj:Class):\"\"\")\ntest_eq(tst.groups(), (\"func\", \"Class\", None))\ntst = _re_patch_func.search(\"\"\"\n@patch\ndef func (obj:Class, a)\"\"\")\ntest_eq(tst.groups(), (\"func\", \"Class\", None))\ntst = _re_patch_func.search(\"\"\"\n@patch\ndef func (obj:(Class1, Class2), a)\"\"\")\ntest_eq(tst.groups(), (\"func\", None, \"(Class1, Class2)\"))\ntst = _re_patch_func.search(\"\"\"\n@patch\ndef func (obj:(Class1, Class2), a:int)->int:\"\"\")\ntest_eq(tst.groups(), (\"func\", None, \"(Class1, Class2)\"))\ntst = _re_patch_func.search(\"\"\"\n@patch\n@log_args(but='a,b')\n@funcs_kwargs\ndef func (obj:(Class1, Class2), a:int)->int:\"\"\")\ntest_eq(tst.groups(), (\"func\", None, \"(Class1, Class2)\"))\ntst = _re_patch_func.search(\"\"\"\n@patch\n@contextmanager\ndef func (obj:Class, a:int)->int:\"\"\")\ntest_eq(tst.groups(), (\"func\", \"Class\", None))",
"_____no_output_____"
],
[
"#export\n_re_typedispatch_func = re.compile(r\"\"\"\n# Catches any function decorated with @typedispatch\n(@typedispatch # At any place in the cell, catch a group with something that begins with @typedispatch\n\\s*def # Any number of whitespace (including a new line probably) followed by def\n\\s+ # One whitespace or more\n[^\\(]+ # Anything but whitespace or an opening parenthesis (name of the function)\n\\s*\\( # Any number of whitespace followed by an opening parenthesis\n[^\\)]* # Any number of character different of )\n\\)[\\s\\S]*:) # A closing parenthesis followed by any number of characters and whitespace (type annotation) and :\n\"\"\", re.VERBOSE)",
"_____no_output_____"
],
[
"#hide\nassert _re_typedispatch_func.search(\"@typedispatch\\ndef func(a, b):\").groups() == ('@typedispatch\\ndef func(a, b):',)\nassert (_re_typedispatch_func.search(\"@typedispatch\\ndef func(a:str, b:bool)->int:\").groups() ==\n ('@typedispatch\\ndef func(a:str, b:bool)->int:',))",
"_____no_output_____"
],
[
"#export\n_re_class_func_def = re.compile(r\"\"\"\n# Catches any 0-indented function or class definition with its name in group 1\n^ # Beginning of a line (since re.MULTILINE is passed)\n(?:async\\sdef|def|class) # Non-catching group for def or class\n\\s+ # One whitespace or more\n([^\\(\\s]+) # Catching group with any character except an opening parenthesis or a whitespace (name)\n\\s* # Any number of whitespace\n(?:\\(|:) # Non-catching group with either an opening parenthesis or a : (classes don't need ())\n\"\"\", re.MULTILINE | re.VERBOSE)",
"_____no_output_____"
],
[
"#hide\ntest_eq(_re_class_func_def.search(\"class Class:\").groups(), ('Class',))\ntest_eq(_re_class_func_def.search(\"def func(a, b):\").groups(), ('func',))\ntest_eq(_re_class_func_def.search(\"def func(a:str, b:bool)->int:\").groups(), ('func',))\ntest_eq(_re_class_func_def.search(\"async def func(a, b):\").groups(), ('func',))",
"_____no_output_____"
],
[
"#export\n_re_obj_def = re.compile(r\"\"\"\n# Catches any 0-indented object definition (bla = thing) with its name in group 1\n^ # Beginning of a line (since re.MULTILINE is passed)\n([_a-zA-Z]+[a-zA-Z0-9_\\.]*) # Catch a group which is a valid python variable name\n\\s* # Any number of whitespace\n(?::\\s*\\S.*|)= # Non-catching group of either a colon followed by a type annotation, or nothing; followed by an =\n\"\"\", re.MULTILINE | re.VERBOSE)",
"_____no_output_____"
],
[
"#hide\ntest_eq(_re_obj_def.search(\"a = 1\").groups(), ('a',))\ntest_eq(_re_obj_def.search(\"a.b = 1\").groups(), ('a.b',))\ntest_eq(_re_obj_def.search(\"_aA1=1\").groups(), ('_aA1',))\ntest_eq(_re_obj_def.search(\"a : int =1\").groups(), ('a',))\ntest_eq(_re_obj_def.search(\"a:f(':=')=1\").groups(), ('a',))\nassert _re_obj_def.search(\"@abc=2\") is None\nassert _re_obj_def.search(\"a a=2\") is None",
"_____no_output_____"
],
[
"#export\ndef _not_private(n):\n for t in n.split('.'):\n if (t.startswith('_') and not t.startswith('__')) or t.startswith('@'): return False\n return '\\\\' not in t and '^' not in t and '[' not in t and t != 'else'\n\ndef export_names(code, func_only=False):\n \"Find the names of the objects, functions or classes defined in `code` that are exported.\"\n #Format monkey-patches with @patch\n def _f(gps):\n nm, cls, t = gps.groups()\n if cls is not None: return f\"def {cls}.{nm}():\"\n return '\\n'.join([f\"def {c}.{nm}():\" for c in re.split(', *', t[1:-1])])\n\n code = _re_typedispatch_func.sub('', code)\n code = _re_patch_func.sub(_f, code)\n names = _re_class_func_def.findall(code)\n if not func_only: names += _re_obj_def.findall(code)\n return [n for n in names if _not_private(n) and not iskeyword(n)]",
"_____no_output_____"
]
],
[
[
"This function only picks the zero-indented objects on the left side of an =, functions or classes (we don't want the class methods for instance) and excludes private names (that begin with `_`) but no dunder names. It only returns func and class names (not the objects) when `func_only=True`. \n\nTo work properly with fastai added python functionality, this function ignores function decorated with `@typedispatch` (since they are defined multiple times) and unwraps properly functions decorated with `@patch`.",
"_____no_output_____"
]
],
[
[
"test_eq(export_names(\"def my_func(x):\\n pass\\nclass MyClass():\"), [\"my_func\", \"MyClass\"])",
"_____no_output_____"
],
[
"#hide\n#Indented funcs are ignored (funcs inside a class)\ntest_eq(export_names(\" def my_func(x):\\n pass\\nclass MyClass():\"), [\"MyClass\"])\n\n#Private funcs are ignored, dunder are not\ntest_eq(export_names(\"def _my_func():\\n pass\\nclass MyClass():\"), [\"MyClass\"])\ntest_eq(export_names(\"__version__ = 1:\\n pass\\nclass MyClass():\"), [\"MyClass\", \"__version__\"])\n\n#trailing spaces\ntest_eq(export_names(\"def my_func ():\\n pass\\nclass MyClass():\"), [\"my_func\", \"MyClass\"])\n\n#class without parenthesis\ntest_eq(export_names(\"def my_func ():\\n pass\\nclass MyClass:\"), [\"my_func\", \"MyClass\"])\n\n#object and funcs\ntest_eq(export_names(\"def my_func ():\\n pass\\ndefault_bla=[]:\"), [\"my_func\", \"default_bla\"])\ntest_eq(export_names(\"def my_func ():\\n pass\\ndefault_bla=[]:\", func_only=True), [\"my_func\"])\n\n#Private objects are ignored\ntest_eq(export_names(\"def my_func ():\\n pass\\n_default_bla = []:\"), [\"my_func\"])\n\n#Objects with dots are privates if one part is private\ntest_eq(export_names(\"def my_func ():\\n pass\\ndefault.bla = []:\"), [\"my_func\", \"default.bla\"])\ntest_eq(export_names(\"def my_func ():\\n pass\\ndefault._bla = []:\"), [\"my_func\"])\n\n#Monkey-path with @patch are properly renamed\ntest_eq(export_names(\"@patch\\ndef my_func(x:Class):\\n pass\"), [\"Class.my_func\"])\ntest_eq(export_names(\"@patch\\ndef my_func(x:Class):\\n pass\", func_only=True), [\"Class.my_func\"])\ntest_eq(export_names(\"some code\\n@patch\\ndef my_func(x:Class, y):\\n pass\"), [\"Class.my_func\"])\ntest_eq(export_names(\"some code\\n@patch\\ndef my_func(x:(Class1,Class2), y):\\n pass\"), [\"Class1.my_func\", \"Class2.my_func\"])\n\n#Check delegates\ntest_eq(export_names(\"@delegates(keep=True)\\nclass someClass:\\n pass\"), [\"someClass\"])\n\n#Typedispatch decorated functions shouldn't be added\ntest_eq(export_names(\"@patch\\ndef my_func(x:Class):\\n pass\\n@typedispatch\\ndef func(x: TensorImage): pass\"), [\"Class.my_func\"])\n\n#try, except and other keywords should not be picked up (these can look like object def with type annotation)\ntest_eq(export_names(\"try:\\n a=1\\nexcept:\\n b=2\"), [])\ntest_eq(export_names(\"try:\\n this_might_work\\nexcept:\\n b=2\"), [])",
"_____no_output_____"
],
[
"#export\n_re_all_def = re.compile(r\"\"\"\n# Catches a cell with defines \\_all\\_ = [\\*\\*] and get that \\*\\* in group 1\n^_all_ # Beginning of line (since re.MULTILINE is passed)\n\\s*=\\s* # Any number of whitespace, =, any number of whitespace\n\\[ # Opening [\n([^\\n\\]]*) # Catching group with anything except a ] or newline\n\\] # Closing ]\n\"\"\", re.MULTILINE | re.VERBOSE)\n\n#Same with __all__\n_re__all__def = re.compile(r'^__all__\\s*=\\s*\\[([^\\]]*)\\]', re.MULTILINE)",
"_____no_output_____"
],
[
"#export\ndef extra_add(flags, code):\n \"Catch adds to `__all__` required by a cell with `_all_=`\"\n m = check_re({'source': code}, _re_all_def, False)\n if m:\n code = m.re.sub('#nbdev_' + 'comment \\g<0>', code)\n code = re.sub(r'([^\\n]|^)\\n*$', r'\\1', code)\n if not m: return [], code\n def clean_quotes(s):\n \"Return `s` enclosed in single quotes, removing double quotes if needed\"\n if s.startswith(\"'\") and s.endswith(\"'\"): return s\n if s.startswith('\"') and s.endswith('\"'): s = s[1:-1]\n return f\"'{s}'\"\n return [clean_quotes(s) for s in parse_line(m.group(1))], code",
"_____no_output_____"
]
],
[
[
"Sometimes objects are not picked to be automatically added to the `__all__` of the module so you will need to add them manually. To do so, create an exported cell with the following code `_all_ = [\"name\", \"name2\"]`",
"_____no_output_____"
]
],
[
[
"#hide\nfor code, expected in [\n ['_all_ = [\"func\", \"func1\", \"func2\"]', \n ([\"'func'\", \"'func1'\", \"'func2'\"],'#nbdev_comment _all_ = [\"func\", \"func1\", \"func2\"]')],\n ['_all_=[func, func1, func2]', \n ([\"'func'\", \"'func1'\", \"'func2'\"],'#nbdev_comment _all_=[func, func1, func2]')],\n [\"_all_ = ['func', 'func1', 'func2']\", \n ([\"'func'\", \"'func1'\", \"'func2'\"],\"#nbdev_comment _all_ = ['func', 'func1', 'func2']\")],\n ['_all_ = [\"func\", \"func1\" , \"func2\"]', \n ([\"'func'\", \"'func1'\", \"'func2'\"],'#nbdev_comment _all_ = [\"func\", \"func1\" , \"func2\"]')],\n [\"_all_ = ['func','func1', 'func2']\\n\", \n ([\"'func'\", \"'func1'\", \"'func2'\"],\"#nbdev_comment _all_ = ['func','func1', 'func2']\")],\n [\"_all_ = ['func']\\n_all_ = ['func1', 'func2']\\n\", \n ([\"'func'\"],\"#nbdev_comment _all_ = ['func']\\n#nbdev_comment _all_ = ['func1', 'func2']\")],\n ['code\\n\\n_all_ = [\"func\", \"func1\", \"func2\"]', \n ([\"'func'\", \"'func1'\", \"'func2'\"],'code\\n\\n#nbdev_comment _all_ = [\"func\", \"func1\", \"func2\"]')],\n ['code\\n\\n_all_ = [func]\\nmore code', \n ([\"'func'\"],'code\\n\\n#nbdev_comment _all_ = [func]\\nmore code')]]:\n test_eq(extra_add('', code), expected)\n \n# line breaks within the list of names means _all_ is ignored\ntest_eq(extra_add('', \"_all_ = ['func',\\n'func1', 'func2']\\n\"), ([],\"_all_ = ['func',\\n'func1', 'func2']\\n\"))",
"_____no_output_____"
],
[
"#export\n_re_from_future_import = re.compile(r\"^from[ \\t]+__future__[ \\t]+import.*$\", re.MULTILINE)\n\ndef _from_future_import(fname, flags, code, to_dict=None):\n \"Write `__future__` imports to `fname` and return `code` with `__future__` imports commented out\"\n from_future_imports = _re_from_future_import.findall(code)\n if from_future_imports: code = _re_from_future_import.sub('#nbdev' + '_comment \\g<0>', code)\n else: from_future_imports = _re_from_future_import.findall(flags)\n if not from_future_imports or to_dict is not None: return code\n with open(fname, 'r', encoding='utf8') as f: text = f.read()\n start = _re__all__def.search(text).start()\n with open(fname, 'w', encoding='utf8') as f:\n f.write('\\n'.join([text[:start], *from_future_imports, '\\n', text[start:]]))\n return code",
"_____no_output_____"
]
],
[
[
"If you need a `from __future__ import` in your library, you can export your cell with special comments:\n\n```python\n#export\nfrom __future__ import annotations\nclass ...\n```\n\nNotice that `#export` is after the `__future__` import. Because `__future__` imports must occur at the beginning of the file, nbdev allows `__future__` imports in the flags section of a cell.",
"_____no_output_____"
]
],
[
[
"#hide\ntxt = \"\"\"\n# AUTOHEADER ... File to edit: mod.ipynb (unless otherwise specified).\n\n__all__ = [my_file, MyClas]\n# Cell\ndef valid_code(): pass\"\"\"\nexpected_txt = \"\"\"\n# AUTOHEADER ... File to edit: mod.ipynb (unless otherwise specified).\n\n\nfrom __future__ import annotations \nfrom __future__ import generator_stop\n\n\n__all__ = [my_file, MyClas]\n# Cell\ndef valid_code(): pass\"\"\"\nflags=\"# export\"\ncode = \"\"\"\n# comment\nfrom __future__ import annotations \nvalid_code = False # but _from_future_import will work anyway\nfrom __future__ import generator_stop\n from __future__ import not_zero_indented\nvalid_code = True\n\"\"\"\nexpected_code = \"\"\"\n# comment\n#nbdev_comment from __future__ import annotations \nvalid_code = False # but _from_future_import will work anyway\n#nbdev_comment from __future__ import generator_stop\n from __future__ import not_zero_indented\nvalid_code = True\n\"\"\"",
"_____no_output_____"
],
[
"def _run_from_future_import_test():\n fname = 'test_from_future_import.txt'\n with open(fname, 'w', encoding='utf8') as f: f.write(txt)\n\n actual_code=_from_future_import(fname, flags, code, {})\n test_eq(expected_code, actual_code)\n with open(fname, 'r', encoding='utf8') as f: test_eq(f.read(), txt)\n\n actual_code=_from_future_import(fname, flags, code)\n test_eq(expected_code, actual_code)\n with open(fname, 'r', encoding='utf8') as f: test_eq(f.read(), expected_txt)\n\n os.remove(fname)\n\n_run_from_future_import_test()\n\nflags=\"\"\"from __future__ import annotations \nfrom __future__ import generator_stop\n#export\"\"\"\ncode = \"\"\nexpected_code = \"\"\nfname = 'test_from_future_import.txt'\n\n_run_from_future_import_test()",
"_____no_output_____"
],
[
"#export\ndef _add2all(fname, names, line_width=120):\n if len(names) == 0: return\n with open(fname, 'r', encoding='utf8') as f: text = f.read()\n tw = TextWrapper(width=120, initial_indent='', subsequent_indent=' '*11, break_long_words=False)\n re_all = _re__all__def.search(text)\n start,end = re_all.start(),re_all.end()\n text_all = tw.wrap(f\"{text[start:end-1]}{'' if text[end-2]=='[' else ', '}{', '.join(names)}]\")\n with open(fname, 'w', encoding='utf8') as f: f.write(text[:start] + '\\n'.join(text_all) + text[end:])",
"_____no_output_____"
],
[
"#hide\nfname = 'test_add.txt'\nwith open(fname, 'w', encoding='utf8') as f: f.write(\"Bla\\n__all__ = [my_file, MyClas]\\nBli\")\n_add2all(fname, ['new_function'])\nwith open(fname, 'r', encoding='utf8') as f: \n test_eq(f.read(), \"Bla\\n__all__ = [my_file, MyClas, new_function]\\nBli\")\n_add2all(fname, [f'new_function{i}' for i in range(10)])\nwith open(fname, 'r', encoding='utf8') as f: \n test_eq(f.read(), \"\"\"Bla\n__all__ = [my_file, MyClas, new_function, new_function0, new_function1, new_function2, new_function3, new_function4,\n new_function5, new_function6, new_function7, new_function8, new_function9]\nBli\"\"\")\nos.remove(fname)",
"_____no_output_____"
],
[
"#export\ndef relative_import(name, fname):\n \"Convert a module `name` to a name relative to `fname`\"\n mods = name.split('.')\n splits = str(fname).split(os.path.sep)\n if mods[0] not in splits: return name\n i=len(splits)-1\n while i>0 and splits[i] != mods[0]: i-=1\n splits = splits[i:]\n while len(mods)>0 and splits[0] == mods[0]: splits,mods = splits[1:],mods[1:]\n return '.' * (len(splits)) + '.'.join(mods)",
"_____no_output_____"
]
],
[
[
"When we say from \n``` python\nfrom lib_name.module.submodule import bla\n``` \nin a notebook, it needs to be converted to something like \n```\nfrom .module.submodule import bla\n```\nor \n```from .submodule import bla``` \ndepending on where we are. This function deals with those imports renaming.\n\nNote that import of the form\n```python\nimport lib_name.module\n```\nare left as is as the syntax `import module` does not work for relative imports.",
"_____no_output_____"
]
],
[
[
"test_eq(relative_import('nbdev.core', Path.cwd()/'nbdev'/'data.py'), '.core')\ntest_eq(relative_import('nbdev.core', Path('nbdev')/'vision'/'data.py'), '..core')\ntest_eq(relative_import('nbdev.vision.transform', Path('nbdev')/'vision'/'data.py'), '.transform')\ntest_eq(relative_import('nbdev.notebook.core', Path('nbdev')/'data'/'external.py'), '..notebook.core')\ntest_eq(relative_import('nbdev.vision', Path('nbdev')/'vision'/'learner.py'), '.')",
"_____no_output_____"
],
[
"#export\n_re_import = ReLibName(r'^(\\s*)from (LIB_NAME\\.\\S*) import (.*)$')",
"_____no_output_____"
],
[
"#export\ndef _deal_import(code_lines, fname):\n def _replace(m):\n sp,mod,obj = m.groups()\n return f\"{sp}from {relative_import(mod, fname)} import {obj}\"\n return [_re_import.re.sub(_replace,line) for line in code_lines]",
"_____no_output_____"
],
[
"#hide\nlines = [\"from nbdev.core import *\", \n \"nothing to see\", \n \" from nbdev.vision import bla1, bla2\", \n \"from nbdev.vision import models\",\n \"import nbdev.vision\"]\ntest_eq(_deal_import(lines, Path.cwd()/'nbdev'/'data.py'), [\n \"from .core import *\", \n \"nothing to see\", \n \" from .vision import bla1, bla2\", \n \"from .vision import models\",\n \"import nbdev.vision\"\n])",
"_____no_output_____"
]
],
[
[
"## Create the library",
"_____no_output_____"
],
[
"### Saving an index",
"_____no_output_____"
],
[
"To be able to build back a correspondence between functions and the notebooks they are defined in, we need to store an index. It's done in the private module <code>_nbdev</code> inside your library, and the following function are used to define it.",
"_____no_output_____"
]
],
[
[
"#export\n_re_index_custom = re.compile(r'def custom_doc_links\\(name\\):(.*)$', re.DOTALL)",
"_____no_output_____"
],
[
"#export\ndef reset_nbdev_module():\n \"Create a skeleton for <code>_nbdev</code>\"\n fname = Config().path(\"lib_path\")/'_nbdev.py'\n fname.parent.mkdir(parents=True, exist_ok=True)\n sep = '\\n'* (int(Config().get('cell_spacing', '1'))+1)\n if fname.is_file():\n with open(fname, 'r') as f: search = _re_index_custom.search(f.read())\n else: search = None\n prev_code = search.groups()[0] if search is not None else ' return None\\n'\n with open(fname, 'w') as f:\n f.write(f\"# AUTOGENERATED BY NBDEV! DO NOT EDIT!\")\n f.write('\\n\\n__all__ = [\"index\", \"modules\", \"custom_doc_links\", \"git_url\"]')\n f.write('\\n\\nindex = {}')\n f.write('\\n\\nmodules = []')\n f.write(f'\\n\\ndoc_url = \"{Config().doc_host}{Config().doc_baseurl}\"')\n f.write(f'\\n\\ngit_url = \"{Config().git_url}\"')\n f.write(f'{sep}def custom_doc_links(name):{prev_code}')",
"_____no_output_____"
],
[
"#export\nclass _EmptyModule():\n def __init__(self):\n self.index,self.modules = {},[]\n self.doc_url,self.git_url = f\"{Config().doc_host}{Config().doc_baseurl}\",Config().git_url\n\n def custom_doc_links(self, name): return None",
"_____no_output_____"
],
[
"#export\ndef get_nbdev_module():\n \"Reads <code>_nbdev</code>\"\n try:\n spec = importlib.util.spec_from_file_location(f\"{Config().lib_name}._nbdev\", Config().path(\"lib_path\")/'_nbdev.py')\n mod = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(mod)\n return mod\n except: return _EmptyModule()",
"_____no_output_____"
],
[
"#export\n_re_index_idx = re.compile(r'index\\s*=\\s*{[^}]*}')\n_re_index_mod = re.compile(r'modules\\s*=\\s*\\[[^\\]]*\\]')",
"_____no_output_____"
],
[
"#export\ndef save_nbdev_module(mod):\n \"Save `mod` inside <code>_nbdev</code>\"\n fname = Config().path(\"lib_path\")/'_nbdev.py'\n with open(fname, 'r') as f: code = f.read()\n t = r',\\n '.join([f'\"{k}\": \"{v}\"' for k,v in mod.index.items()])\n code = _re_index_idx.sub(\"index = {\"+ t +\"}\", code)\n t = r',\\n '.join(['\"' + f.replace('\\\\','/') + '\"' for f in mod.modules])\n code = _re_index_mod.sub(f\"modules = [{t}]\", code)\n with open(fname, 'w') as f: f.write(code)",
"_____no_output_____"
],
[
"#hide\nind,ind_bak = Config().path(\"lib_path\")/'_nbdev.py',Config().path(\"lib_path\")/'_nbdev.bak'\nif ind.exists(): shutil.move(ind, ind_bak)\ntry:\n reset_nbdev_module()\n mod = get_nbdev_module()\n test_eq(mod.index, {})\n test_eq(mod.modules, [])\n\n mod.index = {'foo':'bar'}\n mod.modules.append('lala.bla')\n save_nbdev_module(mod)\n\n mod = get_nbdev_module()\n test_eq(mod.index, {'foo':'bar'})\n test_eq(mod.modules, ['lala.bla'])\nfinally:\n if ind_bak.exists(): shutil.move(ind_bak, ind)",
"_____no_output_____"
]
],
[
[
"### Create the modules",
"_____no_output_____"
]
],
[
[
"#export\ndef split_flags_and_code(cell, return_type=list):\n \"Splits the `source` of a cell into 2 parts and returns (flags, code)\"\n code_lines = cell['source'].split('\\n')\n split_pos = 0 if code_lines[0].strip().startswith('#') else -1\n for i, line in enumerate(code_lines):\n if not line.startswith('#') and line.strip() and not _re_from_future_import.match(line): break\n split_pos+=1\n res = code_lines[:split_pos], code_lines[split_pos:]\n if return_type is list: return res\n return tuple('\\n'.join(r) for r in res)",
"_____no_output_____"
]
],
[
[
"`return_type` tells us if the tuple returned will contain `list`s of lines or `str`ings with line breaks. \n\nWe treat the first comment line as a flag",
"_____no_output_____"
],
[
"<img alt=\"split_flags_and_code example\" width=\"450\" align=\"left\" src=\"images/split_flags_and_code.png\" />",
"_____no_output_____"
]
],
[
[
"def _test_split_flags_and_code(expected_flags, expected_code):\n cell = nbformat.v4.new_code_cell('\\n'.join(expected_flags + expected_code))\n test_eq((expected_flags, expected_code), split_flags_and_code(cell))\n expected=('\\n'.join(expected_flags), '\\n'.join(expected_code))\n test_eq(expected, split_flags_and_code(cell, str))\n \n_test_split_flags_and_code([\n '#export'],\n ['# TODO: write this function',\n 'def func(x): pass'])",
"_____no_output_____"
],
[
"#export\ndef create_mod_file(fname, nb_path, bare=False):\n \"Create a module file for `fname`.\"\n bare = str(Config().get('bare', bare)) == 'True'\n fname.parent.mkdir(parents=True, exist_ok=True)\n file_path = os.path.relpath(nb_path, Config().config_file.parent).replace('\\\\', '/')\n with open(fname, 'w') as f:\n if not bare: f.write(f\"# AUTOGENERATED! DO NOT EDIT! File to edit: {file_path} (unless otherwise specified).\")\n f.write('\\n\\n__all__ = []')",
"_____no_output_____"
]
],
[
[
"A new module filename is created each time a notebook has a cell marked with `#default_exp`. In your collection of notebooks, you should only have one notebook that creates a given module since they are re-created each time you do a library build (to ensure the library is clean). Note that any file you create manually will never be overwritten (unless it has the same name as one of the modules defined in a `#default_exp` cell) so you are responsible to clean up those yourself.\n\n`fname` is the notebook that contained the `#default_exp` cell.",
"_____no_output_____"
]
],
[
[
"#export\ndef create_mod_files(files, to_dict=False, bare=False):\n \"Create mod files for default exports found in `files`\"\n modules = []\n for f in files:\n fname = Path(f)\n nb = read_nb(fname)\n default = find_default_export(nb['cells'])\n if default is not None:\n default = os.path.sep.join(default.split('.'))\n modules.append(default)\n if not to_dict:\n create_mod_file(Config().path(\"lib_path\")/f'{default}.py', Config().path(\"nbs_path\")/f'{fname}', bare=bare)\n return modules",
"_____no_output_____"
]
],
[
[
"Create module files for all `#default_export` flags found in `files` and return a list containing the names of modules created. \n\nNote: The number if modules returned will be less that the number of files passed in if files do not `#default_export`.\n\nBy creating all module files before calling `_notebook2script`, the order of execution no longer matters - so you can now export to a notebook that is run \"later\".\n\nYou might still have problems when\n- converting a subset of notebooks or\n- exporting to a module that does not have a `#default_export` yet\n\nin which case `_notebook2script` will print warnings like;\n```\nWarning: Exporting to \"core.py\" but this module is not part of this build\n```\n\nIf you see a warning like this\n- and the module file (e.g. \"core.py\") does not exist, you'll see a `FileNotFoundError`\n- if the module file exists, the exported cell will be written - even if the exported cell is already in the module file",
"_____no_output_____"
]
],
[
[
"#export\ndef _notebook2script(fname, modules, silent=False, to_dict=None, bare=False):\n \"Finds cells starting with `#export` and puts them into a module created by `create_mod_files`\"\n bare = str(Config().get('bare', bare)) == 'True'\n if os.environ.get('IN_TEST',0): return # don't export if running tests\n sep = '\\n'* (int(Config().get('cell_spacing', '1'))+1)\n fname = Path(fname)\n nb = read_nb(fname)\n default = find_default_export(nb['cells'])\n if default is not None:\n default = os.path.sep.join(default.split('.'))\n mod = get_nbdev_module()\n exports = [is_export(c, default) for c in nb['cells']]\n cells = [(i,c,e) for i,(c,e) in enumerate(zip(nb['cells'],exports)) if e is not None]\n for i,c,(e,a) in cells:\n if e not in modules: print(f'Warning: Exporting to \"{e}.py\" but this module is not part of this build')\n fname_out = Config().path(\"lib_path\")/f'{e}.py'\n if bare: orig = \"\\n\"\n else: orig = (f'# {\"\" if a else \"Internal \"}C' if e==default else f'# Comes from {fname.name}, c') + 'ell\\n'\n flag_lines,code_lines = split_flags_and_code(c)\n code_lines = _deal_import(code_lines, fname_out)\n code = sep + orig + '\\n'.join(code_lines)\n names = export_names(code)\n flags = '\\n'.join(flag_lines)\n extra,code = extra_add(flags, code)\n code = _from_future_import(fname_out, flags, code, to_dict)\n if a:\n if to_dict is None: _add2all(fname_out, [f\"'{f}'\" for f in names if '.' not in f and len(f) > 0] + extra)\n mod.index.update({f: fname.name for f in names})\n code = re.sub(r' +$', '', code, flags=re.MULTILINE)\n if code != sep + orig[:-1]:\n if to_dict is not None: to_dict[e].append((i, fname, code))\n else:\n with open(fname_out, 'a', encoding='utf8') as f: f.write(code)\n if f'{e}.py' not in mod.modules: mod.modules.append(f'{e}.py')\n save_nbdev_module(mod)\n\n if not silent: print(f\"Converted {fname.name}.\")\n return to_dict",
"_____no_output_____"
],
[
"#hide\nif not os.environ.get('IN_TEST',0):\n modules = create_mod_files(glob.glob('00_export.ipynb'))\n _notebook2script('00_export.ipynb', modules)",
"Converted 00_export.ipynb.\n"
],
[
"#hide\nwith open(Config().path(\"lib_path\")/('export.py')) as f: l = f.readline()\ntest_eq(l, '# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_export.ipynb (unless otherwise specified).\\n')",
"_____no_output_____"
],
[
"#export\ndef add_init(path):\n \"Add `__init__.py` in all subdirs of `path` containing python files if it's not there already\"\n for p,d,f in os.walk(path):\n for f_ in f:\n if f_.endswith('.py'):\n if not (Path(p)/'__init__.py').exists(): (Path(p)/'__init__.py').touch()\n break",
"_____no_output_____"
],
[
"with tempfile.TemporaryDirectory() as d:\n os.makedirs(Path(d)/'a', exist_ok=True)\n (Path(d)/'a'/'f.py').touch()\n os.makedirs(Path(d)/'a/b', exist_ok=True)\n (Path(d)/'a'/'b'/'f.py').touch()\n add_init(d)\n assert not (Path(d)/'__init__.py').exists()\n for e in [Path(d)/'a', Path(d)/'a/b']:\n assert (e/'__init__.py').exists()",
"_____no_output_____"
],
[
"#export\n_re_version = re.compile('^__version__\\s*=.*$', re.MULTILINE)",
"_____no_output_____"
],
[
"#export\ndef update_version():\n \"Add or update `__version__` in the main `__init__.py` of the library\"\n fname = Config().path(\"lib_path\")/'__init__.py'\n if not fname.exists(): fname.touch()\n version = f'__version__ = \"{Config().version}\"'\n with open(fname, 'r') as f: code = f.read()\n if _re_version.search(code) is None: code = version + \"\\n\" + code\n else: code = _re_version.sub(version, code)\n with open(fname, 'w') as f: f.write(code)",
"_____no_output_____"
],
[
"#export\n_re_baseurl = re.compile('^baseurl\\s*:.*$', re.MULTILINE)",
"_____no_output_____"
],
[
"#export\ndef update_baseurl():\n \"Add or update `baseurl` in `_config.yml` for the docs\"\n fname = Config().path(\"doc_path\")/'_config.yml'\n if not fname.exists(): return\n with open(fname, 'r') as f: code = f.read()\n if _re_baseurl.search(code) is None: code = code + f\"\\nbaseurl: {Config().doc_baseurl}\"\n else: code = _re_baseurl.sub(f\"baseurl: {Config().doc_baseurl}\", code)\n with open(fname, 'w') as f: f.write(code)",
"_____no_output_____"
],
[
"#export\ndef notebook2script(fname=None, silent=False, to_dict=False, bare=False):\n \"Convert notebooks matching `fname` to modules\"\n # initial checks\n if os.environ.get('IN_TEST',0): return # don't export if running tests\n if fname is None:\n reset_nbdev_module()\n update_version()\n update_baseurl()\n files = [f for f in Config().path(\"nbs_path\").glob('*.ipynb') if not f.name.startswith('_')]\n else: files = glob.glob(fname)\n d = collections.defaultdict(list) if to_dict else None\n modules = create_mod_files(files, to_dict, bare=bare)\n for f in sorted(files): d = _notebook2script(f, modules, silent=silent, to_dict=d, bare=bare)\n if to_dict: return d\n else: add_init(Config().path(\"lib_path\"))",
"_____no_output_____"
]
],
[
[
"Finds cells starting with `#export` and puts them into the appropriate module. If `fname` is not specified, this will convert all notebook not beginning with an underscore in the `nb_folder` defined in `setting.ini`. Otherwise `fname` can be a single filename or a glob expression.\n\n`silent` makes the command not print any statement and `to_dict` is used internally to convert the library to a dictionary. ",
"_____no_output_____"
]
],
[
[
"#export\nclass DocsTestClass:\n \"for tests only\"\n def test(): pass",
"_____no_output_____"
],
[
"#hide\n#exporti\n#for tests only\ndef update_lib_with_exporti_testfn(): pass",
"_____no_output_____"
]
],
[
[
"## Export -",
"_____no_output_____"
]
],
[
[
"#hide\nnotebook2script()",
"Converted 00_export.ipynb.\nConverted 01_sync.ipynb.\nConverted 02_showdoc.ipynb.\nConverted 03_export2html.ipynb.\nConverted 04_test.ipynb.\nConverted 05_merge.ipynb.\nConverted 06_cli.ipynb.\nConverted 07_clean.ipynb.\nConverted 99_search.ipynb.\nConverted example.ipynb.\nConverted index.ipynb.\nConverted try_save.ipynb.\nConverted tutorial.ipynb.\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb12fea1090902703783ca19ee1b149040e2ea7
| 163,430 |
ipynb
|
Jupyter Notebook
|
tests/notebooks/base.ipynb
|
RileyMShea/vectorbt
|
92ce571ce9fd0667f2994a2c922fb4cfcde10c88
|
[
"Apache-2.0"
] | 1 |
2021-01-15T00:02:11.000Z
|
2021-01-15T00:02:11.000Z
|
tests/notebooks/base.ipynb
|
RileyMShea/vectorbt
|
92ce571ce9fd0667f2994a2c922fb4cfcde10c88
|
[
"Apache-2.0"
] | null | null | null |
tests/notebooks/base.ipynb
|
RileyMShea/vectorbt
|
92ce571ce9fd0667f2994a2c922fb4cfcde10c88
|
[
"Apache-2.0"
] | null | null | null | 27.188488 | 193 | 0.373316 |
[
[
[
"# base",
"_____no_output_____"
]
],
[
[
"import vectorbt as vbt\n\nfrom vectorbt.base import column_grouper, array_wrapper, combine_fns, index_fns, indexing, reshape_fns",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd\nfrom datetime import datetime\nfrom numba import njit\nimport itertools",
"_____no_output_____"
],
[
"v1 = 0\na1 = np.array([1])\na2 = np.array([1, 2, 3])\na3 = np.array([[1, 2, 3]])\na4 = np.array([[1], [2], [3]])\na5 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\nsr_none = pd.Series([1])\nprint(sr_none)\nsr1 = pd.Series([1], index=pd.Index(['x1'], name='i1'), name='a1')\nprint(sr1)\nsr2 = pd.Series([1, 2, 3], index=pd.Index(['x2', 'y2', 'z2'], name='i2'), name='a2')\nprint(sr2)\ndf_none = pd.DataFrame([[1]])\nprint(df_none)\ndf1 = pd.DataFrame(\n [[1]], \n index=pd.Index(['x3'], name='i3'), \n columns=pd.Index(['a3'], name='c3'))\nprint(df1)\ndf2 = pd.DataFrame(\n [[1], [2], [3]], \n index=pd.Index(['x4', 'y4', 'z4'], name='i4'), \n columns=pd.Index(['a4'], name='c4'))\nprint(df2)\ndf3 = pd.DataFrame(\n [[1, 2, 3]], \n index=pd.Index(['x5'], name='i5'), \n columns=pd.Index(['a5', 'b5', 'c5'], name='c5'))\nprint(df3)\ndf4 = pd.DataFrame(\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]], \n index=pd.Index(['x6', 'y6', 'z6'], name='i6'), \n columns=pd.Index(['a6', 'b6', 'c6'], name='c6'))\nprint(df4)\n\nmulti_i = pd.MultiIndex.from_arrays([['x7', 'y7', 'z7'], ['x8', 'y8', 'z8']], names=['i7', 'i8']) \nmulti_c = pd.MultiIndex.from_arrays([['a7', 'b7', 'c7'], ['a8', 'b8', 'c8']], names=['c7', 'c8'])\ndf5 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=multi_i, columns=multi_c)\nprint(df5)",
"0 1\ndtype: int64\ni1\nx1 1\nName: a1, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n 0\n0 1\nc3 a3\ni3 \nx3 1\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 2 3\ny7 y8 4 5 6\nz7 z8 7 8 9\n"
]
],
[
[
"## column_grouper",
"_____no_output_____"
]
],
[
[
"some_columns = pd.MultiIndex.from_arrays([\n [1, 1, 1, 1, 0, 0, 0, 0],\n [3, 3, 2, 2, 1, 1, 0, 0],\n [7, 6, 5, 4, 3, 2, 1, 0]\n], names=['first', 'second', 'third'])",
"_____no_output_____"
],
[
"print(column_grouper.group_by_to_index(some_columns, group_by=0))\nprint(column_grouper.group_by_to_index(some_columns, group_by='first'))\nprint(column_grouper.group_by_to_index(some_columns, group_by=[0, 1]))\nprint(column_grouper.group_by_to_index(some_columns, group_by=['first', 'second']))\nprint(column_grouper.group_by_to_index(some_columns, group_by=np.array([3, 2, 1, 1, 1, 0, 0, 0])))\nprint(column_grouper.group_by_to_index(some_columns, group_by=pd.Index([3, 2, 1, 1, 1, 0, 0, 0], name='fourth')))",
"Int64Index([1, 1, 1, 1, 0, 0, 0, 0], dtype='int64', name='first')\nInt64Index([1, 1, 1, 1, 0, 0, 0, 0], dtype='int64', name='first')\nMultiIndex([(1, 3),\n (1, 3),\n (1, 2),\n (1, 2),\n (0, 1),\n (0, 1),\n (0, 0),\n (0, 0)],\n names=['first', 'second'])\nMultiIndex([(1, 3),\n (1, 3),\n (1, 2),\n (1, 2),\n (0, 1),\n (0, 1),\n (0, 0),\n (0, 0)],\n names=['first', 'second'])\nInt64Index([3, 2, 1, 1, 1, 0, 0, 0], dtype='int64')\nInt64Index([3, 2, 1, 1, 1, 0, 0, 0], dtype='int64', name='fourth')\n"
],
[
"# group_arr comes always from 0 to n, also keeps order\nprint(column_grouper.get_groups_and_index(some_columns, 0))\nprint(column_grouper.get_groups_and_index(some_columns, [0, 1]))\nprint(column_grouper.get_groups_and_index(some_columns, np.array([3, 2, 1, 1, 1, 0, 0, 0])))",
"(array([0, 0, 0, 0, 1, 1, 1, 1]), Int64Index([1, 0], dtype='int64', name='first'))\n(array([0, 0, 1, 1, 2, 2, 3, 3]), MultiIndex([(1, 3),\n (1, 2),\n (0, 1),\n (0, 0)],\n names=['first', 'second']))\n(array([0, 1, 2, 2, 2, 3, 3, 3]), Int64Index([3, 2, 1, 0], dtype='int64'))\n"
],
[
"print(column_grouper.get_group_lens_nb(np.array([0, 0, 0, 0, 1, 1, 1, 1])))\nprint(column_grouper.get_group_lens_nb(np.array([0, 1])))\nprint(column_grouper.get_group_lens_nb(np.array([0, 0])))\nprint(column_grouper.get_group_lens_nb(np.array([0])))\nprint(column_grouper.get_group_lens_nb(np.array([])))",
"[4 4]\n[1 1]\n[2]\n[1]\n[]\n"
],
[
"print(column_grouper.ColumnGrouper(sr2.to_frame().columns, group_by=np.array([0])).group_by)\nprint(column_grouper.ColumnGrouper(sr2.to_frame().columns, group_by=np.array([0])).get_groups_and_columns())\nprint(column_grouper.ColumnGrouper(sr2.to_frame().columns, group_by=np.array([0])).get_groups())\nprint(column_grouper.ColumnGrouper(sr2.to_frame().columns, group_by=np.array([0])).get_columns())\nprint(column_grouper.ColumnGrouper(sr2.to_frame().columns, group_by=np.array([0])).get_group_lens())\nprint(column_grouper.ColumnGrouper(sr2.to_frame().columns, group_by=np.array([0])).get_group_start_idxs())\nprint(column_grouper.ColumnGrouper(sr2.to_frame().columns, group_by=np.array([0])).get_group_end_idxs())",
"Int64Index([0], dtype='int64')\n(array([0]), Int64Index([0], dtype='int64'))\n[0]\nInt64Index([0], dtype='int64')\n[1]\n[0]\n[1]\n"
],
[
"print(column_grouper.ColumnGrouper(df4.columns, group_by=np.array([0, 0, 1])).group_by)\nprint(column_grouper.ColumnGrouper(df4.columns, group_by=np.array([0, 0, 1])).get_groups_and_columns())\nprint(column_grouper.ColumnGrouper(df4.columns, group_by=np.array([0, 0, 1])).get_groups())\nprint(column_grouper.ColumnGrouper(df4.columns, group_by=np.array([0, 0, 1])).get_columns())\nprint(column_grouper.ColumnGrouper(df4.columns, group_by=np.array([0, 0, 1])).get_group_lens())\nprint(column_grouper.ColumnGrouper(df4.columns, group_by=np.array([0, 0, 1])).get_group_start_idxs())\nprint(column_grouper.ColumnGrouper(df4.columns, group_by=np.array([0, 0, 1])).get_group_end_idxs())",
"Int64Index([0, 0, 1], dtype='int64')\n(array([0, 0, 1]), Int64Index([0, 1], dtype='int64'))\n[0 0 1]\nInt64Index([0, 1], dtype='int64')\n[2 1]\n[0 2]\n[2 3]\n"
]
],
[
[
"## array_wrapper",
"_____no_output_____"
]
],
[
[
"sr2_wrapper = array_wrapper.ArrayWrapper.from_obj(sr2)\ndf4_wrapper = array_wrapper.ArrayWrapper.from_obj(df4)\n\nsr2_wrapper_co = sr2_wrapper.copy(column_only_select=True)\ndf4_wrapper_co = df4_wrapper.copy(column_only_select=True)\n\nsr2_grouped_wrapper = sr2_wrapper.copy(group_by=np.array([0]))\ndf4_grouped_wrapper = df4_wrapper.copy(group_by=np.array([0, 0, 1]))\n\nsr2_grouped_wrapper_co = sr2_grouped_wrapper.copy(column_only_select=True)\ndf4_grouped_wrapper_co = df4_grouped_wrapper.copy(column_only_select=True)",
"_____no_output_____"
],
[
"# test indexing\nprint(sr2_wrapper._indexing_func_meta(lambda x: x.iloc[:2])[1:])\nprint(df4_wrapper._indexing_func_meta(lambda x: x.iloc[0, :2])[1:])\nprint(df4_wrapper._indexing_func_meta(lambda x: x.iloc[:2, 0])[1:])\nprint(df4_wrapper._indexing_func_meta(lambda x: x.iloc[:2, [0]])[1:])\nprint(df4_wrapper._indexing_func_meta(lambda x: x.iloc[:2, :2])[1:])",
"(array([0, 1]), 0, 0)\n(0, array([0, 1]), array([0, 1]))\n(array([0, 1]), 0, 0)\n(array([0, 1]), array([0]), array([0]))\n(array([0, 1]), array([0, 1]), array([0, 1]))\n"
],
[
"print(df4_wrapper_co._indexing_func_meta(lambda x: x.iloc[0])[1:])\nprint(df4_wrapper_co._indexing_func_meta(lambda x: x.iloc[[0]])[1:])\nprint(df4_wrapper_co._indexing_func_meta(lambda x: x.iloc[:2])[1:])",
"(array([0, 1, 2]), 0, 0)\n(array([0, 1, 2]), array([0]), array([0]))\n(array([0, 1, 2]), array([0, 1]), array([0, 1]))\n"
],
[
"print(sr2_grouped_wrapper._indexing_func_meta(lambda x: x.iloc[:2])[1:])\nprint(df4_grouped_wrapper._indexing_func_meta(lambda x: x.iloc[:2, 0])[1:])\nprint(df4_grouped_wrapper._indexing_func_meta(lambda x: x.iloc[:2, 1])[1:])\nprint(df4_grouped_wrapper._indexing_func_meta(lambda x: x.iloc[:2, [1]])[1:])\nprint(df4_grouped_wrapper._indexing_func_meta(lambda x: x.iloc[:2, :2])[1:])",
"(array([0, 1]), 0, 0)\n(array([0, 1]), 0, array([0, 1]))\n(array([0, 1]), 1, 2)\n(array([0, 1]), array([1]), array([2]))\n(array([0, 1]), array([0, 1]), array([0, 1, 2]))\n"
],
[
"print(df4_grouped_wrapper_co._indexing_func_meta(lambda x: x.iloc[0])[1:])\nprint(df4_grouped_wrapper_co._indexing_func_meta(lambda x: x.iloc[1])[1:])\nprint(df4_grouped_wrapper_co._indexing_func_meta(lambda x: x.iloc[[1]])[1:])\nprint(df4_grouped_wrapper_co._indexing_func_meta(lambda x: x.iloc[:2])[1:])",
"(array([0, 1, 2]), 0, array([0, 1]))\n(array([0, 1, 2]), 1, 2)\n(array([0, 1, 2]), array([1]), array([2]))\n(array([0, 1, 2]), array([0, 1]), array([0, 1, 2]))\n"
],
[
"print(sr2_wrapper.iloc[:2].index)\nprint(sr2_wrapper.iloc[:2].columns)\nprint(sr2_wrapper.iloc[:2].ndim)\n\nprint(df4_wrapper.iloc[0, :2].index)\nprint(df4_wrapper.iloc[0, :2].columns)\nprint(df4_wrapper.iloc[0, :2].ndim)\n\nprint(df4_wrapper.iloc[:2, 0].index)\nprint(df4_wrapper.iloc[:2, 0].columns)\nprint(df4_wrapper.iloc[:2, 0].ndim)\n\nprint(df4_wrapper.iloc[:2, [0]].index)\nprint(df4_wrapper.iloc[:2, [0]].columns)\nprint(df4_wrapper.iloc[:2, [0]].ndim)\n\nprint(df4_wrapper.iloc[:2, :2].index)\nprint(df4_wrapper.iloc[:2, :2].columns)\nprint(df4_wrapper.iloc[:2, :2].ndim)",
"Index(['x2', 'y2'], dtype='object', name='i2')\nIndex(['a2'], dtype='object')\n1\nIndex(['a6', 'b6'], dtype='object', name='c6')\nIndex(['x6'], dtype='object', name='i6')\n1\nIndex(['x6', 'y6'], dtype='object', name='i6')\nIndex(['a6'], dtype='object', name='c6')\n1\nIndex(['x6', 'y6'], dtype='object', name='i6')\nIndex(['a6'], dtype='object', name='c6')\n2\nIndex(['x6', 'y6'], dtype='object', name='i6')\nIndex(['a6', 'b6'], dtype='object', name='c6')\n2\n"
],
[
"print(df4_wrapper_co.iloc[0].index)\nprint(df4_wrapper_co.iloc[0].columns)\nprint(df4_wrapper_co.iloc[0].ndim)\n\nprint(df4_wrapper_co.iloc[[0]].index)\nprint(df4_wrapper_co.iloc[[0]].columns)\nprint(df4_wrapper_co.iloc[[0]].ndim)\n\nprint(df4_wrapper_co.iloc[:2].index)\nprint(df4_wrapper_co.iloc[:2].columns)\nprint(df4_wrapper_co.iloc[:2].ndim)",
"Index(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['a6'], dtype='object', name='c6')\n1\nIndex(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['a6'], dtype='object', name='c6')\n2\nIndex(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['a6', 'b6'], dtype='object', name='c6')\n2\n"
],
[
"print(sr2_grouped_wrapper.iloc[:2].index)\nprint(sr2_grouped_wrapper.iloc[:2].columns)\nprint(sr2_grouped_wrapper.iloc[:2].ndim)\nprint(sr2_grouped_wrapper.iloc[:2].grouped_ndim)\nprint(sr2_grouped_wrapper.iloc[:2].grouper.group_by)\n\nprint(df4_grouped_wrapper.iloc[:2, 0].index)\nprint(df4_grouped_wrapper.iloc[:2, 0].columns)\nprint(df4_grouped_wrapper.iloc[:2, 0].ndim)\nprint(df4_grouped_wrapper.iloc[:2, 0].grouped_ndim)\nprint(df4_grouped_wrapper.iloc[:2, 0].grouper.group_by)\n\nprint(df4_grouped_wrapper.iloc[:2, 1].index)\nprint(df4_grouped_wrapper.iloc[:2, 1].columns)\nprint(df4_grouped_wrapper.iloc[:2, 1].ndim)\nprint(df4_grouped_wrapper.iloc[:2, 1].grouped_ndim)\nprint(df4_grouped_wrapper.iloc[:2, 1].grouper.group_by)\n\nprint(df4_grouped_wrapper.iloc[:2, [1]].index)\nprint(df4_grouped_wrapper.iloc[:2, [1]].columns)\nprint(df4_grouped_wrapper.iloc[:2, [1]].ndim)\nprint(df4_grouped_wrapper.iloc[:2, [1]].grouped_ndim)\nprint(df4_grouped_wrapper.iloc[:2, [1]].grouper.group_by)\n\nprint(df4_grouped_wrapper.iloc[:2, :2].index)\nprint(df4_grouped_wrapper.iloc[:2, :2].columns)\nprint(df4_grouped_wrapper.iloc[:2, :2].ndim)\nprint(df4_grouped_wrapper.iloc[:2, :2].grouped_ndim)\nprint(df4_grouped_wrapper.iloc[:2, :2].grouper.group_by)",
"Index(['x2', 'y2'], dtype='object', name='i2')\nIndex(['a2'], dtype='object')\n1\n1\nInt64Index([0], dtype='int64')\nIndex(['x6', 'y6'], dtype='object', name='i6')\nIndex(['a6', 'b6'], dtype='object', name='c6')\n2\n1\nInt64Index([0, 0], dtype='int64')\nIndex(['x6', 'y6'], dtype='object', name='i6')\nIndex(['c6'], dtype='object', name='c6')\n1\n1\nInt64Index([1], dtype='int64')\nIndex(['x6', 'y6'], dtype='object', name='i6')\nIndex(['c6'], dtype='object', name='c6')\n2\n2\nInt64Index([1], dtype='int64')\nIndex(['x6', 'y6'], dtype='object', name='i6')\nIndex(['a6', 'b6', 'c6'], dtype='object', name='c6')\n2\n2\nInt64Index([0, 0, 1], dtype='int64')\n"
],
[
"print(df4_grouped_wrapper_co.iloc[0].index)\nprint(df4_grouped_wrapper_co.iloc[0].columns)\nprint(df4_grouped_wrapper_co.iloc[0].ndim)\nprint(df4_grouped_wrapper_co.iloc[0].grouped_ndim)\nprint(df4_grouped_wrapper_co.iloc[0].grouper.group_by)\n\nprint(df4_grouped_wrapper_co.iloc[1].index)\nprint(df4_grouped_wrapper_co.iloc[1].columns)\nprint(df4_grouped_wrapper_co.iloc[1].ndim)\nprint(df4_grouped_wrapper_co.iloc[1].grouped_ndim)\nprint(df4_grouped_wrapper_co.iloc[1].grouper.group_by)\n\nprint(df4_grouped_wrapper_co.iloc[[1]].index)\nprint(df4_grouped_wrapper_co.iloc[[1]].columns)\nprint(df4_grouped_wrapper_co.iloc[[1]].ndim)\nprint(df4_grouped_wrapper_co.iloc[[1]].grouped_ndim)\nprint(df4_grouped_wrapper_co.iloc[[1]].grouper.group_by)\n\nprint(df4_grouped_wrapper_co.iloc[:2].index)\nprint(df4_grouped_wrapper_co.iloc[:2].columns)\nprint(df4_grouped_wrapper_co.iloc[:2].ndim)\nprint(df4_grouped_wrapper_co.iloc[:2].grouped_ndim)\nprint(df4_grouped_wrapper_co.iloc[:2].grouper.group_by)",
"Index(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['a6', 'b6'], dtype='object', name='c6')\n2\n1\nInt64Index([0, 0], dtype='int64')\nIndex(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['c6'], dtype='object', name='c6')\n1\n1\nInt64Index([1], dtype='int64')\nIndex(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['c6'], dtype='object', name='c6')\n2\n2\nInt64Index([1], dtype='int64')\nIndex(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['a6', 'b6', 'c6'], dtype='object', name='c6')\n2\n2\nInt64Index([0, 0, 1], dtype='int64')\n"
],
[
"big_df = pd.DataFrame(np.empty((1000, 1000)))\n\nbig_df_wrapper = array_wrapper.ArrayWrapper.from_obj(big_df)\nbig_df_wrapper_co = big_df_wrapper.copy(column_only_select=True)\nbig_df_grouped_wrapper = df4_wrapper.copy(group_by=np.array([0, 0, 1]))\nbig_df_grouped_wrapper_co = big_df_grouped_wrapper.copy(column_only_select=True)",
"_____no_output_____"
],
[
"%timeit big_df_wrapper.iloc[:, 0]\n%timeit big_df_wrapper.iloc[:, :]\n\n%timeit big_df_wrapper_co.iloc[0]\n%timeit big_df_wrapper_co.iloc[:]\n\n%timeit big_df_grouped_wrapper.iloc[:, 0]\n%timeit big_df_grouped_wrapper.iloc[:, :]\n\n%timeit big_df_grouped_wrapper_co.iloc[0]\n%timeit big_df_grouped_wrapper_co.iloc[:]",
"897 µs ± 280 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n635 µs ± 80.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n319 µs ± 9.72 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n287 µs ± 2.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n851 µs ± 31.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n648 µs ± 21.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n499 µs ± 24.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n476 µs ± 13.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
],
[
"print(df4_grouped_wrapper_co.wrap(np.array([[1, 2], [3, 4], [5, 6]])))\nprint(df4_grouped_wrapper_co.wrap_reduced(np.array([1, 2])))\n\nprint(df4_grouped_wrapper_co.wrap(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), group_by=False))\nprint(df4_grouped_wrapper_co.wrap_reduced(np.array([1, 2, 3]), group_by=False))",
" 0 1\ni6 \nx6 1 2\ny6 3 4\nz6 5 6\n0 1\n1 2\ndtype: int64\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nc6\na6 1\nb6 2\nc6 3\ndtype: int64\n"
],
[
"print(df4_grouped_wrapper_co.iloc[0].wrap(np.array([1, 2, 3])))\nprint(df4_grouped_wrapper_co.iloc[0].wrap_reduced(np.array([1])))\n\nprint(df4_grouped_wrapper_co.iloc[0].wrap(np.array([[1, 2], [3, 4], [5, 6]]), group_by=False))\nprint(df4_grouped_wrapper_co.iloc[0].wrap_reduced(np.array([1, 2]), group_by=False))",
"i6\nx6 1\ny6 2\nz6 3\ndtype: int64\n1\nc6 a6 b6\ni6 \nx6 1 2\ny6 3 4\nz6 5 6\nc6\na6 1\nb6 2\ndtype: int64\n"
],
[
"print(df4_grouped_wrapper_co.iloc[[0]].wrap(np.array([1, 2, 3])))\nprint(df4_grouped_wrapper_co.iloc[[0]].wrap_reduced(np.array([1])))\n\nprint(df4_grouped_wrapper_co.iloc[[0]].wrap(np.array([[1, 2], [3, 4], [5, 6]]), group_by=False))\nprint(df4_grouped_wrapper_co.iloc[[0]].wrap_reduced(np.array([1, 2]), group_by=False))",
" 0\ni6 \nx6 1\ny6 2\nz6 3\n0 1\ndtype: int64\nc6 a6 b6\ni6 \nx6 1 2\ny6 3 4\nz6 5 6\nc6\na6 1\nb6 2\ndtype: int64\n"
],
[
"print(df4_grouped_wrapper_co.iloc[1].wrap(np.array([1, 2, 3])))\nprint(df4_grouped_wrapper_co.iloc[1].wrap_reduced(np.array([1])))\n\nprint(df4_grouped_wrapper_co.iloc[1].wrap(np.array([1, 2, 3]), group_by=False))\nprint(df4_grouped_wrapper_co.iloc[1].wrap_reduced(np.array([1]), group_by=False))",
"i6\nx6 1\ny6 2\nz6 3\nName: 1, dtype: int64\n1\ni6\nx6 1\ny6 2\nz6 3\nName: c6, dtype: int64\n1\n"
],
[
"print(df4_grouped_wrapper_co.iloc[[1]].wrap(np.array([1, 2, 3])))\nprint(df4_grouped_wrapper_co.iloc[[1]].wrap_reduced(np.array([1])))\n\nprint(df4_grouped_wrapper_co.iloc[[1]].wrap(np.array([1, 2, 3]), group_by=False))\nprint(df4_grouped_wrapper_co.iloc[[1]].wrap_reduced(np.array([1]), group_by=False))",
" 1\ni6 \nx6 1\ny6 2\nz6 3\n1 1\ndtype: int64\nc6 c6\ni6 \nx6 1\ny6 2\nz6 3\nc6\nc6 1\ndtype: int64\n"
]
],
[
[
"## index_fns",
"_____no_output_____"
]
],
[
[
"i1 = index_fns.index_from_values([0.1, 0.2], name='a')\ni2 = index_fns.index_from_values(np.tile(np.arange(1, 4)[:, None][:, None], (1, 3, 3)), name='b')\ni3 = index_fns.index_from_values(np.random.uniform(size=(3, 3, 3)), name='c')\n\nprint(i1)\nprint(i2)\nprint(i3)",
"Float64Index([0.1, 0.2], dtype='float64', name='a')\nInt64Index([1, 2, 3], dtype='int64', name='b')\nIndex(['mix_0', 'mix_1', 'mix_2'], dtype='object', name='c')\n"
],
[
"print(index_fns.repeat_index(i2, 3))\nprint(index_fns.repeat_index(multi_i, 3))",
"Int64Index([1, 1, 1, 2, 2, 2, 3, 3, 3], dtype='int64', name='b')\nMultiIndex([('x7', 'x8'),\n ('x7', 'x8'),\n ('x7', 'x8'),\n ('y7', 'y8'),\n ('y7', 'y8'),\n ('y7', 'y8'),\n ('z7', 'z8'),\n ('z7', 'z8'),\n ('z7', 'z8')],\n names=['i7', 'i8'])\n"
],
[
"print(index_fns.tile_index(i2, 3))\nprint(index_fns.tile_index(multi_i, 3))",
"Int64Index([1, 2, 3, 1, 2, 3, 1, 2, 3], dtype='int64', name='b')\nMultiIndex([('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8'),\n ('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8'),\n ('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8')],\n names=['i7', 'i8'])\n"
],
[
"i23 = index_fns.stack_indexes(i2, i3)\ni32 = index_fns.stack_indexes(i3, i2)\n\nprint(i23)\nprint(i32)\n\nprint(index_fns.stack_indexes(multi_i, multi_i, drop_duplicates=False))\nprint(index_fns.stack_indexes(multi_i, multi_i, drop_duplicates=True))\nprint(index_fns.stack_indexes([0, 1], ['a', 'b'], drop_redundant=False))\nprint(index_fns.stack_indexes([0, 1], ['a', 'b'], drop_redundant=True))\nprint(index_fns.stack_indexes(pd.Index([0, 1], name='test_name'), ['a', 'b'], drop_redundant=True))\nprint(index_fns.stack_indexes(['a', 'a'], ['a', 'b'], drop_redundant=True))\nprint(index_fns.stack_indexes(pd.Index(['a', 'a'], name='test_name'), ['a', 'b'], drop_redundant=True))",
"MultiIndex([(1, 'mix_0'),\n (2, 'mix_1'),\n (3, 'mix_2')],\n names=['b', 'c'])\nMultiIndex([('mix_0', 1),\n ('mix_1', 2),\n ('mix_2', 3)],\n names=['c', 'b'])\nMultiIndex([('x7', 'x8', 'x7', 'x8'),\n ('y7', 'y8', 'y7', 'y8'),\n ('z7', 'z8', 'z7', 'z8')],\n names=['i7', 'i8', 'i7', 'i8'])\nMultiIndex([('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8')],\n names=['i7', 'i8'])\nMultiIndex([(0, 'a'),\n (1, 'b')],\n )\nIndex(['a', 'b'], dtype='object')\nMultiIndex([(0, 'a'),\n (1, 'b')],\n names=['test_name', None])\nIndex(['a', 'b'], dtype='object')\nMultiIndex([('a', 'a'),\n ('a', 'b')],\n names=['test_name', None])\n"
],
[
"print(index_fns.combine_indexes(pd.Index([1]), pd.Index([2, 3]), drop_duplicates=False))\nprint(index_fns.combine_indexes(pd.Index([1]), pd.Index([2, 3]), drop_duplicates=True))\nprint(index_fns.combine_indexes(pd.Index([1, 2]), pd.Index([3]), drop_duplicates=False))\nprint(index_fns.combine_indexes(pd.Index([1, 2]), pd.Index([3]), drop_duplicates=True))\nprint(index_fns.combine_indexes(i1, i2)) # combine_fns uses stack\nprint(index_fns.combine_indexes(i2, i3))\nprint(index_fns.combine_indexes(i23, i23))",
"Int64Index([2, 3], dtype='int64')\nInt64Index([2, 3], dtype='int64')\nInt64Index([1, 2], dtype='int64')\nInt64Index([1, 2], dtype='int64')\nMultiIndex([(0.1, 1),\n (0.1, 2),\n (0.1, 3),\n (0.2, 1),\n (0.2, 2),\n (0.2, 3)],\n names=['a', 'b'])\nMultiIndex([(1, 'mix_0'),\n (1, 'mix_1'),\n (1, 'mix_2'),\n (2, 'mix_0'),\n (2, 'mix_1'),\n (2, 'mix_2'),\n (3, 'mix_0'),\n (3, 'mix_1'),\n (3, 'mix_2')],\n names=['b', 'c'])\nMultiIndex([(1, 'mix_0', 1, 'mix_0'),\n (1, 'mix_0', 2, 'mix_1'),\n (1, 'mix_0', 3, 'mix_2'),\n (2, 'mix_1', 1, 'mix_0'),\n (2, 'mix_1', 2, 'mix_1'),\n (2, 'mix_1', 3, 'mix_2'),\n (3, 'mix_2', 1, 'mix_0'),\n (3, 'mix_2', 2, 'mix_1'),\n (3, 'mix_2', 3, 'mix_2')],\n names=['b', 'c', 'b', 'c'])\n"
],
[
"print(index_fns.drop_levels(multi_i, 'i10'))\nprint(index_fns.drop_levels(multi_i, ['i7', 'i8']))",
"MultiIndex([('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8')],\n names=['i7', 'i8'])\nMultiIndex([('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8')],\n names=['i7', 'i8'])\n"
],
[
"print(index_fns.rename_levels(pd.Int64Index([1, 2, 3], name='i'), {'i': 'f'}))\nprint(index_fns.rename_levels(multi_i, {'i7': 'f7', 'i8': 'f8'}))",
"Int64Index([1, 2, 3], dtype='int64', name='f')\nMultiIndex([('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8')],\n names=['f7', 'f8'])\n"
],
[
"print(index_fns.select_levels(multi_i, 'i7'))\nprint(index_fns.select_levels(multi_i, ['i7']))\nprint(index_fns.select_levels(multi_i, ['i7', 'i8']))",
"Index(['x7', 'y7', 'z7'], dtype='object', name='i7')\nMultiIndex([('x7',),\n ('y7',),\n ('z7',)],\n names=['i7'])\nMultiIndex([('x7', 'x8'),\n ('y7', 'y8'),\n ('z7', 'z8')],\n names=['i7', 'i8'])\n"
],
[
"print(index_fns.drop_redundant_levels(pd.Index(['a', 'a']))) # ignores levels with single element\nprint(index_fns.drop_redundant_levels(pd.Index(['a', 'a'], name='hi')))\nprint(index_fns.drop_redundant_levels(pd.MultiIndex.from_arrays([['a', 'a'], ['b', 'b']], names=['hi', 'hi2'])))\nprint(index_fns.drop_redundant_levels(pd.MultiIndex.from_arrays([['a', 'b'], ['a', 'b']], names=['hi', 'hi2'])))\nprint(index_fns.drop_redundant_levels(pd.MultiIndex.from_arrays([[0, 1], ['a', 'b']], names=[None, 'hi2']))) # ignores 0-to-n\nprint(index_fns.drop_redundant_levels(pd.MultiIndex.from_arrays([[0, 2], ['a', 'b']], names=[None, 'hi2']))) # legit\nprint(index_fns.drop_redundant_levels(pd.MultiIndex.from_arrays([[0, 1], ['a', 'b']], names=['hi', 'hi2']))) # legit (w/ name)",
"Index(['a', 'a'], dtype='object')\nIndex(['a', 'a'], dtype='object', name='hi')\nMultiIndex([('a', 'b'),\n ('a', 'b')],\n names=['hi', 'hi2'])\nMultiIndex([('a', 'a'),\n ('b', 'b')],\n names=['hi', 'hi2'])\nIndex(['a', 'b'], dtype='object', name='hi2')\nMultiIndex([(0, 'a'),\n (2, 'b')],\n names=[None, 'hi2'])\nMultiIndex([(0, 'a'),\n (1, 'b')],\n names=['hi', 'hi2'])\n"
],
[
"print(index_fns.drop_duplicate_levels(pd.MultiIndex.from_arrays(\n [[1, 2, 3], [1, 2, 3]], names=['a', 'a'])))\nprint(index_fns.drop_duplicate_levels(pd.MultiIndex.from_tuples(\n [(0, 1, 2, 1), ('a', 'b', 'c', 'b')], names=['x', 'y', 'z', 'y']), keep='last'))\nprint(index_fns.drop_duplicate_levels(pd.MultiIndex.from_tuples(\n [(0, 1, 2, 1), ('a', 'b', 'c', 'b')], names=['x', 'y', 'z', 'y']), keep='first'))",
"Int64Index([1, 2, 3], dtype='int64', name='a')\nMultiIndex([( 0, 2, 1),\n ('a', 'c', 'b')],\n names=['x', 'z', 'y'])\nMultiIndex([( 0, 1, 2),\n ('a', 'b', 'c')],\n names=['x', 'y', 'z'])\n"
],
[
"multi_c1 = pd.MultiIndex.from_arrays([['a8', 'b8']], names=['c8'])\nmulti_c2 = pd.MultiIndex.from_arrays([['a7', 'a7', 'c7', 'c7'], ['a8', 'b8', 'a8', 'b8']], names=['c7', 'c8'])\n\nindex_fns.align_index_to(multi_c1, multi_c2)",
"_____no_output_____"
],
[
"print(index_fns.pick_levels(multi_c, required_levels=[], optional_levels=[]))\nprint(index_fns.pick_levels(multi_c, required_levels=['c8'], optional_levels=[]))\nprint(index_fns.pick_levels(multi_c, required_levels=['c8'], optional_levels=[]))\nprint(index_fns.pick_levels(multi_c, required_levels=['c7', 'c8'], optional_levels=[]))\nprint(index_fns.pick_levels(multi_c, required_levels=['c8', None], optional_levels=[]))\nprint(index_fns.pick_levels(multi_c, required_levels=[None, None], optional_levels=[]))\nprint(index_fns.pick_levels(multi_c, required_levels=[None], optional_levels=['c8']))\nprint(index_fns.pick_levels(multi_c, required_levels=['c8'], optional_levels=[None]))\nprint(index_fns.pick_levels(multi_c, required_levels=[], optional_levels=['c7', 'c8']))",
"([], [])\n([1], [])\n([1], [])\n([0, 1], [])\n([1, 0], [])\n([0, 1], [])\n([0], [1])\n([1], [None])\n([], [0, 1])\n"
]
],
[
[
"## reshape_fns",
"_____no_output_____"
]
],
[
[
"print(reshape_fns.soft_to_ndim(a2, 1))\nprint(reshape_fns.soft_to_ndim(sr2, 1))\nprint(reshape_fns.soft_to_ndim(df2, 1))\nprint(reshape_fns.soft_to_ndim(df4, 1)) # cannot -> do nothing\nprint(reshape_fns.soft_to_ndim(a2, 2))\nprint(reshape_fns.soft_to_ndim(sr2, 2))\nprint(reshape_fns.soft_to_ndim(df2, 2))",
"[1 2 3]\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\ni4\nx4 1\ny4 2\nz4 3\nName: a4, dtype: int64\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n[[1]\n [2]\n [3]]\n a2\ni2 \nx2 1\ny2 2\nz2 3\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n"
],
[
"print(reshape_fns.to_1d(None))\nprint(reshape_fns.to_1d(v1))\nprint(reshape_fns.to_1d(a1))\nprint(reshape_fns.to_1d(a2))\nprint(reshape_fns.to_1d(sr1))\nprint(reshape_fns.to_1d(sr2))\nprint(reshape_fns.to_1d(df1))\nprint(reshape_fns.to_1d(df2))",
"[None]\n[0]\n[1]\n[1 2 3]\ni1\nx1 1\nName: a1, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\ni3\nx3 1\nName: a3, dtype: int64\ni4\nx4 1\ny4 2\nz4 3\nName: a4, dtype: int64\n"
],
[
"print(reshape_fns.to_2d(None))\nprint(reshape_fns.to_2d(v1))\nprint(reshape_fns.to_2d(a1))\nprint(reshape_fns.to_2d(a2))\nprint(reshape_fns.to_2d(sr1))\nprint(reshape_fns.to_2d(sr2))\nprint(reshape_fns.to_2d(sr2, expand_axis=0))",
"[[None]]\n[[0]]\n[[1]]\n[[1]\n [2]\n [3]]\n a1\ni1 \nx1 1\n a2\ni2 \nx2 1\ny2 2\nz2 3\ni2 x2 y2 z2\n0 1 2 3\n"
],
[
"print(reshape_fns.repeat(v1, 3, axis=0))\nprint(reshape_fns.repeat(a1, 3, axis=0))\nprint(reshape_fns.repeat(a2, 3, axis=0))\nprint(reshape_fns.repeat(a3, 3, axis=0))\nprint(reshape_fns.repeat(a4, 3, axis=0))\nprint(reshape_fns.repeat(a5, 3, axis=0))\nprint(reshape_fns.repeat(sr_none, 3, axis=0))\nprint(reshape_fns.repeat(sr1, 3, axis=0))\nprint(reshape_fns.repeat(sr2, 3, axis=0))\nprint(reshape_fns.repeat(df_none, 3, axis=0))\nprint(reshape_fns.repeat(df1, 3, axis=0))\nprint(reshape_fns.repeat(df2, 3, axis=0))\nprint(reshape_fns.repeat(df3, 3, axis=0))\nprint(reshape_fns.repeat(df4, 3, axis=0))",
"[0 0 0]\n[1 1 1]\n[1 1 1 2 2 2 3 3 3]\n[[1 2 3]\n [1 2 3]\n [1 2 3]]\n[[1]\n [1]\n [1]\n [2]\n [2]\n [2]\n [3]\n [3]\n [3]]\n[[1 2 3]\n [1 2 3]\n [1 2 3]\n [4 5 6]\n [4 5 6]\n [4 5 6]\n [7 8 9]\n [7 8 9]\n [7 8 9]]\n0 1\n1 1\n2 1\ndtype: int64\ni1\nx1 1\nx1 1\nx1 1\nName: a1, dtype: int64\ni2\nx2 1\nx2 1\nx2 1\ny2 2\ny2 2\ny2 2\nz2 3\nz2 3\nz2 3\nName: a2, dtype: int64\n 0\n0 1\n1 1\n2 1\nc3 a3\ni3 \nx3 1\nx3 1\nx3 1\nc4 a4\ni4 \nx4 1\nx4 1\nx4 1\ny4 2\ny4 2\ny4 2\nz4 3\nz4 3\nz4 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nx5 1 2 3\nx5 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\nx6 1 2 3\nx6 1 2 3\ny6 4 5 6\ny6 4 5 6\ny6 4 5 6\nz6 7 8 9\nz6 7 8 9\nz6 7 8 9\n"
],
[
"print(reshape_fns.repeat(v1, 3, axis=1))\nprint(reshape_fns.repeat(a1, 3, axis=1))\nprint(reshape_fns.repeat(a2, 3, axis=1))\nprint(reshape_fns.repeat(a3, 3, axis=1))\nprint(reshape_fns.repeat(a4, 3, axis=1))\nprint(reshape_fns.repeat(a5, 3, axis=1))\nprint(reshape_fns.repeat(sr_none, 3, axis=1))\nprint(reshape_fns.repeat(sr1, 3, axis=1))\nprint(reshape_fns.repeat(sr2, 3, axis=1))\nprint(reshape_fns.repeat(df_none, 3, axis=1))\nprint(reshape_fns.repeat(df1, 3, axis=1))\nprint(reshape_fns.repeat(df2, 3, axis=1))\nprint(reshape_fns.repeat(df3, 3, axis=1))\nprint(reshape_fns.repeat(df4, 3, axis=1))",
"[[0 0 0]]\n[[1 1 1]]\n[[1 1 1]\n [2 2 2]\n [3 3 3]]\n[[1 1 1 2 2 2 3 3 3]]\n[[1 1 1]\n [2 2 2]\n [3 3 3]]\n[[1 1 1 2 2 2 3 3 3]\n [4 4 4 5 5 5 6 6 6]\n [7 7 7 8 8 8 9 9 9]]\n 0 1 2\n0 1 1 1\n a1 a1 a1\ni1 \nx1 1 1 1\n a2 a2 a2\ni2 \nx2 1 1 1\ny2 2 2 2\nz2 3 3 3\n 0 1 2\n0 1 1 1\nc3 a3 a3 a3\ni3 \nx3 1 1 1\nc4 a4 a4 a4\ni4 \nx4 1 1 1\ny4 2 2 2\nz4 3 3 3\nc5 a5 a5 a5 b5 b5 b5 c5 c5 c5\ni5 \nx5 1 1 1 2 2 2 3 3 3\nc6 a6 a6 a6 b6 b6 b6 c6 c6 c6\ni6 \nx6 1 1 1 2 2 2 3 3 3\ny6 4 4 4 5 5 5 6 6 6\nz6 7 7 7 8 8 8 9 9 9\n"
],
[
"print(reshape_fns.tile(v1, 3, axis=0))\nprint(reshape_fns.tile(a1, 3, axis=0))\nprint(reshape_fns.tile(a2, 3, axis=0))\nprint(reshape_fns.tile(a3, 3, axis=0))\nprint(reshape_fns.tile(a4, 3, axis=0))\nprint(reshape_fns.tile(a5, 3, axis=0))\nprint(reshape_fns.tile(sr_none, 3, axis=0))\nprint(reshape_fns.tile(sr1, 3, axis=0))\nprint(reshape_fns.tile(sr2, 3, axis=0))\nprint(reshape_fns.tile(df_none, 3, axis=0))\nprint(reshape_fns.tile(df1, 3, axis=0))\nprint(reshape_fns.tile(df2, 3, axis=0))\nprint(reshape_fns.tile(df3, 3, axis=0))\nprint(reshape_fns.tile(df4, 3, axis=0))",
"[0 0 0]\n[1 1 1]\n[1 2 3 1 2 3 1 2 3]\n[[1 2 3]\n [1 2 3]\n [1 2 3]]\n[[1]\n [2]\n [3]\n [1]\n [2]\n [3]\n [1]\n [2]\n [3]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]\n [1 2 3]\n [4 5 6]\n [7 8 9]\n [1 2 3]\n [4 5 6]\n [7 8 9]]\n0 1\n1 1\n2 1\ndtype: int64\ni1\nx1 1\nx1 1\nx1 1\nName: a1, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nx2 1\ny2 2\nz2 3\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n 0\n0 1\n1 1\n2 1\nc3 a3\ni3 \nx3 1\nx3 1\nx3 1\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nx4 1\ny4 2\nz4 3\nx4 1\ny4 2\nz4 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nx5 1 2 3\nx5 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n"
],
[
"print(reshape_fns.tile(v1, 3, axis=1))\nprint(reshape_fns.tile(a1, 3, axis=1))\nprint(reshape_fns.tile(a2, 3, axis=1))\nprint(reshape_fns.tile(a3, 3, axis=1))\nprint(reshape_fns.tile(a4, 3, axis=1))\nprint(reshape_fns.tile(a5, 3, axis=1))\nprint(reshape_fns.tile(sr_none, 3, axis=1))\nprint(reshape_fns.tile(sr1, 3, axis=1))\nprint(reshape_fns.tile(sr2, 3, axis=1))\nprint(reshape_fns.tile(df_none, 3, axis=1))\nprint(reshape_fns.tile(df1, 3, axis=1))\nprint(reshape_fns.tile(df2, 3, axis=1))\nprint(reshape_fns.tile(df3, 3, axis=1))\nprint(reshape_fns.tile(df4, 3, axis=1))",
"[[0 0 0]]\n[[1 1 1]]\n[[1 1 1]\n [2 2 2]\n [3 3 3]]\n[[1 2 3 1 2 3 1 2 3]]\n[[1 1 1]\n [2 2 2]\n [3 3 3]]\n[[1 2 3 1 2 3 1 2 3]\n [4 5 6 4 5 6 4 5 6]\n [7 8 9 7 8 9 7 8 9]]\n 0 1 2\n0 1 1 1\n a1 a1 a1\ni1 \nx1 1 1 1\n a2 a2 a2\ni2 \nx2 1 1 1\ny2 2 2 2\nz2 3 3 3\n 0 1 2\n0 1 1 1\nc3 a3 a3 a3\ni3 \nx3 1 1 1\nc4 a4 a4 a4\ni4 \nx4 1 1 1\ny4 2 2 2\nz4 3 3 3\nc5 a5 b5 c5 a5 b5 c5 a5 b5 c5\ni5 \nx5 1 2 3 1 2 3 1 2 3\nc6 a6 b6 c6 a6 b6 c6 a6 b6 c6\ni6 \nx6 1 2 3 1 2 3 1 2 3\ny6 4 5 6 4 5 6 4 5 6\nz6 7 8 9 7 8 9 7 8 9\n"
],
[
"# Change broadcasting rules globally\nvbt.settings.broadcasting['index_from'] = 'stack' # default is 'strict'\nvbt.settings.broadcasting['columns_from'] = 'stack'\n\nprint(vbt.settings.broadcasting)",
"{'align_index': False, 'align_columns': True, 'index_from': 'stack', 'columns_from': 'stack', 'ignore_sr_names': True, 'drop_duplicates': True, 'keep': 'last', 'drop_redundant': True}\n"
],
[
"# Broadcasting arrays\nargs = [\n ('v1', v1),\n ('a1', a1),\n ('a2', a2),\n ('a3', a3),\n ('a4', a4),\n ('a5', a5)\n]\narg_combs = list(itertools.combinations_with_replacement(args, 2))\n\nfor (n1, arg1), (n2, arg2) in arg_combs:\n print(arg1)\n print(arg2)\n print(\"================\")\n arg1, arg2 = reshape_fns.broadcast(arg1, arg2)\n print(arg1)\n print(arg2)\n print()",
"0\n0\n================\n0\n0\n\n0\n[1]\n================\n[0]\n[1]\n\n0\n[1 2 3]\n================\n[0 0 0]\n[1 2 3]\n\n0\n[[1 2 3]]\n================\n[[0 0 0]]\n[[1 2 3]]\n\n0\n[[1]\n [2]\n [3]]\n================\n[[0]\n [0]\n [0]]\n[[1]\n [2]\n [3]]\n\n0\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n================\n[[0 0 0]\n [0 0 0]\n [0 0 0]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n[1]\n[1]\n================\n[1]\n[1]\n\n[1]\n[1 2 3]\n================\n[1 1 1]\n[1 2 3]\n\n[1]\n[[1 2 3]]\n================\n[[1 1 1]]\n[[1 2 3]]\n\n[1]\n[[1]\n [2]\n [3]]\n================\n[[1]\n [1]\n [1]]\n[[1]\n [2]\n [3]]\n\n[1]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n================\n[[1 1 1]\n [1 1 1]\n [1 1 1]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n[1 2 3]\n[1 2 3]\n================\n[1 2 3]\n[1 2 3]\n\n[1 2 3]\n[[1 2 3]]\n================\n[[1 2 3]]\n[[1 2 3]]\n\n[1 2 3]\n[[1]\n [2]\n [3]]\n================\n[[1 2 3]\n [1 2 3]\n [1 2 3]]\n[[1 1 1]\n [2 2 2]\n [3 3 3]]\n\n[1 2 3]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n================\n[[1 2 3]\n [1 2 3]\n [1 2 3]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n[[1 2 3]]\n[[1 2 3]]\n================\n[[1 2 3]]\n[[1 2 3]]\n\n[[1 2 3]]\n[[1]\n [2]\n [3]]\n================\n[[1 2 3]\n [1 2 3]\n [1 2 3]]\n[[1 1 1]\n [2 2 2]\n [3 3 3]]\n\n[[1 2 3]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n================\n[[1 2 3]\n [1 2 3]\n [1 2 3]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n[[1]\n [2]\n [3]]\n[[1]\n [2]\n [3]]\n================\n[[1]\n [2]\n [3]]\n[[1]\n [2]\n [3]]\n\n[[1]\n [2]\n [3]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n================\n[[1 1 1]\n [2 2 2]\n [3 3 3]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n================\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n\n"
],
[
"# Broadcasting series\nargs = [\n ('sr_none', sr_none),\n ('sr1', sr1),\n ('sr2', sr2)\n]\narg_combs = list(itertools.combinations_with_replacement(args, 2))\n\nfor (n1, arg1), (n2, arg2) in arg_combs:\n print(n1 + '+' + n2)\n print(arg1)\n print(arg2)\n print(\"================\")\n arg1, arg2 = reshape_fns.broadcast(arg1, arg2)\n print(arg1)\n print(arg2)\n print()",
"sr_none+sr_none\n0 1\ndtype: int64\n0 1\ndtype: int64\n================\n0 1\ndtype: int64\n0 1\ndtype: int64\n\nsr_none+sr1\n0 1\ndtype: int64\ni1\nx1 1\nName: a1, dtype: int64\n================\ni1\nx1 1\ndtype: int64\ni1\nx1 1\ndtype: int64\n\nsr_none+sr2\n0 1\ndtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\ni2\nx2 1\ny2 1\nz2 1\ndtype: int64\ni2\nx2 1\ny2 2\nz2 3\ndtype: int64\n\nsr1+sr1\ni1\nx1 1\nName: a1, dtype: int64\ni1\nx1 1\nName: a1, dtype: int64\n================\ni1\nx1 1\nName: a1, dtype: int64\ni1\nx1 1\nName: a1, dtype: int64\n\nsr1+sr2\ni1\nx1 1\nName: a1, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\ni1 i2\nx1 x2 1\n y2 1\n z2 1\ndtype: int64\ni1 i2\nx1 x2 1\n y2 2\n z2 3\ndtype: int64\n\nsr2+sr2\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n\n"
],
[
"# Broadcasting arrays and series\na_args = [\n ('v1', v1),\n ('a1', a1),\n ('a2', a2),\n ('a3', a3),\n ('a4', a4),\n ('a5', a5)\n]\nsr_args = [\n ('sr_none', sr_none),\n ('sr1', sr1),\n ('sr2', sr2)\n]\narg_combs = list(itertools.product(a_args, sr_args))\n\nfor (n1, arg1), (n2, arg2) in arg_combs:\n print(n1 + '+' + n2)\n print(arg1)\n print(arg2)\n print(\"================\")\n arg1, arg2 = reshape_fns.broadcast(arg1, arg2)\n print(arg1)\n print(arg2)\n print()",
"v1+sr_none\n0\n0 1\ndtype: int64\n================\n0 0\ndtype: int64\n0 1\ndtype: int64\n\nv1+sr1\n0\ni1\nx1 1\nName: a1, dtype: int64\n================\ni1\nx1 0\nName: a1, dtype: int64\ni1\nx1 1\nName: a1, dtype: int64\n\nv1+sr2\n0\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\ni2\nx2 0\ny2 0\nz2 0\nName: a2, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n\na1+sr_none\n[1]\n0 1\ndtype: int64\n================\n0 1\ndtype: int64\n0 1\ndtype: int64\n\na1+sr1\n[1]\ni1\nx1 1\nName: a1, dtype: int64\n================\ni1\nx1 1\nName: a1, dtype: int64\ni1\nx1 1\nName: a1, dtype: int64\n\na1+sr2\n[1]\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\ni2\nx2 1\ny2 1\nz2 1\nName: a2, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n\na2+sr_none\n[1 2 3]\n0 1\ndtype: int64\n================\n0 1\n1 2\n2 3\ndtype: int64\n0 1\n1 1\n2 1\ndtype: int64\n\na2+sr1\n[1 2 3]\ni1\nx1 1\nName: a1, dtype: int64\n================\ni1\nx1 1\nx1 2\nx1 3\nName: a1, dtype: int64\ni1\nx1 1\nx1 1\nx1 1\nName: a1, dtype: int64\n\na2+sr2\n[1 2 3]\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n\na3+sr_none\n[[1 2 3]]\n0 1\ndtype: int64\n================\n 0 1 2\n0 1 2 3\n 0 1 2\n0 1 1 1\n\na3+sr1\n[[1 2 3]]\ni1\nx1 1\nName: a1, dtype: int64\n================\n a1 a1 a1\ni1 \nx1 1 2 3\n a1 a1 a1\ni1 \nx1 1 1 1\n\na3+sr2\n[[1 2 3]]\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\n a2 a2 a2\ni2 \nx2 1 2 3\ny2 1 2 3\nz2 1 2 3\n a2 a2 a2\ni2 \nx2 1 1 1\ny2 2 2 2\nz2 3 3 3\n\na4+sr_none\n[[1]\n [2]\n [3]]\n0 1\ndtype: int64\n================\n 0\n0 1\n1 2\n2 3\n 0\n0 1\n1 1\n2 1\n\na4+sr1\n[[1]\n [2]\n [3]]\ni1\nx1 1\nName: a1, dtype: int64\n================\n a1\ni1 \nx1 1\nx1 2\nx1 3\n a1\ni1 \nx1 1\nx1 1\nx1 1\n\na4+sr2\n[[1]\n [2]\n [3]]\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\n a2\ni2 \nx2 1\ny2 2\nz2 3\n a2\ni2 \nx2 1\ny2 2\nz2 3\n\na5+sr_none\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n0 1\ndtype: int64\n================\n 0 1 2\n0 1 2 3\n1 4 5 6\n2 7 8 9\n 0 1 2\n0 1 1 1\n1 1 1 1\n2 1 1 1\n\na5+sr1\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\ni1\nx1 1\nName: a1, dtype: int64\n================\n a1 a1 a1\ni1 \nx1 1 2 3\nx1 4 5 6\nx1 7 8 9\n a1 a1 a1\ni1 \nx1 1 1 1\nx1 1 1 1\nx1 1 1 1\n\na5+sr2\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n================\n a2 a2 a2\ni2 \nx2 1 2 3\ny2 4 5 6\nz2 7 8 9\n a2 a2 a2\ni2 \nx2 1 1 1\ny2 2 2 2\nz2 3 3 3\n\n"
],
[
"# Broadcasting dataframes\nargs = [\n ('df_none', df_none),\n ('df1', df1),\n ('df2', df2),\n ('df3', df3),\n ('df4', df4)\n]\narg_combs = list(itertools.combinations_with_replacement(args, 2))\n\nfor (n1, arg1), (n2, arg2) in arg_combs:\n print(n1 + '+' + n2)\n print(arg1)\n print(arg2)\n print(\"================\")\n arg1, arg2 = reshape_fns.broadcast(arg1, arg2)\n print(arg1)\n print(arg2)\n print()",
"df_none+df_none\n 0\n0 1\n 0\n0 1\n================\n 0\n0 1\n 0\n0 1\n\ndf_none+df1\n 0\n0 1\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni3 \nx3 1\nc3 a3\ni3 \nx3 1\n\ndf_none+df2\n 0\n0 1\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni4 \nx4 1\ny4 1\nz4 1\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n\ndf_none+df3\n 0\n0 1\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 1 1\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n\ndf_none+df4\n 0\n0 1\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\ndf1+df1\nc3 a3\ni3 \nx3 1\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni3 \nx3 1\nc3 a3\ni3 \nx3 1\n\ndf1+df2\nc3 a3\ni3 \nx3 1\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc3 a3\nc4 a4\ni3 i4 \nx3 x4 1\n y4 1\n z4 1\nc3 a3\nc4 a4\ni3 i4 \nx3 x4 1\n y4 2\n z4 3\n\ndf1+df3\nc3 a3\ni3 \nx3 1\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc3 a3 \nc5 a5 b5 c5\ni3 i5 \nx3 x5 1 1 1\nc3 a3 \nc5 a5 b5 c5\ni3 i5 \nx3 x5 1 2 3\n\ndf1+df4\nc3 a3\ni3 \nx3 1\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc3 a3 \nc6 a6 b6 c6\ni3 i6 \nx3 x6 1 1 1\n y6 1 1 1\n z6 1 1 1\nc3 a3 \nc6 a6 b6 c6\ni3 i6 \nx3 x6 1 2 3\n y6 4 5 6\n z6 7 8 9\n\ndf2+df2\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n\ndf2+df3\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc4 a4 \nc5 a5 b5 c5\ni4 i5 \nx4 x5 1 1 1\ny4 x5 2 2 2\nz4 x5 3 3 3\nc4 a4 \nc5 a5 b5 c5\ni4 i5 \nx4 x5 1 2 3\ny4 x5 1 2 3\nz4 x5 1 2 3\n\ndf2+df4\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc4 a4 \nc6 a6 b6 c6\ni4 i6 \nx4 x6 1 1 1\ny4 y6 2 2 2\nz4 z6 3 3 3\nc4 a4 \nc6 a6 b6 c6\ni4 i6 \nx4 x6 1 2 3\ny4 y6 4 5 6\nz4 z6 7 8 9\n\ndf3+df3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n\ndf3+df4\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc5 a5 b5 c5\nc6 a6 b6 c6\ni5 i6 \nx5 x6 1 2 3\n y6 1 2 3\n z6 1 2 3\nc5 a5 b5 c5\nc6 a6 b6 c6\ni5 i6 \nx5 x6 1 2 3\n y6 4 5 6\n z6 7 8 9\n\ndf4+df4\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\n"
],
[
"# Broadcasting arrays and dataframes\na_args = [\n ('v1', v1),\n ('a1', a1),\n ('a2', a2),\n ('a3', a3),\n ('a4', a4),\n ('a5', a5)\n]\nsr_args = [\n ('df_none', df_none),\n ('df1', df1),\n ('df2', df2),\n ('df3', df3),\n ('df4', df4)\n]\narg_combs = list(itertools.product(a_args, sr_args))\n\nfor (n1, arg1), (n2, arg2) in arg_combs:\n print(n1 + '+' + n2)\n print(arg1)\n print(arg2)\n print(\"================\")\n arg1, arg2 = reshape_fns.broadcast(arg1, arg2)\n print(arg1)\n print(arg2)\n print()",
"v1+df_none\n0\n 0\n0 1\n================\n 0\n0 0\n 0\n0 1\n\nv1+df1\n0\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni3 \nx3 0\nc3 a3\ni3 \nx3 1\n\nv1+df2\n0\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni4 \nx4 0\ny4 0\nz4 0\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n\nv1+df3\n0\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 0 0 0\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n\nv1+df4\n0\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 0 0 0\ny6 0 0 0\nz6 0 0 0\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\na1+df_none\n[1]\n 0\n0 1\n================\n 0\n0 1\n 0\n0 1\n\na1+df1\n[1]\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni3 \nx3 1\nc3 a3\ni3 \nx3 1\n\na1+df2\n[1]\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni4 \nx4 1\ny4 1\nz4 1\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n\na1+df3\n[1]\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 1 1\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n\na1+df4\n[1]\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\na2+df_none\n[1 2 3]\n 0\n0 1\n================\n 0 1 2\n0 1 2 3\n 0 1 2\n0 1 1 1\n\na2+df1\n[1 2 3]\nc3 a3\ni3 \nx3 1\n================\nc3 a3 a3 a3\ni3 \nx3 1 2 3\nc3 a3 a3 a3\ni3 \nx3 1 1 1\n\na2+df2\n[1 2 3]\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4 a4 a4\ni4 \nx4 1 2 3\ny4 1 2 3\nz4 1 2 3\nc4 a4 a4 a4\ni4 \nx4 1 1 1\ny4 2 2 2\nz4 3 3 3\n\na2+df3\n[1 2 3]\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n\na2+df4\n[1 2 3]\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 1 2 3\nz6 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\na3+df_none\n[[1 2 3]]\n 0\n0 1\n================\n 0 1 2\n0 1 2 3\n 0 1 2\n0 1 1 1\n\na3+df1\n[[1 2 3]]\nc3 a3\ni3 \nx3 1\n================\nc3 a3 a3 a3\ni3 \nx3 1 2 3\nc3 a3 a3 a3\ni3 \nx3 1 1 1\n\na3+df2\n[[1 2 3]]\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4 a4 a4\ni4 \nx4 1 2 3\ny4 1 2 3\nz4 1 2 3\nc4 a4 a4 a4\ni4 \nx4 1 1 1\ny4 2 2 2\nz4 3 3 3\n\na3+df3\n[[1 2 3]]\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n\na3+df4\n[[1 2 3]]\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 1 2 3\nz6 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\na4+df_none\n[[1]\n [2]\n [3]]\n 0\n0 1\n================\n 0\n0 1\n1 2\n2 3\n 0\n0 1\n1 1\n2 1\n\na4+df1\n[[1]\n [2]\n [3]]\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni3 \nx3 1\nx3 2\nx3 3\nc3 a3\ni3 \nx3 1\nx3 1\nx3 1\n\na4+df2\n[[1]\n [2]\n [3]]\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n\na4+df3\n[[1]\n [2]\n [3]]\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 1 1\nx5 2 2 2\nx5 3 3 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nx5 1 2 3\nx5 1 2 3\n\na4+df4\n[[1]\n [2]\n [3]]\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 2 2 2\nz6 3 3 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\na5+df_none\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n 0\n0 1\n================\n 0 1 2\n0 1 2 3\n1 4 5 6\n2 7 8 9\n 0 1 2\n0 1 1 1\n1 1 1 1\n2 1 1 1\n\na5+df1\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\nc3 a3\ni3 \nx3 1\n================\nc3 a3 a3 a3\ni3 \nx3 1 2 3\nx3 4 5 6\nx3 7 8 9\nc3 a3 a3 a3\ni3 \nx3 1 1 1\nx3 1 1 1\nx3 1 1 1\n\na5+df2\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4 a4 a4\ni4 \nx4 1 2 3\ny4 4 5 6\nz4 7 8 9\nc4 a4 a4 a4\ni4 \nx4 1 1 1\ny4 2 2 2\nz4 3 3 3\n\na5+df3\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nx5 4 5 6\nx5 7 8 9\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nx5 1 2 3\nx5 1 2 3\n\na5+df4\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\n"
],
[
"# Broadcasting series and dataframes\na_args = [\n ('sr_none', sr_none),\n ('sr1', sr1),\n ('sr2', sr2)\n]\nsr_args = [\n ('df_none', df_none),\n ('df1', df1),\n ('df2', df2),\n ('df3', df3),\n ('df4', df4)\n]\narg_combs = list(itertools.product(a_args, sr_args))\n\nfor (n1, arg1), (n2, arg2) in arg_combs:\n print(n1 + '+' + n2)\n print(arg1)\n print(arg2)\n print(\"================\")\n arg1, arg2 = reshape_fns.broadcast(arg1, arg2)\n print(arg1)\n print(arg2)\n print()",
"sr_none+df_none\n0 1\ndtype: int64\n 0\n0 1\n================\n 0\n0 1\n 0\n0 1\n\nsr_none+df1\n0 1\ndtype: int64\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni3 \nx3 1\nc3 a3\ni3 \nx3 1\n\nsr_none+df2\n0 1\ndtype: int64\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni4 \nx4 1\ny4 1\nz4 1\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n\nsr_none+df3\n0 1\ndtype: int64\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni5 \nx5 1 1 1\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n\nsr_none+df4\n0 1\ndtype: int64\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n\nsr1+df_none\ni1\nx1 1\nName: a1, dtype: int64\n 0\n0 1\n================\n 0\ni1 \nx1 1\n 0\ni1 \nx1 1\n\nsr1+df1\ni1\nx1 1\nName: a1, dtype: int64\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni1 i3 \nx1 x3 1\nc3 a3\ni1 i3 \nx1 x3 1\n\nsr1+df2\ni1\nx1 1\nName: a1, dtype: int64\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni1 i4 \nx1 x4 1\n y4 1\n z4 1\nc4 a4\ni1 i4 \nx1 x4 1\n y4 2\n z4 3\n\nsr1+df3\ni1\nx1 1\nName: a1, dtype: int64\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni1 i5 \nx1 x5 1 1 1\nc5 a5 b5 c5\ni1 i5 \nx1 x5 1 2 3\n\nsr1+df4\ni1\nx1 1\nName: a1, dtype: int64\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni1 i6 \nx1 x6 1 1 1\n y6 1 1 1\n z6 1 1 1\nc6 a6 b6 c6\ni1 i6 \nx1 x6 1 2 3\n y6 4 5 6\n z6 7 8 9\n\nsr2+df_none\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\n 0\n0 1\n================\n 0\ni2 \nx2 1\ny2 2\nz2 3\n 0\ni2 \nx2 1\ny2 1\nz2 1\n\nsr2+df1\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\nc3 a3\ni3 \nx3 1\n================\nc3 a3\ni2 i3 \nx2 x3 1\ny2 x3 2\nz2 x3 3\nc3 a3\ni2 i3 \nx2 x3 1\ny2 x3 1\nz2 x3 1\n\nsr2+df2\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n================\nc4 a4\ni2 i4 \nx2 x4 1\ny2 y4 2\nz2 z4 3\nc4 a4\ni2 i4 \nx2 x4 1\ny2 y4 2\nz2 z4 3\n\nsr2+df3\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\nc5 a5 b5 c5\ni5 \nx5 1 2 3\n================\nc5 a5 b5 c5\ni2 i5 \nx2 x5 1 1 1\ny2 x5 2 2 2\nz2 x5 3 3 3\nc5 a5 b5 c5\ni2 i5 \nx2 x5 1 2 3\ny2 x5 1 2 3\nz2 x5 1 2 3\n\nsr2+df4\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n================\nc6 a6 b6 c6\ni2 i6 \nx2 x6 1 1 1\ny2 y6 2 2 2\nz2 z6 3 3 3\nc6 a6 b6 c6\ni2 i6 \nx2 x6 1 2 3\ny2 y6 4 5 6\nz2 z6 7 8 9\n\n"
],
[
"[np.broadcast_to(x, (3, 3)) for x in (0, a1, a2, sr_none, sr1, sr2)]",
"_____no_output_____"
],
[
"# Broadcasting all at once\nfor i in reshape_fns.broadcast(\n 0, a1, a2, sr_none, sr1, sr2,\n to_shape=(3, 3),\n index_from='stack',\n columns_from='stack'\n):\n print(i)",
" 0 1 2\ni1 i2 \nx1 x2 0 0 0\n y2 0 0 0\n z2 0 0 0\n 0 1 2\ni1 i2 \nx1 x2 1 1 1\n y2 1 1 1\n z2 1 1 1\n 0 1 2\ni1 i2 \nx1 x2 1 2 3\n y2 1 2 3\n z2 1 2 3\n 0 1 2\ni1 i2 \nx1 x2 1 1 1\n y2 1 1 1\n z2 1 1 1\n 0 1 2\ni1 i2 \nx1 x2 1 1 1\n y2 1 1 1\n z2 1 1 1\n 0 1 2\ni1 i2 \nx1 x2 1 1 1\n y2 2 2 2\n z2 3 3 3\n"
],
[
"# Broadcasting all at once\nfor i in reshape_fns.broadcast(\n v1, a1, a2, a3, a4, a5, sr_none, sr1, sr2, df_none, df1, df2, df3, df4,\n index_from='stack',\n columns_from='stack'\n):\n print(i)",
"c3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 0 0 0\n y2 x3 y4 x5 y6 0 0 0\n z2 x3 z4 x5 z6 0 0 0\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 1 2 3\n z2 x3 z4 x5 z6 1 2 3\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 1 2 3\n z2 x3 z4 x5 z6 1 2 3\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 2 2 2\n z2 x3 z4 x5 z6 3 3 3\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 4 5 6\n z2 x3 z4 x5 z6 7 8 9\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 2 2 2\n z2 x3 z4 x5 z6 3 3 3\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 2 2 2\n z2 x3 z4 x5 z6 3 3 3\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 1 2 3\n z2 x3 z4 x5 z6 1 2 3\nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 4 5 6\n z2 x3 z4 x5 z6 7 8 9\n"
],
[
"for i in reshape_fns.broadcast(\n v1, a1, a2, a3, a4, a5, sr_none, sr1, sr2, df_none, df1, df2, df3, df4,\n index_from=None, # use as-is\n columns_from=None\n):\n print(i)",
" 0 1 2\n0 0 0 0\n1 0 0 0\n2 0 0 0\n 0 1 2\n0 1 1 1\n1 1 1 1\n2 1 1 1\n 0 1 2\n0 1 2 3\n1 1 2 3\n2 1 2 3\n 0 1 2\n0 1 2 3\n1 1 2 3\n2 1 2 3\n 0 1 2\n0 1 1 1\n1 2 2 2\n2 3 3 3\n 0 1 2\n0 1 2 3\n1 4 5 6\n2 7 8 9\n 0 1 2\n0 1 1 1\n1 1 1 1\n2 1 1 1\n a1 a1 a1\ni1 \nx1 1 1 1\nx1 1 1 1\nx1 1 1 1\n a2 a2 a2\ni2 \nx2 1 1 1\ny2 2 2 2\nz2 3 3 3\n 0 1 2\n0 1 1 1\n1 1 1 1\n2 1 1 1\nc3 a3 a3 a3\ni3 \nx3 1 1 1\nx3 1 1 1\nx3 1 1 1\nc4 a4 a4 a4\ni4 \nx4 1 1 1\ny4 2 2 2\nz4 3 3 3\nc5 a5 b5 c5\ni5 \nx5 1 2 3\nx5 1 2 3\nx5 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n"
],
[
"for i in reshape_fns.broadcast(\n v1, a1, a2, a3, a4, a5, sr_none, sr1, sr2, df_none, df1, df2, df3, df4,\n index_from=-1, # take index from the last dataframe\n columns_from=-1\n):\n print(i)",
"c6 a6 b6 c6\ni6 \nx6 0 0 0\ny6 0 0 0\nz6 0 0 0\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 1 2 3\nz6 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 1 2 3\nz6 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 2 2 2\nz6 3 3 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 2 2 2\nz6 3 3 3\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 2 2 2\nz6 3 3 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 1 2 3\nz6 1 2 3\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n"
],
[
"for i in reshape_fns.broadcast(\n v1, a1, a2, a3, a4, a5, sr_none, sr1, sr2, df_none, df1, df2, df3, df4,\n index_from=multi_i, # specify manually\n columns_from=multi_c\n):\n print(i)",
"c7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 0 0 0\ny7 y8 0 0 0\nz7 z8 0 0 0\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 1 1 1\nz7 z8 1 1 1\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 2 3\ny7 y8 1 2 3\nz7 z8 1 2 3\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 2 3\ny7 y8 1 2 3\nz7 z8 1 2 3\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 2 2 2\nz7 z8 3 3 3\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 2 3\ny7 y8 4 5 6\nz7 z8 7 8 9\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 1 1 1\nz7 z8 1 1 1\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 1 1 1\nz7 z8 1 1 1\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 2 2 2\nz7 z8 3 3 3\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 1 1 1\nz7 z8 1 1 1\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 1 1 1\nz7 z8 1 1 1\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 1 1\ny7 y8 2 2 2\nz7 z8 3 3 3\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 2 3\ny7 y8 1 2 3\nz7 z8 1 2 3\nc7 a7 b7 c7\nc8 a8 b8 c8\ni7 i8 \nx7 x8 1 2 3\ny7 y8 4 5 6\nz7 z8 7 8 9\n"
],
[
"# Do not clean columns\nvbt.settings.broadcasting['drop_duplicates'] = False\nvbt.settings.broadcasting['drop_redundant'] = False\nvbt.settings.broadcasting['ignore_sr_names'] = False\n\nfor i in reshape_fns.broadcast(\n v1, a1, a2, a3, a4, a5, sr_none, sr1, sr2, df_none, df1, df2, df3, df4,\n index_from='stack', # stack but do not clean\n columns_from='stack'\n):\n print(i)\n \nvbt.settings.broadcasting.reset()",
" a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 0 0 0\n y2 x3 y4 x5 y6 0 0 0\n z2 x3 z4 x5 z6 0 0 0\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 1 2 3\n z2 x3 z4 x5 z6 1 2 3\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 1 2 3\n z2 x3 z4 x5 z6 1 2 3\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 2 2 2\n z2 x3 z4 x5 z6 3 3 3\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 4 5 6\n z2 x3 z4 x5 z6 7 8 9\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 2 2 2\n z2 x3 z4 x5 z6 3 3 3\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 1 1 1\n z2 x3 z4 x5 z6 1 1 1\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 1 1\n y2 x3 y4 x5 y6 2 2 2\n z2 x3 z4 x5 z6 3 3 3\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 1 2 3\n z2 x3 z4 x5 z6 1 2 3\n a1 \n a2 \nc3 a3 \nc4 a4 \nc5 a5 b5 c5\nc6 a6 b6 c6\ni1 i2 i3 i4 i5 i6 \nx1 x2 x3 x4 x5 x6 1 2 3\n y2 x3 y4 x5 y6 4 5 6\n z2 x3 z4 x5 z6 7 8 9\n"
],
[
"big_a = np.empty((1000, 1000))",
"_____no_output_____"
],
[
"print(reshape_fns.broadcast(np.empty((1,)), big_a)[0].flags)\n%timeit reshape_fns.broadcast(np.empty((1,)), big_a)\n\nprint(reshape_fns.broadcast(np.empty((1,)), big_a, require_kwargs={'requirements': 'W'})[0].flags)\n%timeit reshape_fns.broadcast(np.empty((1,)), big_a, require_kwargs={'requirements': 'W'})\n\nprint(reshape_fns.broadcast(np.empty((1,)), big_a, require_kwargs={'requirements': 'C'})[0].flags)\n%timeit reshape_fns.broadcast(np.empty((1,)), big_a, require_kwargs={'requirements': 'C'})\n\nprint(reshape_fns.broadcast(np.empty((1,)), big_a, require_kwargs={'requirements': 'F'})[0].flags)\n%timeit reshape_fns.broadcast(np.empty((1,)), big_a, require_kwargs={'requirements': 'F'})",
" C_CONTIGUOUS : False\n F_CONTIGUOUS : False\n OWNDATA : False\n WRITEABLE : False\n ALIGNED : True\n WRITEBACKIFCOPY : False\n UPDATEIFCOPY : False\n\n31.4 µs ± 325 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n C_CONTIGUOUS : True\n F_CONTIGUOUS : False\n OWNDATA : True\n WRITEABLE : True\n ALIGNED : True\n WRITEBACKIFCOPY : False\n UPDATEIFCOPY : False\n\n4.09 ms ± 50.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n C_CONTIGUOUS : True\n F_CONTIGUOUS : False\n OWNDATA : True\n WRITEABLE : True\n ALIGNED : True\n WRITEBACKIFCOPY : False\n UPDATEIFCOPY : False\n\n2.12 ms ± 430 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n C_CONTIGUOUS : False\n F_CONTIGUOUS : True\n OWNDATA : True\n WRITEABLE : True\n ALIGNED : True\n WRITEBACKIFCOPY : False\n UPDATEIFCOPY : False\n\n8.54 ms ± 678 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
],
[
"print(reshape_fns.broadcast(v1, df4, to_pd=False))\nprint(reshape_fns.broadcast(v1, df4, to_pd=True))",
"(array([[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]), array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]))\n(c6 a6 b6 c6\ni6 \nx6 0 0 0\ny6 0 0 0\nz6 0 0 0, c6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9)\n"
],
[
"# One-side broadcasting, default behaviour is copying index/columns from the second argument\nprint(reshape_fns.broadcast_to(sr1, sr1))\nprint(reshape_fns.broadcast_to(sr1, sr2))\nprint(reshape_fns.broadcast_to(sr1, df1))\nprint(reshape_fns.broadcast_to(sr1, df2))\nprint(reshape_fns.broadcast_to(sr1, df3))\nprint(reshape_fns.broadcast_to(sr1, df4))",
"i1\nx1 1\nName: a1, dtype: int64\ni2\nx2 1\ny2 1\nz2 1\nName: a2, dtype: int64\nc3 a3\ni3 \nx3 1\nc4 a4\ni4 \nx4 1\ny4 1\nz4 1\nc5 a5 b5 c5\ni5 \nx5 1 1 1\nc6 a6 b6 c6\ni6 \nx6 1 1 1\ny6 1 1 1\nz6 1 1 1\n"
],
[
"# Broadcasting first element to be an array out of the second argument\nprint(reshape_fns.broadcast_to_array_of(0.1, v1))\nprint(reshape_fns.broadcast_to_array_of([0.1], v1))\nprint(reshape_fns.broadcast_to_array_of([0.1, 0.2], v1))",
"[0.1]\n[0.1]\n[0.1 0.2]\n"
],
[
"print(reshape_fns.broadcast_to_array_of(0.1, sr2))\nprint(reshape_fns.broadcast_to_array_of([0.1], sr2))\nprint(reshape_fns.broadcast_to_array_of([0.1, 0.2], sr2))\nprint(reshape_fns.broadcast_to_array_of([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], sr2))",
"[[0.1 0.1 0.1]]\n[[0.1 0.1 0.1]]\n[[0.1 0.1 0.1]\n [0.2 0.2 0.2]]\n[[0.1 0.2 0.3]\n [0.4 0.5 0.6]]\n"
],
[
"print(reshape_fns.broadcast_to_array_of(0.1, df2))\nprint(reshape_fns.broadcast_to_array_of([0.1], df2))\nprint(reshape_fns.broadcast_to_array_of([0.1, 0.2], df2))\nprint(reshape_fns.broadcast_to_array_of([[[0.1], [0.2], [0.3]], [[0.4], [0.5], [0.6]]], df2))",
"[[[0.1]\n [0.1]\n [0.1]]]\n[[[0.1]\n [0.1]\n [0.1]]]\n[[[0.1]\n [0.1]\n [0.1]]\n\n [[0.2]\n [0.2]\n [0.2]]]\n[[[0.1]\n [0.2]\n [0.3]]\n\n [[0.4]\n [0.5]\n [0.6]]]\n"
],
[
"print(reshape_fns.broadcast_to_array_of(0.1, np.empty((2, 2, 2)))) # works even for ndim > 2",
"[[[[0.1 0.1]\n [0.1 0.1]]\n\n [[0.1 0.1]\n [0.1 0.1]]]]\n"
],
[
"print(reshape_fns.broadcast_to_axis_of(10, np.empty((2,)), 0))\nprint(reshape_fns.broadcast_to_axis_of(10, np.empty((2,)), 1))\nprint(reshape_fns.broadcast_to_axis_of(10, np.empty((2, 3)), 0))\nprint(reshape_fns.broadcast_to_axis_of(10, np.empty((2, 3)), 1))\nprint(reshape_fns.broadcast_to_axis_of(10, np.empty((2, 3)), 2))",
"[10 10]\n10\n[10 10]\n[10 10 10]\n10\n"
],
[
"i = pd.MultiIndex.from_arrays([[1, 1, 2, 2], [3, 4, 3, 4], ['a', 'b', 'c', 'd']])\nsr = pd.Series([1, 2, 3, 4], index=i)\nprint(reshape_fns.unstack_to_array(sr))",
"[[[ 1. nan nan nan]\n [nan 2. nan nan]]\n\n [[nan nan 3. nan]\n [nan nan nan 4.]]]\n"
],
[
"print(reshape_fns.make_symmetric(sr1))\nprint(reshape_fns.make_symmetric(sr2))\nprint(reshape_fns.make_symmetric(df1))\nprint(reshape_fns.make_symmetric(df2))\nprint(reshape_fns.make_symmetric(df3))\nprint(reshape_fns.make_symmetric(df4))\nprint(reshape_fns.make_symmetric(df5))\nprint(reshape_fns.make_symmetric(pd.Series([1, 2, 3], name='yo'), sort=False))",
"('i1', None) a1 x1\n(i1, None) \na1 NaN 1.0\nx1 1.0 NaN\n('i2', None) a2 x2 y2 z2\n(i2, None) \na2 NaN 1.0 2.0 3.0\nx2 1.0 NaN NaN NaN\ny2 2.0 NaN NaN NaN\nz2 3.0 NaN NaN NaN\n('i3', 'c3') a3 x3\n(i3, c3) \na3 NaN 1.0\nx3 1.0 NaN\n('i4', 'c4') a4 x4 y4 z4\n(i4, c4) \na4 NaN 1.0 2.0 3.0\nx4 1.0 NaN NaN NaN\ny4 2.0 NaN NaN NaN\nz4 3.0 NaN NaN NaN\n('i5', 'c5') a5 b5 c5 x5\n(i5, c5) \na5 NaN NaN NaN 1.0\nb5 NaN NaN NaN 2.0\nc5 NaN NaN NaN 3.0\nx5 1.0 2.0 3.0 NaN\n('i6', 'c6') a6 b6 c6 x6 y6 z6\n(i6, c6) \na6 NaN NaN NaN 1.0 4.0 7.0\nb6 NaN NaN NaN 2.0 5.0 8.0\nc6 NaN NaN NaN 3.0 6.0 9.0\nx6 1.0 2.0 3.0 NaN NaN NaN\ny6 4.0 5.0 6.0 NaN NaN NaN\nz6 7.0 8.0 9.0 NaN NaN NaN\n('i7', 'c7') a7 b7 c7 x7 y7 z7\n('i8', 'c8') a8 b8 c8 x8 y8 z8\n(i7, c7) (i8, c8) \na7 a8 NaN NaN NaN 1.0 4.0 7.0\nb7 b8 NaN NaN NaN 2.0 5.0 8.0\nc7 c8 NaN NaN NaN 3.0 6.0 9.0\nx7 x8 1.0 2.0 3.0 NaN NaN NaN\ny7 y8 4.0 5.0 6.0 NaN NaN NaN\nz7 z8 7.0 8.0 9.0 NaN NaN NaN\n 0 1 2 yo\n0 NaN NaN NaN 1.0\n1 NaN NaN NaN 2.0\n2 NaN NaN NaN 3.0\nyo 1.0 2.0 3.0 NaN\n"
],
[
"print(reshape_fns.unstack_to_df(df5.iloc[0]))\nprint(reshape_fns.unstack_to_df(sr, index_levels=0, column_levels=1))\nprint(reshape_fns.unstack_to_df(sr, index_levels=(0, 1), column_levels=2))\nprint(reshape_fns.unstack_to_df(sr, index_levels=0, column_levels=1, symmetric=True).columns)",
"c8 a8 b8 c8\nc7 \na7 1.0 NaN NaN\nb7 NaN 2.0 NaN\nc7 NaN NaN 3.0\n 3 4\n1 1.0 2.0\n2 3.0 4.0\n a b c d\n1 3 1.0 NaN NaN NaN\n 4 NaN 2.0 NaN NaN\n2 3 NaN NaN 3.0 NaN\n 4 NaN NaN NaN 4.0\nInt64Index([1, 2, 3, 4], dtype='int64')\n"
]
],
[
[
"## indexing",
"_____no_output_____"
]
],
[
[
"PandasIndexer = indexing.PandasIndexer\nParamIndexer = indexing.ParamIndexerFactory(['param1', 'param2', 'tuple'])\n\nclass H(PandasIndexer, ParamIndexer):\n def __init__(self, a, param1_mapper, param2_mapper, tuple_mapper):\n self.a = a\n \n self._param1_mapper = param1_mapper\n self._param2_mapper = param2_mapper\n self._tuple_mapper = tuple_mapper\n \n PandasIndexer.__init__(self, my_kw='PandasIndexer')\n ParamIndexer.__init__(self, [param1_mapper, param2_mapper, tuple_mapper], my_kw='ParamIndexer')\n \n def _indexing_func(self, pd_indexing_func, my_kw=None): \n # As soon as you call iloc etc., performs it on each dataframe and mapper and returns a new class instance\n print(my_kw)\n param1_mapper = indexing.indexing_on_mapper(self._param1_mapper, self.a, pd_indexing_func)\n param2_mapper = indexing.indexing_on_mapper(self._param2_mapper, self.a, pd_indexing_func)\n tuple_mapper = indexing.indexing_on_mapper(self._tuple_mapper, self.a, pd_indexing_func)\n return H(pd_indexing_func(self.a), param1_mapper, param2_mapper, tuple_mapper)\n \n @classmethod\n def run(cls, a, params1, params2, level_names=('p1', 'p2')):\n a = reshape_fns.to_2d(a)\n # Build column hierarchy\n params1_idx = pd.Index(params1, name=level_names[0])\n params2_idx = pd.Index(params2, name=level_names[1])\n params_idx = index_fns.stack_indexes(params1_idx, params2_idx)\n new_columns = index_fns.combine_indexes(params_idx, a.columns)\n \n # Build mappers\n param1_mapper = np.repeat(params1, len(a.columns))\n param1_mapper = pd.Series(param1_mapper, index=new_columns, name=params1_idx.name)\n \n param2_mapper = np.repeat(params2, len(a.columns))\n param2_mapper = pd.Series(param2_mapper, index=new_columns, name=params2_idx.name)\n \n tuple_mapper = list(zip(*list(map(lambda x: x.values, [param1_mapper, param2_mapper]))))\n tuple_mapper = pd.Series(tuple_mapper, index=new_columns, name=(params1_idx.name, params2_idx.name))\n \n # Tile a to match the length of new_columns\n a = array_wrapper.ArrayWrapper(a.index, new_columns, 2).wrap(reshape_fns.tile(a.values, 4, axis=1))\n return cls(a, param1_mapper, param2_mapper, tuple_mapper)\n \n\n# Similate an indicator with two params\nh = H.run(df4, [0.1, 0.1, 0.2, 0.2], [0.3, 0.4, 0.5, 0.6])\n\nprint(df4)\nprint(h.a)\nprint(h._param1_mapper)\nprint(h._param2_mapper)\nprint(h._tuple_mapper)",
"c6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\np1 0.1 0.2 \np2 0.3 0.4 0.5 0.6 \nc6 a6 b6 c6 a6 b6 c6 a6 b6 c6 a6 b6 c6\ni6 \nx6 1 2 3 1 2 3 1 2 3 1 2 3\ny6 4 5 6 4 5 6 4 5 6 4 5 6\nz6 7 8 9 7 8 9 7 8 9 7 8 9\np1 p2 c6\n0.1 0.3 a6 0.1\n b6 0.1\n c6 0.1\n 0.4 a6 0.1\n b6 0.1\n c6 0.1\n0.2 0.5 a6 0.2\n b6 0.2\n c6 0.2\n 0.6 a6 0.2\n b6 0.2\n c6 0.2\nName: p1, dtype: float64\np1 p2 c6\n0.1 0.3 a6 0.3\n b6 0.3\n c6 0.3\n 0.4 a6 0.4\n b6 0.4\n c6 0.4\n0.2 0.5 a6 0.5\n b6 0.5\n c6 0.5\n 0.6 a6 0.6\n b6 0.6\n c6 0.6\nName: p2, dtype: float64\np1 p2 c6\n0.1 0.3 a6 (0.1, 0.3)\n b6 (0.1, 0.3)\n c6 (0.1, 0.3)\n 0.4 a6 (0.1, 0.4)\n b6 (0.1, 0.4)\n c6 (0.1, 0.4)\n0.2 0.5 a6 (0.2, 0.5)\n b6 (0.2, 0.5)\n c6 (0.2, 0.5)\n 0.6 a6 (0.2, 0.6)\n b6 (0.2, 0.6)\n c6 (0.2, 0.6)\nName: (p1, p2), dtype: object\n"
],
[
"# Indexing operations are delegated to the underlying dataframes\nprint(h[(0.1, 0.3, 'a6')].a)\nprint(h.loc[:, (0.1, 0.3, 'a6'):(0.1, 0.3, 'c6')].a)\nprint(h.iloc[-2:, -2:].a)\nprint(h.xs((0.1, 0.3), level=('p1', 'p2'), axis=1).a.columns)",
"PandasIndexer\ni6\nx6 1\ny6 4\nz6 7\nName: (0.1, 0.3, a6), dtype: int64\nPandasIndexer\np1 0.1 \np2 0.3 \nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nPandasIndexer\np1 0.2 \np2 0.6 \nc6 b6 c6\ni6 \ny6 5 6\nz6 8 9\nPandasIndexer\nIndex(['a6', 'b6', 'c6'], dtype='object', name='c6')\n"
],
[
"print(h.param1_loc[0.1].a.columns)\nprint(h.param1_loc[0.1:0.1].a)\nprint(h.param1_loc[[0.1, 0.1]].a)",
"ParamIndexer\nMultiIndex([(0.1, 0.3, 'a6'),\n (0.1, 0.3, 'b6'),\n (0.1, 0.3, 'c6'),\n (0.1, 0.4, 'a6'),\n (0.1, 0.4, 'b6'),\n (0.1, 0.4, 'c6')],\n names=['p1', 'p2', 'c6'])\nParamIndexer\np1 0.1 \np2 0.3 0.4 \nc6 a6 b6 c6 a6 b6 c6\ni6 \nx6 1 2 3 1 2 3\ny6 4 5 6 4 5 6\nz6 7 8 9 7 8 9\nParamIndexer\np1 0.1 \np2 0.3 0.4 0.3 0.4 \nc6 a6 b6 c6 a6 b6 c6 a6 b6 c6 a6 b6 c6\ni6 \nx6 1 2 3 1 2 3 1 2 3 1 2 3\ny6 4 5 6 4 5 6 4 5 6 4 5 6\nz6 7 8 9 7 8 9 7 8 9 7 8 9\n"
],
[
"print(h.param2_loc[0.3].a)\nprint(h.param2_loc[0.3:0.3].a)\nprint(h.param2_loc[[0.3, 0.3]].a.columns)",
"ParamIndexer\np1 0.1 \np2 0.3 \nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nParamIndexer\np1 0.1 \np2 0.3 \nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nParamIndexer\nMultiIndex([(0.1, 0.3, 'a6'),\n (0.1, 0.3, 'b6'),\n (0.1, 0.3, 'c6'),\n (0.1, 0.3, 'a6'),\n (0.1, 0.3, 'b6'),\n (0.1, 0.3, 'c6')],\n names=['p1', 'p2', 'c6'])\n"
],
[
"print(h.tuple_loc[(0.1, 0.3)].a)\nprint(h.tuple_loc[(0.1, 0.3):(0.1, 0.3)].a.columns)\nprint(h.tuple_loc[[(0.1, 0.3), (0.1, 0.3)]].a.columns)",
"ParamIndexer\np1 0.1 \np2 0.3 \nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\nParamIndexer\nMultiIndex([(0.1, 0.3, 'a6'),\n (0.1, 0.3, 'b6'),\n (0.1, 0.3, 'c6')],\n names=['p1', 'p2', 'c6'])\nParamIndexer\nMultiIndex([(0.1, 0.3, 'a6'),\n (0.1, 0.3, 'b6'),\n (0.1, 0.3, 'c6'),\n (0.1, 0.3, 'a6'),\n (0.1, 0.3, 'b6'),\n (0.1, 0.3, 'c6')],\n names=['p1', 'p2', 'c6'])\n"
]
],
[
[
"## combine_fns",
"_____no_output_____"
]
],
[
[
"vbt.settings.broadcasting['index_from'] = 'stack'\nvbt.settings.broadcasting['columns_from'] = 'stack'",
"_____no_output_____"
],
[
"print(combine_fns.apply_and_concat_one(3, lambda i, x, a: x + a[i], sr2.values, [10, 20, 30]))\nprint(combine_fns.apply_and_concat_one_nb(3, njit(lambda i, x, a: x + a[i]), sr2.values, (10, 20, 30)))\n\nprint(combine_fns.apply_and_concat_one(3, lambda i, x, a: x + a[i], df4.values, [10, 20, 30]))\nprint(combine_fns.apply_and_concat_one_nb(3, njit(lambda i, x, a: x + a[i]), df4.values, (10, 20, 30)))",
"[[11 21 31]\n [12 22 32]\n [13 23 33]]\n[[11 21 31]\n [12 22 32]\n [13 23 33]]\n[[11 12 13 21 22 23 31 32 33]\n [14 15 16 24 25 26 34 35 36]\n [17 18 19 27 28 29 37 38 39]]\n[[11 12 13 21 22 23 31 32 33]\n [14 15 16 24 25 26 34 35 36]\n [17 18 19 27 28 29 37 38 39]]\n"
],
[
"print(combine_fns.apply_and_concat_multiple(3, lambda i, x, a: (x, x + a[i]), sr2.values, [10, 20, 30]))\nprint(combine_fns.apply_and_concat_multiple_nb(3, njit(lambda i, x, a: (x, x + a[i])), sr2.values, (10, 20, 30)))\n\nprint(combine_fns.apply_and_concat_multiple(3, lambda i, x, a: (x, x + a[i]), df4.values, [10, 20, 30]))\nprint(combine_fns.apply_and_concat_multiple_nb(3, njit(lambda i, x, a: (x, x + a[i])), df4.values, (10, 20, 30)))",
"[array([[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]]), array([[11, 21, 31],\n [12, 22, 32],\n [13, 23, 33]])]\n[array([[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]]), array([[11, 21, 31],\n [12, 22, 32],\n [13, 23, 33]])]\n[array([[1, 2, 3, 1, 2, 3, 1, 2, 3],\n [4, 5, 6, 4, 5, 6, 4, 5, 6],\n [7, 8, 9, 7, 8, 9, 7, 8, 9]]), array([[11, 12, 13, 21, 22, 23, 31, 32, 33],\n [14, 15, 16, 24, 25, 26, 34, 35, 36],\n [17, 18, 19, 27, 28, 29, 37, 38, 39]])]\n[array([[1, 2, 3, 1, 2, 3, 1, 2, 3],\n [4, 5, 6, 4, 5, 6, 4, 5, 6],\n [7, 8, 9, 7, 8, 9, 7, 8, 9]]), array([[11, 12, 13, 21, 22, 23, 31, 32, 33],\n [14, 15, 16, 24, 25, 26, 34, 35, 36],\n [17, 18, 19, 27, 28, 29, 37, 38, 39]])]\n"
],
[
"print(combine_fns.combine_and_concat(sr2.values, (sr2.values*2, sr2.values*3), lambda x, y, a: x + y + a, 100))\nprint(combine_fns.combine_and_concat_nb(sr2.values, (sr2.values*2, sr2.values*3), njit(lambda x, y, a: x + y + a), 100))\n\nprint(combine_fns.combine_and_concat(df4.values, (df4.values*2, df4.values*3), lambda x, y, a: x + y + a, 100))\nprint(combine_fns.combine_and_concat_nb(df4.values, (df4.values*2, df4.values*3), njit(lambda x, y, a: x + y + a), 100))",
"[[103 104]\n [106 108]\n [109 112]]\n[[103 104]\n [106 108]\n [109 112]]\n[[103 106 109 104 108 112]\n [112 115 118 116 120 124]\n [121 124 127 128 132 136]]\n[[103 106 109 104 108 112]\n [112 115 118 116 120 124]\n [121 124 127 128 132 136]]\n"
],
[
"print(combine_fns.combine_multiple((sr2.values, sr2.values*2, sr2.values*3), lambda x, y, a: x + y + a, 100))\nprint(combine_fns.combine_multiple_nb((sr2.values, sr2.values*2, sr2.values*3), njit(lambda x, y, a: x + y + a), 100))\n\nprint(combine_fns.combine_multiple((df4.values, df4.values*2, df4.values*3), lambda x, y, a: x + y + a, 100))\nprint(combine_fns.combine_multiple_nb((df4.values, df4.values*2, df4.values*3), njit(lambda x, y, a: x + y + a), 100))",
"[206 212 218]\n[206 212 218]\n[[206 212 218]\n [224 230 236]\n [242 248 254]]\n[[206 212 218]\n [224 230 236]\n [242 248 254]]\n"
]
],
[
[
"## accessors",
"_____no_output_____"
]
],
[
[
"print(pd.Series.vbt.empty(5, index=np.arange(10, 15), name='a', fill_value=5))\nprint(pd.DataFrame.vbt.empty((5, 3), index=np.arange(10, 15), columns=['a', 'b', 'c'], fill_value=5))\n\nprint(pd.Series.vbt.empty_like(sr2, fill_value=5))\nprint(pd.DataFrame.vbt.empty_like(df4, fill_value=5))",
"10 5\n11 5\n12 5\n13 5\n14 5\nName: a, dtype: int64\n a b c\n10 5 5 5\n11 5 5 5\n12 5 5 5\n13 5 5 5\n14 5 5 5\ni2\nx2 5\ny2 5\nz2 5\nName: a2, dtype: int64\nc6 a6 b6 c6\ni6 \nx6 5 5 5\ny6 5 5 5\nz6 5 5 5\n"
],
[
"print(sr1.vbt.is_series())\nprint(sr1.vbt.is_frame())\nprint(df1.vbt.is_series())\nprint(df2.vbt.is_frame())",
"True\nFalse\nFalse\nTrue\n"
],
[
"print(sr2.vbt.wrapper.index)\nprint(sr2.vbt.wrapper.columns)\nprint(df4.vbt.wrapper.index)\nprint(df4.vbt.wrapper.columns)",
"Index(['x2', 'y2', 'z2'], dtype='object', name='i2')\nIndex(['a2'], dtype='object')\nIndex(['x6', 'y6', 'z6'], dtype='object', name='i6')\nIndex(['a6', 'b6', 'c6'], dtype='object', name='c6')\n"
],
[
"print(df1.vbt.apply_on_index(lambda idx: idx + '_yo', axis=0))\nprint(df1.vbt.apply_on_index(lambda idx: idx + '_yo', axis=1))\ndf1_copy = df1.copy()\ndf1_copy.vbt.apply_on_index(lambda idx: idx + '_yo', axis=0, inplace=True)\nprint(df1_copy)\ndf1_copy.vbt.apply_on_index(lambda idx: idx + '_yo', axis=1, inplace=True)\nprint(df1_copy)",
"c3 a3\ni3 \nx3_yo 1\nc3 a3_yo\ni3 \nx3 1\nc3 a3\ni3 \nx3_yo 1\nc3 a3_yo\ni3 \nx3_yo 1\n"
],
[
"print(sr2.vbt.to_1d_array())\nprint(sr2.vbt.to_2d_array())",
"[1 2 3]\n[[1]\n [2]\n [3]]\n"
],
[
"# It will try to return pd.Series\nprint(sr2.vbt.wrapper.wrap(a2)) # returns sr\nprint(sr2.vbt.wrapper.wrap(df2.values)) # returns sr\nprint(sr2.vbt.wrapper.wrap(df2.values, index=df2.index, columns=df2.columns)) # returns sr\nprint(sr2.vbt.wrapper.wrap(df4.values, columns=df4.columns)) # returns df\nprint(sr2.vbt.wrapper.wrap(df4.values, index=df4.index, columns=df4.columns)) # returns df",
"i2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\ni2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64\ni4\nx4 1\ny4 2\nz4 3\nName: a4, dtype: int64\nc6 a6 b6 c6\ni2 \nx2 1 2 3\ny2 4 5 6\nz2 7 8 9\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n"
],
[
"# It will try to return pd.DataFrame\nprint(df2.vbt.wrapper.wrap(a2)) # returns df\nprint(df2.vbt.wrapper.wrap(sr2.values)) # returns df\nprint(df2.vbt.wrapper.wrap(df4.values, columns=df4.columns)) # returns df\nprint(df2.vbt.wrapper.wrap(df4.values, index=df4.index, columns=df4.columns)) # returns df",
"c4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\nc6 a6 b6 c6\ni4 \nx4 1 2 3\ny4 4 5 6\nz4 7 8 9\nc6 a6 b6 c6\ni6 \nx6 1 2 3\ny6 4 5 6\nz6 7 8 9\n"
],
[
"print(df4.vbt.tile(2, keys=['a', 'b']))\nprint(df4.vbt.repeat(2, keys=['a', 'b']))",
" a b \nc6 a6 b6 c6 a6 b6 c6\ni6 \nx6 1 2 3 1 2 3\ny6 4 5 6 4 5 6\nz6 7 8 9 7 8 9\nc6 a6 b6 c6 \n a b a b a b\ni6 \nx6 1 1 2 2 3 3\ny6 4 4 5 5 6 6\nz6 7 7 8 8 9 9\n"
],
[
"df10 = pd.DataFrame([[1, 2], [4, 5], [7, 8]], columns=multi_c1)\ndf20 = pd.DataFrame([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], columns=multi_c2)\n\nprint(df10)\nprint(df20)\nprint(df10.vbt.align_to(df20))",
"c8 a8 b8\n0 1 2\n1 4 5\n2 7 8\nc7 a7 c7 \nc8 a8 b8 a8 b8\n0 1 2 3 4\n1 4 5 6 7\n2 7 8 9 10\nc7 a7 c7 \nc8 a8 b8 a8 b8\n0 1 2 1 2\n1 4 5 4 5\n2 7 8 7 8\n"
],
[
"print(pd.DataFrame.vbt.broadcast(\n sr2,\n 10\n))\nprint(sr2.vbt.broadcast(\n 10\n))\nprint(sr2.vbt.broadcast_to(\n df2\n))",
"(i2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64, i2\nx2 10\ny2 10\nz2 10\nName: a2, dtype: int64)\n(i2\nx2 1\ny2 2\nz2 3\nName: a2, dtype: int64, i2\nx2 10\ny2 10\nz2 10\nName: a2, dtype: int64)\nc4 a4\ni4 \nx4 1\ny4 2\nz4 3\n"
],
[
"print(sr2.vbt.make_symmetric())\nprint(df2.vbt.make_symmetric())\nprint(df3.vbt.make_symmetric())\nprint(df4.vbt.make_symmetric())",
"('i2', None) a2 x2 y2 z2\n(i2, None) \na2 NaN 1.0 2.0 3.0\nx2 1.0 NaN NaN NaN\ny2 2.0 NaN NaN NaN\nz2 3.0 NaN NaN NaN\n('i4', 'c4') a4 x4 y4 z4\n(i4, c4) \na4 NaN 1.0 2.0 3.0\nx4 1.0 NaN NaN NaN\ny4 2.0 NaN NaN NaN\nz4 3.0 NaN NaN NaN\n('i5', 'c5') a5 b5 c5 x5\n(i5, c5) \na5 NaN NaN NaN 1.0\nb5 NaN NaN NaN 2.0\nc5 NaN NaN NaN 3.0\nx5 1.0 2.0 3.0 NaN\n('i6', 'c6') a6 b6 c6 x6 y6 z6\n(i6, c6) \na6 NaN NaN NaN 1.0 4.0 7.0\nb6 NaN NaN NaN 2.0 5.0 8.0\nc6 NaN NaN NaN 3.0 6.0 9.0\nx6 1.0 2.0 3.0 NaN NaN NaN\ny6 4.0 5.0 6.0 NaN NaN NaN\nz6 7.0 8.0 9.0 NaN NaN NaN\n"
],
[
"print(df5.iloc[:, 0].vbt.unstack_to_array())",
"[[ 1. nan nan]\n [nan 4. nan]\n [nan nan 7.]]\n"
],
[
"print(df5.iloc[:, 0].vbt.unstack_to_df())",
"i8 x8 y8 z8\ni7 \nx7 1.0 NaN NaN\ny7 NaN 4.0 NaN\nz7 NaN NaN 7.0\n"
],
[
"print(sr2.vbt.apply(apply_func=lambda x: x ** 2))\nprint(sr2.vbt.apply(apply_func=lambda x: x ** 2, to_2d=True))\nprint(df2.vbt.apply(apply_func=lambda x: x ** 2))",
"i2\nx2 1\ny2 4\nz2 9\nName: a2, dtype: int64\ni2\nx2 1\ny2 4\nz2 9\nName: a2, dtype: int64\nc4 a4\ni4 \nx4 1\ny4 4\nz4 9\n"
],
[
"print(pd.DataFrame.vbt.concat(sr2, 10, df4, keys=['a', 'b', 'c']))\nprint(sr2.vbt.concat(10, df4, keys=['a', 'b', 'c']))",
" a b c \nc6 a6 b6 c6 a6 b6 c6 a6 b6 c6\ni2 i6 \nx2 x6 1 1 1 10 10 10 1 2 3\ny2 y6 2 2 2 10 10 10 4 5 6\nz2 z6 3 3 3 10 10 10 7 8 9\n a b c \nc6 a6 b6 c6 a6 b6 c6 a6 b6 c6\ni2 i6 \nx2 x6 1 1 1 10 10 10 1 2 3\ny2 y6 2 2 2 10 10 10 4 5 6\nz2 z6 3 3 3 10 10 10 7 8 9\n"
],
[
"print(sr2.vbt.apply_and_concat(3, sr2.values, 10, apply_func=lambda i, x, y, c, d=1: x + y[i] + c + d, d=100))\nprint(sr2.vbt.apply_and_concat(3, sr2.values, 10, apply_func=njit(lambda i, x, y, c: x + y[i] + c + 100)))\nprint(sr2.vbt.apply_and_concat(3, df4.values, 10, apply_func=lambda i, x, y, c, d=1: x + y[:, i] + c + d, d=100))\nprint(sr2.vbt.apply_and_concat(3, df4.values, 10, apply_func=njit(lambda i, x, y, c: x + y[:, i] + c + 100)))\nprint(df4.vbt.apply_and_concat(3, df4.values, 10, apply_func=lambda i, x, y, c, d=1: x + y[:, i] + c + d, d=100))\nprint(df4.vbt.apply_and_concat(\n 3, \n df4.values, \n 10, \n apply_func=njit(lambda i, x, y, c: x + y[:, i] + c + 100), \n keys=pd.Index(['a', 'b', 'c'], name='hello')))",
"apply_idx 0 1 2\ni2 \nx2 112 113 114\ny2 113 114 115\nz2 114 115 116\napply_idx 0 1 2\ni2 \nx2 112 113 114\ny2 113 114 115\nz2 114 115 116\napply_idx 0 1 2\ni2 \nx2 112 113 114\ny2 116 117 118\nz2 120 121 122\napply_idx 0 1 2\ni2 \nx2 112 113 114\ny2 116 117 118\nz2 120 121 122\napply_idx 0 1 2 \nc6 a6 b6 c6 a6 b6 c6 a6 b6 c6\ni6 \nx6 112 116 120 113 117 121 114 118 122\ny6 115 119 123 116 120 124 117 121 125\nz6 118 122 126 119 123 127 120 124 128\nhello a b c \nc6 a6 b6 c6 a6 b6 c6 a6 b6 c6\ni6 \nx6 112 116 120 113 117 121 114 118 122\ny6 115 119 123 116 120 124 117 121 125\nz6 118 122 126 119 123 127 120 124 128\n"
],
[
"print(sr2.vbt.combine_with(10., combine_func=lambda x, y: x + y))\nprint(sr2.vbt.combine_with(10, 100, d=1000, combine_func=lambda x, y, c, d=1: x + y + c + d)) # test args and kwargs\nprint(sr2.vbt.combine_with([10, 20, 30], combine_func=lambda x, y: x + y))\nprint(sr2.vbt.combine_with([[10, 20, 30]], combine_func=lambda x, y: x + y))\nprint(sr2.vbt.combine_with(sr1, combine_func=lambda x, y: x + y, broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with(sr2, combine_func=lambda x, y: x + y, broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with(df2, combine_func=lambda x, y: x + y, broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with(df3, combine_func=lambda x, y: x + y, broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with(df4, combine_func=lambda x, y: x + y, broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with(df5, combine_func=lambda x, y: x + y, broadcast_kwargs=dict(index_from='stack')))",
"i2\nx2 11.0\ny2 12.0\nz2 13.0\nName: a2, dtype: float64\ni2\nx2 1111\ny2 1112\nz2 1113\nName: a2, dtype: int64\ni2\nx2 11\ny2 22\nz2 33\nName: a2, dtype: int64\n a2 a2 a2\ni2 \nx2 11 21 31\ny2 12 22 32\nz2 13 23 33\ni2 i1\nx2 x1 2\ny2 x1 3\nz2 x1 4\ndtype: int64\ni2\nx2 2\ny2 4\nz2 6\nName: a2, dtype: int64\nc4 a4\ni2 i4 \nx2 x4 2\ny2 y4 4\nz2 z4 6\nc5 a5 b5 c5\ni2 i5 \nx2 x5 2 3 4\ny2 x5 3 4 5\nz2 x5 4 5 6\nc6 a6 b6 c6\ni2 i6 \nx2 x6 2 3 4\ny2 y6 6 7 8\nz2 z6 10 11 12\nc7 a7 b7 c7\nc8 a8 b8 c8\ni2 i7 i8 \nx2 x7 x8 2 3 4\ny2 y7 y8 6 7 8\nz2 z7 z8 10 11 12\n"
],
[
"print(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n pd.Series([10, 20, 30])],\n 10, b=100,\n combine_func=lambda x, y, a, b=1: x + y + a + b, \n broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n [[10, 20, 30]],\n pd.Series([10, 20, 30]),\n df1,\n df3],\n 10, b=100,\n combine_func=lambda x, y, a, b=1: x + y + a + b, \n broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n [[10, 20, 30]],\n pd.Series([10, 20, 30]),\n df1,\n df3],\n 10,\n combine_func=njit(lambda x, y, a, b=1: x + y + a + 100), \n broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n [[10, 20, 30]],\n pd.Series([10, 20, 30]),\n df1,\n df3],\n 10,\n combine_func=njit(lambda x, y, a, b=1: x + y + a + 100), \n broadcast_kwargs=dict(index_from='stack')))",
"i2\nx2 361\ny2 382\nz2 403\ndtype: int64\nc3 a3 \nc5 a5 b5 c5\ni2 i3 i5 \nx2 x3 x5 703 724 745\ny2 x3 x5 714 735 756\nz2 x3 x5 725 746 767\nc3 a3 \nc5 a5 b5 c5\ni2 i3 i5 \nx2 x3 x5 703 724 745\ny2 x3 x5 714 735 756\nz2 x3 x5 725 746 767\nc3 a3 \nc5 a5 b5 c5\ni2 i3 i5 \nx2 x3 x5 703 724 745\ny2 x3 x5 714 735 756\nz2 x3 x5 725 746 767\n"
],
[
"# Test concat=True\nprint(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n pd.Series([10, 20, 30])],\n 10, b=100,\n combine_func=lambda x, y, a, b=1: x + y + a + b, \n concat=True,\n broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n [[10, 20, 30]],\n pd.Series([10, 20, 30]),\n df1,\n df3],\n 10, b=100,\n combine_func=lambda x, y, a, b=1: x + y + a + b, \n concat=True,\n broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n [[10, 20, 30]],\n pd.Series([10, 20, 30]),\n df1,\n df3],\n 10,\n combine_func=njit(lambda x, y, a, b=1: x + y + a + 100),\n concat=True,\n broadcast_kwargs=dict(index_from='stack')))\nprint(sr2.vbt.combine_with_multiple(\n [10, \n [10, 20, 30],\n [[10, 20, 30]],\n pd.Series([10, 20, 30]),\n df1,\n df3],\n 10,\n combine_func=njit(lambda x, y, a, b=1: x + y + a + 100),\n concat=True,\n keys=['a', 'b', 'c', 'd', 'e', 'f'],\n broadcast_kwargs=dict(index_from='stack')))",
"combine_idx 0 1 2\ni2 \nx2 121 121 121\ny2 122 132 132\nz2 123 143 143\ncombine_idx 0 1 2 3 4 \\\nc3 a3 a3 a3 a3 a3 \nc5 a5 b5 c5 a5 b5 c5 a5 b5 c5 a5 b5 c5 a5 \ni2 i3 i5 \nx2 x3 x5 121 121 121 121 131 141 121 131 141 121 121 121 112 \ny2 x3 x5 122 122 122 122 132 142 122 132 142 132 132 132 113 \nz2 x3 x5 123 123 123 123 133 143 123 133 143 143 143 143 114 \n\ncombine_idx 5 \nc3 a3 \nc5 b5 c5 a5 b5 c5 \ni2 i3 i5 \nx2 x3 x5 112 112 112 113 114 \ny2 x3 x5 113 113 113 114 115 \nz2 x3 x5 114 114 114 115 116 \ncombine_idx 0 1 2 3 4 \\\nc3 a3 a3 a3 a3 a3 \nc5 a5 b5 c5 a5 b5 c5 a5 b5 c5 a5 b5 c5 a5 \ni2 i3 i5 \nx2 x3 x5 121 121 121 121 131 141 121 131 141 121 121 121 112 \ny2 x3 x5 122 122 122 122 132 142 122 132 142 132 132 132 113 \nz2 x3 x5 123 123 123 123 133 143 123 133 143 143 143 143 114 \n\ncombine_idx 5 \nc3 a3 \nc5 b5 c5 a5 b5 c5 \ni2 i3 i5 \nx2 x3 x5 112 112 112 113 114 \ny2 x3 x5 113 113 113 114 115 \nz2 x3 x5 114 114 114 115 116 \n a b c d e \\\nc3 a3 a3 a3 a3 a3 \nc5 a5 b5 c5 a5 b5 c5 a5 b5 c5 a5 b5 c5 a5 \ni2 i3 i5 \nx2 x3 x5 121 121 121 121 131 141 121 131 141 121 121 121 112 \ny2 x3 x5 122 122 122 122 132 142 122 132 142 132 132 132 113 \nz2 x3 x5 123 123 123 123 133 143 123 133 143 143 143 143 114 \n\n f \nc3 a3 \nc5 b5 c5 a5 b5 c5 \ni2 i3 i5 \nx2 x3 x5 112 112 112 113 114 \ny2 x3 x5 113 113 113 114 115 \nz2 x3 x5 114 114 114 115 116 \n"
],
[
"# Use magic methods with .vbt to do operations with custom broadcasting\n# Regular df3 + df4 will return nans\nprint(df3.vbt + df4.vbt)",
"c5 a5 b5 c5\nc6 a6 b6 c6\ni5 i6 \nx5 x6 2 4 6\n y6 5 7 9\n z6 8 10 12\n"
]
]
] |
[
"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",
"code",
"code"
],
[
"markdown"
],
[
"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"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb15f15f5151ed31a5f01286e118fd62c9f66d3
| 32,122 |
ipynb
|
Jupyter Notebook
|
Types_construits/Les_dictionnaires/Les dictionnaires - Tableaux associatifs.ipynb
|
FDehove/NSI-1ere
|
1a95c5bbe90a913cfa2b4be508d0cf6cb1e4a5fc
|
[
"CC0-1.0"
] | null | null | null |
Types_construits/Les_dictionnaires/Les dictionnaires - Tableaux associatifs.ipynb
|
FDehove/NSI-1ere
|
1a95c5bbe90a913cfa2b4be508d0cf6cb1e4a5fc
|
[
"CC0-1.0"
] | null | null | null |
Types_construits/Les_dictionnaires/Les dictionnaires - Tableaux associatifs.ipynb
|
FDehove/NSI-1ere
|
1a95c5bbe90a913cfa2b4be508d0cf6cb1e4a5fc
|
[
"CC0-1.0"
] | null | null | null | 30.709369 | 549 | 0.507752 |
[
[
[
"<h4>Le but de ce document est de présenter les <b>dictionnaires</b> python.</h4>",
"_____no_output_____"
],
[
"<h1 class=\"alert alert-success\">Les dictionnaires</h1>",
"_____no_output_____"
],
[
"<h2 class=\"alert alert-info\">\nDéfinition : Les dictionnaires</h2>",
"_____no_output_____"
],
[
"<p class=\"alert-warning\">Un <span class=\"inline_code\">dictionnaire</span> est une collection non-ordonnée (non indicée) d’objets (simples ou évolués) qui utilise le mécanisme associatif <span class=\"inline_code\">clef-valeur</span>.</p>",
"_____no_output_____"
],
[
"Une collection, c'est donc comme une liste mais là, elle n'est pas ordonnée : ça n'a pas de sens de dire qu'un élément est avant un autre puiqu'on va les appeler par leur nom (enfin leur clef !). En pratique :",
"_____no_output_____"
],
[
"<h2 class=\"alert alert-info\">Utilisation des dictionnaires</h2>",
"_____no_output_____"
]
],
[
[
"#définition d'un dictionnaire\nage_eleve = {'Pierre':17, 'Paul':15,'Jacques':16}\nprint(age_eleve)",
"{'Pierre': 17, 'Paul': 15, 'Jacques': 16}\n"
]
],
[
[
"<p><span class=inline_code>age_eleve</span> est un dictionnaire, il est délimité par des {}.</p>\n\n<span class=inline_code>Pierre</span> est une <span class=inline_code>clef</span> : <code>key</code> et 17 est la <span class=inline_code>valeur</span> : <code>value</code> associée à cette <span class=inline_code>clef</span>.</p>",
"_____no_output_____"
],
[
"<h2 class=\"alert alert-info\">\n Accès à une valeur du dictionnaire à partir d'une clef</h2>",
"_____no_output_____"
],
[
"Pour connaître l'âge de Pierre on écrit :\nage_eleve[\"Pierre\"]",
"_____no_output_____"
]
],
[
[
"age_eleve[\"Pierre\"]",
"_____no_output_____"
]
],
[
[
"<p class=\"alert alert-danger\"><u>Remarque</u> : si on oublie les guillemets à \"Pierre\", l'interpréteur en déduit que l'on fait référence à une variable nommée Pierre, et il ne la connaît pas. Normal puisqu'ici, elle n'existe pas.</p>",
"_____no_output_____"
]
],
[
[
"age_eleve[Pierre]",
"_____no_output_____"
],
[
"#Alors que l'on peut utiliser une variable ainsi :\nnom=\"Pierre\"\nage_eleve[nom]",
"_____no_output_____"
]
],
[
[
"Pour savoir si une clef est présente dans un dictionnaire on utilise <code>in</code> :",
"_____no_output_____"
]
],
[
[
"print(\"Pierre\" in age_eleve)\nprint(\"Steven\" in age_eleve)",
"_____no_output_____"
]
],
[
[
"<h2 class=\"alert alert-info\">\nParcours des valeurs d'un dictionnaire</h2>",
"_____no_output_____"
],
[
"Pour énumérer toutes les valeurs d'un dictionnaire, on utilise une boucle après avoir créer un itérateur : <code>items()</code> de ses éléments :",
"_____no_output_____"
]
],
[
[
"# age_eleve.item() est de type dict_item c'est une sorte de liste de tuples (clef,valeur)\nage_eleve.items()",
"_____no_output_____"
],
[
"#Ce qui donne, avec une boucle for à deux variables clef,valeur :\nfor clef,valeur in age_eleve.items():\n print(clef+\"\\t\", valeur) #\\t est une tabulation, pour que les valeurs soient alignées.\n ",
"_____no_output_____"
]
],
[
[
"On aurait pu ne lister que les clefs : ",
"_____no_output_____"
]
],
[
[
"#liste des clés\nfor key in age_eleve.keys():\n print(key)",
"_____no_output_____"
]
],
[
[
"Ou ne lister que les valeurs : ",
"_____no_output_____"
]
],
[
[
"#liste des valeurs :\nfor value in age_eleve.values():\n print(value)",
"_____no_output_____"
]
],
[
[
"<p class=\"alert alert-danger\"><u>Remarque</u> :</br>\nSi on ne précise pas keys() ou values(), on itère par défaut sur les clefs :</p>",
"_____no_output_____"
]
],
[
[
"for element in age_eleve: #on itère sans préciser, sur les éléments du dictionnaire\n print(element)\nprint(\"--> On a obtenu une énumération des clefs.\")",
"_____no_output_____"
]
],
[
[
"<h2 class=\"alert alert-info\">Application aux données exif d'une image :</h2>\n\nPour consulter les données exif d'une photo on peut utiliser le module <code>exifread</code> qui s'installe en ligne de commande par : <br/>\n<code>$pip3 install exifread.</code><br/>\nLes données exif peuvent alors être récupérées sous forme de dictionnaire. Comme dans le code suivant :",
"_____no_output_____"
]
],
[
[
"import exifread\nimport os\nprint(\"Le repertoire courant est : \", os.getcwd(),'\\n')\n# Ouverture d'une image pour lecture (en mode binaire)\nf = open(\"ma_photo.jpg\", 'rb')\n\n# Retourne les Exif dans un dictionnaire (variable tags)\ntags = exifread.process_file(f)\nprint(\" \"*(40-len(\"RUBRIQUE\")),\"RUBRIQUE\",\" | \",\"VALEUR\")\nprint(\"-\"*70)\nfor key, val in tags.items():\n if key!=\"JPEGThumbnail\":\n compl=40-len(key)\n print(\" \"*compl,key,\" : \",val)",
"Possibly corrupted field Tag 0x1490 in MakerNote IFD\n"
]
],
[
[
"<p class=\"alert alert-warning\"><u>Travail demandé n°1 :</u><br/>\n1.Munis-toi d'une photo au format compressé jpeg et place-la dans le même répertoire que ce document sous le nom \"ma_photo.jpg\"<br/>\n2. A l'aide du code ci-dessus, retrouve et affiche les dates de prise de vue, la largeur et la hauteur, la durée d'exposition, l'ouverture (FNumber).<br/>\n3. Pendant combien de temps l'obturateur s'est-il ouvert durant la prise de vue ? </p>",
"_____no_output_____"
],
[
"<h2 class=\"alert alert-info\">\nLes types de clefs</h2>",
"_____no_output_____"
],
[
"Les clefs ne sont pas nécessairement de type <span class=\"inline_code\">string</span> :",
"_____no_output_____"
]
],
[
[
"#Des entiers pour les clefs\nshifumi={1:\"Pierre\",2:\"Feuille\",3:\"Ciseaux\"}",
"_____no_output_____"
],
[
"from random import randint\n\n#On associe ainsi à un tirage aléatoire : pierre, feuille ou ciseaux !\nshifumi[randint(1,3)]\n",
"_____no_output_____"
]
],
[
[
"On peut même utiliser des tuples soit pour la clef, soit pour la valeur, soit pour les deux :",
"_____no_output_____"
]
],
[
[
"fiche_adherent={('Pierre',56):(15.4,'à jour de cotisation'),('Lucie',24):(15.1,'à jour de cotisation'),\n ('Pierre',22):(2.6,'à jour de cotisation'),('Lucie',3.2e6):('Non Classé', 'cotisation en retard')}",
"_____no_output_____"
],
[
"#Classement de l 'adhérent.e (on remarquera que sauf en cas d'ambiguité, les \n# parenthèses ne sont pas nécessaires pour appeler un tuple)\nprint(\"fiche_adherent['Lucie',24][0] renvoie : \",fiche_adherent['Lucie',24][0])\n",
"fiche_adherent['Lucie',24][0] renvoie : 15.1\n"
]
],
[
[
"<p class=\"alert alert-warning\"><u>Travail demandé n°2 :</u><br/>\nDans la cellule ci-dessous, écrire un programme avec une boucle réalisant l'affichage suivant :\n\n\n\n</p>",
"_____no_output_____"
]
],
[
[
"#Etat de la cotisation annuelle :\nprint(\"\\r\") #Retour à la ligne\nprint(\"Fichier des adhérent.e.s :\")",
"\nFichier des adhérent.e.s :\n"
]
],
[
[
"<p class=\"alert alert-danger\"><u>Remarque</u></span>.<br/>Il y a une restriction notable : __on ne peut pas utiliser une liste pour définir une clef__ .<br/>\nUne <a href=\"https://wiki.python.org/moin/DictionaryKeys\">explication</a> sur le wiki : les clefs doivent être *hachable* c'est-à-dire que leur valeur permet de calculer un entier qui ne change pas au cours du temps. C'est à cette condition que l'accès à une valeur par la clef via une *table de hash* sera performant.</p>",
"_____no_output_____"
]
],
[
[
"dico={[1,2]:'a'}",
"_____no_output_____"
]
],
[
[
"<h2 class=\"alert alert-info\">\nModification de valeur</h2>",
"_____no_output_____"
],
[
"Les dictionnaires sont modifiables :",
"_____no_output_____"
]
],
[
[
"#Si Lucie améliore sont classement on met à jour le dictionnaire :\nfiche_adherent[('Lucie',24)]=(15.0,'à jour de cotisation')\n#Classement de l 'adhérent.e\nprint(fiche_adherent[('Lucie',24)][0])",
"15.0\n"
]
],
[
[
"Avec un dictionnaire, pour ajouter une paire clef/valeur, il suffit d'écrire :",
"_____no_output_____"
]
],
[
[
"#Si on veut rajouter le puits au shifumi, on rajoute une clef 4 et sa valeur \"Puits\" :\nshifumi[4]=\"Puits\"\n#La liste shifumi devient :\nprint(shifumi)",
"{1: 'Pierre', 2: 'Feuille', 3: 'Ciseaux', 4: 'Puits'}\n"
]
],
[
[
"Alors que l'équivalent avec une liste conduit à un message d'erreur <span class=\"inline_code\">index out of range</span> :",
"_____no_output_____"
]
],
[
[
"#Créons une liste pour notre exemple :\nliste_nature=['arbre','fruit','feuille']\nprint(liste_nature[1])",
"fruit\n"
],
[
"#On voudrait rajouter un élément au rang suivant (3) de la liste en faisant :\nliste_nature[3]='fleur'",
"_____no_output_____"
],
[
"#Il aurait fallu écrire :\nliste_nature.append('fleur')\nliste_nature",
"_____no_output_____"
]
],
[
[
"<p class=\"alert alert-warning\"><u>Travail demandé n°3 :</u><br/>\n1.Reprends les donnees exif de la photo vue ci-dessus et modifie le Copyright en ajoutant ton nom.<br/>\n2.Affiche à nouveau les données et vérifie qu'elles ont bien été modifées.",
"_____no_output_____"
],
[
"<h2 class=\"alert alert-info\">Création en compréhension</h2>",
"_____no_output_____"
],
[
"A l'instar d'une liste, on peut créer un dictionnaire en compréhension !\nDans l'exemple qui suit, on crée la table ascii des lettres majuscules :",
"_____no_output_____"
]
],
[
[
"# chr(n) renvoie le caractère ascii correspondant à un entier.\nprint(\"Dans la table ascii 65 correspond au caractère\",chr(65))\n\n#On génère le dictionnaire associant l'entier à la lettre de l'alphabet majuscule :\nnumero_table_ascii={chr(n): n for n in range(65, 65+26)}\n\nprint(\"Table ascii par lettre :\")\nprint(numero_table_ascii)",
"Dans la table ascii 65 correspond au caractère A\nTable ascii par lettre :\n{'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70, 'G': 71, 'H': 72, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'M': 77, 'N': 78, 'O': 79, 'P': 80, 'Q': 81, 'R': 82, 'S': 83, 'T': 84, 'U': 85, 'V': 86, 'W': 87, 'X': 88, 'Y': 89, 'Z': 90}\n"
],
[
"#Ou à l'inverse avec la fonction ord() qui renvoie l'entier correponsdant à un caractère ascii :\nprint(\"L'entier correspondant au caractère a dans la table ascii est\",ord('a'))\n#On génère le dictionnaire associant la lettre de l'alphabet minuscule au nombre entier entre 97 et 122 :\ncaractere_ascii={ord(i):i for i in \"abcdefghijklmnopqrstuvwxyz\"}\nprint(\"Table ascii par numéro :\")\nprint(caractere_ascii)",
"L'entier correspondant au caractère a dans la table ascii est 97\nTable ascii par numéro :\n{97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g', 104: 'h', 105: 'i', 106: 'j', 107: 'k', 108: 'l', 109: 'm', 110: 'n', 111: 'o', 112: 'p', 113: 'q', 114: 'r', 115: 's', 116: 't', 117: 'u', 118: 'v', 119: 'w', 120: 'x', 121: 'y', 122: 'z'}\n"
],
[
"#Remarque :\n############\n#Pour avoir l'alphabet de façon savante, on peut utiliser le module string :\nimport string\nprint(\"l'alphabet est :\", string.ascii_lowercase)\n#Faire help('string') pour les autres attributs possibles de string",
"l'alphabet est : abcdefghijklmnopqrstuvwxyz\n"
]
],
[
[
"<p class=\"alert alert-warning\"><u>Travail demandé n°4 :</u><br/>\nOn considère la chaîne de caractère (string) :<br/><br/>\n\" >La caméra volante nous pistait depuis notre entrée\n<br/>sur l'anneau périphérique. Dès la rampe, j'avais décon-<br/>necté le pilote et poussé le bobsleigh à deux cents -\"<br/><br/>\n(A. Damasio - La Zone du Dehors).<br/><br/>\nConstruire un dictionnaire dont les clefs sont les caractères ascii utilisés dans la citation et les valeurs, le nombre d'occurences de chaque caractère (on ne prendra pas en compte les sauts de ligne).\n</p>",
"_____no_output_____"
],
[
"<u>Solution:</u>",
"_____no_output_____"
]
],
[
[
"#Placer la solution ici :\n",
"_____no_output_____"
]
],
[
[
"<p class=\"alert alert-warning\"><u>Travail demandé n°5 : chiffrement d'un message.</u><br/>\n1.Créer un dictionnaire dans lequel chaque caractère est une clef, et sa valeur est un caractère différent.<br/>\n2.Réécrire la string <span class='inline_code'>chaine</span> avec ce nouvel alphabet.<br/>\n3.A quelle condition le message est-il facilement déchiffrable ?<br/>\n4.Ecrire un programme de déchiffrement du message.</p>",
"_____no_output_____"
]
],
[
[
"#Placer la solution ici :\n",
"_____no_output_____"
]
],
[
[
"Quelques références :<br/>\nwikibook :https://fr.wikibooks.org/wiki/Programmation_Python/Dictionnaires reprend le livre de swinnen.<br/>\nLe Swinnen : https://inforef.be/swi/download/apprendre_python3_5.pdf<br/>\nSite python-django.dev sur le mode \"comment faire\" : https://python-django.dev/page-apprendre-dictionnaire-python<br/>\nSur la table de hachage :https://fr.wikipedia.org/wiki/Table_de_hachage<br/>\nCompléments : https://thispointer.com/python-6-different-ways-to-create-dictionaries/",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbb181916e0a8559bdbbd29c97429cfff9649284
| 3,713 |
ipynb
|
Jupyter Notebook
|
Data Structures/Recursion/Factorial using recursion.ipynb
|
gmendozah/Data-Structures-and-Algorithms
|
07474db45acfe42855cc0f4cc968c0564b2cb91a
|
[
"MIT"
] | 5 |
2021-10-08T11:21:08.000Z
|
2022-01-24T22:40:03.000Z
|
Data Structures/Recursion/Factorial using recursion.ipynb
|
gmendozah/Data-Structures-and-Algorithms
|
07474db45acfe42855cc0f4cc968c0564b2cb91a
|
[
"MIT"
] | null | null | null |
Data Structures/Recursion/Factorial using recursion.ipynb
|
gmendozah/Data-Structures-and-Algorithms
|
07474db45acfe42855cc0f4cc968c0564b2cb91a
|
[
"MIT"
] | 3 |
2021-12-13T06:50:58.000Z
|
2022-02-05T03:38:49.000Z
| 26.905797 | 256 | 0.538379 |
[
[
[
"# Factorial using recursion",
"_____no_output_____"
],
[
"The **factorial** function is a mathematical function that multiplies a given number, $n$, and all of the whole numbers from $n$ down to 1.\n\nFor example, if $n$ is $4$ then we will get:\n\n$4*3*2*1 = 24$\n\nThis is often notated using an exclamation point, as in $4!$ (which would be read as \"four factorial\").\n\nSo $4! = 4*3*2*1 = 24$\n\nMore generally, we can say that for any input $n$:\n\n$n! = n * (n-1) * (n-2) ... 1$\n\nIf you look at this more closely, you will find that the factorial of any number is the product of that number and the factorial of the next smallest number. In other words:\n\n$n! = n*(n-1)!$\n\nNotice that this is recursive, meaning that we can solve for the factorial of any given number by first solving for the factorial of the next smallest number, and the next smallest number, and the next smallest number, and so on, until we reach 1.\n\nIf you were to write a Python function called `factorial` to calculate the factorial of a number, then we could restate what we said above as follows:\n\n`factorial(n) = n * factorial(n-1)`\n\nSo that is the goal of this exercise: To use recursion to write a function that will take a number and return the factorial of that number.\n\nFor example, you should be able to call your function with `factorial(4)` and get back `24`.\n\n**Note:** By definition, $0! = 1$",
"_____no_output_____"
]
],
[
[
"# Code\n\ndef factorial(n):\n \"\"\"\n Calculate n!\n \n Args:\n n(int): factorial to be computed\n Returns:\n n!\n \"\"\"\n \n # TODO: Write your recursive factorial function here\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n",
"_____no_output_____"
],
[
"# Test Cases\n\nprint (\"Pass\" if (1 == factorial(0)) else \"Fail\")\nprint (\"Pass\" if (1 == factorial(1)) else \"Fail\")\nprint (\"Pass\" if (120 == factorial(5)) else \"Fail\")",
"Pass\nPass\nPass\n"
]
],
[
[
"<span class=\"graffiti-highlight graffiti-id_hfidq8t-id_ok8sbqr\"><i></i><button>Show Solution</button></span>",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cbb182a8e70b329a374b45ef5c04f6539dd02a08
| 30,239 |
ipynb
|
Jupyter Notebook
|
first-neural-network/DLSandboxProject001.ipynb
|
b2btvgs/udacity-deep-learning-first-neural-network
|
9c4054615beaa4b1efb4329239e907cfe00be969
|
[
"MIT"
] | null | null | null |
first-neural-network/DLSandboxProject001.ipynb
|
b2btvgs/udacity-deep-learning-first-neural-network
|
9c4054615beaa4b1efb4329239e907cfe00be969
|
[
"MIT"
] | null | null | null |
first-neural-network/DLSandboxProject001.ipynb
|
b2btvgs/udacity-deep-learning-first-neural-network
|
9c4054615beaa4b1efb4329239e907cfe00be969
|
[
"MIT"
] | null | null | null | 38.277215 | 1,320 | 0.421443 |
[
[
[
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"data_path = 'Bike-Sharing-Dataset/hour.csv'\n\nrides = pd.read_csv(data_path)",
"_____no_output_____"
],
[
"rides.head()",
"_____no_output_____"
],
[
"dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']\nfor each in dummy_fields:\n dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)\n rides = pd.concat([rides, dummies], axis=1)\n \nfields_to_drop = ['instant', 'dteday', 'season', 'weathersit', \n 'weekday', 'atemp', 'mnth', 'workingday', 'hr']\ndata = rides.drop(fields_to_drop, axis=1)\ndata.head()",
"_____no_output_____"
],
[
"quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']\n# Store scalings in a dictionary so we can convert back later\nscaled_features = {}\nfor each in quant_features:\n mean, std = data[each].mean(), data[each].std()\n scaled_features[each] = [mean, std]\n data.loc[:, each] = (data[each] - mean)/std\n ",
"_____no_output_____"
],
[
"# Save data for approximately the last 21 days \ntest_data = data[-21*24:]\n\n# Now remove the test data from the data set \ndata = data[:-21*24]\n\n# Separate the data into features and targets\ntarget_fields = ['cnt', 'casual', 'registered']\nfeatures, targets = data.drop(target_fields, axis=1), data[target_fields]\ntest_features, test_targets = test_data.drop(target_fields, axis=1), test_data[target_fields]",
"_____no_output_____"
],
[
"# Hold out the last 60 days or so of the remaining data as a validation set\ntrain_features, train_targets = features[:-60*24], targets[:-60*24]\nval_features, val_targets = features[-60*24:], targets[-60*24:]",
"_____no_output_____"
],
[
"class NeuralNetwork(object):\n def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):\n # Set number of nodes in input, hidden and output layers.\n self.input_nodes = input_nodes\n self.hidden_nodes = hidden_nodes\n self.output_nodes = output_nodes\n \n # Initialize weights\n self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes**-0.5, \n (self.input_nodes, self.hidden_nodes))\n\n self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes**-0.5, \n (self.hidden_nodes, self.output_nodes))\n self.lr = learning_rate\n \n #### TODO: Set self.activation_function to your implemented sigmoid function ####\n self.activation_function = lambda x : 1/(1+np.exp(-x))\n # def sigmoid(self, x):\n # return 1/(1+np.exp(-x))\n # self.activation_function = sigmoid\n \n def train(self, features, targets):\n n_records = features.shape[0]\n \n delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape)\n delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape)\n \n for X, y in zip(features, targets):\n \n# print('X is: ' + str(X))\n# print('X.shape is: ' + str(X.shape))\n #### Implement the forward pass here ####\n ### Forward pass ###\n # TODO: Hidden layer - Replace these values with your calculations.\n \n hidden_inputs = np.dot(X, self.weights_input_to_hidden) ## verified\n hidden_outputs = self.activation_function(hidden_inputs) ## verified\n# print('hidden_inputs is: ' + str(hidden_inputs))\n# print('hidden_outputs is: ' + str(hidden_outputs));\n \n # TODO: Output layer - Replace these values with your calculations.\n# final_inputs = self.activation_function(np.dot(hidden_outputs, self.weights_hidden_to_output))\n\n # signals into final output layer\n final_inputs = np.dot(hidden_outputs,self.weights_hidden_to_output) \n final_outputs = final_inputs ## verified\n \n# print('final_inputs is: ' + str(final_inputs))\n# print('final_outputs is: ' + str(final_outputs))\n \n #### Implement the backward pass here ####\n ### Backward pass ###\n \n # TODO: Output error - Replace this value with your calculations.\n error = y - final_outputs\n# error = final_outputs - y\n# print('error is: ' + str(error))\n \n # TODO: Calculate error term for the output unit\n output_error_term = error * 1 ## verified\n# print('output_error_term is: ' + str(output_error_term))\n# print('self.weights_hidden_to_output is: ' + str(self.weights_hidden_to_output))\n\n# print('self.weights_hidden_to_output.shape is: ' + str(self.weights_hidden_to_output.shape))\n # TODO: Calculate the hidden layer's contribution to the error\n# hidden_error = np.dot(output_error_term, self.weights_hidden_to_output)\n# hidden_error = np.dot(delta_weights_h_o,output_error_term)\n# hidden_error = np.dot(output_error_term, self.weights_hidden_to_output.T)\n hidden_error = np.dot(self.weights_hidden_to_output, output_error_term)\n# print('hidden_error is: ' + str(hidden_error))\n \n # TODO: Calculate the error term for the hidden layer\n hidden_error_term = hidden_error * hidden_outputs * (1 - hidden_outputs) ## verified\n# print('hidden_error_term is: ' + str(hidden_error_term))\n \n# # Weight step (input to hidden)\n# delta_weights_i_h += hidden_error_term.T * X[:, None]\n# # Weight step (hidden to output)\n# delta_weights_h_o += output_error_term * hidden_outputs[:, None]\n \n # Weight step (input to hidden)\n# delta_weights_i_h += hidden_error_term * X[:, None]\n# delta_weights_i_h += hidden_error_term * X\n delta_weights_i_h += hidden_error_term.T * X[:, None] ## verified\n# print('delta_weights_i_h is: ' + str(delta_weights_i_h))\n # Weight step (hidden to output)\n# delta_weights_h_o += output_error_term * hidden_outputsg\n delta_weights_h_o += output_error_term * hidden_outputs[:, None] ## verified\n \n # TODO: Update the weights - Replace these values with your calculations. \n # update hidden-to-output weights with gradient descent step\n self.weights_hidden_to_output += self.lr * delta_weights_h_o / n_records\n # update input-to-hidden weights with gradient descent step\n self.weights_input_to_hidden += self.lr * delta_weights_i_h / n_records\n \n def run(self, features):\n \n #### Implement the forward pass here ####\n \n for X in zip(features):\n \n #### Implement the forward pass here ####\n ### Forward pass ###\n # TODO: Hidden layer - replace these values with the appropriate calculations.\n # signals into hidden layer\n hidden_inputs = np.dot(X, self.weights_input_to_hidden) ## verified\n # signals from hidden layer\n hidden_outputs = self.activation_function(hidden_inputs) ## verified\n # TODO: Output layer - Replace these values with the appropriate calculations.\n # signals from final output layer \n# final_inputs = self.activation_function(np.dot(hidden_outputs, self.weights_hidden_to_output))\n final_inputs = np.dot(hidden_outputs,self.weights_hidden_to_output) \n # signals into final output layer\n final_outputs = final_inputs\n \n return final_outputs\n \n \n \n \n \n ",
"_____no_output_____"
],
[
"def MSE(y, Y):\n return np.mean((y-Y)**2)",
"_____no_output_____"
],
[
"import unittest\n\ninputs = np.array([[0.5, -0.2, 0.1]])\nprint ('inputs.shape: ' + str(inputs.shape))\ntargets = np.array([[0.4]])\nprint ('targets.shape:' + str(targets.shape))\ntest_w_i_h = np.array([[0.1, -0.2],\n [0.4, 0.5],\n [-0.3, 0.2]])\ntest_w_h_o = np.array([[0.3],\n [-0.1]])\n\nclass TestMethods(unittest.TestCase):\n \n ##########\n # Unit tests for data loading\n ##########\n \n def test_data_path(self):\n # Test that file path to dataset has been unaltered\n self.assertTrue(data_path.lower() == 'bike-sharing-dataset/hour.csv')\n \n def test_data_loaded(self):\n # Test that data frame loaded\n self.assertTrue(isinstance(rides, pd.DataFrame))\n \n ##########\n # Unit tests for network functionality\n ##########\n\n def test_activation(self):\n network = NeuralNetwork(3, 2, 1, 0.5)\n # Test that the activation function is a sigmoid\n self.assertTrue(np.all(network.activation_function(0.5) == 1/(1+np.exp(-0.5))))\n\n def test_train(self):\n # Test that weights are updated correctly on training\n network = NeuralNetwork(3, 2, 1, 0.5)\n network.weights_input_to_hidden = test_w_i_h.copy()\n network.weights_hidden_to_output = test_w_h_o.copy()\n \n network.train(inputs, targets)\n self.assertTrue(np.allclose(network.weights_hidden_to_output, \n np.array([[ 0.37275328], \n [-0.03172939]])))\n self.assertTrue(np.allclose(network.weights_input_to_hidden,\n np.array([[ 0.10562014, -0.20185996], \n [0.39775194, 0.50074398], \n [-0.29887597, 0.19962801]])))\n\n def test_run(self):\n # Test correctness of run method\n network = NeuralNetwork(3, 2, 1, 0.5)\n network.weights_input_to_hidden = test_w_i_h.copy()\n network.weights_hidden_to_output = test_w_h_o.copy()\n\n self.assertTrue(np.allclose(network.run(inputs), 0.09998924))\n\nsuite = unittest.TestLoader().loadTestsFromModule(TestMethods())\nunittest.TextTestRunner().run(suite)",
"....."
],
[
"import sys\n\n### Set the hyperparameters here ###\niterations = 100\nlearning_rate = 0.1\nhidden_nodes = 2\noutput_nodes = 1\n\nN_i = train_features.shape[1]\nnetwork = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate)\n\nlosses = {'train':[], 'validation':[]}\n\nfor ii in range(iterations):\n # Go through a random batch of 128 records from the training data set\n batch = np.random.choice(train_features.index, size=128)\n X, y = train_features.loc[batch].values, train_targets.iloc[batch]['cnt']\n \n network.train(X, y)\n \n # Printing out the training progress\n MSE(network.run(train_features).T, train_targets['cnt'].values)\n",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb196a98a259e30190ac6c352f1ab177aff4f10
| 134,574 |
ipynb
|
Jupyter Notebook
|
Old Versions/Pipeline-P3.ipynb
|
Hamidreza3252/CarND-Behavioral-Cloning-P3
|
10eb66fbc5c8266fe43aa04aee6f8e460215df09
|
[
"MIT"
] | null | null | null |
Old Versions/Pipeline-P3.ipynb
|
Hamidreza3252/CarND-Behavioral-Cloning-P3
|
10eb66fbc5c8266fe43aa04aee6f8e460215df09
|
[
"MIT"
] | null | null | null |
Old Versions/Pipeline-P3.ipynb
|
Hamidreza3252/CarND-Behavioral-Cloning-P3
|
10eb66fbc5c8266fe43aa04aee6f8e460215df09
|
[
"MIT"
] | null | null | null | 65.42246 | 787 | 0.635836 |
[
[
[
"from IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:80% !important; }</style>\"))",
"_____no_output_____"
]
],
[
[
"## Behavorial Cloning \n\n### Review Articles\n- [An overview of gradient descent optimization algorithms](http://ruder.io/optimizing-gradient-descent/index.html#adam)\n\n### Enrichment Readings \n- [Review: SegNet (Semantic Segmentation)](https://towardsdatascience.com/review-segnet-semantic-segmentation-e66f2e30fb96)\n- [Installing TensorFlow Object Detection API on Windows 10](https://medium.com/@marklabinski/installing-tensorflow-object-detection-api-on-windows-10-7a4eb83e1e7b)\n- [Multi-Sensor Data Fusion (MSDF) for Driverless Cars, An Essential Primer\n](https://medium.com/@lance.eliot/multi-sensor-data-fusion-msdf-for-driverless-cars-an-essential-primer-a1948bb8b57c)\n- [How to validate your deep learning model with the Diffgram SDK — Tutorial](https://medium.com/diffgram/how-to-validate-your-deep-learning-model-with-the-diffgram-sdk-tutorial-22234a9a35?_hsenc=p2ANqtz-_o0BTtZu_UHjEOD4taLJqxrDs0xDP_xl-Do12O-pIoMFjzmoS945j4gYYqt96YCTANNiUtfOuRCPnutqNDwwtgSCRMhQ&_hsmi=74444548)\n- [How do I design a visual deep learning system in 2019?](https://medium.com/diffgram/how-do-i-design-a-visual-deep-learning-system-in-2019-8597aaa35d03?_hsenc=p2ANqtz-_o0BTtZu_UHjEOD4taLJqxrDs0xDP_xl-Do12O-pIoMFjzmoS945j4gYYqt96YCTANNiUtfOuRCPnutqNDwwtgSCRMhQ&_hsmi=74444548)\n\n### Useful Tips\n- [A detailed example of how to use data generators with Keras](https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly)\n- [Writing Custom Keras Generators](https://towardsdatascience.com/writing-custom-keras-generators-fe815d992c5a)\n\n### Image Database\n- [A dataset of images containing...](https://www.kaggle.com/moltean/fruits/downloads/fruits.zip/57)\n\n### General Tips\n- It is not necessary to use the left and right images to derive a successful model. Recording recovery driving from the sides of the road is also effective.",
"_____no_output_____"
],
[
"**Center Driving**\n\nSo that the car drives down the center of the road, it's essential to capture center lane driving. Try driving around the track various times while staying as close to the middle of the track as possible even when making turns.\n\nIn the real world, the car would need to stay in a lane rather than driving down the center. But for the purposes of this project, aim for center of the road driving.\n\n**Strategies for Collecting Data**\n\nNow that you have driven the simulator and know how to record data, it's time to think about collecting data that will ensure a successful model. There are a few general concepts to think about that we will later discuss in more detail:\n\n- the car should stay in the center of the road as much as possible\n- if the car veers off to the side, it should recover back to center\n- driving counter-clockwise can help the model generalize\n- flipping the images is a quick way to augment the data\n- collecting data from the second track can also help generalize the model\n- we want to avoid overfitting or underfitting when training the model\n- knowing when to stop collecting more data\n",
"_____no_output_____"
]
],
[
[
"# Load pickled data\nimport pickle\n\nimport pandas as pd\nimport cv2\nimport numpy as np\nfrom sklearn import preprocessing\nimport os\nfrom random import shuffle\nimport glob\nfrom pathlib import Path\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport math\nimport matplotlib.image as mpimg\nimport csv\n\nfrom keras.layers import Input, InputLayer, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D\nfrom keras.layers import AveragePooling2D, MaxPooling2D, Dropout, Lambda, Cropping2D\nfrom keras.models import Sequential, Model\nfrom keras.optimizers import SGD\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nimport keras\nfrom keras import backend as K\nfrom keras.preprocessing import image\nfrom keras.callbacks import EarlyStopping\nfrom keras.models import load_model\n",
"Using TensorFlow backend.\n"
],
[
"from importlib import reload\n\nimport selfDrivingCarModules\nreload(selfDrivingCarModules)\nfrom selfDrivingCarModules import Sdc\n\nimport dataProcessingModules\nreload(dataProcessingModules)\nfrom dataProcessingModules import DataGenerator4Regression\n",
"_____no_output_____"
],
[
"data_path = \"data/\"\ncsv_file = data_path + \"sim-00/driving_log.csv\"\n# csv_file = data_path + \"driving_log-combined.csv\"\n\nx_partitions = {\"train\": None, \"validation\": None}\n# y_partitions = {\"train\": None, \"validation\": None}\n\nbatch_size = 32\nimage_sizes = (160, 320)\n\nparams = {\"dims\": (*image_sizes, 3), \n \"batch_size\": batch_size, \n \"n_channels\": 1,\n \"augment_data\": True,\n \"rescale_zero_mean\": True,\n \"shuffle\": True}\n",
"_____no_output_____"
],
[
"# x_partitions[\"train\"], x_partitions[\"validation\"], y_partitions[\"train\"], y_partitions[\"validation\"] = \\\n# Sdc.generate_partition_ids(data_path, csv_file, validation_split=0.2, limit=64, image_series_type=Sdc.__CENTER_IMAGES__)\n\nx_partitions[\"train\"], x_partitions[\"validation\"], y_values = \\\n Sdc.generate_partition_ids(data_path, csv_file, validation_split=0.2, limit=0, image_series_type=Sdc.__ALL_IMAGES__, \n correction_factor=0.1)\n\ntraining_generator = DataGenerator4Regression(x_partitions[\"train\"], y_values, **params)\nvalidation_generator = DataGenerator4Regression(x_partitions[\"validation\"], y_values, **params)\n\n# testing data generators \nx_data = training_generator[0][0]\ny_data = training_generator[0][1]\n\ntest_index = 10\n\nprint(\"batch size={0:d} , number of batches={1:d}\".format(batch_size, len(training_generator)))\n\n# for augmented, they should be opposite values\nprint(\"sample training y_data: {0:0.3f}, {1:0.3f}\".format(y_data[test_index], y_data[test_index + batch_size]))\n\ny_data = validation_generator[0][1]\nprint(\"sample validation y_data: {0:0.3f}, {1:0.3f}\".format(y_data[test_index], y_data[test_index + batch_size]))\n\n# a check-point whether the values are re-scaled or not\nprint(np.min(x_data[test_index]), np.max(x_data[test_index]))\n",
"slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\nbatch size=32 , number of batches=602\nsample training y_data: 0.000, -0.000\nsample validation y_data: 0.100, -0.100\n-1.0 1.0\n"
]
],
[
[
"### Training New CNN Model from Scratch (No Transfer Learning) ",
"_____no_output_____"
]
],
[
[
"model = Sdc.generate_model(\"cnn-01\", image_sizes, rescale_input_zero_mean=False)\nmodel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ncropping2d_2 (Cropping2D) (None, 90, 320, 3) 0 \n_________________________________________________________________\nconv_layer_01 (Conv2D) (None, 90, 320, 16) 1216 \n_________________________________________________________________\nbatch_normalization_7 (Batch (None, 90, 320, 16) 64 \n_________________________________________________________________\nactivation_7 (Activation) (None, 90, 320, 16) 0 \n_________________________________________________________________\nmax_pool_01 (MaxPooling2D) (None, 45, 160, 16) 0 \n_________________________________________________________________\nconv_layer_02 (Conv2D) (None, 45, 160, 32) 4640 \n_________________________________________________________________\nbatch_normalization_8 (Batch (None, 45, 160, 32) 128 \n_________________________________________________________________\nactivation_8 (Activation) (None, 45, 160, 32) 0 \n_________________________________________________________________\nmax_pool_2 (MaxPooling2D) (None, 22, 80, 32) 0 \n_________________________________________________________________\nconv_layer_03 (Conv2D) (None, 22, 80, 32) 9248 \n_________________________________________________________________\nbatch_normalization_9 (Batch (None, 22, 80, 32) 128 \n_________________________________________________________________\nactivation_9 (Activation) (None, 22, 80, 32) 0 \n_________________________________________________________________\nmax_pool_3 (MaxPooling2D) (None, 11, 40, 32) 0 \n_________________________________________________________________\nconv_layer_04 (Conv2D) (None, 11, 40, 64) 18496 \n_________________________________________________________________\nbatch_normalization_10 (Batc (None, 11, 40, 64) 256 \n_________________________________________________________________\nactivation_10 (Activation) (None, 11, 40, 64) 0 \n_________________________________________________________________\nmax_pool_4 (MaxPooling2D) (None, 5, 20, 64) 0 \n_________________________________________________________________\nconv_layer_05 (Conv2D) (None, 5, 20, 64) 36928 \n_________________________________________________________________\nbatch_normalization_11 (Batc (None, 5, 20, 64) 256 \n_________________________________________________________________\nactivation_11 (Activation) (None, 5, 20, 64) 0 \n_________________________________________________________________\nmax_pool_5 (MaxPooling2D) (None, 2, 10, 64) 0 \n_________________________________________________________________\nconv_layer_06 (Conv2D) (None, 2, 10, 128) 8320 \n_________________________________________________________________\nbatch_normalization_12 (Batc (None, 2, 10, 128) 512 \n_________________________________________________________________\nactivation_12 (Activation) (None, 2, 10, 128) 0 \n_________________________________________________________________\nmax_pool_6 (MaxPooling2D) (None, 1, 5, 128) 0 \n_________________________________________________________________\nflatten_2 (Flatten) (None, 640) 0 \n_________________________________________________________________\nfc1 (Dense) (None, 128) 82048 \n_________________________________________________________________\ndropout_4 (Dropout) (None, 128) 0 \n_________________________________________________________________\nfc2 (Dense) (None, 64) 8256 \n_________________________________________________________________\ndropout_5 (Dropout) (None, 64) 0 \n_________________________________________________________________\nfc3 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndropout_6 (Dropout) (None, 32) 0 \n_________________________________________________________________\nfc4 (Dense) (None, 1) 33 \n=================================================================\nTotal params: 172,609\nTrainable params: 171,937\nNon-trainable params: 672\n_________________________________________________________________\n"
],
[
"import pickle",
"_____no_output_____"
],
[
"model_name = \"001-model-conv-6-fc-4-all-aug-crop\"\nmodel_filename = \"saved-models/\" + model_name + \".h5\"\nhistory_filename = \"saved-models/\" + model_name + \".p\"\n\ncheckpoint_file = model_filename",
"_____no_output_____"
],
[
"checkpoint = ModelCheckpoint(filepath=checkpoint_file, monitor=\"val_loss\", save_best_only=True)\nstopper = EarlyStopping(monitor=\"val_loss\", min_delta=1e-5, patience=5)\n\nmodel.compile(loss=\"mse\", optimizer=\"adam\")\nhistory = model.fit_generator(generator=training_generator, validation_data=validation_generator, \n use_multiprocessing=True, workers=2, epochs=50, callbacks=[checkpoint, stopper])\n\nmodel.save(model_filename)\n",
"WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\ops\\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nEpoch 1/50\n 4/435 [..............................] - ETA: 50:06 - loss: 80.2208 "
],
[
"with open(history_filename, \"wb\") as file_pi:\n pickle.dump(history.history, file_pi)\n",
"_____no_output_____"
],
[
"# model = load_model(saved_model_filename, custom_objects={\"tf\": tf})\n\nwith open(history_filename, \"rb\") as file_pi:\n history_data = pickle.load(file_pi)",
"_____no_output_____"
],
[
"# define SGD optimizer\n# momentum = 0.5\n# sgd = SGD(lr=0.01, momentum=momentum, decay=0.0, nesterov=False)\n\n# compile the model\n# model.compile(loss=\"categorical_crossentropy\", optimizer=sgd, metrics=[\"accuracy\"])\n# history = model.fit(x_trains, y_trains, validation_split=0.2, epochs=5, shuffle=True, callbacks=None, verbose=1)\n\n# model.fit(x_trains, y_trains, validation_split=0.2, shuffle=True, epochs=5)",
"_____no_output_____"
]
],
[
[
"One can fairly quickly utilize a pre-trained model with [Keras Applications](https://keras.io/applications/). \n\n### Transfer Learning, Available Models \n\n1. **AlexNet**, developed in 2012, was the first breakthrough NN. AlexNet is one of the most understood and one of the best network architectures that one likes to start with. \n\n- **VGGNet or VGG (using 224x224 images as input):**, developed by Virtual Geometry Group at Oxford university in 2014, contains simple and elegant architcture which makes it great for transfer learning. The VGG architecture is just a long sequence of 3x3 convolutions, broken up by 2x2 pooling layers, and then followed up by two or three FC layers at the end. The flexibility of VGG is one of its biggest strengths. There are actually two versions of VGG, VGG16 and VGG19 (where the numbers denote the number of layers included in each respective model). Both of them are supported by Keras. \n\n```python\nfrom keras.applications.vgg16 import VGG16\nmodel = VGG16(weights='imagenet', include_top=False)\n```\n\n- **GoogLeNet/Inception in Keras (using 229x229 images as input):**, developed in 2013 by Google, performed even slightly better than the VGG, 6.7% vs 7.3% error. GoogLeNet's great advantage is that it really runs very fast. The Google team developed a model called Inception module which trains really well and it is efficiently deployable. The Inception module creates a situation that in which the total number of parameters is very small. This is why GoogLeNet almost runs as fast as AlexNet. Therefore, GoogLeNet is a great choice to investigate if we need to run our network in realtime. \n\n```python\nfrom keras.applications.inception_v3 import InceptionV3\nmodel = InceptionV3(weights='imagenet', include_top=False)\n```\n\n- **ResNet (using 224x224 images as input):**, developed by Microsoft in 2015, has a massive 152 layers (AlexNet has 8 layers, VGG has 19 layers, and GoogLeNet has 22 layers). ResNet structure is similar to VGG's. ResNet achives a loss of only 3% on imagenet, which is actually better than normal human accuracy. \n\n\n**Transfeer Learning Tips:**\n\nThe approach for using transfer learning will be different. There are four main cases: \n\n1. new data set is small, new data is similar to original training data\n- new data set is small, new data is different from original training data\n- new data set is large, new data is similar to original training data\n- new data set is large, new data is different from original training data \n\n\n### Small new data set and similar to the original training data: \n\n- slice off the end of the neural network\n- add a new fully connected layer that matches the number of classes in the new data set\n- randomize the weights of the new fully connected layer; freeze all the weights from the pre-trained network\n- train the network to update the weights of the new fully connected layer \n\nTo avoid overfitting on the small data set, the weights of the original network will be held constant rather than re-training the weights.\n",
"_____no_output_____"
],
[
"## Transfer learning using provided data \n\n### InceptionV3: Pre-trained with frozen weights \nTo start, we use an ImageNet pre-trained model with all weights frozen in the InceptionV3 model. We will also drop the end layer and append new layers onto it. \n\n### Adding new layers\n\nUnlike the Keras's `Sequential` model that I used above for pure training model, I rather use the [Model API](https://keras.io/models/model/) this time. This model is useful if one wants to use more advanced concepts like [skip layers](https://en.wikipedia.org/wiki/Residual_neural_network), for instance (which were used heavily in ResNet). \n\nThe camera image sizes that I am going to use are `160x320` (height, width), so I need to re-size the images up to the `input_size` I specified earlier `139x139`. To do so, I try both fixed and variable aspect ratios. \n\n[GlobalAveragePooling2D, an alternative to overfitting](https://datascience.stackexchange.com/questions/28120/globalaveragepooling2d-in-inception-v3-example) ",
"_____no_output_____"
]
],
[
[
"# Load our images first, and we'll check what we have\n# from keras.applications.vgg16 import preprocess_input\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.applications.inception_v3 import preprocess_input\n\nfrom keras.layers import Input, Lambda\nimport tensorflow as tf\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.callbacks import EarlyStopping\n",
"_____no_output_____"
],
[
"resized_input_shape = (139, 139)\n\nfreeze_flag = False # `True` to freeze layers, `False` for full training \nweights_flag = \"imagenet\" # 'imagenet' or None \npreprocess_flag = True # Should be true for ImageNet pre-trained typically \n\n\n# Using smaller than the default 299x299x3 input for InceptionV3\n# which will speed up training. Keras v2.0.9 supports down to 139x139x3\n\n# input_size = 139\n\n# Using Inception with ImageNet pre-trained weights\ninception = InceptionV3(weights=weights_flag, include_top=False, input_shape=(*resized_input_shape, 3))\n\nif (freeze_flag == True):\n for layer in inception.layers:\n layer.trainable = False\n\n# inception.summary()\n",
"WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\envs\\tfgpu\\lib\\site-packages\\tensorflow\\python\\framework\\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\n"
],
[
"# Makes the input placeholder layer with image shape\ninput_ph = Input(shape=(*image_sizes, 3))\n\npreprocessed_input = Cropping2D(cropping=((50,20), (0,0)), input_shape=(*image_sizes, 3))(input_ph)\npreprocessed_input = Lambda(lambda image: tf.image.resize_images( \\\n image, (139, 139), method=tf.image.ResizeMethod.BILINEAR, preserve_aspect_ratio=False))(preprocessed_input)\n\n# preprocessed_input = Lambda(lambda x: x / 255.0 - 0.5, input_shape=(*input_size, 3))(preprocessed_input)\n\ninception_output = inception(preprocessed_input)\n\n# layer_output = Flatten()(inception_output)\nlayer_output = GlobalAveragePooling2D()(inception_output)\n\nlayer_output = Dense(128, activation=None, name=\"fc1\")(layer_output)\nlayer_output = Dropout(rate=0.20)(layer_output)\n\nlayer_output = Dense(64, activation=None, name=\"fc2\")(layer_output)\nlayer_output = Dropout(rate=0.20)(layer_output)\n\nlayer_output = Dense(32, activation=None, name=\"fc3\")(layer_output)\nlayer_output = Dropout(rate=0.20)(layer_output)\n\npredictions = Dense(1, activation=None, name=\"fc4\")(layer_output)\n\n\n# layer_output = GlobalAveragePooling2D()(inception_output)\n# layer_output = Dense(64, activation=\"relu\")(layer_output)\n# predictions = Dense(1, activation=\"relu\")(layer_output)\n\n# predictions = Dense(1, activation=\"softmax\")(layer_output)\n",
"WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\envs\\tfgpu\\lib\\site-packages\\keras\\backend\\tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n"
],
[
"model = Model(inputs=input_ph, outputs=predictions, name=\"cnn-20\")\nmodel.compile(optimizer=\"Adam\", loss=\"mse\", metrics=[\"mse\"])\nmodel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_2 (InputLayer) (None, 160, 320, 3) 0 \n_________________________________________________________________\ncropping2d_1 (Cropping2D) (None, 90, 320, 3) 0 \n_________________________________________________________________\nlambda_1 (Lambda) (None, 139, 139, 3) 0 \n_________________________________________________________________\ninception_v3 (Model) (None, 3, 3, 2048) 21802784 \n_________________________________________________________________\nglobal_average_pooling2d_1 ( (None, 2048) 0 \n_________________________________________________________________\nfc1 (Dense) (None, 128) 262272 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 128) 0 \n_________________________________________________________________\nfc2 (Dense) (None, 64) 8256 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 64) 0 \n_________________________________________________________________\nfc3 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 32) 0 \n_________________________________________________________________\nfc4 (Dense) (None, 1) 33 \n=================================================================\nTotal params: 22,075,425\nTrainable params: 22,040,993\nNon-trainable params: 34,432\n_________________________________________________________________\n"
],
[
"model_name = \"051-model-inception-fc-4-all-data-01\"\nmodel_filename = \"saved-models/\" + model_name + \".h5\"\nhistory_filename = \"saved-models/\" + model_name + \".p\"\n\ncheckpoint_file = model_filename",
"_____no_output_____"
],
[
"checkpoint = ModelCheckpoint(filepath=checkpoint_file, monitor=\"val_loss\", save_best_only=True)\nstopper = EarlyStopping(monitor=\"val_loss\", min_delta=1e-6, patience=5)",
"_____no_output_____"
],
[
"history = model.fit_generator(generator=training_generator, validation_data=validation_generator, \n use_multiprocessing=True, workers=2, epochs=100, callbacks=[checkpoint])",
"WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\envs\\tfgpu\\lib\\site-packages\\tensorflow\\python\\ops\\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nEpoch 1/100\n601/602 [============================>.] - ETA: 2s - loss: 0.5629 - mean_squared_error: 0.5629slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\n602/602 [==============================] - 1341s 2s/step - loss: 0.5624 - mean_squared_error: 0.5624 - val_loss: 0.0233 - val_mean_squared_error: 0.0233\nEpoch 2/100\n601/602 [============================>.] - ETA: 2s - loss: 0.0617 - mean_squared_error: 0.0617slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\n602/602 [==============================] - 1371s 2s/step - loss: 0.0617 - mean_squared_error: 0.0617 - val_loss: 0.3463 - val_mean_squared_error: 0.3463\nEpoch 3/100\n601/602 [============================>.] - ETA: 2s - loss: 0.0263 - mean_squared_error: 0.0263slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\n602/602 [==============================] - 1384s 2s/step - loss: 0.0263 - mean_squared_error: 0.0263 - val_loss: 0.0112 - val_mean_squared_error: 0.0112\nEpoch 4/100\n601/602 [============================>.] - ETA: 2s - loss: 0.0140 - mean_squared_error: 0.0140slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\n602/602 [==============================] - 1391s 2s/step - loss: 0.0140 - mean_squared_error: 0.0140 - val_loss: 0.0099 - val_mean_squared_error: 0.0099\nEpoch 5/100\n601/602 [============================>.] - ETA: 2s - loss: 0.0118 - mean_squared_error: 0.0118slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\n602/602 [==============================] - 1368s 2s/step - loss: 0.0118 - mean_squared_error: 0.0118 - val_loss: 0.0106 - val_mean_squared_error: 0.0106\nEpoch 6/100\n601/602 [============================>.] - ETA: 2s - loss: 0.0104 - mean_squared_error: 0.0104slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\n602/602 [==============================] - 1372s 2s/step - loss: 0.0104 - mean_squared_error: 0.0104 - val_loss: 0.0109 - val_mean_squared_error: 0.0109\nEpoch 7/100\n601/602 [============================>.] - ETA: 2s - loss: 0.0091 - mean_squared_error: 0.0091slepping for 30 secs to cool down...\nslepping for 30 secs to cool down...\n602/602 [==============================] - 1394s 2s/step - loss: 0.0091 - mean_squared_error: 0.0091 - val_loss: 0.0088 - val_mean_squared_error: 0.0088\nEpoch 8/100\n329/602 [===============>..............] - ETA: 10:07 - loss: 0.0089 - mean_squared_error: 0.0089"
],
[
"model.save(\"saved-models/020-model-inception-fc-3-all-aug-crop.h5\")",
"_____no_output_____"
],
[
"history.history[\"val_loss\"]",
"_____no_output_____"
],
[
"history.history[\"loss\"]",
"_____no_output_____"
],
[
"image_paths = glob(\"images/*.jpg\")\n\ni = 2 # Can change this to your desired image to test\nimg_path = image_paths[i]\n\nimg = image.load_img(img_path, target_size=(224, 224))\n\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = preprocess_input(x)",
"_____no_output_____"
],
[
"\n",
"_____no_output_____"
],
[
"# Set a couple flags for training - you can ignore these for now\nfreeze_flag = True # `True` to freeze layers, `False` for full training\nweights_flag = \"imagenet\" # 'imagenet' or None\npreprocess_flag = True # Should be true for ImageNet pre-trained typically\n\n# Loads in InceptionV3\nfrom keras.applications.inception_v3 import InceptionV3\n\n# We can use smaller than the default 299x299x3 input for InceptionV3\n# which will speed up training. Keras v2.0.9 supports down to 139x139x3\ninput_size = 139\n\n# Using Inception with ImageNet pre-trained weights\ninception = InceptionV3(weights=weights_flag, include_top=False,\n input_shape=(input_size,input_size,3))",
"Using TensorFlow backend.\n"
]
],
[
[
"We'll use Inception V3 for this lab, although you can use the same techniques with any of the models in [Keras Applications](https://keras.io/applications/). Do note that certain models are only available in certain versions of Keras; this workspace uses Keras v2.0.9, for which you can see the available models [here](https://faroit.github.io/keras-docs/2.0.9/applications/).\n\nIn the above, we've set Inception to use an `input_shape` of 139x139x3 instead of the default 299x299x3. This will help us to speed up our training a bit later (and we'll actually be upsampling from smaller images, so we aren't losing data here). In order to do so, we also must set `include_top` to `False`, which means the final fully-connected layer with 1,000 nodes for each ImageNet class is dropped, as well as a Global Average Pooling layer.\n\n### Pre-trained with frozen weights\nTo start, we'll see how an ImageNet pre-trained model with all weights frozen in the InceptionV3 model performs. We will also drop the end layer and append new layers onto it, although you could do this in different ways (not drop the end and add new layers, drop more layers than we will here, etc.).\n\nYou can freeze layers by setting `layer.trainable` to False for a given `layer`. Within a `model`, you can get the list of layers with `model.layers`.",
"_____no_output_____"
]
],
[
[
"if freeze_flag == True:\n ## TODO: Iterate through the layers of the Inception model\n ## loaded above and set all of them to have trainable = False\n for layer in inception.layers:\n layer.trainable = False",
"_____no_output_____"
]
],
[
[
"### Dropping layers\nYou can drop layers from a model with `model.layers.pop()`. Before you do this, you should check out what the actual layers of the model are with Keras's `.summary()` function.",
"_____no_output_____"
]
],
[
[
"## TODO: Use the model summary function to see all layers in the\n## loaded Inception model\ninception.summary()",
"__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_1 (InputLayer) (None, 139, 139, 3) 0 \n__________________________________________________________________________________________________\nconv2d_1 (Conv2D) (None, 69, 69, 32) 864 input_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_1 (BatchNor (None, 69, 69, 32) 96 conv2d_1[0][0] \n__________________________________________________________________________________________________\nactivation_1 (Activation) (None, 69, 69, 32) 0 batch_normalization_1[0][0] \n__________________________________________________________________________________________________\nconv2d_2 (Conv2D) (None, 67, 67, 32) 9216 activation_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_2 (BatchNor (None, 67, 67, 32) 96 conv2d_2[0][0] \n__________________________________________________________________________________________________\nactivation_2 (Activation) (None, 67, 67, 32) 0 batch_normalization_2[0][0] \n__________________________________________________________________________________________________\nconv2d_3 (Conv2D) (None, 67, 67, 64) 18432 activation_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_3 (BatchNor (None, 67, 67, 64) 192 conv2d_3[0][0] \n__________________________________________________________________________________________________\nactivation_3 (Activation) (None, 67, 67, 64) 0 batch_normalization_3[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_1 (MaxPooling2D) (None, 33, 33, 64) 0 activation_3[0][0] \n__________________________________________________________________________________________________\nconv2d_4 (Conv2D) (None, 33, 33, 80) 5120 max_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_4 (BatchNor (None, 33, 33, 80) 240 conv2d_4[0][0] \n__________________________________________________________________________________________________\nactivation_4 (Activation) (None, 33, 33, 80) 0 batch_normalization_4[0][0] \n__________________________________________________________________________________________________\nconv2d_5 (Conv2D) (None, 31, 31, 192) 138240 activation_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_5 (BatchNor (None, 31, 31, 192) 576 conv2d_5[0][0] \n__________________________________________________________________________________________________\nactivation_5 (Activation) (None, 31, 31, 192) 0 batch_normalization_5[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_2 (MaxPooling2D) (None, 15, 15, 192) 0 activation_5[0][0] \n__________________________________________________________________________________________________\nconv2d_9 (Conv2D) (None, 15, 15, 64) 12288 max_pooling2d_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_9 (BatchNor (None, 15, 15, 64) 192 conv2d_9[0][0] \n__________________________________________________________________________________________________\nactivation_9 (Activation) (None, 15, 15, 64) 0 batch_normalization_9[0][0] \n__________________________________________________________________________________________________\nconv2d_7 (Conv2D) (None, 15, 15, 48) 9216 max_pooling2d_2[0][0] \n__________________________________________________________________________________________________\nconv2d_10 (Conv2D) (None, 15, 15, 96) 55296 activation_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_7 (BatchNor (None, 15, 15, 48) 144 conv2d_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_10 (BatchNo (None, 15, 15, 96) 288 conv2d_10[0][0] \n__________________________________________________________________________________________________\nactivation_7 (Activation) (None, 15, 15, 48) 0 batch_normalization_7[0][0] \n__________________________________________________________________________________________________\nactivation_10 (Activation) (None, 15, 15, 96) 0 batch_normalization_10[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_1 (AveragePoo (None, 15, 15, 192) 0 max_pooling2d_2[0][0] \n__________________________________________________________________________________________________\nconv2d_6 (Conv2D) (None, 15, 15, 64) 12288 max_pooling2d_2[0][0] \n__________________________________________________________________________________________________\nconv2d_8 (Conv2D) (None, 15, 15, 64) 76800 activation_7[0][0] \n__________________________________________________________________________________________________\nconv2d_11 (Conv2D) (None, 15, 15, 96) 82944 activation_10[0][0] \n__________________________________________________________________________________________________\nconv2d_12 (Conv2D) (None, 15, 15, 32) 6144 average_pooling2d_1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_6 (BatchNor (None, 15, 15, 64) 192 conv2d_6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_8 (BatchNor (None, 15, 15, 64) 192 conv2d_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_11 (BatchNo (None, 15, 15, 96) 288 conv2d_11[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_12 (BatchNo (None, 15, 15, 32) 96 conv2d_12[0][0] \n__________________________________________________________________________________________________\nactivation_6 (Activation) (None, 15, 15, 64) 0 batch_normalization_6[0][0] \n__________________________________________________________________________________________________\nactivation_8 (Activation) (None, 15, 15, 64) 0 batch_normalization_8[0][0] \n__________________________________________________________________________________________________\nactivation_11 (Activation) (None, 15, 15, 96) 0 batch_normalization_11[0][0] \n__________________________________________________________________________________________________\nactivation_12 (Activation) (None, 15, 15, 32) 0 batch_normalization_12[0][0] \n__________________________________________________________________________________________________\nmixed0 (Concatenate) (None, 15, 15, 256) 0 activation_6[0][0] \n activation_8[0][0] \n activation_11[0][0] \n activation_12[0][0] \n__________________________________________________________________________________________________\nconv2d_16 (Conv2D) (None, 15, 15, 64) 16384 mixed0[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_16 (BatchNo (None, 15, 15, 64) 192 conv2d_16[0][0] \n__________________________________________________________________________________________________\nactivation_16 (Activation) (None, 15, 15, 64) 0 batch_normalization_16[0][0] \n__________________________________________________________________________________________________\nconv2d_14 (Conv2D) (None, 15, 15, 48) 12288 mixed0[0][0] \n__________________________________________________________________________________________________\nconv2d_17 (Conv2D) (None, 15, 15, 96) 55296 activation_16[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_14 (BatchNo (None, 15, 15, 48) 144 conv2d_14[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_17 (BatchNo (None, 15, 15, 96) 288 conv2d_17[0][0] \n__________________________________________________________________________________________________\nactivation_14 (Activation) (None, 15, 15, 48) 0 batch_normalization_14[0][0] \n__________________________________________________________________________________________________\nactivation_17 (Activation) (None, 15, 15, 96) 0 batch_normalization_17[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_2 (AveragePoo (None, 15, 15, 256) 0 mixed0[0][0] \n__________________________________________________________________________________________________\nconv2d_13 (Conv2D) (None, 15, 15, 64) 16384 mixed0[0][0] \n__________________________________________________________________________________________________\nconv2d_15 (Conv2D) (None, 15, 15, 64) 76800 activation_14[0][0] \n__________________________________________________________________________________________________\nconv2d_18 (Conv2D) (None, 15, 15, 96) 82944 activation_17[0][0] \n__________________________________________________________________________________________________\nconv2d_19 (Conv2D) (None, 15, 15, 64) 16384 average_pooling2d_2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_13 (BatchNo (None, 15, 15, 64) 192 conv2d_13[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_15 (BatchNo (None, 15, 15, 64) 192 conv2d_15[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_18 (BatchNo (None, 15, 15, 96) 288 conv2d_18[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_19 (BatchNo (None, 15, 15, 64) 192 conv2d_19[0][0] \n__________________________________________________________________________________________________\nactivation_13 (Activation) (None, 15, 15, 64) 0 batch_normalization_13[0][0] \n__________________________________________________________________________________________________\nactivation_15 (Activation) (None, 15, 15, 64) 0 batch_normalization_15[0][0] \n__________________________________________________________________________________________________\nactivation_18 (Activation) (None, 15, 15, 96) 0 batch_normalization_18[0][0] \n__________________________________________________________________________________________________\nactivation_19 (Activation) (None, 15, 15, 64) 0 batch_normalization_19[0][0] \n__________________________________________________________________________________________________\nmixed1 (Concatenate) (None, 15, 15, 288) 0 activation_13[0][0] \n activation_15[0][0] \n activation_18[0][0] \n activation_19[0][0] \n__________________________________________________________________________________________________\nconv2d_23 (Conv2D) (None, 15, 15, 64) 18432 mixed1[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_23 (BatchNo (None, 15, 15, 64) 192 conv2d_23[0][0] \n__________________________________________________________________________________________________\nactivation_23 (Activation) (None, 15, 15, 64) 0 batch_normalization_23[0][0] \n__________________________________________________________________________________________________\nconv2d_21 (Conv2D) (None, 15, 15, 48) 13824 mixed1[0][0] \n__________________________________________________________________________________________________\nconv2d_24 (Conv2D) (None, 15, 15, 96) 55296 activation_23[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_21 (BatchNo (None, 15, 15, 48) 144 conv2d_21[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_24 (BatchNo (None, 15, 15, 96) 288 conv2d_24[0][0] \n__________________________________________________________________________________________________\nactivation_21 (Activation) (None, 15, 15, 48) 0 batch_normalization_21[0][0] \n__________________________________________________________________________________________________\nactivation_24 (Activation) (None, 15, 15, 96) 0 batch_normalization_24[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_3 (AveragePoo (None, 15, 15, 288) 0 mixed1[0][0] \n__________________________________________________________________________________________________\nconv2d_20 (Conv2D) (None, 15, 15, 64) 18432 mixed1[0][0] \n__________________________________________________________________________________________________\nconv2d_22 (Conv2D) (None, 15, 15, 64) 76800 activation_21[0][0] \n__________________________________________________________________________________________________\nconv2d_25 (Conv2D) (None, 15, 15, 96) 82944 activation_24[0][0] \n__________________________________________________________________________________________________\nconv2d_26 (Conv2D) (None, 15, 15, 64) 18432 average_pooling2d_3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_20 (BatchNo (None, 15, 15, 64) 192 conv2d_20[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_22 (BatchNo (None, 15, 15, 64) 192 conv2d_22[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_25 (BatchNo (None, 15, 15, 96) 288 conv2d_25[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_26 (BatchNo (None, 15, 15, 64) 192 conv2d_26[0][0] \n__________________________________________________________________________________________________\nactivation_20 (Activation) (None, 15, 15, 64) 0 batch_normalization_20[0][0] \n__________________________________________________________________________________________________\nactivation_22 (Activation) (None, 15, 15, 64) 0 batch_normalization_22[0][0] \n__________________________________________________________________________________________________\nactivation_25 (Activation) (None, 15, 15, 96) 0 batch_normalization_25[0][0] \n__________________________________________________________________________________________________\nactivation_26 (Activation) (None, 15, 15, 64) 0 batch_normalization_26[0][0] \n__________________________________________________________________________________________________\nmixed2 (Concatenate) (None, 15, 15, 288) 0 activation_20[0][0] \n activation_22[0][0] \n activation_25[0][0] \n activation_26[0][0] \n__________________________________________________________________________________________________\nconv2d_28 (Conv2D) (None, 15, 15, 64) 18432 mixed2[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_28 (BatchNo (None, 15, 15, 64) 192 conv2d_28[0][0] \n__________________________________________________________________________________________________\nactivation_28 (Activation) (None, 15, 15, 64) 0 batch_normalization_28[0][0] \n__________________________________________________________________________________________________\nconv2d_29 (Conv2D) (None, 15, 15, 96) 55296 activation_28[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_29 (BatchNo (None, 15, 15, 96) 288 conv2d_29[0][0] \n__________________________________________________________________________________________________\nactivation_29 (Activation) (None, 15, 15, 96) 0 batch_normalization_29[0][0] \n__________________________________________________________________________________________________\nconv2d_27 (Conv2D) (None, 7, 7, 384) 995328 mixed2[0][0] \n__________________________________________________________________________________________________\nconv2d_30 (Conv2D) (None, 7, 7, 96) 82944 activation_29[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_27 (BatchNo (None, 7, 7, 384) 1152 conv2d_27[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_30 (BatchNo (None, 7, 7, 96) 288 conv2d_30[0][0] \n__________________________________________________________________________________________________\nactivation_27 (Activation) (None, 7, 7, 384) 0 batch_normalization_27[0][0] \n__________________________________________________________________________________________________\nactivation_30 (Activation) (None, 7, 7, 96) 0 batch_normalization_30[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_3 (MaxPooling2D) (None, 7, 7, 288) 0 mixed2[0][0] \n__________________________________________________________________________________________________\nmixed3 (Concatenate) (None, 7, 7, 768) 0 activation_27[0][0] \n activation_30[0][0] \n max_pooling2d_3[0][0] \n__________________________________________________________________________________________________\nconv2d_35 (Conv2D) (None, 7, 7, 128) 98304 mixed3[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_35 (BatchNo (None, 7, 7, 128) 384 conv2d_35[0][0] \n__________________________________________________________________________________________________\nactivation_35 (Activation) (None, 7, 7, 128) 0 batch_normalization_35[0][0] \n__________________________________________________________________________________________________\nconv2d_36 (Conv2D) (None, 7, 7, 128) 114688 activation_35[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_36 (BatchNo (None, 7, 7, 128) 384 conv2d_36[0][0] \n__________________________________________________________________________________________________\nactivation_36 (Activation) (None, 7, 7, 128) 0 batch_normalization_36[0][0] \n__________________________________________________________________________________________________\nconv2d_32 (Conv2D) (None, 7, 7, 128) 98304 mixed3[0][0] \n__________________________________________________________________________________________________\nconv2d_37 (Conv2D) (None, 7, 7, 128) 114688 activation_36[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_32 (BatchNo (None, 7, 7, 128) 384 conv2d_32[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_37 (BatchNo (None, 7, 7, 128) 384 conv2d_37[0][0] \n__________________________________________________________________________________________________\nactivation_32 (Activation) (None, 7, 7, 128) 0 batch_normalization_32[0][0] \n__________________________________________________________________________________________________\nactivation_37 (Activation) (None, 7, 7, 128) 0 batch_normalization_37[0][0] \n__________________________________________________________________________________________________\nconv2d_33 (Conv2D) (None, 7, 7, 128) 114688 activation_32[0][0] \n__________________________________________________________________________________________________\nconv2d_38 (Conv2D) (None, 7, 7, 128) 114688 activation_37[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_33 (BatchNo (None, 7, 7, 128) 384 conv2d_33[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_38 (BatchNo (None, 7, 7, 128) 384 conv2d_38[0][0] \n__________________________________________________________________________________________________\nactivation_33 (Activation) (None, 7, 7, 128) 0 batch_normalization_33[0][0] \n__________________________________________________________________________________________________\nactivation_38 (Activation) (None, 7, 7, 128) 0 batch_normalization_38[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_4 (AveragePoo (None, 7, 7, 768) 0 mixed3[0][0] \n__________________________________________________________________________________________________\nconv2d_31 (Conv2D) (None, 7, 7, 192) 147456 mixed3[0][0] \n__________________________________________________________________________________________________\nconv2d_34 (Conv2D) (None, 7, 7, 192) 172032 activation_33[0][0] \n__________________________________________________________________________________________________\nconv2d_39 (Conv2D) (None, 7, 7, 192) 172032 activation_38[0][0] \n__________________________________________________________________________________________________\nconv2d_40 (Conv2D) (None, 7, 7, 192) 147456 average_pooling2d_4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_31 (BatchNo (None, 7, 7, 192) 576 conv2d_31[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_34 (BatchNo (None, 7, 7, 192) 576 conv2d_34[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_39 (BatchNo (None, 7, 7, 192) 576 conv2d_39[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_40 (BatchNo (None, 7, 7, 192) 576 conv2d_40[0][0] \n__________________________________________________________________________________________________\nactivation_31 (Activation) (None, 7, 7, 192) 0 batch_normalization_31[0][0] \n__________________________________________________________________________________________________\nactivation_34 (Activation) (None, 7, 7, 192) 0 batch_normalization_34[0][0] \n__________________________________________________________________________________________________\nactivation_39 (Activation) (None, 7, 7, 192) 0 batch_normalization_39[0][0] \n__________________________________________________________________________________________________\nactivation_40 (Activation) (None, 7, 7, 192) 0 batch_normalization_40[0][0] \n__________________________________________________________________________________________________\nmixed4 (Concatenate) (None, 7, 7, 768) 0 activation_31[0][0] \n activation_34[0][0] \n activation_39[0][0] \n activation_40[0][0] \n__________________________________________________________________________________________________\nconv2d_45 (Conv2D) (None, 7, 7, 160) 122880 mixed4[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_45 (BatchNo (None, 7, 7, 160) 480 conv2d_45[0][0] \n__________________________________________________________________________________________________\nactivation_45 (Activation) (None, 7, 7, 160) 0 batch_normalization_45[0][0] \n__________________________________________________________________________________________________\nconv2d_46 (Conv2D) (None, 7, 7, 160) 179200 activation_45[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_46 (BatchNo (None, 7, 7, 160) 480 conv2d_46[0][0] \n__________________________________________________________________________________________________\nactivation_46 (Activation) (None, 7, 7, 160) 0 batch_normalization_46[0][0] \n__________________________________________________________________________________________________\nconv2d_42 (Conv2D) (None, 7, 7, 160) 122880 mixed4[0][0] \n__________________________________________________________________________________________________\nconv2d_47 (Conv2D) (None, 7, 7, 160) 179200 activation_46[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_42 (BatchNo (None, 7, 7, 160) 480 conv2d_42[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_47 (BatchNo (None, 7, 7, 160) 480 conv2d_47[0][0] \n__________________________________________________________________________________________________\nactivation_42 (Activation) (None, 7, 7, 160) 0 batch_normalization_42[0][0] \n__________________________________________________________________________________________________\nactivation_47 (Activation) (None, 7, 7, 160) 0 batch_normalization_47[0][0] \n__________________________________________________________________________________________________\nconv2d_43 (Conv2D) (None, 7, 7, 160) 179200 activation_42[0][0] \n__________________________________________________________________________________________________\nconv2d_48 (Conv2D) (None, 7, 7, 160) 179200 activation_47[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_43 (BatchNo (None, 7, 7, 160) 480 conv2d_43[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_48 (BatchNo (None, 7, 7, 160) 480 conv2d_48[0][0] \n__________________________________________________________________________________________________\nactivation_43 (Activation) (None, 7, 7, 160) 0 batch_normalization_43[0][0] \n__________________________________________________________________________________________________\nactivation_48 (Activation) (None, 7, 7, 160) 0 batch_normalization_48[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_5 (AveragePoo (None, 7, 7, 768) 0 mixed4[0][0] \n__________________________________________________________________________________________________\nconv2d_41 (Conv2D) (None, 7, 7, 192) 147456 mixed4[0][0] \n__________________________________________________________________________________________________\nconv2d_44 (Conv2D) (None, 7, 7, 192) 215040 activation_43[0][0] \n__________________________________________________________________________________________________\nconv2d_49 (Conv2D) (None, 7, 7, 192) 215040 activation_48[0][0] \n__________________________________________________________________________________________________\nconv2d_50 (Conv2D) (None, 7, 7, 192) 147456 average_pooling2d_5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_41 (BatchNo (None, 7, 7, 192) 576 conv2d_41[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_44 (BatchNo (None, 7, 7, 192) 576 conv2d_44[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_49 (BatchNo (None, 7, 7, 192) 576 conv2d_49[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_50 (BatchNo (None, 7, 7, 192) 576 conv2d_50[0][0] \n__________________________________________________________________________________________________\nactivation_41 (Activation) (None, 7, 7, 192) 0 batch_normalization_41[0][0] \n__________________________________________________________________________________________________\nactivation_44 (Activation) (None, 7, 7, 192) 0 batch_normalization_44[0][0] \n__________________________________________________________________________________________________\nactivation_49 (Activation) (None, 7, 7, 192) 0 batch_normalization_49[0][0] \n__________________________________________________________________________________________________\nactivation_50 (Activation) (None, 7, 7, 192) 0 batch_normalization_50[0][0] \n__________________________________________________________________________________________________\nmixed5 (Concatenate) (None, 7, 7, 768) 0 activation_41[0][0] \n activation_44[0][0] \n activation_49[0][0] \n activation_50[0][0] \n__________________________________________________________________________________________________\nconv2d_55 (Conv2D) (None, 7, 7, 160) 122880 mixed5[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_55 (BatchNo (None, 7, 7, 160) 480 conv2d_55[0][0] \n__________________________________________________________________________________________________\nactivation_55 (Activation) (None, 7, 7, 160) 0 batch_normalization_55[0][0] \n__________________________________________________________________________________________________\nconv2d_56 (Conv2D) (None, 7, 7, 160) 179200 activation_55[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_56 (BatchNo (None, 7, 7, 160) 480 conv2d_56[0][0] \n__________________________________________________________________________________________________\nactivation_56 (Activation) (None, 7, 7, 160) 0 batch_normalization_56[0][0] \n__________________________________________________________________________________________________\nconv2d_52 (Conv2D) (None, 7, 7, 160) 122880 mixed5[0][0] \n__________________________________________________________________________________________________\nconv2d_57 (Conv2D) (None, 7, 7, 160) 179200 activation_56[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_52 (BatchNo (None, 7, 7, 160) 480 conv2d_52[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_57 (BatchNo (None, 7, 7, 160) 480 conv2d_57[0][0] \n__________________________________________________________________________________________________\nactivation_52 (Activation) (None, 7, 7, 160) 0 batch_normalization_52[0][0] \n__________________________________________________________________________________________________\nactivation_57 (Activation) (None, 7, 7, 160) 0 batch_normalization_57[0][0] \n__________________________________________________________________________________________________\nconv2d_53 (Conv2D) (None, 7, 7, 160) 179200 activation_52[0][0] \n__________________________________________________________________________________________________\nconv2d_58 (Conv2D) (None, 7, 7, 160) 179200 activation_57[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_53 (BatchNo (None, 7, 7, 160) 480 conv2d_53[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_58 (BatchNo (None, 7, 7, 160) 480 conv2d_58[0][0] \n__________________________________________________________________________________________________\nactivation_53 (Activation) (None, 7, 7, 160) 0 batch_normalization_53[0][0] \n__________________________________________________________________________________________________\nactivation_58 (Activation) (None, 7, 7, 160) 0 batch_normalization_58[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_6 (AveragePoo (None, 7, 7, 768) 0 mixed5[0][0] \n__________________________________________________________________________________________________\nconv2d_51 (Conv2D) (None, 7, 7, 192) 147456 mixed5[0][0] \n__________________________________________________________________________________________________\nconv2d_54 (Conv2D) (None, 7, 7, 192) 215040 activation_53[0][0] \n__________________________________________________________________________________________________\nconv2d_59 (Conv2D) (None, 7, 7, 192) 215040 activation_58[0][0] \n__________________________________________________________________________________________________\nconv2d_60 (Conv2D) (None, 7, 7, 192) 147456 average_pooling2d_6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_51 (BatchNo (None, 7, 7, 192) 576 conv2d_51[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_54 (BatchNo (None, 7, 7, 192) 576 conv2d_54[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_59 (BatchNo (None, 7, 7, 192) 576 conv2d_59[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_60 (BatchNo (None, 7, 7, 192) 576 conv2d_60[0][0] \n__________________________________________________________________________________________________\nactivation_51 (Activation) (None, 7, 7, 192) 0 batch_normalization_51[0][0] \n__________________________________________________________________________________________________\nactivation_54 (Activation) (None, 7, 7, 192) 0 batch_normalization_54[0][0] \n__________________________________________________________________________________________________\nactivation_59 (Activation) (None, 7, 7, 192) 0 batch_normalization_59[0][0] \n__________________________________________________________________________________________________\nactivation_60 (Activation) (None, 7, 7, 192) 0 batch_normalization_60[0][0] \n__________________________________________________________________________________________________\nmixed6 (Concatenate) (None, 7, 7, 768) 0 activation_51[0][0] \n activation_54[0][0] \n activation_59[0][0] \n activation_60[0][0] \n__________________________________________________________________________________________________\nconv2d_65 (Conv2D) (None, 7, 7, 192) 147456 mixed6[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_65 (BatchNo (None, 7, 7, 192) 576 conv2d_65[0][0] \n__________________________________________________________________________________________________\nactivation_65 (Activation) (None, 7, 7, 192) 0 batch_normalization_65[0][0] \n__________________________________________________________________________________________________\nconv2d_66 (Conv2D) (None, 7, 7, 192) 258048 activation_65[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_66 (BatchNo (None, 7, 7, 192) 576 conv2d_66[0][0] \n__________________________________________________________________________________________________\nactivation_66 (Activation) (None, 7, 7, 192) 0 batch_normalization_66[0][0] \n__________________________________________________________________________________________________\nconv2d_62 (Conv2D) (None, 7, 7, 192) 147456 mixed6[0][0] \n__________________________________________________________________________________________________\nconv2d_67 (Conv2D) (None, 7, 7, 192) 258048 activation_66[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_62 (BatchNo (None, 7, 7, 192) 576 conv2d_62[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_67 (BatchNo (None, 7, 7, 192) 576 conv2d_67[0][0] \n__________________________________________________________________________________________________\nactivation_62 (Activation) (None, 7, 7, 192) 0 batch_normalization_62[0][0] \n__________________________________________________________________________________________________\nactivation_67 (Activation) (None, 7, 7, 192) 0 batch_normalization_67[0][0] \n__________________________________________________________________________________________________\nconv2d_63 (Conv2D) (None, 7, 7, 192) 258048 activation_62[0][0] \n__________________________________________________________________________________________________\nconv2d_68 (Conv2D) (None, 7, 7, 192) 258048 activation_67[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_63 (BatchNo (None, 7, 7, 192) 576 conv2d_63[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_68 (BatchNo (None, 7, 7, 192) 576 conv2d_68[0][0] \n__________________________________________________________________________________________________\nactivation_63 (Activation) (None, 7, 7, 192) 0 batch_normalization_63[0][0] \n__________________________________________________________________________________________________\nactivation_68 (Activation) (None, 7, 7, 192) 0 batch_normalization_68[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_7 (AveragePoo (None, 7, 7, 768) 0 mixed6[0][0] \n__________________________________________________________________________________________________\nconv2d_61 (Conv2D) (None, 7, 7, 192) 147456 mixed6[0][0] \n__________________________________________________________________________________________________\nconv2d_64 (Conv2D) (None, 7, 7, 192) 258048 activation_63[0][0] \n__________________________________________________________________________________________________\nconv2d_69 (Conv2D) (None, 7, 7, 192) 258048 activation_68[0][0] \n__________________________________________________________________________________________________\nconv2d_70 (Conv2D) (None, 7, 7, 192) 147456 average_pooling2d_7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_61 (BatchNo (None, 7, 7, 192) 576 conv2d_61[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_64 (BatchNo (None, 7, 7, 192) 576 conv2d_64[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_69 (BatchNo (None, 7, 7, 192) 576 conv2d_69[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_70 (BatchNo (None, 7, 7, 192) 576 conv2d_70[0][0] \n__________________________________________________________________________________________________\nactivation_61 (Activation) (None, 7, 7, 192) 0 batch_normalization_61[0][0] \n__________________________________________________________________________________________________\nactivation_64 (Activation) (None, 7, 7, 192) 0 batch_normalization_64[0][0] \n__________________________________________________________________________________________________\nactivation_69 (Activation) (None, 7, 7, 192) 0 batch_normalization_69[0][0] \n__________________________________________________________________________________________________\nactivation_70 (Activation) (None, 7, 7, 192) 0 batch_normalization_70[0][0] \n__________________________________________________________________________________________________\nmixed7 (Concatenate) (None, 7, 7, 768) 0 activation_61[0][0] \n activation_64[0][0] \n activation_69[0][0] \n activation_70[0][0] \n__________________________________________________________________________________________________\nconv2d_73 (Conv2D) (None, 7, 7, 192) 147456 mixed7[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_73 (BatchNo (None, 7, 7, 192) 576 conv2d_73[0][0] \n__________________________________________________________________________________________________\nactivation_73 (Activation) (None, 7, 7, 192) 0 batch_normalization_73[0][0] \n__________________________________________________________________________________________________\nconv2d_74 (Conv2D) (None, 7, 7, 192) 258048 activation_73[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_74 (BatchNo (None, 7, 7, 192) 576 conv2d_74[0][0] \n__________________________________________________________________________________________________\nactivation_74 (Activation) (None, 7, 7, 192) 0 batch_normalization_74[0][0] \n__________________________________________________________________________________________________\nconv2d_71 (Conv2D) (None, 7, 7, 192) 147456 mixed7[0][0] \n__________________________________________________________________________________________________\nconv2d_75 (Conv2D) (None, 7, 7, 192) 258048 activation_74[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_71 (BatchNo (None, 7, 7, 192) 576 conv2d_71[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_75 (BatchNo (None, 7, 7, 192) 576 conv2d_75[0][0] \n__________________________________________________________________________________________________\nactivation_71 (Activation) (None, 7, 7, 192) 0 batch_normalization_71[0][0] \n__________________________________________________________________________________________________\nactivation_75 (Activation) (None, 7, 7, 192) 0 batch_normalization_75[0][0] \n__________________________________________________________________________________________________\nconv2d_72 (Conv2D) (None, 3, 3, 320) 552960 activation_71[0][0] \n__________________________________________________________________________________________________\nconv2d_76 (Conv2D) (None, 3, 3, 192) 331776 activation_75[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_72 (BatchNo (None, 3, 3, 320) 960 conv2d_72[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_76 (BatchNo (None, 3, 3, 192) 576 conv2d_76[0][0] \n__________________________________________________________________________________________________\nactivation_72 (Activation) (None, 3, 3, 320) 0 batch_normalization_72[0][0] \n__________________________________________________________________________________________________\nactivation_76 (Activation) (None, 3, 3, 192) 0 batch_normalization_76[0][0] \n__________________________________________________________________________________________________\nmax_pooling2d_4 (MaxPooling2D) (None, 3, 3, 768) 0 mixed7[0][0] \n__________________________________________________________________________________________________\nmixed8 (Concatenate) (None, 3, 3, 1280) 0 activation_72[0][0] \n activation_76[0][0] \n max_pooling2d_4[0][0] \n__________________________________________________________________________________________________\nconv2d_81 (Conv2D) (None, 3, 3, 448) 573440 mixed8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_81 (BatchNo (None, 3, 3, 448) 1344 conv2d_81[0][0] \n__________________________________________________________________________________________________\nactivation_81 (Activation) (None, 3, 3, 448) 0 batch_normalization_81[0][0] \n__________________________________________________________________________________________________\nconv2d_78 (Conv2D) (None, 3, 3, 384) 491520 mixed8[0][0] \n__________________________________________________________________________________________________\nconv2d_82 (Conv2D) (None, 3, 3, 384) 1548288 activation_81[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_78 (BatchNo (None, 3, 3, 384) 1152 conv2d_78[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_82 (BatchNo (None, 3, 3, 384) 1152 conv2d_82[0][0] \n__________________________________________________________________________________________________\nactivation_78 (Activation) (None, 3, 3, 384) 0 batch_normalization_78[0][0] \n__________________________________________________________________________________________________\nactivation_82 (Activation) (None, 3, 3, 384) 0 batch_normalization_82[0][0] \n__________________________________________________________________________________________________\nconv2d_79 (Conv2D) (None, 3, 3, 384) 442368 activation_78[0][0] \n__________________________________________________________________________________________________\nconv2d_80 (Conv2D) (None, 3, 3, 384) 442368 activation_78[0][0] \n__________________________________________________________________________________________________\nconv2d_83 (Conv2D) (None, 3, 3, 384) 442368 activation_82[0][0] \n__________________________________________________________________________________________________\nconv2d_84 (Conv2D) (None, 3, 3, 384) 442368 activation_82[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_8 (AveragePoo (None, 3, 3, 1280) 0 mixed8[0][0] \n__________________________________________________________________________________________________\nconv2d_77 (Conv2D) (None, 3, 3, 320) 409600 mixed8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_79 (BatchNo (None, 3, 3, 384) 1152 conv2d_79[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_80 (BatchNo (None, 3, 3, 384) 1152 conv2d_80[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_83 (BatchNo (None, 3, 3, 384) 1152 conv2d_83[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_84 (BatchNo (None, 3, 3, 384) 1152 conv2d_84[0][0] \n__________________________________________________________________________________________________\nconv2d_85 (Conv2D) (None, 3, 3, 192) 245760 average_pooling2d_8[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_77 (BatchNo (None, 3, 3, 320) 960 conv2d_77[0][0] \n__________________________________________________________________________________________________\nactivation_79 (Activation) (None, 3, 3, 384) 0 batch_normalization_79[0][0] \n__________________________________________________________________________________________________\nactivation_80 (Activation) (None, 3, 3, 384) 0 batch_normalization_80[0][0] \n__________________________________________________________________________________________________\nactivation_83 (Activation) (None, 3, 3, 384) 0 batch_normalization_83[0][0] \n__________________________________________________________________________________________________\nactivation_84 (Activation) (None, 3, 3, 384) 0 batch_normalization_84[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_85 (BatchNo (None, 3, 3, 192) 576 conv2d_85[0][0] \n__________________________________________________________________________________________________\nactivation_77 (Activation) (None, 3, 3, 320) 0 batch_normalization_77[0][0] \n__________________________________________________________________________________________________\nmixed9_0 (Concatenate) (None, 3, 3, 768) 0 activation_79[0][0] \n activation_80[0][0] \n__________________________________________________________________________________________________\nconcatenate_1 (Concatenate) (None, 3, 3, 768) 0 activation_83[0][0] \n activation_84[0][0] \n__________________________________________________________________________________________________\nactivation_85 (Activation) (None, 3, 3, 192) 0 batch_normalization_85[0][0] \n__________________________________________________________________________________________________\nmixed9 (Concatenate) (None, 3, 3, 2048) 0 activation_77[0][0] \n mixed9_0[0][0] \n concatenate_1[0][0] \n activation_85[0][0] \n__________________________________________________________________________________________________\nconv2d_90 (Conv2D) (None, 3, 3, 448) 917504 mixed9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_90 (BatchNo (None, 3, 3, 448) 1344 conv2d_90[0][0] \n__________________________________________________________________________________________________\nactivation_90 (Activation) (None, 3, 3, 448) 0 batch_normalization_90[0][0] \n__________________________________________________________________________________________________\nconv2d_87 (Conv2D) (None, 3, 3, 384) 786432 mixed9[0][0] \n__________________________________________________________________________________________________\nconv2d_91 (Conv2D) (None, 3, 3, 384) 1548288 activation_90[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_87 (BatchNo (None, 3, 3, 384) 1152 conv2d_87[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_91 (BatchNo (None, 3, 3, 384) 1152 conv2d_91[0][0] \n__________________________________________________________________________________________________\nactivation_87 (Activation) (None, 3, 3, 384) 0 batch_normalization_87[0][0] \n__________________________________________________________________________________________________\nactivation_91 (Activation) (None, 3, 3, 384) 0 batch_normalization_91[0][0] \n__________________________________________________________________________________________________\nconv2d_88 (Conv2D) (None, 3, 3, 384) 442368 activation_87[0][0] \n__________________________________________________________________________________________________\nconv2d_89 (Conv2D) (None, 3, 3, 384) 442368 activation_87[0][0] \n__________________________________________________________________________________________________\nconv2d_92 (Conv2D) (None, 3, 3, 384) 442368 activation_91[0][0] \n__________________________________________________________________________________________________\nconv2d_93 (Conv2D) (None, 3, 3, 384) 442368 activation_91[0][0] \n__________________________________________________________________________________________________\naverage_pooling2d_9 (AveragePoo (None, 3, 3, 2048) 0 mixed9[0][0] \n__________________________________________________________________________________________________\nconv2d_86 (Conv2D) (None, 3, 3, 320) 655360 mixed9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_88 (BatchNo (None, 3, 3, 384) 1152 conv2d_88[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_89 (BatchNo (None, 3, 3, 384) 1152 conv2d_89[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_92 (BatchNo (None, 3, 3, 384) 1152 conv2d_92[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_93 (BatchNo (None, 3, 3, 384) 1152 conv2d_93[0][0] \n__________________________________________________________________________________________________\nconv2d_94 (Conv2D) (None, 3, 3, 192) 393216 average_pooling2d_9[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_86 (BatchNo (None, 3, 3, 320) 960 conv2d_86[0][0] \n__________________________________________________________________________________________________\nactivation_88 (Activation) (None, 3, 3, 384) 0 batch_normalization_88[0][0] \n__________________________________________________________________________________________________\nactivation_89 (Activation) (None, 3, 3, 384) 0 batch_normalization_89[0][0] \n__________________________________________________________________________________________________\nactivation_92 (Activation) (None, 3, 3, 384) 0 batch_normalization_92[0][0] \n__________________________________________________________________________________________________\nactivation_93 (Activation) (None, 3, 3, 384) 0 batch_normalization_93[0][0] \n__________________________________________________________________________________________________\nbatch_normalization_94 (BatchNo (None, 3, 3, 192) 576 conv2d_94[0][0] \n__________________________________________________________________________________________________\nactivation_86 (Activation) (None, 3, 3, 320) 0 batch_normalization_86[0][0] \n__________________________________________________________________________________________________\nmixed9_1 (Concatenate) (None, 3, 3, 768) 0 activation_88[0][0] \n activation_89[0][0] \n__________________________________________________________________________________________________\nconcatenate_2 (Concatenate) (None, 3, 3, 768) 0 activation_92[0][0] \n activation_93[0][0] \n__________________________________________________________________________________________________\nactivation_94 (Activation) (None, 3, 3, 192) 0 batch_normalization_94[0][0] \n__________________________________________________________________________________________________\nmixed10 (Concatenate) (None, 3, 3, 2048) 0 activation_86[0][0] \n mixed9_1[0][0] \n concatenate_2[0][0] \n activation_94[0][0] \n==================================================================================================\nTotal params: 21,802,784\nTrainable params: 0\nNon-trainable params: 21,802,784\n__________________________________________________________________________________________________\n"
]
],
[
[
"In a normal Inception network, you would see from the model summary that the last two layers were a global average pooling layer, and a fully-connected \"Dense\" layer. However, since we set `include_top` to `False`, both of these get dropped. If you otherwise wanted to drop additional layers, you would use:\n\n```\ninception.layers.pop()\n```\n\nNote that `pop()` works from the end of the model backwards.",
"_____no_output_____"
],
[
"It's important to note two things here:\n1. How many layers you drop is up to you, typically. We dropped the final two already by setting `include_top` to False in the original loading of the model, but you could instead just run `pop()` twice to achieve similar results. (*Note:* Keras requires us to set `include_top` to False in order to change the `input_shape`.) Additional layers could be dropped by additional calls to `pop()`.\n2. If you make a mistake with `pop()`, you'll want to reload the model. If you use it multiple times, the model will continue to drop more and more layers, so you may need to check `model.summary()` again to check your work.",
"_____no_output_____"
],
[
"### Adding new layers\n\nNow, you can start to add your own layers. While we've used Keras's `Sequential` model before for simplicity, we'll actually use the [Model API](https://keras.io/models/model/) this time. This functions a little differently, in that instead of using `model.add()`, you explicitly tell the model which previous layer to attach to the current layer. This is useful if you want to use more advanced concepts like [skip layers](https://en.wikipedia.org/wiki/Residual_neural_network), for instance (which were used heavily in ResNet).\n\nFor example, if you had a previous layer named `inp`:\n```\nx = Dropout(0.2)(inp)\n```\nis how you would attach a new dropout layer `x`, with it's input coming from a layer with the variable name `inp`.\n\nWe are going to use the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html), which consists of 60,000 32x32 images of 10 classes. We need to use Keras's `Input` function to do so, and then we want to re-size the images up to the `input_size` we specified earlier (139x139).",
"_____no_output_____"
]
],
[
[
"from keras.layers import Input, Lambda\nimport tensorflow as tf\n\n# Makes the input placeholder layer 32x32x3 for CIFAR-10\ncifar_input = Input(shape=(32,32,3))\n\n# Re-sizes the input with Kera's Lambda layer & attach to cifar_input\nresized_input = Lambda(lambda image: tf.image.resize_images( \n image, (input_size, input_size)))(cifar_input)\n\n# Feeds the re-sized input into Inception model\n# You will need to update the model name if you changed it earlier!\ninp = inception(resized_input)",
"_____no_output_____"
],
[
"# Imports fully-connected \"Dense\" layers & Global Average Pooling\nfrom keras.layers import Dense, GlobalAveragePooling2D\n\n## TODO: Setting `include_top` to False earlier also removed the\n## GlobalAveragePooling2D layer, but we still want it.\n## Add it here, and make sure to connect it to the end of Inception\nx = GlobalAveragePooling2D()(inp)\n\n## TODO: Create two new fully-connected layers using the Model API\n## format discussed above. The first layer should use `out`\n## as its input, along with ReLU activation. You can choose\n## how many nodes it has, although 512 or less is a good idea.\n## The second layer should take this first layer as input, and\n## be named \"predictions\", with Softmax activation and \n## 10 nodes, as we'll be using the CIFAR10 dataset.\nx = Dense(512, activation = 'relu')(x)\npredictions = Dense(10, activation = 'softmax')(x)",
"_____no_output_____"
]
],
[
[
"We're almost done with our new model! Now we just need to use the actual Model API to create the full model.",
"_____no_output_____"
]
],
[
[
"# Imports the Model API\nfrom keras.models import Model\n\n# Creates the model, assuming your final layer is named \"predictions\"\nmodel = Model(inputs=cifar_input, outputs=predictions)\n\n# Compile the model\nmodel.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Check the summary of this new model to confirm the architecture\nmodel.summary()",
"_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_2 (InputLayer) (None, 32, 32, 3) 0 \n_________________________________________________________________\nlambda_1 (Lambda) (None, 139, 139, 3) 0 \n_________________________________________________________________\ninception_v3 (Model) (None, 3, 3, 2048) 21802784 \n_________________________________________________________________\nglobal_average_pooling2d_1 ( (None, 2048) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 512) 1049088 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 5130 \n=================================================================\nTotal params: 22,857,002\nTrainable params: 1,054,218\nNon-trainable params: 21,802,784\n_________________________________________________________________\n"
]
],
[
[
"Great job creating a new model architecture from Inception! Notice how this method of adding layers before InceptionV3 and appending to the end of it made InceptionV3 condense down into one line in the summary; if you use the Inception model's normal input (which you could gather from `inception.layers.input`), it would instead show all the layers like before.\n\nMost of the rest of the code in the notebook just goes toward loading our data, pre-processing it, and starting our training in Keras, although there's one other good point to make here - Keras callbacks.\n\n### Keras Callbacks\nKeras [callbacks](https://keras.io/callbacks/) allow you to gather and store additional information during training, such as the best model, or even stop training early if the validation accuracy has stopped improving. These methods can help to avoid overfitting, or avoid other issues.\n\nThere's two key callbacks to mention here, `ModelCheckpoint` and `EarlyStopping`. As the names may suggest, model checkpoint saves down the best model so far based on a given metric, while early stopping will end training before the specified number of epochs if the chosen metric no longer improves after a given amount of time.\n\nTo set these callbacks, you could do the following:\n```\ncheckpoint = ModelCheckpoint(filepath=save_path, monitor='val_loss', save_best_only=True)\n```\nThis would save a model to a specified `save_path`, based on validation loss, and only save down the best models. If you set `save_best_only` to `False`, every single epoch will save down another version of the model.\n```\nstopper = EarlyStopping(monitor='val_acc', min_delta=0.0003, patience=5)\n```\nThis will monitor validation accuracy, and if it has not decreased by more than 0.0003 from the previous best validation accuracy for 5 epochs, training will end early.\n\n\nYou still need to actually feed these callbacks into `fit()` when you train the model (along with all other relevant data to feed into `fit`):\n```\nmodel.fit(callbacks=[checkpoint, stopper])\n```",
"_____no_output_____"
],
[
"## GPU time\n\nThe rest of the notebook will give you the code for training, so you can turn on the GPU at this point - but first, **make sure to save your jupyter notebook**. Once the GPU is turned on, it will load whatever your last notebook checkpoint is. \n\nWhile we suggest reading through the code below to make sure you understand it, you can otherwise go ahead and select *Cell > Run All* (or *Kernel > Restart & Run All* if already using GPU) to run through all cells in the notebook.",
"_____no_output_____"
]
],
[
[
"from sklearn.utils import shuffle\nfrom sklearn.preprocessing import LabelBinarizer\nfrom keras.datasets import cifar10\n\n(X_train, y_train), (X_val, y_val) = cifar10.load_data()\n\n# One-hot encode the labels\nlabel_binarizer = LabelBinarizer()\ny_one_hot_train = label_binarizer.fit_transform(y_train)\ny_one_hot_val = label_binarizer.fit_transform(y_val)\n\n# Shuffle the training & test data\nX_train, y_one_hot_train = shuffle(X_train, y_one_hot_train)\nX_val, y_one_hot_val = shuffle(X_val, y_one_hot_val)\n\n# We are only going to use the first 10,000 images for speed reasons\n# And only the first 2,000 images from the test set\nX_train = X_train[:10000]\ny_one_hot_train = y_one_hot_train[:10000]\nX_val = X_val[:2000]\ny_one_hot_val = y_one_hot_val[:2000]",
"Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n170500096/170498071 [==============================] - 9s 0us/step\n"
]
],
[
[
"You can check out Keras's [ImageDataGenerator documentation](https://faroit.github.io/keras-docs/2.0.9/preprocessing/image/) for more information on the below - you can also add additional image augmentation through this function, although we are skipping that step here so you can potentially explore it in the upcoming project.",
"_____no_output_____"
]
],
[
[
"# Use a generator to pre-process our images for ImageNet\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.inception_v3 import preprocess_input\n\nif preprocess_flag == True:\n datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n val_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\nelse:\n datagen = ImageDataGenerator()\n val_datagen = ImageDataGenerator()",
"_____no_output_____"
],
[
"# Train the model\nbatch_size = 32\nepochs = 5\n# Note: we aren't using callbacks here since we only are using 5 epochs to conserve GPU time\nmodel.fit_generator(datagen.flow(X_train, y_one_hot_train, batch_size=batch_size), \n steps_per_epoch=len(X_train)/batch_size, epochs=epochs, verbose=1, \n validation_data=val_datagen.flow(X_val, y_one_hot_val, batch_size=batch_size),\n validation_steps=len(X_val)/batch_size)",
"WARNING:tensorflow:From C:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\python\\ops\\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nEpoch 1/5\n313/312 [==============================] - 554s 2s/step - loss: 1.2907 - acc: 0.5694 - val_loss: 1.6065 - val_acc: 0.6680\nEpoch 2/5\n313/312 [==============================] - 559s 2s/step - loss: 0.9867 - acc: 0.6616 - val_loss: 1.4338 - val_acc: 0.6960\nEpoch 3/5\n313/312 [==============================] - 581s 2s/step - loss: 0.8792 - acc: 0.6967 - val_loss: 1.3231 - val_acc: 0.7190\nEpoch 4/5\n313/312 [==============================] - 531s 2s/step - loss: 0.8161 - acc: 0.7192 - val_loss: 1.7038 - val_acc: 0.6770\nEpoch 5/5\n313/312 [==============================] - 529s 2s/step - loss: 0.7953 - acc: 0.7246 - val_loss: 1.4295 - val_acc: 0.7000\n"
]
],
[
[
"As you may have noticed, CIFAR-10 is a fairly tough dataset. However, given that we are only training on a small subset of the data, only training for five epochs, and not using any image augmentation, the results are still fairly impressive!\n\nWe achieved ~70% validation accuracy here, although your results may vary.",
"_____no_output_____"
],
[
"## [Optional] Test without frozen weights, or by training from scratch.\n\nSince the majority of the model was frozen above, training speed is pretty quick. You may also want to check out the training speed, as well as final accuracy, if you don't freeze the weights. Note that this can be fairly slow, so we're marking this as optional in order to conserve GPU time. \n\nIf you do want to see the results from doing so, go back to the first code cell and set `freeze_flag` to `False`. If you want to completely train from scratch without ImageNet pre-trained weights, follow the previous step as well as setting `weights_flag` to `None`. Then, go to *Kernel > Restart & Run All*.",
"_____no_output_____"
],
[
"## Comparison\n\nSo that you don't use up your GPU time, we've tried out these results ourselves as well.\n\nTraining Mode | Val Acc @ 1 epoch | Val Acc @ 5 epoch | Time per epoch\n---- | :----: | :----: | ----:\nFrozen weights | 65.5% | 70.3% | 50 seconds\nUnfrozen weights | 50.6% | 71.6% | 142 seconds\nNo pre-trained weights | 19.2% | 39.2% | 142 seconds\n\nFrom the above, we can see that the pre-trained model with frozen weights actually began converging the fastest (already at 65.5% after 1 epoch), while the model re-training from the pre-trained weights slightly edged it out after 5 epochs.\n\nHowever, this does not tell the whole story - the training accuracy was substantially higher, nearing 87% for the unfrozen weights model. It actually began overfit the data much more under this method. We would likely be able to counteract some of this issue by using data augmentation. On the flip side, the model using frozen weights could also have been improved by actually only freezing a portion of the weights; some of these are likely more specific to ImageNet classes as it gets later in the network, as opposed to the simpler features extracted early in the network.\n\n### The Power of Transfer Learning\nComparing the last line to the other two really shows the power of transfer learning. After five epochs, a model without ImageNet pre-training had only achieved 39.2% accuracy, compared to over 70% for the other two. As such, pre-training the network has saved substantial time, especially given the additional training time needed when the weights are not frozen.\n\nThere is also evidence found in various research that pre-training on ImageNet weights will result in a higher overall accuracy than completely training from scratch, even when using a substantially different dataset.",
"_____no_output_____"
]
]
] |
[
"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",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cbb19e002ace77c2bd6960fdbbbdece83c42e8b1
| 51,745 |
ipynb
|
Jupyter Notebook
|
notebooks/istio_example.ipynb
|
peter-vandenabeele-axa/seldon-core
|
b79b0f3d1ae4b190e23d034c11769f20025fc571
|
[
"Apache-2.0"
] | null | null | null |
notebooks/istio_example.ipynb
|
peter-vandenabeele-axa/seldon-core
|
b79b0f3d1ae4b190e23d034c11769f20025fc571
|
[
"Apache-2.0"
] | 16 |
2019-12-16T22:22:13.000Z
|
2022-03-12T00:07:55.000Z
|
notebooks/istio_example.ipynb
|
peter-vandenabeele-axa/seldon-core
|
b79b0f3d1ae4b190e23d034c11769f20025fc571
|
[
"Apache-2.0"
] | null | null | null | 35.248638 | 2,002 | 0.537926 |
[
[
[
"# Example Seldon Core Deployments using Helm\n<img src=\"images/deploy-graph.png\" alt=\"predictor with canary\" title=\"ml graph\"/>",
"_____no_output_____"
],
[
"## Prerequisites\nYou will need\n - [Git clone of Seldon Core](https://github.com/SeldonIO/seldon-core)\n - A running Kubernetes cluster with kubectl authenticated\n - [seldon-core Python package](https://pypi.org/project/seldon-core/) (```pip install seldon-core>=0.2.6.1```)\n - [Helm client](https://helm.sh/)",
"_____no_output_____"
],
[
"### Creating a Kubernetes Cluster\n\nFollow the [Kubernetes documentation to create a cluster](https://kubernetes.io/docs/setup/).\n\nOnce created ensure ```kubectl``` is authenticated against the running cluster.",
"_____no_output_____"
],
[
"## Setup",
"_____no_output_____"
]
],
[
[
"!kubectl create namespace seldon",
"namespace/seldon created\r\n"
],
[
"!kubectl config set-context $(kubectl config current-context) --namespace=seldon",
"Context \"minikube\" modified.\r\n"
],
[
"!kubectl create clusterrolebinding kube-system-cluster-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default",
"clusterrolebinding.rbac.authorization.k8s.io/kube-system-cluster-admin created\r\n"
]
],
[
[
"## Install Helm",
"_____no_output_____"
]
],
[
[
"!kubectl -n kube-system create sa tiller\n!kubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller\n!helm init --service-account tiller",
"serviceaccount/tiller created\nclusterrolebinding.rbac.authorization.k8s.io/tiller created\n$HELM_HOME has been configured at /home/clive/.helm.\n\nTiller (the Helm server-side component) has been installed into your Kubernetes Cluster.\n\nPlease note: by default, Tiller is deployed with an insecure 'allow unauthenticated users' policy.\nTo prevent this, run `helm init` with the --tiller-tls-verify flag.\nFor more information on securing your installation see: https://docs.helm.sh/using_helm/#securing-your-helm-installation\nHappy Helming!\n"
],
[
"!kubectl rollout status deploy/tiller-deploy -n kube-system",
"Waiting for deployment \"tiller-deploy\" rollout to finish: 0 of 1 updated replicas are available...\ndeployment \"tiller-deploy\" successfully rolled out\n"
]
],
[
[
"## Setup Istio\n\nEnsure you have istio installed. Follow their [docs](https://istio.io/docs)\n\nFor this example we will create the default istio gateway for seldon which needs to be called `seldon-gateway`. You can supply your own gateway by adding to your SeldonDeployments resources the annotation `seldon.io/istio-gateway` with values the name of your istio gateway.",
"_____no_output_____"
],
[
"Create a gateway for our istio-ingress",
"_____no_output_____"
]
],
[
[
"!kubectl create -f resources/seldon-gateway.yaml",
"gateway.networking.istio.io/seldon-gateway created\r\n"
]
],
[
[
"Label our namespace so istio creates sidecars",
"_____no_output_____"
]
],
[
[
"!kubectl label namespace seldon istio-injection=enabled",
"namespace/seldon labeled\r\n"
]
],
[
[
"If you are using Minikube for your Kubernetes cluster you will need to run as root in a separte terminal:\n```\nminikube tunnel\n```\nThis will allow a LoadBalancer to be simulated on your local machine. ",
"_____no_output_____"
]
],
[
[
"INGRESS_HOST=!kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}'\nINGRESS_PORT=!kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name==\"http2\")].port}'\nISTIO_GATEWAY=INGRESS_HOST[0]+\":\"+INGRESS_PORT[0]",
"_____no_output_____"
],
[
"ISTIO_GATEWAY",
"_____no_output_____"
]
],
[
[
"## Start seldon-core",
"_____no_output_____"
]
],
[
[
"!helm install ../helm-charts/seldon-core-operator --name seldon-core --set istio.enabled=true --set usageMetrics.enabled=true --namespace seldon-system",
"NAME: seldon-core\nLAST DEPLOYED: Sat May 25 11:33:25 2019\nNAMESPACE: seldon-system\nSTATUS: DEPLOYED\n\nRESOURCES:\n==> v1/ClusterRole\nNAME AGE\nseldon-operator-manager-role 1s\n\n==> v1/ClusterRoleBinding\nNAME AGE\nseldon-operator-manager-rolebinding 1s\n\n==> v1/ConfigMap\nNAME DATA AGE\nseldon-spartakus-config 3 1s\n\n==> v1/Pod(related)\nNAME READY STATUS RESTARTS AGE\nseldon-operator-controller-manager-0 0/1 ContainerCreating 0 1s\nseldon-spartakus-volunteer-5554c4d8b6-hvmt2 0/1 ContainerCreating 0 0s\n\n==> v1/Secret\nNAME TYPE DATA AGE\nseldon-operator-webhook-server-secret Opaque 0 1s\n\n==> v1/Service\nNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE\nseldon-operator-controller-manager-service ClusterIP 10.103.145.68 <none> 443/TCP 1s\n\n==> v1/ServiceAccount\nNAME SECRETS AGE\nseldon-spartakus-volunteer 1 1s\n\n==> v1/StatefulSet\nNAME READY AGE\nseldon-operator-controller-manager 0/1 1s\n\n==> v1beta1/ClusterRole\nNAME AGE\nseldon-spartakus-volunteer 1s\n\n==> v1beta1/ClusterRoleBinding\nNAME AGE\nseldon-spartakus-volunteer 0s\n\n==> v1beta1/CustomResourceDefinition\nNAME AGE\nseldondeployments.machinelearning.seldon.io 1s\n\n==> v1beta1/Deployment\nNAME READY UP-TO-DATE AVAILABLE AGE\nseldon-spartakus-volunteer 0/1 1 0 1s\n\n\nNOTES:\nNOTES: TODO\n\n\n"
],
[
"!kubectl rollout status deploy/seldon-controller-manager -n seldon-system",
"partitioned roll out complete: 1 new pods have been updated...\r\n"
]
],
[
[
"## Serve Single Model",
"_____no_output_____"
]
],
[
[
"!helm install ../helm-charts/seldon-single-model --name mymodel",
"NAME: mymodel\nLAST DEPLOYED: Sat May 25 11:36:23 2019\nNAMESPACE: seldon\nSTATUS: DEPLOYED\n\nRESOURCES:\n==> v1alpha2/SeldonDeployment\nNAME AGE\nmymodel 0s\n\n\n"
],
[
"!helm template ../helm-charts/seldon-single-model | pygmentize -l json",
"\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\r\n\u001b[04m\u001b[31;01m#\u001b[39;49;00m \u001b[04m\u001b[31;01mS\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mu\u001b[39;49;00m\u001b[04m\u001b[31;01mr\u001b[39;49;00m\u001b[04m\u001b[31;01mc\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01m:\u001b[39;49;00m \u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mi\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\u001b[04m\u001b[31;01mg\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01mp\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01m.\u001b[39;49;00m\u001b[04m\u001b[31;01mj\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\r\n{\r\n \u001b[34;01m\"apiVersion\"\u001b[39;49;00m: \u001b[33m\"machinelearning.seldon.io/v1alpha2\"\u001b[39;49;00m,\r\n \u001b[34;01m\"kind\"\u001b[39;49;00m: \u001b[33m\"SeldonDeployment\"\u001b[39;49;00m,\r\n \u001b[34;01m\"metadata\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"labels\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"app\"\u001b[39;49;00m: \u001b[33m\"seldon\"\u001b[39;49;00m\r\n },\r\n \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m\r\n },\r\n \u001b[34;01m\"spec\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m,\r\n \u001b[34;01m\"predictors\"\u001b[39;49;00m: [\r\n {\r\n \u001b[34;01m\"componentSpecs\"\u001b[39;49;00m: [{\r\n \u001b[34;01m\"spec\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"containers\"\u001b[39;49;00m: [\r\n {\r\n \u001b[34;01m\"image\"\u001b[39;49;00m: \u001b[33m\"seldonio/mock_classifier:1.0\"\u001b[39;49;00m,\r\n \u001b[34;01m\"imagePullPolicy\"\u001b[39;49;00m: \u001b[33m\"IfNotPresent\"\u001b[39;49;00m,\r\n \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier\"\u001b[39;49;00m,\r\n \u001b[34;01m\"resources\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"requests\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"memory\"\u001b[39;49;00m: \u001b[33m\"1Mi\"\u001b[39;49;00m\r\n }\r\n }\r\n }\r\n ],\r\n \u001b[34;01m\"terminationGracePeriodSeconds\"\u001b[39;49;00m: \u001b[34m1\u001b[39;49;00m\r\n }}\r\n ],\r\n \u001b[34;01m\"graph\"\u001b[39;49;00m:\r\n {\r\n \u001b[34;01m\"children\"\u001b[39;49;00m: [],\r\n \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier\"\u001b[39;49;00m,\r\n \u001b[34;01m\"type\"\u001b[39;49;00m: \u001b[33m\"MODEL\"\u001b[39;49;00m,\r\n \u001b[34;01m\"endpoint\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"type\"\u001b[39;49;00m: \u001b[33m\"REST\"\u001b[39;49;00m\r\n }},\r\n \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m,\r\n \u001b[34;01m\"replicas\"\u001b[39;49;00m: \u001b[34m1\u001b[39;49;00m,\r\n \u001b[34;01m\"labels\"\u001b[39;49;00m: {\r\n \u001b[34;01m\"version\"\u001b[39;49;00m : \u001b[33m\"v1\"\u001b[39;49;00m\r\n }\r\n }\r\n ]\r\n }\r\n}\r\n"
],
[
"!kubectl rollout status deploy/mymodel-mymodel-7cd068f",
"deployment \"mymodel-mymodel-7cd068f\" successfully rolled out\r\n"
]
],
[
[
"### Get predictions",
"_____no_output_____"
]
],
[
[
"from seldon_core.seldon_client import SeldonClient\nsc = SeldonClient(deployment_name=\"mymodel\",namespace=\"seldon\",gateway_endpoint=ISTIO_GATEWAY)",
"_____no_output_____"
]
],
[
[
"#### REST Request",
"_____no_output_____"
]
],
[
[
"r = sc.predict(gateway=\"istio\",transport=\"rest\")\nprint(r)",
"Success:True message:\nRequest:\ndata {\n tensor {\n shape: 1\n shape: 1\n values: 0.17442955533025983\n }\n}\n\nResponse:\nmeta {\n puid: \"q51i2q9ri9scl4uqi9bjrkr25f\"\n requestPath {\n key: \"classifier\"\n value: \"seldonio/mock_classifier:1.0\"\n }\n}\ndata {\n names: \"proba\"\n tensor {\n shape: 1\n shape: 1\n values: 0.060526569086473254\n }\n}\n\n"
]
],
[
[
"#### gRPC Request",
"_____no_output_____"
]
],
[
[
"r = sc.predict(gateway=\"istio\",transport=\"grpc\")\nprint(r)",
"Success:True message:\nRequest:\ndata {\n tensor {\n shape: 1\n shape: 1\n values: 0.876372699790597\n }\n}\n\nResponse:\nmeta {\n puid: \"hfd50d101q22qkjpme5t1r3b92\"\n requestPath {\n key: \"classifier\"\n value: \"seldonio/mock_classifier:1.0\"\n }\n}\ndata {\n names: \"proba\"\n tensor {\n shape: 1\n shape: 1\n values: 0.11503680184999401\n }\n}\n\n"
],
[
"!helm delete mymodel --purge",
"release \"mymodel\" deleted\r\n"
]
],
[
[
"## Serve AB Test",
"_____no_output_____"
]
],
[
[
"!helm install ../helm-charts/seldon-abtest --name myabtest",
"NAME: myabtest\nLAST DEPLOYED: Sat May 25 11:11:01 2019\nNAMESPACE: seldon\nSTATUS: DEPLOYED\n\nRESOURCES:\n==> v1alpha2/SeldonDeployment\nNAME AGE\nmyabtest 0s\n\n\n"
],
[
"!helm template ../helm-charts/seldon-abtest | pygmentize -l json",
"\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\r\n\u001b[04m\u001b[31;01m#\u001b[39;49;00m \u001b[04m\u001b[31;01mS\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mu\u001b[39;49;00m\u001b[04m\u001b[31;01mr\u001b[39;49;00m\u001b[04m\u001b[31;01mc\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01m:\u001b[39;49;00m \u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mb\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01mp\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mb\u001b[39;49;00m\u001b[04m\u001b[31;01m_\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01m_\u001b[39;49;00m\u001b[34m1\u001b[39;49;00m\u001b[04m\u001b[31;01mp\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01m.\u001b[39;49;00m\u001b[04m\u001b[31;01mj\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\r\n\r\n\r\n\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\r\n\u001b[04m\u001b[31;01m#\u001b[39;49;00m \u001b[04m\u001b[31;01mS\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mu\u001b[39;49;00m\u001b[04m\u001b[31;01mr\u001b[39;49;00m\u001b[04m\u001b[31;01mc\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01m:\u001b[39;49;00m \u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mb\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01mp\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mb\u001b[39;49;00m\u001b[04m\u001b[31;01m_\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01m_\u001b[39;49;00m\u001b[34m2\u001b[39;49;00m\u001b[04m\u001b[31;01mp\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01m.\u001b[39;49;00m\u001b[04m\u001b[31;01mj\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\r\n\r\n{\r\n \u001b[34;01m\"apiVersion\"\u001b[39;49;00m: \u001b[33m\"machinelearning.seldon.io/v1alpha2\"\u001b[39;49;00m,\r\n \u001b[34;01m\"kind\"\u001b[39;49;00m: \u001b[33m\"SeldonDeployment\"\u001b[39;49;00m,\r\n \u001b[34;01m\"metadata\"\u001b[39;49;00m: {\r\n\t\u001b[34;01m\"labels\"\u001b[39;49;00m: {\r\n\t \u001b[34;01m\"app\"\u001b[39;49;00m: \u001b[33m\"seldon\"\u001b[39;49;00m\r\n\t},\r\n\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m\r\n },\r\n \u001b[34;01m\"spec\"\u001b[39;49;00m: {\r\n\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m,\r\n\t\u001b[34;01m\"predictors\"\u001b[39;49;00m: [\r\n\t {\r\n\t\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"abtest\"\u001b[39;49;00m,\r\n\t\t\u001b[34;01m\"replicas\"\u001b[39;49;00m: \u001b[34m1\u001b[39;49;00m,\r\n\t\t\u001b[34;01m\"componentSpecs\"\u001b[39;49;00m: [{\r\n\t\t \u001b[34;01m\"spec\"\u001b[39;49;00m: {\r\n\t\t\t\u001b[34;01m\"containers\"\u001b[39;49;00m: [\r\n\t\t\t {\r\n\t\t\t\t\u001b[34;01m\"image\"\u001b[39;49;00m: \u001b[33m\"seldonio/mock_classifier:1.0\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"imagePullPolicy\"\u001b[39;49;00m: \u001b[33m\"IfNotPresent\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-1\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"resources\"\u001b[39;49;00m: {\r\n\t\t\t\t \u001b[34;01m\"requests\"\u001b[39;49;00m: {\r\n\t\t\t\t\t\u001b[34;01m\"memory\"\u001b[39;49;00m: \u001b[33m\"1Mi\"\u001b[39;49;00m\r\n\t\t\t\t }\r\n\t\t\t\t}\r\n\t\t\t }],\r\n\t\t\t\u001b[34;01m\"terminationGracePeriodSeconds\"\u001b[39;49;00m: \u001b[34m20\u001b[39;49;00m\r\n\t\t }},\r\n\t {\r\n\t\t \u001b[34;01m\"metadata\"\u001b[39;49;00m:{\r\n\t\t\t\u001b[34;01m\"labels\"\u001b[39;49;00m:{\r\n\t\t\t \u001b[34;01m\"version\"\u001b[39;49;00m:\u001b[33m\"v2\"\u001b[39;49;00m\r\n\t\t\t}\r\n\t\t }, \r\n\t\t\t\u001b[34;01m\"spec\"\u001b[39;49;00m:{\r\n\t\t\t \u001b[34;01m\"containers\"\u001b[39;49;00m:[\r\n\t\t\t {\r\n\t\t\t\t\u001b[34;01m\"image\"\u001b[39;49;00m: \u001b[33m\"seldonio/mock_classifier:1.0\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"imagePullPolicy\"\u001b[39;49;00m: \u001b[33m\"IfNotPresent\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-2\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"resources\"\u001b[39;49;00m: {\r\n\t\t\t\t \u001b[34;01m\"requests\"\u001b[39;49;00m: {\r\n\t\t\t\t\t\u001b[34;01m\"memory\"\u001b[39;49;00m: \u001b[33m\"1Mi\"\u001b[39;49;00m\r\n\t\t\t\t }\r\n\t\t\t\t}\r\n\t\t\t }\r\n\t\t\t],\r\n\t\t\t\u001b[34;01m\"terminationGracePeriodSeconds\"\u001b[39;49;00m: \u001b[34m20\u001b[39;49;00m\r\n\t\t\t\t }\r\n\t\t\t\t }],\r\n\t\t\u001b[34;01m\"graph\"\u001b[39;49;00m: {\r\n\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m,\r\n\t\t \u001b[34;01m\"endpoint\"\u001b[39;49;00m:{},\r\n\t\t \u001b[34;01m\"implementation\"\u001b[39;49;00m:\u001b[33m\"RANDOM_ABTEST\"\u001b[39;49;00m,\r\n\t\t \u001b[34;01m\"parameters\"\u001b[39;49;00m: [\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m:\u001b[33m\"ratioA\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"value\"\u001b[39;49;00m:\u001b[33m\"0.5\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"FLOAT\"\u001b[39;49;00m\r\n\t\t\t}\r\n\t\t ],\r\n\t\t \u001b[34;01m\"children\"\u001b[39;49;00m: [\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-1\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"endpoint\"\u001b[39;49;00m:{\r\n\t\t\t\t\u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"REST\"\u001b[39;49;00m\r\n\t\t\t },\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"MODEL\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"children\"\u001b[39;49;00m:[]\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-2\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"endpoint\"\u001b[39;49;00m:{\r\n\t\t\t\t\u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"REST\"\u001b[39;49;00m\r\n\t\t\t },\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"MODEL\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"children\"\u001b[39;49;00m:[]\r\n\t\t\t} \r\n\t\t ]\r\n\t\t}\r\n\t }\r\n\t]\r\n }\r\n}\t\t\r\n\t\t\r\n\r\n \r\n"
],
[
"!kubectl rollout status deploy/myabtest-abtest-41de5b8\n!kubectl rollout status deploy/myabtest-abtest-df66c5c",
"Waiting for deployment \"myabtest-abtest-41de5b8\" rollout to finish: 0 of 1 updated replicas are available...\ndeployment \"myabtest-abtest-41de5b8\" successfully rolled out\ndeployment \"myabtest-abtest-df66c5c\" successfully rolled out\n"
]
],
[
[
"### Get predictions",
"_____no_output_____"
]
],
[
[
"from seldon_core.seldon_client import SeldonClient\nsc = SeldonClient(deployment_name=\"myabtest\",namespace=\"seldon\",gateway_endpoint=ISTIO_GATEWAY)",
"_____no_output_____"
]
],
[
[
"#### REST Request",
"_____no_output_____"
]
],
[
[
"r = sc.predict(gateway=\"istio\",transport=\"rest\")\nprint(r)",
"Success:True message:\nRequest:\ndata {\n tensor {\n shape: 1\n shape: 1\n values: 0.5812964139653322\n }\n}\n\nResponse:\nmeta {\n puid: \"qik8lbat9jfhl6e1uf9u3nlm2s\"\n routing {\n key: \"myabtest\"\n value: 1\n }\n requestPath {\n key: \"classifier-2\"\n value: \"seldonio/mock_classifier:1.0\"\n }\n requestPath {\n key: \"myabtest\"\n value: \"\"\n }\n}\ndata {\n names: \"proba\"\n tensor {\n shape: 1\n shape: 1\n values: 0.08823566926521886\n }\n}\n\n"
]
],
[
[
"#### gRPC Request",
"_____no_output_____"
]
],
[
[
"r = sc.predict(gateway=\"istio\",transport=\"grpc\")\nprint(r)",
"Success:True message:\nRequest:\ndata {\n tensor {\n shape: 1\n shape: 1\n values: 0.7479179869186225\n }\n}\n\nResponse:\nmeta {\n puid: \"n2q4a586hp3aen91a0k26kiskd\"\n routing {\n key: \"myabtest\"\n value: 0\n }\n requestPath {\n key: \"classifier-1\"\n value: \"seldonio/mock_classifier:1.0\"\n }\n requestPath {\n key: \"myabtest\"\n value: \"\"\n }\n}\ndata {\n names: \"proba\"\n tensor {\n shape: 1\n shape: 1\n values: 0.10259218150165016\n }\n}\n\n"
],
[
"!helm delete myabtest --purge",
"release \"myabtest\" deleted\r\n"
]
],
[
[
"## Serve Multi-Armed Bandit",
"_____no_output_____"
]
],
[
[
"!helm install ../helm-charts/seldon-mab --name mymab",
"NAME: mymab\nLAST DEPLOYED: Sat May 25 11:12:08 2019\nNAMESPACE: seldon\nSTATUS: DEPLOYED\n\nRESOURCES:\n==> v1alpha2/SeldonDeployment\nNAME AGE\nmymab 1s\n\n\n"
],
[
"!helm template ../helm-charts/seldon-mab | pygmentize -l json",
"\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\r\n\u001b[04m\u001b[31;01m#\u001b[39;49;00m \u001b[04m\u001b[31;01mS\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mu\u001b[39;49;00m\u001b[04m\u001b[31;01mr\u001b[39;49;00m\u001b[04m\u001b[31;01mc\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01m:\u001b[39;49;00m \u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01md\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\u001b[04m\u001b[31;01m-\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mb\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01mp\u001b[39;49;00m\u001b[04m\u001b[31;01ml\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mt\u001b[39;49;00m\u001b[04m\u001b[31;01me\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01m/\u001b[39;49;00m\u001b[04m\u001b[31;01mm\u001b[39;49;00m\u001b[04m\u001b[31;01ma\u001b[39;49;00m\u001b[04m\u001b[31;01mb\u001b[39;49;00m\u001b[04m\u001b[31;01m.\u001b[39;49;00m\u001b[04m\u001b[31;01mj\u001b[39;49;00m\u001b[04m\u001b[31;01ms\u001b[39;49;00m\u001b[04m\u001b[31;01mo\u001b[39;49;00m\u001b[04m\u001b[31;01mn\u001b[39;49;00m\r\n{\r\n \u001b[34;01m\"apiVersion\"\u001b[39;49;00m: \u001b[33m\"machinelearning.seldon.io/v1alpha2\"\u001b[39;49;00m,\r\n \u001b[34;01m\"kind\"\u001b[39;49;00m: \u001b[33m\"SeldonDeployment\"\u001b[39;49;00m,\r\n \u001b[34;01m\"metadata\"\u001b[39;49;00m: {\r\n\t\u001b[34;01m\"labels\"\u001b[39;49;00m: {\r\n\t \u001b[34;01m\"app\"\u001b[39;49;00m: \u001b[33m\"seldon\"\u001b[39;49;00m\r\n\t},\r\n\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m\r\n },\r\n \u001b[34;01m\"spec\"\u001b[39;49;00m: {\r\n\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"release-name\"\u001b[39;49;00m,\r\n\t\u001b[34;01m\"predictors\"\u001b[39;49;00m: [\r\n\t {\r\n\t\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"abtest\"\u001b[39;49;00m,\r\n\t\t\u001b[34;01m\"replicas\"\u001b[39;49;00m: \u001b[34m1\u001b[39;49;00m,\r\n\t\t\u001b[34;01m\"componentSpecs\"\u001b[39;49;00m: [{\r\n\t\t \u001b[34;01m\"spec\"\u001b[39;49;00m: {\r\n\t\t\t\u001b[34;01m\"containers\"\u001b[39;49;00m: [\r\n\t\t\t {\r\n\t\t\t\t\u001b[34;01m\"image\"\u001b[39;49;00m: \u001b[33m\"seldonio/mock_classifier:1.0\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"imagePullPolicy\"\u001b[39;49;00m: \u001b[33m\"IfNotPresent\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-1\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"resources\"\u001b[39;49;00m: {\r\n\t\t\t\t \u001b[34;01m\"requests\"\u001b[39;49;00m: {\r\n\t\t\t\t\t\u001b[34;01m\"memory\"\u001b[39;49;00m: \u001b[33m\"1Mi\"\u001b[39;49;00m\r\n\t\t\t\t }\r\n\t\t\t\t}\r\n\t\t\t }],\r\n\t\t\t\u001b[34;01m\"terminationGracePeriodSeconds\"\u001b[39;49;00m: \u001b[34m20\u001b[39;49;00m\r\n\t\t }},\r\n\t {\r\n\t\t \u001b[34;01m\"metadata\"\u001b[39;49;00m:{\r\n\t\t\t\u001b[34;01m\"labels\"\u001b[39;49;00m:{\r\n\t\t\t \u001b[34;01m\"version\"\u001b[39;49;00m:\u001b[33m\"v2\"\u001b[39;49;00m\r\n\t\t\t}\r\n\t\t }, \r\n\t\t\t\u001b[34;01m\"spec\"\u001b[39;49;00m:{\r\n\t\t\t \u001b[34;01m\"containers\"\u001b[39;49;00m:[\r\n\t\t\t {\r\n\t\t\t\t\u001b[34;01m\"image\"\u001b[39;49;00m: \u001b[33m\"seldonio/mock_classifier:1.0\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"imagePullPolicy\"\u001b[39;49;00m: \u001b[33m\"IfNotPresent\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-2\"\u001b[39;49;00m,\r\n\t\t\t\t\u001b[34;01m\"resources\"\u001b[39;49;00m: {\r\n\t\t\t\t \u001b[34;01m\"requests\"\u001b[39;49;00m: {\r\n\t\t\t\t\t\u001b[34;01m\"memory\"\u001b[39;49;00m: \u001b[33m\"1Mi\"\u001b[39;49;00m\r\n\t\t\t\t }\r\n\t\t\t\t}\r\n\t\t\t }\r\n\t\t\t],\r\n\t\t\t\u001b[34;01m\"terminationGracePeriodSeconds\"\u001b[39;49;00m: \u001b[34m20\u001b[39;49;00m\r\n\t\t\t}\r\n\t\t},\r\n\t {\r\n\t\t \u001b[34;01m\"spec\"\u001b[39;49;00m:{\r\n\t\t\t\u001b[34;01m\"containers\"\u001b[39;49;00m: [{\r\n\t\t\t \u001b[34;01m\"image\"\u001b[39;49;00m: \u001b[33m\"seldonio/mab_epsilon_greedy:1.1\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"eg-router\"\u001b[39;49;00m\r\n\t\t\t}],\r\n\t\t\t\u001b[34;01m\"terminationGracePeriodSeconds\"\u001b[39;49;00m: \u001b[34m20\u001b[39;49;00m\r\n\t\t }}\r\n\t ],\r\n\t\t\u001b[34;01m\"graph\"\u001b[39;49;00m: {\r\n\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"eg-router\"\u001b[39;49;00m,\r\n\t\t \u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"ROUTER\"\u001b[39;49;00m,\r\n\t\t \u001b[34;01m\"parameters\"\u001b[39;49;00m: [\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"n_branches\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"value\"\u001b[39;49;00m: \u001b[33m\"2\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m: \u001b[33m\"INT\"\u001b[39;49;00m\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"epsilon\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"value\"\u001b[39;49;00m: \u001b[33m\"0.2\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m: \u001b[33m\"FLOAT\"\u001b[39;49;00m\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"verbose\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"value\"\u001b[39;49;00m: \u001b[33m\"1\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m: \u001b[33m\"BOOL\"\u001b[39;49;00m\r\n\t\t\t}\r\n\t\t ],\r\n\t\t \u001b[34;01m\"children\"\u001b[39;49;00m: [\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-1\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"endpoint\"\u001b[39;49;00m:{\r\n\t\t\t\t\u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"REST\"\u001b[39;49;00m\r\n\t\t\t },\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"MODEL\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"children\"\u001b[39;49;00m:[]\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t \u001b[34;01m\"name\"\u001b[39;49;00m: \u001b[33m\"classifier-2\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"endpoint\"\u001b[39;49;00m:{\r\n\t\t\t\t\u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"REST\"\u001b[39;49;00m\r\n\t\t\t },\r\n\t\t\t \u001b[34;01m\"type\"\u001b[39;49;00m:\u001b[33m\"MODEL\"\u001b[39;49;00m,\r\n\t\t\t \u001b[34;01m\"children\"\u001b[39;49;00m:[]\r\n\t\t\t} \r\n\t\t ]\r\n\t\t}\r\n\t }\r\n\t]\r\n }\r\n}\r\n\t\t\r\n\r\n \r\n"
],
[
"!kubectl rollout status deploy/mymab-abtest-41de5b8\n!kubectl rollout status deploy/mymab-abtest-b8038b2\n!kubectl rollout status deploy/mymab-abtest-df66c5c ",
"Waiting for deployment \"mymab-abtest-41de5b8\" rollout to finish: 0 of 1 updated replicas are available...\ndeployment \"mymab-abtest-41de5b8\" successfully rolled out\nWaiting for deployment \"mymab-abtest-b8038b2\" rollout to finish: 0 of 1 updated replicas are available...\ndeployment \"mymab-abtest-b8038b2\" successfully rolled out\ndeployment \"mymab-abtest-df66c5c\" successfully rolled out\n"
]
],
[
[
"### Get predictions",
"_____no_output_____"
]
],
[
[
"from seldon_core.seldon_client import SeldonClient\nsc = SeldonClient(deployment_name=\"mymab\",namespace=\"seldon\",gateway_endpoint=ISTIO_GATEWAY)",
"_____no_output_____"
]
],
[
[
"#### REST Request",
"_____no_output_____"
]
],
[
[
"r = sc.predict(gateway=\"istio\",transport=\"rest\")\nprint(r)",
"Success:True message:\nRequest:\ndata {\n tensor {\n shape: 1\n shape: 1\n values: 0.48031921945868383\n }\n}\n\nResponse:\nmeta {\n puid: \"ppp3u5i1q5gl27oo16pag7h257\"\n routing {\n key: \"eg-router\"\n value: 1\n }\n requestPath {\n key: \"classifier-2\"\n value: \"seldonio/mock_classifier:1.0\"\n }\n requestPath {\n key: \"eg-router\"\n value: \"seldonio/mab_epsilon_greedy:1.1\"\n }\n}\ndata {\n names: \"proba\"\n tensor {\n shape: 1\n shape: 1\n values: 0.08044268384752119\n }\n}\n\n"
]
],
[
[
"#### gRPC Request",
"_____no_output_____"
]
],
[
[
"r = sc.predict(gateway=\"istio\",transport=\"grpc\")\nprint(r)",
"Success:True message:\nRequest:\ndata {\n tensor {\n shape: 1\n shape: 1\n values: 0.16200320120248235\n }\n}\n\nResponse:\nmeta {\n puid: \"7a936sho0ajsq17q2q62f06j0p\"\n routing {\n key: \"eg-router\"\n value: 0\n }\n requestPath {\n key: \"classifier-1\"\n value: \"seldonio/mock_classifier:1.0\"\n }\n requestPath {\n key: \"eg-router\"\n value: \"seldonio/mab_epsilon_greedy:1.1\"\n }\n}\ndata {\n names: \"proba\"\n tensor {\n shape: 1\n shape: 1\n values: 0.05982381484602229\n }\n}\n\n"
],
[
"!helm delete mymab --purge",
"release \"mymab\" deleted\r\n"
]
],
[
[
"## Serve with Shadow",
"_____no_output_____"
],
[
"#### We'll use a pre-packaged model server but the 'shadow' flag can be set on any predictor.",
"_____no_output_____"
]
],
[
[
"!pygmentize ./resources/istio_shadow.yaml",
"\u001b[94mkind\u001b[39;49;00m: SeldonDeployment\r\n\u001b[94mapiVersion\u001b[39;49;00m: machinelearning.seldon.io/v1alpha2\r\n\u001b[94mmetadata\u001b[39;49;00m:\r\n \u001b[94mname\u001b[39;49;00m: iris\r\n\u001b[94mspec\u001b[39;49;00m:\r\n \u001b[94mname\u001b[39;49;00m: iris\r\n \u001b[94mpredictors\u001b[39;49;00m:\r\n - \u001b[94mname\u001b[39;49;00m: default\r\n \u001b[94mgraph\u001b[39;49;00m:\r\n \u001b[94mname\u001b[39;49;00m: iris-default\r\n \u001b[94mimplementation\u001b[39;49;00m: SKLEARN_SERVER\r\n \u001b[94mmodelUri\u001b[39;49;00m: gs://seldon-models/sklearn/iris\r\n \u001b[94mreplicas\u001b[39;49;00m: 1\r\n - \u001b[94mname\u001b[39;49;00m: shadow\r\n \u001b[94mgraph\u001b[39;49;00m:\r\n \u001b[94mname\u001b[39;49;00m: iris-shadow\r\n \u001b[94mimplementation\u001b[39;49;00m: SKLEARN_SERVER\r\n \u001b[94mmodelUri\u001b[39;49;00m: gs://seldon-models/sklearn/iris\r\n \u001b[94mreplicas\u001b[39;49;00m: 1\r\n \u001b[94mshadow\u001b[39;49;00m: true\r\n"
],
[
"!kubectl apply -f ./resources/istio_shadow.yaml",
"seldondeployment.machinelearning.seldon.io/iris configured\r\n"
],
[
"!kubectl rollout status deploy/iris-default-54fcd84",
"_____no_output_____"
],
[
"from seldon_core.seldon_client import SeldonClient\nsc = SeldonClient(deployment_name=\"sklearn\",namespace=\"seldon\",gateway_endpoint=ISTIO_GATEWAY)",
"_____no_output_____"
],
[
"r = sc.predict(gateway=\"istio\",transport=\"rest\",shape=(1,4))\nprint(r)",
"Success:True message:\nRequest:\ndata {\n tensor {\n shape: 1\n shape: 4\n values: 0.44028212923599264\n values: 0.22694244373903638\n values: 0.08693601526817618\n values: 0.721446205469061\n }\n}\n\nResponse:\nmeta {\n puid: \"2k933j6cl1sq2kgh24ck96fmi8\"\n requestPath {\n key: \"classifier\"\n value: \"seldonio/sklearnserver_rest:0.2\"\n }\n}\ndata {\n names: \"t:0\"\n names: \"t:1\"\n names: \"t:2\"\n tensor {\n shape: 1\n shape: 3\n values: 0.3328333104192785\n values: 0.352243232066047\n values: 0.3149234575146744\n }\n}\n\n"
]
],
[
[
"#### The traffic should go to both the default predictor and the shadow. If desired this can be checked in istio dashboards in the same way as with the istio canary example. When shadowing only the responses from the default predictor are used.",
"_____no_output_____"
]
],
[
[
"!kubectl delete -f ./resources/istio_shadow.yaml",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb1a7334f021032854333b4f545a685caa38cce
| 3,419 |
ipynb
|
Jupyter Notebook
|
python/nvstrings/notebooks/category_merge1.ipynb
|
prabindh/cudf
|
f370f7d5702cf5325877ef3c946efe83611c3cee
|
[
"Apache-2.0"
] | 46 |
2019-03-11T19:44:23.000Z
|
2021-09-28T06:01:25.000Z
|
python/nvstrings/notebooks/category_merge1.ipynb
|
prabindh/cudf
|
f370f7d5702cf5325877ef3c946efe83611c3cee
|
[
"Apache-2.0"
] | 196 |
2019-03-11T18:31:28.000Z
|
2019-09-30T20:06:57.000Z
|
python/nvstrings/notebooks/category_merge1.ipynb
|
prabindh/cudf
|
f370f7d5702cf5325877ef3c946efe83611c3cee
|
[
"Apache-2.0"
] | 43 |
2019-03-11T18:15:02.000Z
|
2021-07-27T08:36:44.000Z
| 19.763006 | 100 | 0.43346 |
[
[
[
"import nvstrings, nvcategory",
"_____no_output_____"
],
[
"s1 = nvstrings.to_device(['a','a','d','c','c','e'])\ns2 = nvstrings.to_device(['a','b','b','f','c','f'])",
"_____no_output_____"
],
[
"c1 = nvcategory.from_strings(s1)\nc2 = nvcategory.from_strings(s2)",
"_____no_output_____"
],
[
"print(c1.keys(),c1.values())\nprint(c2.keys(),c2.values())",
"['a', 'c', 'd', 'e'] [0, 0, 2, 1, 1, 3]\n['a', 'b', 'c', 'f'] [0, 1, 1, 3, 2, 3]\n"
],
[
"nc = c1.merge_category(c2)\nprint(nc.keys(),nc.values())",
"['a', 'c', 'd', 'e', 'b', 'f'] [0, 0, 2, 1, 1, 3, 0, 4, 4, 5, 1, 5]\n"
],
[
"s22 = nvstrings.to_device(['b','a','a','e','g','b'])\nc22 = nvcategory.from_strings(s22)\nprint(c22.keys(), c22.values())",
"['a', 'b', 'e', 'g'] [1, 0, 0, 2, 3, 1]\n"
],
[
"nc = nc.merge_category(c22)\nprint(nc.keys(),nc.values())",
"['a', 'c', 'd', 'e', 'b', 'f', 'g'] [0, 0, 2, 1, 1, 3, 0, 4, 4, 5, 1, 5, 4, 0, 0, 3, 6, 4]\n"
],
[
"nc = c1.merge_category(c2)\nnc = c22.merge_category(nc)\nprint(nc.keys(),nc.values())",
"['a', 'b', 'e', 'g', 'c', 'd', 'f'] [1, 0, 0, 2, 3, 1, 0, 0, 5, 4, 4, 2, 0, 1, 1, 6, 4, 6]\n"
],
[
"nc = c2.merge_category(c1)\nprint(nc.keys(),nc.values())",
"['a', 'b', 'c', 'f', 'd', 'e'] [0, 1, 1, 3, 2, 3, 0, 0, 4, 2, 2, 5]\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb1aaf9f8475684d2bba0936e49d85869562902
| 6,446 |
ipynb
|
Jupyter Notebook
|
DIY_NN/A1-MNIST.ipynb
|
PinmanHuang/CrashCourseML
|
b59ebf138d42fc9a1669735c6363d50938200e69
|
[
"MIT"
] | 3 |
2019-02-16T05:57:09.000Z
|
2019-09-16T07:07:18.000Z
|
DIY_NN/A1-MNIST.ipynb
|
PinmanHuang/CrashCourseML
|
b59ebf138d42fc9a1669735c6363d50938200e69
|
[
"MIT"
] | null | null | null |
DIY_NN/A1-MNIST.ipynb
|
PinmanHuang/CrashCourseML
|
b59ebf138d42fc9a1669735c6363d50938200e69
|
[
"MIT"
] | 8 |
2019-02-14T02:51:26.000Z
|
2019-10-07T07:44:24.000Z
| 25.478261 | 120 | 0.486814 |
[
[
[
"from PIL import Image\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"\n\n先下載 MNIST 資料\n",
"_____no_output_____"
]
],
[
[
"import os\nimport urllib\nfrom urllib.request import urlretrieve\ndataset = 'mnist.pkl.gz'\ndef reporthook(a,b,c):\n print(\"\\rdownloading: %5.1f%%\"%(a*b*100.0/c), end=\"\")\n \nif not os.path.isfile(dataset):\n origin = \"https://github.com/mnielsen/neural-networks-and-deep-learning/raw/master/data/mnist.pkl.gz\"\n print('Downloading data from %s' % origin)\n urlretrieve(origin, dataset, reporthook=reporthook)",
"_____no_output_____"
],
[
"import gzip\nimport pickle\nwith gzip.open(dataset, 'rb') as f:\n train_set, validation_set, test_set = pickle.load(f, encoding='latin1')",
"_____no_output_____"
],
[
"# 設定好訓練及測試資料\ntrain_X, train_y = train_set\ntest_X, test_y = test_set\n# 設定成我們的格式\ntrain_X = train_X[..., None]\ntest_X = test_X[..., None]\n",
"_____no_output_____"
],
[
"# 有 10 種類別,輸入的是 784 維\nprint(train_X.shape)\nnp.unique(train_y)",
"_____no_output_____"
],
[
"from IPython.display import display\ndef showX(X):\n int_X = (X*255).clip(0,255).astype('uint8')\n # N*784 -> N*28*28 -> 28*N*28 -> 28 * 28N\n int_X_reshape = int_X.reshape(-1,28,28).swapaxes(0,1).reshape(28,-1)\n display(Image.fromarray(int_X_reshape))\n# 訓練資料, X 的前 20 筆\nprint(train_y[:20])\nshowX(train_X[:20])",
"_____no_output_____"
],
[
"# 參考範例 softmax regression\nW = np.random.normal(size=(10, 784))\nb = np.random.normal(size=(10, 1))\nn_data = train_X.shape[0]\n# 紀錄 loss\nloss_history = []\naccuracy_history = []\nfor epoch in range(5000): \n idx = np.random.choice(n_data, 300, replace=False)\n X = train_X[idx]\n y = train_y[idx]\n one_y = np.eye(10)[y][..., None]\n d = np.exp(W @ X + b)\n q = d/d.sum(axis=(1,2), keepdims=True)\n loss = -np.log(q[range(len(y)), y]).mean()\n loss_history.append(loss)\n accuracy = (q.argmax(axis=1).ravel() == y).mean()\n accuracy_history.append(accuracy)\n if epoch%100 == 0:\n print(epoch, accuracy, loss)\n grad_b_all = q - one_y\n grad_b = grad_b_all.mean(axis=0)\n grad_W_all = grad_b_all @ X.swapaxes(1,2)\n grad_W = grad_W_all.mean(axis=0)\n W -= grad_W\n b -= grad_b \n",
"_____no_output_____"
],
[
"# test data 的正確率\n((W @ test_X + b).argmax(axis=1).ravel() == test_y).mean()",
"_____no_output_____"
],
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\n# 準確率的圖\nplt.plot(accuracy_history);",
"_____no_output_____"
],
[
"# loss 的圖\nplt.plot(loss_history);",
"_____no_output_____"
],
[
"def softmax(x):\n t = np.exp(x)\n return t/t.sum(axis=(-2,-1),keepdims=True)\ndef relu(x):\n return np.maximum(x, 0)\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\n# 微分\ndef Drelu(x):\n return (x>0).astype('float32')\ndef Dsigmoid(x):\n q = sigmoid(x)\n return q * (1-q) \n # or \n #return np.exp(x)/(1+np.exp(-x))**2",
"_____no_output_____"
],
[
"# 參考範例 feedforward network\nfrom time import time\naccuracy_history = []\nγ = 0.02\nA = np.random.normal(size=(50,784))\nb = np.random.normal(size=(50,1))\nC = np.random.normal(size=(10,50))\nd = np.random.normal(size=(10,1))\nt0 = time()\nfor epochs in range(20):\n idx = np.random.choice(n_data, n_data, replace=False)\n for i in idx:\n x = train_X[i]\n y = train_y[i]\n U_ = A@x+b\n U = relu(U_)\n q = softmax(C@U+d)\n L = - np.log(q[y])[0]\n p = np.eye(10)[y][:, None]\n grad_d = q - p\n grad_C = grad_d @ U.T\n grad_b = (C.T @ grad_d ) * Drelu(U_)\n grad_A = grad_b @ x.T\n A -= γ * grad_A\n b -= γ * grad_b\n C -= γ * grad_C\n d -= γ * grad_d \n score = ((C@relu(A@test_X+b)+d).argmax(axis=1).ravel()==test_y).mean()\n print(epochs, score, \"%.1f\"%(time()-t0), L)\nprint(time()-t0)",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb1b9b5399f46bddeb40390f217119ab1c5ef4d
| 60,250 |
ipynb
|
Jupyter Notebook
|
CGCF.ipynb
|
Zhanghaotian1/Deep_Conf
|
2a3a18d757ee62ee9d444d404242a8c4e9ca8b31
|
[
"MIT"
] | null | null | null |
CGCF.ipynb
|
Zhanghaotian1/Deep_Conf
|
2a3a18d757ee62ee9d444d404242a8c4e9ca8b31
|
[
"MIT"
] | null | null | null |
CGCF.ipynb
|
Zhanghaotian1/Deep_Conf
|
2a3a18d757ee62ee9d444d404242a8c4e9ca8b31
|
[
"MIT"
] | 1 |
2022-01-28T07:56:46.000Z
|
2022-01-28T07:56:46.000Z
| 66.574586 | 1,688 | 0.599054 |
[
[
[
"!git clone https://github.com/MinkaiXu/CGCF-ConfGen",
"Cloning into 'CGCF-ConfGen'...\nremote: Enumerating objects: 74, done.\u001b[K\nremote: Counting objects: 100% (74/74), done.\u001b[K\nremote: Compressing objects: 100% (71/71), done.\u001b[K\nremote: Total 74 (delta 25), reused 34 (delta 1), pack-reused 0\u001b[K\nUnpacking objects: 100% (74/74), done.\n"
],
[
"!pip install kora -q\nimport kora.install.rdkit",
"\u001b[?25l\r\u001b[K |█████▊ | 10 kB 39.9 MB/s eta 0:00:01\r\u001b[K |███████████▍ | 20 kB 41.3 MB/s eta 0:00:01\r\u001b[K |█████████████████ | 30 kB 45.8 MB/s eta 0:00:01\r\u001b[K |██████████████████████▊ | 40 kB 27.4 MB/s eta 0:00:01\r\u001b[K |████████████████████████████▍ | 51 kB 24.2 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 57 kB 5.4 MB/s \n\u001b[?25h\u001b[?25l\r\u001b[K |█████▊ | 10 kB 49.1 MB/s eta 0:00:01\r\u001b[K |███████████▌ | 20 kB 57.5 MB/s eta 0:00:01\r\u001b[K |█████████████████▎ | 30 kB 63.6 MB/s eta 0:00:01\r\u001b[K |███████████████████████ | 40 kB 59.9 MB/s eta 0:00:01\r\u001b[K |████████████████████████████▉ | 51 kB 63.3 MB/s eta 0:00:01\r\u001b[K |████████████████████████████████| 56 kB 5.8 MB/s \n\u001b[?25h"
],
[
"pip install torch==1.6.0",
"Collecting torch==1.6.0\n Downloading torch-1.6.0-cp37-cp37m-manylinux1_x86_64.whl (748.8 MB)\n\u001b[K |████████████████████████████████| 748.8 MB 18 kB/s \n\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch==1.6.0) (1.19.5)\nRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from torch==1.6.0) (0.16.0)\nInstalling collected packages: torch\n Attempting uninstall: torch\n Found existing installation: torch 1.10.0+cu111\n Uninstalling torch-1.10.0+cu111:\n Successfully uninstalled torch-1.10.0+cu111\n\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ntorchvision 0.11.1+cu111 requires torch==1.10.0, but you have torch 1.6.0 which is incompatible.\ntorchtext 0.11.0 requires torch==1.10.0, but you have torch 1.6.0 which is incompatible.\ntorchaudio 0.10.0+cu111 requires torch==1.10.0, but you have torch 1.6.0 which is incompatible.\u001b[0m\nSuccessfully installed torch-1.6.0\n"
],
[
"!pip install torchvision==0.7.0",
"Collecting torchvision==0.7.0\n Downloading torchvision-0.7.0-cp37-cp37m-manylinux1_x86_64.whl (5.9 MB)\n\u001b[K |████████████████████████████████| 5.9 MB 29.5 MB/s \n\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torchvision==0.7.0) (1.19.5)\nRequirement already satisfied: torch==1.6.0 in /usr/local/lib/python3.7/dist-packages (from torchvision==0.7.0) (1.6.0)\nRequirement already satisfied: pillow>=4.1.1 in /usr/local/lib/python3.7/dist-packages (from torchvision==0.7.0) (7.1.2)\nRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from torch==1.6.0->torchvision==0.7.0) (0.16.0)\nInstalling collected packages: torchvision\n Attempting uninstall: torchvision\n Found existing installation: torchvision 0.11.1+cu111\n Uninstalling torchvision-0.11.1+cu111:\n Successfully uninstalled torchvision-0.11.1+cu111\nSuccessfully installed torchvision-0.7.0\n"
],
[
"pip install torchdiffeq==0.0.1",
"Collecting torchdiffeq==0.0.1\n Downloading torchdiffeq-0.0.1-py3-none-any.whl (27 kB)\nRequirement already satisfied: torch>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from torchdiffeq==0.0.1) (1.6.0)\nRequirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from torch>=0.4.1->torchdiffeq==0.0.1) (0.16.0)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch>=0.4.1->torchdiffeq==0.0.1) (1.19.5)\nInstalling collected packages: torchdiffeq\nSuccessfully installed torchdiffeq-0.0.1\n"
],
[
"pip install tqdm networkx scipy scikit-learn h5py tensorboard ",
"Requirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (4.62.3)\nRequirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (2.6.3)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (1.4.1)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (1.0.2)\nRequirement already satisfied: h5py in /usr/local/lib/python3.7/dist-packages (3.1.0)\nRequirement already satisfied: tensorboard in /usr/local/lib/python3.7/dist-packages (2.7.0)\nRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from scipy) (1.19.5)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (3.0.0)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn) (1.1.0)\nRequirement already satisfied: cached-property in /usr/local/lib/python3.7/dist-packages (from h5py) (1.5.2)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.0.1)\nRequirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (0.6.1)\nRequirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.43.0)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (3.3.6)\nRequirement already satisfied: requests<3,>=2.21.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (2.23.0)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.8.1)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (0.4.6)\nRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (0.37.1)\nRequirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (0.12.0)\nRequirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (57.4.0)\nRequirement already satisfied: google-auth<3,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (1.35.0)\nRequirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard) (3.17.3)\nRequirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from absl-py>=0.4->tensorboard) (1.15.0)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard) (0.2.8)\nRequirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard) (4.8)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<3,>=1.6.3->tensorboard) (4.2.4)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard) (1.3.0)\nRequirement already satisfied: importlib-metadata>=4.4 in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard) (4.10.0)\nRequirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard) (3.10.0.2)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard) (3.7.0)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard) (0.4.8)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (1.24.3)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (2021.10.8)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests<3,>=2.21.0->tensorboard) (3.0.4)\nRequirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard) (3.1.1)\n"
],
[
"pip install --no-index torch-scatter -f https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html",
"Looking in links: https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html\nCollecting torch-scatter\n Downloading https://data.pyg.org/whl/torch-1.6.0%2Bcu101/torch_scatter-2.0.6-cp37-cp37m-linux_x86_64.whl (2.8 MB)\n\u001b[K |████████████████████████████████| 2.8 MB 701 kB/s \n\u001b[?25hInstalling collected packages: torch-scatter\nSuccessfully installed torch-scatter-2.0.6\n"
],
[
"pip install --no-index torch-sparse -f https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html\n",
"Looking in links: https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html\nCollecting torch-sparse\n Downloading https://data.pyg.org/whl/torch-1.6.0%2Bcu101/torch_sparse-0.6.9-cp37-cp37m-linux_x86_64.whl (1.6 MB)\n\u001b[K |████████████████████████████████| 1.6 MB 547 kB/s \n\u001b[?25hRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-sparse) (1.4.1)\nRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from scipy->torch-sparse) (1.19.5)\nInstalling collected packages: torch-sparse\nSuccessfully installed torch-sparse-0.6.9\n"
],
[
"pip install --no-index torch-cluster -f https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html",
"Looking in links: https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html\nCollecting torch-cluster\n Downloading https://data.pyg.org/whl/torch-1.6.0%2Bcu101/torch_cluster-1.5.9-cp37-cp37m-linux_x86_64.whl (1.1 MB)\n\u001b[K |████████████████████████████████| 1.1 MB 34.6 MB/s \n\u001b[?25hInstalling collected packages: torch-cluster\nSuccessfully installed torch-cluster-1.5.9\n"
],
[
"pip install --no-index torch-spline-conv -f https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html",
"Looking in links: https://pytorch-geometric.com/whl/torch-1.6.0+cu101.html\nCollecting torch-spline-conv\n Downloading https://data.pyg.org/whl/torch-1.6.0%2Bcu101/torch_spline_conv-1.2.1-cp37-cp37m-linux_x86_64.whl (367 kB)\n\u001b[K |████████████████████████████████| 367 kB 556 kB/s \n\u001b[?25hInstalling collected packages: torch-spline-conv\nSuccessfully installed torch-spline-conv-1.2.1\n"
],
[
"pip install torch-geometric",
"Collecting torch-geometric\n Downloading torch_geometric-2.0.3.tar.gz (370 kB)\n\u001b[K |████████████████████████████████| 370 kB 25.6 MB/s \n\u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.19.5)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (4.62.3)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.4.1)\nRequirement already satisfied: networkx in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.6.3)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.0.2)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.23.0)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (1.1.5)\nCollecting rdflib\n Downloading rdflib-6.1.1-py3-none-any.whl (482 kB)\n\u001b[K |████████████████████████████████| 482 kB 52.3 MB/s \n\u001b[?25hRequirement already satisfied: googledrivedownloader in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (0.4)\nRequirement already satisfied: jinja2 in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (2.11.3)\nRequirement already satisfied: pyparsing in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (3.0.6)\nCollecting yacs\n Downloading yacs-0.1.8-py3-none-any.whl (14 kB)\nRequirement already satisfied: PyYAML in /usr/local/lib/python3.7/dist-packages (from torch-geometric) (3.13)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from jinja2->torch-geometric) (2.0.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->torch-geometric) (2.8.2)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->torch-geometric) (1.15.0)\nCollecting isodate\n Downloading isodate-0.6.1-py2.py3-none-any.whl (41 kB)\n\u001b[K |████████████████████████████████| 41 kB 726 kB/s \n\u001b[?25hRequirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from rdflib->torch-geometric) (4.10.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.7/dist-packages (from rdflib->torch-geometric) (57.4.0)\nRequirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->rdflib->torch-geometric) (3.10.0.2)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->rdflib->torch-geometric) (3.7.0)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (1.24.3)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (3.0.4)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2.10)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->torch-geometric) (2021.10.8)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->torch-geometric) (1.1.0)\nRequirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn->torch-geometric) (3.0.0)\nBuilding wheels for collected packages: torch-geometric\n Building wheel for torch-geometric (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for torch-geometric: filename=torch_geometric-2.0.3-py3-none-any.whl size=581968 sha256=2560e1935fde8d1514ce260d048631fde0c093cf15170706a33ecb118ab79a71\n Stored in directory: /root/.cache/pip/wheels/c3/2a/58/87ce0508964d4def1aafb92750c4f3ac77038efd1b9a89dcf5\nSuccessfully built torch-geometric\nInstalling collected packages: isodate, yacs, rdflib, torch-geometric\nSuccessfully installed isodate-0.6.1 rdflib-6.1.1 torch-geometric-2.0.3 yacs-0.1.8\n"
],
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n"
],
[
"cd CGCF-ConfGen/",
"/content/CGCF-ConfGen\n"
],
[
"#@title import packages\nimport os\nimport argparse\nimport torch\nimport torch.utils.tensorboard\nfrom torch_geometric.data import DataLoader\nfrom torch_geometric.loader import DataLoader\nfrom tqdm.auto import tqdm\n\nfrom models.edgecnf import *\nfrom models.cnf_edge import NONLINEARITIES, LAYERS, SOLVERS\nfrom utils.dataset import *\nfrom utils.transforms import *\nfrom utils.misc import *",
"_____no_output_____"
],
[
"#@title Arguments\nparser = argparse.ArgumentParser()\n# BEGIN\n# Model arguments\nparser.add_argument('--activation', type=str, default='softplus')\nparser.add_argument('--hidden_dim', type=int, default=64)\nparser.add_argument(\"--num_blocks\", type=int, default=1,\n help='Number of stacked CNFs.')\nparser.add_argument(\"--layer_type\", type=str, default=\"concatsquash\", choices=LAYERS)\nparser.add_argument('--time_length', type=float, default=0.5)\nparser.add_argument('--train_T', type=eval, default=True, choices=[True, False])\nparser.add_argument('--use_adjoint', type=eval, default=True, choices=[True, False])\nparser.add_argument('--solver', type=str, default='dopri5', choices=SOLVERS)\nparser.add_argument('--atol', type=float, default=1e-5)\nparser.add_argument('--rtol', type=float, default=1e-5)\nparser.add_argument('--batch_norm', type=eval, default=True, choices=[True, False])\nparser.add_argument('--sync_bn', type=eval, default=False, choices=[True, False])\nparser.add_argument('--bn_lag', type=float, default=0)\nparser.add_argument('--spectral_norm', type=eval, default=True, choices=[True, False])\nparser.add_argument('--train_noise_std', type=float, default=0.1)\n\n# Datasets and loaders\nparser.add_argument('--aux_edge_order', type=int, default=3)\nparser.add_argument('--train_dataset', type=str, default='./data/qm9/train.pkl')\nparser.add_argument('--val_dataset', type=str, default='./data/qm9/val.pkl')\nparser.add_argument('--train_batch_size', type=int, default=128)\nparser.add_argument('--val_batch_size', type=int, default=256)\nparser.add_argument('--num_workers', type=int, default=8)\nparser.add_argument('--max_val_batch', type=int, default=5)\n\n# Optimizer and scheduler\nparser.add_argument('--lr', type=float, default=1e-3)\nparser.add_argument('--weight_decay', type=float, default=0)\nparser.add_argument('--sched_factor', type=float, default=0.5)\nparser.add_argument('--sched_patience', type=int, default=3,\n help='Patience steps = sched_patience * val_freq')\nparser.add_argument('--sched_min_lr', type=int, default=1e-5)\nparser.add_argument('--beta1', type=float, default=0.95)\nparser.add_argument('--beta2', type=float, default=0.999)\n\n# Training\nparser.add_argument('--seed', type=int, default=2020)\nparser.add_argument('--logging', type=eval, default=True, choices=[True, False])\nparser.add_argument('--device', type=str, default='cuda')\nparser.add_argument('--max_iters', type=int, default=50*1000, \n help='Max iterations for MLE pre-training of CNF')\nparser.add_argument('--val_freq', type=int, default=300)\nparser.add_argument('--inspect_freq', type=int, default=50)\nparser.add_argument('--tag', type=str, default='')\nparser.add_argument('--resume', type=str, default=None)\nparser.add_argument('--log_root', type=str, default='./logs')\n# END\nargs = parser.parse_args(['--train_dataset','/content/drive/MyDrive/test_QM9.pkl','--val_dataset','/content/drive/MyDrive/val_QM9.pkl'])\nseed_all(args.seed)",
"_____no_output_____"
],
[
"tf = get_standard_transforms(order=args.aux_edge_order)",
"_____no_output_____"
],
[
"train_dset = MoleculeDataset(args.train_dataset, transform=tf)",
"_____no_output_____"
],
[
"train_iterator = get_data_iterator(DataLoader(train_dset, batch_size=args.train_batch_size, shuffle=True, drop_last=True))",
"_____no_output_____"
],
[
"args.device",
"_____no_output_____"
],
[
"model = EdgeCNF(args).to(args.device)",
"_____no_output_____"
],
[
"batch = next(train_iterator).to(args.device)",
"_____no_output_____"
],
[
"import torch\n\nfrom .common import *\nfrom .cnf_edge import CNF, ODEfunc, ODEgnn, MovingBatchNorm1d, SequentialFlow, count_nfe, add_spectral_norm, spectral_norm_power_iteration\nfrom .distgeom import *",
"_____no_output_____"
],
[
"!python train.py --train_dataset /content/drive/MyDrive/train_QM9.pkl --val_dataset /content/drive/MyDrive/val_QM9.pkl",
"[2022-01-16 03:31:45,040::train::INFO] Namespace(activation='softplus', atol=1e-05, aux_edge_order=3, batch_norm=True, beta1=0.95, beta2=0.999, bn_lag=0, device='cuda', hidden_dim=64, inspect_freq=50, layer_type='concatsquash', log_root='./logs', logging=True, lr=0.001, max_iters=50000, max_val_batch=5, num_blocks=1, num_workers=8, resume=None, rtol=1e-05, sched_factor=0.5, sched_min_lr=1e-05, sched_patience=3, seed=2020, solver='dopri5', spectral_norm=True, sync_bn=False, tag='', time_length=0.5, train_T=True, train_batch_size=128, train_dataset='/content/drive/MyDrive/train_QM9.pkl', train_noise_std=0.1, use_adjoint=True, val_batch_size=256, val_dataset='/content/drive/MyDrive/val_QM9.pkl', val_freq=300, weight_decay=0)\n[2022-01-16 03:31:45,040::train::INFO] Loading dataset...\n100% 50000/50000 [01:06<00:00, 750.64it/s]\n100% 2000/2000 [00:02<00:00, 783.22it/s]\n/usr/local/lib/python3.7/dist-packages/torch_geometric/deprecation.py:13: UserWarning: 'data.DataLoader' is deprecated, use 'loader.DataLoader' instead\n warnings.warn(out)\n[2022-01-16 03:33:09,962::train::INFO] TrainSet 50000 | ValSet 2000\n[2022-01-16 03:33:09,962::train::INFO] Building model...\n[2022-01-16 03:33:12,722::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,725::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,725::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,726::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=64, bias=True)\n[2022-01-16 03:33:12,726::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,726::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,727::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=64, bias=True)\n[2022-01-16 03:33:12,727::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,727::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,728::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=64, bias=True)\n[2022-01-16 03:33:12,728::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,728::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,729::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=64, bias=True)\n[2022-01-16 03:33:12,729::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,729::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,730::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=64, bias=True)\n[2022-01-16 03:33:12,730::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,730::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,731::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=64, bias=True)\n[2022-01-16 03:33:12,731::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,731::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,732::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=64, bias=True)\n[2022-01-16 03:33:12,732::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,732::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,733::train::INFO] Adding spectral norm to Linear(in_features=128, out_features=64, bias=True)\n[2022-01-16 03:33:12,733::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=False)\n[2022-01-16 03:33:12,733::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=64, bias=True)\n[2022-01-16 03:33:12,734::train::INFO] Adding spectral norm to Linear(in_features=64, out_features=32, bias=True)\n[2022-01-16 03:33:12,734::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=32, bias=False)\n[2022-01-16 03:33:12,734::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=32, bias=True)\n[2022-01-16 03:33:12,735::train::INFO] Adding spectral norm to Linear(in_features=32, out_features=1, bias=True)\n[2022-01-16 03:33:12,735::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=1, bias=False)\n[2022-01-16 03:33:12,735::train::INFO] Adding spectral norm to Linear(in_features=1, out_features=1, bias=True)\n[2022-01-16 03:33:12,736::train::INFO] EdgeCNF(\n (node_emb): Embedding(100, 64)\n (edge_emb): Embedding(100, 64)\n (flow): SequentialFlow(\n (chain): ModuleList(\n (0): MovingBatchNorm1d(1, eps=0.0001, decay=0.1, bn_lag=0, affine=True)\n (1): CNF(\n (odefunc): ODEfunc(\n (diffeq): ODEgnn(\n (d_fc1): ConcatSquashLinear(\n (_layer): Linear(in_features=1, out_features=64, bias=True)\n (_hyper_bias): Linear(in_features=1, out_features=64, bias=False)\n (_hyper_gate): Linear(in_features=1, out_features=64, bias=True)\n )\n (d_fc2): ConcatSquashLinear(\n (_layer): Linear(in_features=64, out_features=64, bias=True)\n (_hyper_bias): Linear(in_features=1, out_features=64, bias=False)\n (_hyper_gate): Linear(in_features=1, out_features=64, bias=True)\n )\n (conv1): GINEConv()\n (conv2): GINEConv()\n (conv3): GINEConv()\n (out_fc1): ConcatSquashLinear(\n (_layer): Linear(in_features=128, out_features=64, bias=True)\n (_hyper_bias): Linear(in_features=1, out_features=64, bias=False)\n (_hyper_gate): Linear(in_features=1, out_features=64, bias=True)\n )\n (out_fc2): ConcatSquashLinear(\n (_layer): Linear(in_features=64, out_features=32, bias=True)\n (_hyper_bias): Linear(in_features=1, out_features=32, bias=False)\n (_hyper_gate): Linear(in_features=1, out_features=32, bias=True)\n )\n (out_fc3): ConcatSquashLinear(\n (_layer): Linear(in_features=32, out_features=1, bias=True)\n (_hyper_bias): Linear(in_features=1, out_features=1, bias=False)\n (_hyper_gate): Linear(in_features=1, out_features=1, bias=True)\n )\n )\n )\n )\n (2): MovingBatchNorm1d(1, eps=0.0001, decay=0.1, bn_lag=0, affine=True)\n )\n )\n)\n[2022-01-16 03:33:12,736::train::INFO] Start training...\nTraceback (most recent call last):\n File \"train.py\", line 195, in <module>\n train(it)\n File \"train.py\", line 124, in train\n batch = next(train_iterator).to(args.device)\n File \"/content/CGCF-ConfGen/utils/misc.py\", line 160, in get_data_iterator\n yield iterator.__next__()\n File \"/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py\", line 363, in __next__\n data = self._next_data()\n File \"/usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py\", line 403, in _next_data\n data = self._dataset_fetcher.fetch(index) # may raise StopIteration\n File \"/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/fetch.py\", line 47, in fetch\n return self.collate_fn(data)\n File \"/usr/local/lib/python3.7/dist-packages/torch_geometric/loader/dataloader.py\", line 20, in __call__\n self.exclude_keys)\n File \"/usr/local/lib/python3.7/dist-packages/torch_geometric/data/batch.py\", line 75, in from_data_list\n exclude_keys=exclude_keys,\n File \"/usr/local/lib/python3.7/dist-packages/torch_geometric/data/collate.py\", line 109, in collate\n out_store.batch = repeat_interleave(repeats, device=device)\n File \"/usr/local/lib/python3.7/dist-packages/torch_geometric/data/collate.py\", line 205, in repeat_interleave\n outs = [torch.full((n, ), i, device=device) for i, n in enumerate(repeats)]\n File \"/usr/local/lib/python3.7/dist-packages/torch_geometric/data/collate.py\", line 205, in <listcomp>\n outs = [torch.full((n, ), i, device=device) for i, n in enumerate(repeats)]\nRuntimeError: Providing a bool or integral fill value without setting the optional `dtype` or `out` arguments is currently unsupported. In PyTorch 1.7, when `dtype` and `out` are not set a bool fill value will return a tensor of torch.bool dtype, and an integral fill value will return a tensor of torch.long dtype.\n"
],
[
"args.train_dataset",
"_____no_output_____"
],
[
"torch.__version__",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb1bde3f65d70fe3891c93b96c14daffc0442df
| 77,205 |
ipynb
|
Jupyter Notebook
|
git/git_activity.ipynb
|
Bernardo-MG/jupyter-notebook-example
|
3bb254bb9bb371f89f788142d33dc0bf72be0a8f
|
[
"MIT"
] | null | null | null |
git/git_activity.ipynb
|
Bernardo-MG/jupyter-notebook-example
|
3bb254bb9bb371f89f788142d33dc0bf72be0a8f
|
[
"MIT"
] | null | null | null |
git/git_activity.ipynb
|
Bernardo-MG/jupyter-notebook-example
|
3bb254bb9bb371f89f788142d33dc0bf72be0a8f
|
[
"MIT"
] | null | null | null | 127.61157 | 23,244 | 0.850282 |
[
[
[
"# Activity in a git Repository",
"_____no_output_____"
],
[
"We are going to see commit activity in a git repository. The dataset comes from JUnit 4, created by using the git log command:",
"_____no_output_____"
],
[
"``git log --date=iso --pretty=format:\"%h%x09%aN%x09%aE%x09%ad%x09%s\"``",
"_____no_output_____"
],
[
"## Setting Up",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport calendar\nactivity = pd.read_csv(\"../datasets/git_log_junit4.gz\",\n sep=\"\\t\",\n names=[\"hash\", \"author\", \"author_mail\", \"date\", \"comment\"])",
"_____no_output_____"
]
],
[
[
"## Exploring Data\n",
"_____no_output_____"
]
],
[
[
"activity.head()",
"_____no_output_____"
]
],
[
[
"### Formatting Dates",
"_____no_output_____"
],
[
"We may try to show commits based on the date. But we have a problem with that column, it is not defined as a date type.",
"_____no_output_____"
]
],
[
[
"activity.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 2437 entries, 0 to 2436\nData columns (total 5 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 hash 2437 non-null object\n 1 author 2437 non-null object\n 2 author_mail 2437 non-null object\n 3 date 2437 non-null object\n 4 comment 2437 non-null object\ndtypes: object(5)\nmemory usage: 47.7+ KB\n"
]
],
[
[
"We only need to transform using the correct format.",
"_____no_output_____"
]
],
[
[
"activity[\"date\"] = pd.to_datetime(activity[\"date\"], utc=True, format=\"%Y-%m-%d %H:%M:%S\")\nactivity.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 2437 entries, 0 to 2436\nData columns (total 5 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 hash 2437 non-null object \n 1 author 2437 non-null object \n 2 author_mail 2437 non-null object \n 3 date 2437 non-null datetime64[ns, UTC]\n 4 comment 2437 non-null object \ndtypes: datetime64[ns, UTC](1), object(4)\nmemory usage: 57.2+ KB\n"
]
],
[
[
"## Data by Date",
"_____no_output_____"
],
[
"### By Day",
"_____no_output_____"
]
],
[
[
"commits_per_day = activity[\"date\"].dt.date\ncommits_per_day = commits_per_day.value_counts().rename_axis(\"date\").reset_index(name='commits')\ncommits_per_day = commits_per_day.sort_values(\"date\")\ncommits_per_day = commits_per_day.set_index(\"date\")\ncommits_per_day.head()",
"_____no_output_____"
],
[
"ax = commits_per_day.plot.line()\nax.set_title(\"Commits per year\")\nax.axes.get_xaxis().get_label().set_visible(False)",
"_____no_output_____"
]
],
[
[
"### By Month",
"_____no_output_____"
]
],
[
[
"commits_per_month = activity[\"date\"].dt.month\ncommits_per_month = commits_per_month.value_counts().rename_axis(\"month\").reset_index(name='commits')\ncommits_per_month = commits_per_month.sort_values(\"month\")\ncommits_per_month = commits_per_month.set_index(\"month\")\ncommits_per_month.head()",
"_____no_output_____"
],
[
"ax = commits_per_month.plot.line()\nax.set_title(\"Commits per month\")\nax.axes.get_xaxis().get_label().set_visible(False)",
"_____no_output_____"
]
],
[
[
"### By Hour",
"_____no_output_____"
]
],
[
[
"commits_per_hour = activity[\"date\"].dt.hour\ncommits_per_hour = commits_per_hour.value_counts().rename_axis(\"hour\").reset_index(name='commits')\ncommits_per_hour = commits_per_hour.sort_values(\"hour\")\ncommits_per_hour = commits_per_hour.set_index(\"hour\")\ncommits_per_hour.head()",
"_____no_output_____"
],
[
"ax = commits_per_hour.plot.line()\nax.set_title(\"Commits per hour\")\nax.axes.get_xaxis().get_label().set_visible(False)",
"_____no_output_____"
]
]
] |
[
"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",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbb1be0060badce4f9f1728d63991389acc7f757
| 6,552 |
ipynb
|
Jupyter Notebook
|
example_usage.ipynb
|
geangohn/RecSys
|
f53d0322fed414caa820cebf23bef5a0a9237517
|
[
"MIT"
] | 2 |
2019-07-22T09:42:25.000Z
|
2021-03-31T09:29:29.000Z
|
example_usage.ipynb
|
geangohn/RecSys
|
f53d0322fed414caa820cebf23bef5a0a9237517
|
[
"MIT"
] | null | null | null |
example_usage.ipynb
|
geangohn/RecSys
|
f53d0322fed414caa820cebf23bef5a0a9237517
|
[
"MIT"
] | null | null | null | 27.880851 | 132 | 0.56746 |
[
[
[
"import pandas as pd\nimport scipy.sparse as sparse\n\nfrom code.preprocessing import Dataset\nfrom core.database.db import DB\nfrom code.metrics import fuzzy, precision\nfrom implicit.als import AlternatingLeastSquares\n\ndb = DB(db='recsys')\nfrom code.preprocessing import filter_old_cards, filter_rare_cards, filter_rare_goods, filter_old_goods, filter_by_quantile\n%load_ext autoreload\n%autoreload 2",
"_____no_output_____"
]
],
[
[
"### Препроцессинг трейна",
"_____no_output_____"
]
],
[
[
"train = pd.read_sql('select * from db.train', con = db.engine)\nprint('Shape: %s' % train.shape[0])\n\ntrain = filter_rare_goods(train, rarity_num=5)\nprint('Shape without rare goods: %s' % train.shape[0])\n\ntrain = filter_rare_cards(train, rarity_num=5)\nprint('Shape without rare cards: %s' % train.shape[0])\n\ntrain = filter_old_cards(train, month_threshold=1)\nprint('Shape without old cards: %s' % train.shape[0])\n\ntrain = filter_old_goods(train, month_threshold=1)\nprint('Shape without old goods: %s' % train.shape[0])\n\ntrain = filter_by_quantile(train, plu_count_quantiles=(0.5, 0.99), cards_count_quantiles=(0.4, 0.99))\nprint('Shape without low and high quantiles: %s' % train.shape[0])",
""
],
[
"ds = Dataset(train)\nmatrix = ds.make_matrix()\nmatrix = ds.transform(matrix, method='clip', clip_upper_value=1000)\nmatrix = ds.transform(matrix, method='log')\nmatrix = ds.apply_weights(matrix, weight='bm25')",
"_____no_output_____"
]
],
[
[
"## Подготовка и очистка тестового сета",
"_____no_output_____"
]
],
[
[
"products = pd.read_sql('select * from db.products', con = db.engine)\ntest = pd.read_sql('select * from db.test', con = db.engine)\nval = pd.read_sql('select * from db.val', con = db.engine)\n\ntest.columns = [x.lower() for x in test.columns]\nproducts.columns = [x.lower() for x in products.columns]\nval.columns = [x.lower() for x in val.columns]\n\ncrd_no_unique_train = matrix.index.unique()\nplu_id_unique_train = matrix.columns.unique()\ntest = test[test['crd_no'].isin(crd_no_unique_train)]\ntest = test[test['plu_id'].isin(plu_id_unique_train)]\nval = val[val['crd_no'].isin(crd_no_unique_train)]\nval = val[val['plu_id'].isin(plu_id_unique_train)]\n\nplu_category_dict = products.set_index('plu_id').to_dict()['level_2_name']\nval_facts_dict = dict(val[['crd_no', 'plu_id']].groupby('crd_no').apply(lambda x: x['plu_id'].unique().tolist()))\ntest_facts_dict = dict(test[['crd_no', 'plu_id']].groupby('crd_no').apply(lambda x: x['plu_id'].unique().tolist()))\n\nplu_price = pd.read_sql('select * from db.plu_price', con=db.engine)\nplu_price['mean_price'] = plu_price['mean_price'].astype('float16')\nplu_price = dict(plu_price[['plu_id', 'mean_price']].values.tolist())",
"_____no_output_____"
]
],
[
[
"### Строим модель",
"_____no_output_____"
]
],
[
[
"model = AlternatingLeastSquares(factors=50, regularization=0.0001, \n iterations=20, num_threads=16,\n calculate_training_loss=True)\nmodel.fit(sparse.csr_matrix(matrix).T.tocsr(), show_progress=True)",
"_____no_output_____"
]
],
[
[
"### Проверяем метрики",
"_____no_output_____"
]
],
[
[
"%%time\nfz = fuzzy(matrix, model, val_facts_dict, plu_category_dict, weight_by_price=False)\nprc = precision(matrix, model, val_facts_dict, weight_by_price=False)\nfz_w = fuzzy(matrix, model, val_facts_dict, plu_category_dict, plu_price=plu_price)\nprc_w = precision(matrix, model, val_facts_dict, plu_price=plu_price)",
"CPU times: user 31.7 s, sys: 35.9 s, total: 1min 7s\nWall time: 54.4 s\n"
],
[
"print('Fuzzy: %s' % fz)\nprint('Fuzzy Weighted: %s' % fz_w)\nprint('Precision: %s' % prc)\nprint('Precision Weighted: %s' % prc_w)",
"Fuzzy: 0.571240600323802\nFuzzy Weighted: 0.5640391714805725\nPrecision: 0.025803834737907417\nPrecision Weighted: 0.12764180505283507\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbb1c0d6dd12e8544f5a6e248228ed5cc3879b0d
| 7,599 |
ipynb
|
Jupyter Notebook
|
Linear Regression with Regularization/src/Activity 2/Activity 2 - Assumptions of Linear Regression.ipynb
|
Ak-Shaw/Miscellaneous
|
79eb94a6ad467c8a08abdabb79b1e6ddfccacf01
|
[
"MIT"
] | 14 |
2020-10-18T01:14:08.000Z
|
2021-06-17T16:22:52.000Z
|
Linear Regression with Regularization/src/Activity 2/Activity 2 - Assumptions of Linear Regression.ipynb
|
Ak-Shaw/Miscellaneous
|
79eb94a6ad467c8a08abdabb79b1e6ddfccacf01
|
[
"MIT"
] | 73 |
2020-10-18T09:38:19.000Z
|
2021-02-01T20:36:46.000Z
|
Linear Regression with Regularization/src/Activity 2/Activity 2 - Assumptions of Linear Regression.ipynb
|
Ak-Shaw/Miscellaneous
|
79eb94a6ad467c8a08abdabb79b1e6ddfccacf01
|
[
"MIT"
] | 37 |
2020-10-17T07:08:20.000Z
|
2021-06-25T14:40:25.000Z
| 26.946809 | 278 | 0.58613 |
[
[
[
"# Assumptions of Linear Regression\n\nPreviously, we learned to apply linear regression on a given dataset. But it is important to note that Linear Regression have some assumptions related to the data on which it is applied and if they are not followed, it can affect its performance. These assumptions are:\n\n1. There should be a linear relationship between the dependant and the independant features.\n2. There should be no auto-correlation. This means that the error terms should not be correlated.\n3. The variance of error terms should be equal.\n4. There should be no multi-collinearity. This means that no 2 independant features should be highly correlated.\n5. The errors should be normally distributed.\n\nLets check these assumptions on the model which we have trained in the previous activity.\n\n## Loading the previous model",
"_____no_output_____"
]
],
[
[
"#importing libraries\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\n#load the data\n\n\n#seperating dependant and independant features\n\n\n#splitting data into training and test sets\n\n\n#instantiate a model\n\n\n#fit the model to training data",
"_____no_output_____"
]
],
[
[
"<details>\n<summary>Solution</summary>\n<p>\n \n```python\ndata = pd.read_csv('../../data/data_cleaned.csv')\n\nX = data.drop('price', axis= 1)\ny = data.price\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size= 0.2, random_state= 42, shuffle= True)\n \nmodel = LinearRegression()\n \nmodel.fit(X_train, y_train)\n```\n \n</p>\n</details>",
"_____no_output_____"
],
[
"Now, we have the model. Lets calculate the residuals first.\n\n## Calculate residuals",
"_____no_output_____"
]
],
[
[
"#create a dataframe to store residuals\nresult = pd.DataFrame({'Actual': y_test, 'Predicted': model.predict(X_test)})\nresult.reset_index(drop= True, inplace= True) #reset indexes",
"_____no_output_____"
]
],
[
[
"* Make a new column **residuals** by subtracting *Predicted* value from *Actual* values\n* display top 5 rows of the **result** dataframe.",
"_____no_output_____"
]
],
[
[
"#Make a new column residuals\n\n#display top 5 rows of the result dataframe.",
"_____no_output_____"
]
],
[
[
"<details>\n<summary>Solution</summary>\n<p>\n \n```python\nresult['residuals'] = result.Actual - result.Predicted\n \nresult.head()\n```\n \n</p>\n</details>",
"_____no_output_____"
],
[
"## Check the variance and correlation of error terms",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt #importing libraries for plotting graphs",
"_____no_output_____"
],
[
"#plotting the residuals\nplt.scatter(range(len(y_test)), result.residuals)\nplt.show()",
"_____no_output_____"
]
],
[
[
"We can clearly see that apart from 3-4 points, the spread of error terms is constant. Hence we can conclude that the variance is constant.\nAlso, there is no specific pattern in the error terms. They are randomly distributed. So, there is no correlation among them.",
"_____no_output_____"
],
[
"## Check Distribution of Residuals\n\n* draw a histogram of residuals from result dataframe using 300 as the number of bins.",
"_____no_output_____"
]
],
[
[
"#draw a histogram",
"_____no_output_____"
]
],
[
[
"<details>\n<summary>Solution</summary>\n<p>\n \n```python\nplt.hist(result.residuals, bins= 300)\nplt.show()\n```\n \n</p>\n</details>",
"_____no_output_____"
],
[
"From the above graph it can be concluded that the error terms are normally distributed. The unusually high peak to the curve is caused by the outliers that were pointed out in the first activity. To confirm the distribution, we can also plot a qq plot",
"_____no_output_____"
],
[
"## Check for Multi-Collinearity\n\nTo check for multi-collinearity, we can find **Variance Inflation Factor** of all the columns. If for any feature, its value is above 5, we can conclude that the feature is correlated.",
"_____no_output_____"
]
],
[
[
"# Importing Variance_inflation_Factor funtion from the Statsmodels\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom statsmodels.tools.tools import add_constant\n\n# Calculating VIF for every column (only works for the not Catagorical)\nVIF = pd.Series([variance_inflation_factor(data.values, i) for i in range(data.shape[1])], index =data.columns)\nVIF",
"_____no_output_____"
]
],
[
[
"There are 4 features having VIF greater than 5. We can remove the 2 features having the higher values. So, none of the features will be correlated and hence multi-collinearity can be removed.",
"_____no_output_____"
],
[
"## Conclusion\n\nThis is how we can check the assumptions of Linear Regression and see if everything follows.\n\n## Additional Resources\n\n1. VIF : https://www.analyticsvidhya.com/blog/2020/03/what-is-multicollinearity/\n2. Assumptions in detail: https://www.analyticsvidhya.com/blog/2016/07/deeper-regression-analysis-assumptions-plots-solutions/",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbb1e2a2e9b0b016d364b982fc173a92c2dfe06d
| 305,753 |
ipynb
|
Jupyter Notebook
|
dynamic_programming/smoothing.ipynb
|
sbacelar/quantecon-notebooks-jl
|
8a6361f07e0893019cff477c24e46641f2fdb736
|
[
"BSD-3-Clause"
] | null | null | null |
dynamic_programming/smoothing.ipynb
|
sbacelar/quantecon-notebooks-jl
|
8a6361f07e0893019cff477c24e46641f2fdb736
|
[
"BSD-3-Clause"
] | null | null | null |
dynamic_programming/smoothing.ipynb
|
sbacelar/quantecon-notebooks-jl
|
8a6361f07e0893019cff477c24e46641f2fdb736
|
[
"BSD-3-Clause"
] | null | null | null | 238.68306 | 108,697 | 0.903883 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbb1ee49c3fe8505eb9ce96ff3b60e3a4553665f
| 23,530 |
ipynb
|
Jupyter Notebook
|
Autoencoder_Generated_Faces.ipynb
|
PatrickBD/Autoencoder_Generated_Faces
|
e2cfada9681f16f37864678f9b240ff7d1a6ff39
|
[
"Apache-2.0"
] | null | null | null |
Autoencoder_Generated_Faces.ipynb
|
PatrickBD/Autoencoder_Generated_Faces
|
e2cfada9681f16f37864678f9b240ff7d1a6ff39
|
[
"Apache-2.0"
] | null | null | null |
Autoencoder_Generated_Faces.ipynb
|
PatrickBD/Autoencoder_Generated_Faces
|
e2cfada9681f16f37864678f9b240ff7d1a6ff39
|
[
"Apache-2.0"
] | null | null | null | 67.614943 | 3,536 | 0.61785 |
[
[
[
"# Making Faces Using an Autoencoder\n\nAutoencoders learn to compress data into a smaller frame and then reconstruct that data from that frame. When a computer encodes data this way, it is basically simplifying the data into what features it finds to be the most useful. This notebook will train an autoencoder on faces, then use PCA to create new encoded data that looks similar enough to our training data to create artificial faces based on the features that the neural network found was important.",
"_____no_output_____"
]
],
[
[
"!pip3 install face_recognition\nimport face_recognition",
"_____no_output_____"
],
[
"import os\nimport sys\nimport random\nimport warnings\nfrom pylab import imshow, show, get_cmap\n\nimport numpy as np\nimport pandas as pd\nfrom numpy import random\n\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\nfrom itertools import chain\nimport skimage\nfrom PIL import Image\nfrom skimage.io import imread, imshow, imread_collection, concatenate_images\nfrom skimage.transform import resize\nfrom skimage.util import crop, pad\nfrom skimage.morphology import label\n\nfrom keras.models import Model, load_model,Sequential\nfrom keras.layers import Input, Dense, UpSampling2D, Flatten, Reshape\nfrom keras.layers.core import Dropout, Lambda\nfrom keras.layers.convolutional import Conv2D, Conv2DTranspose\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.layers.merge import concatenate\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n\nimport tensorflow as tf\n\nIMG_WIDTH = 128\nIMG_HEIGHT = 128\nIMG_CHANNELS = 3\nINPUT_SHAPE=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS)\nD_INPUT_SHAPE=[192]\nTRAIN_PATH = '../input/lagdataset_200/LAGdataset_200/'\n\nwarnings.filterwarnings('ignore', category=UserWarning, module='skimage')\nseed = 42\nrandom.seed = seed\nnp.random.seed = seed",
"_____no_output_____"
]
],
[
[
"# Read in the Faces\n\nFor preprocessing, the face recognition package will be used to find the bounding box around the face in the image and cut out the surrounding areas. Since the faces are taken from different areas and radically different hairstyles, limiting the area to just the face makes it a little easier on our model and focus on the most important features.",
"_____no_output_____"
]
],
[
[
"def FaceCrop(image):\n face_locations = face_recognition.face_locations(image)\n top, right, bottom, left = face_locations[0]\n image = image[top:bottom,left:right]\n return image",
"_____no_output_____"
],
[
"%%time\ntrain_ids = next(os.walk(TRAIN_PATH))[2]\nX_train = np.zeros((len(train_ids), IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS), dtype=np.uint8)\nfinal_train_ids = []\nmissing_count = 0\nprint('Getting train images ... ')\nsys.stdout.flush()\nfor n, id_ in tqdm(enumerate(train_ids), total=len(train_ids)):\n path = TRAIN_PATH + id_+''\n try:\n img = imread(path)\n img = FaceCrop(img)\n img = resize(img, (IMG_HEIGHT, IMG_WIDTH), mode='constant', preserve_range=True)\n X_train[n-missing_count] = img\n final_train_ids.append(id_)\n except:\n missing_count += 1\n \nprint(\"Total missing: \"+ str(missing_count))\nX_train = X_train[0:X_train.shape[0]-missing_count]",
"_____no_output_____"
],
[
"for n in range(0,5):\n imshow(X_train[n])\n plt.show()",
"_____no_output_____"
]
],
[
[
"# Add Noise\n\nIt is usually a good idea to add some noise to the training images when making an autoencoder.",
"_____no_output_____"
]
],
[
[
"X_train = X_train.astype('float32') / 255.\nX_train_noisy = X_train + 0.1 * np.random.normal(size=X_train.shape)\n\nX_train_noisy = np.clip(X_train_noisy, 0., 1.)",
"_____no_output_____"
]
],
[
[
"# Create the Models\n\nWe will create three models, the encoder, the decoder, and the autoencoder which is a combination of the 2. Make sure to keep the names of the layers consistent with the autoencoder as we will be setting the weights by_name after training the autoencoder.",
"_____no_output_____"
]
],
[
[
"def Encoder():\n inp = Input(shape=INPUT_SHAPE)\n x = Conv2D(128, (4, 4), activation='elu', padding='same',name='encode1')(inp)\n x = Conv2D(64, (3, 3), activation='elu', padding='same',name='encode2')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same',name='encode3')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same',name='encode4')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same',name='encode5')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode6')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same',name='encode7')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same',name='encode8')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode9')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same',name='encode10')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same',name='encode11')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode12')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(32, (4, 4), activation='elu', padding='same',name='encode13')(x)\n x = Conv2D(16, (3, 3), activation='elu', padding='same',name='encode14')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode15')(x)\n x = Conv2D(3, (3, 3), activation='elu', padding='same',name='encode16')(x)\n x = Flatten()(x)\n x = Dense(256, activation='elu',name='encode17')(x)\n encoded = Dense(D_INPUT_SHAPE[0], activation='sigmoid',name='encode18')(x)\n return Model(inp, encoded)\n\nencoder = Encoder()\nencoder.summary()",
"_____no_output_____"
],
[
"def Decoder():\n inp = Input(shape=D_INPUT_SHAPE, name='decoder')\n x = Dense(D_INPUT_SHAPE[0], activation='elu', name='decode1')(inp)\n x = Dense(192, activation='elu', name='decode2')(x)\n x = Reshape((8, 8, 3))(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode3')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode4')(x)\n x = Conv2DTranspose(64, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans1')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode5')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode6')(x)\n x = Conv2DTranspose(64, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans2')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode7')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode8')(x)\n x = Conv2DTranspose(64, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans3')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same', name='decode9')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same', name='decode10')(x)\n x = Conv2DTranspose(128, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans4')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same', name='decode11')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode12')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode13')(x)\n x = Conv2D(16, (1, 1), activation='elu', padding='same', name='decode14')(x)\n decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same', name='decode15')(x)\n return Model(inp, decoded)\n\ndecoder = Decoder()\ndecoder.summary()",
"_____no_output_____"
],
[
"def Autoencoder():\n inp = Input(shape=INPUT_SHAPE)\n x = Conv2D(128, (4, 4), activation='elu', padding='same',name='encode1')(inp)\n x = Conv2D(64, (3, 3), activation='elu', padding='same',name='encode2')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same',name='encode3')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same',name='encode4')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same',name='encode5')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode6')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same',name='encode7')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same',name='encode8')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode9')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same',name='encode10')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same',name='encode11')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode12')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(32, (4, 4), activation='elu', padding='same',name='encode13')(x)\n x = Conv2D(16, (3, 3), activation='elu', padding='same',name='encode14')(x)\n x = Conv2D(16, (2, 2), activation='elu', padding='same',name='encode15')(x)\n x = Conv2D(3, (3, 3), activation='elu', padding='same',name='encode16')(x)\n x = Flatten()(x)\n x = Dense(256, activation='elu',name='encode17')(x)\n encoded = Dense(D_INPUT_SHAPE[0], activation='sigmoid',name='encode18')(x)\n x = Dense(D_INPUT_SHAPE[0], activation='elu', name='decode1')(encoded)\n x = Dense(192, activation='elu', name='decode2')(x)\n x = Reshape((8, 8, 3))(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode3')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode4')(x)\n x = Conv2DTranspose(64, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans1')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode5')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode6')(x)\n x = Conv2DTranspose(64, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans2')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode7')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode8')(x)\n x = Conv2DTranspose(64, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans3')(x)\n x = Conv2D(32, (3, 3), activation='elu', padding='same', name='decode9')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same', name='decode10')(x)\n x = Conv2DTranspose(128, (3, 3), strides=(2, 2), activation='elu', padding='same', name='decodetrans4')(x)\n x = Conv2D(64, (4, 4), activation='elu', padding='same', name='decode11')(x)\n x = Conv2D(64, (3, 3), activation='elu', padding='same', name='decode12')(x)\n x = Conv2D(32, (2, 2), activation='elu', padding='same', name='decode13')(x)\n x = Conv2D(16, (1, 1), activation='elu', padding='same', name='decode14')(x)\n decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same', name='decode15')(x)\n return Model(inp, decoded)\n\nmodel = Autoencoder()\nmodel.compile(optimizer=Adam(lr=0.001), loss='mean_squared_error')\nmodel.summary()",
"_____no_output_____"
]
],
[
[
"# Checkpoints\n\nGood to have some checkpoints for the models. The autoencoder really only benefits from ReduceLROnPlateau, the other checkpoints are just standard. ",
"_____no_output_____"
]
],
[
[
"learning_rate_reduction = ReduceLROnPlateau(monitor='loss', \n patience=2, \n verbose=1, \n factor=0.5,\n min_lr=0.00001)\nfilepath = \"Face_Auto_Model.h5\"\ncheckpoint = ModelCheckpoint(filepath,\n save_best_only=True,\n monitor='loss',\n mode='min')\n\nearly_stopping = EarlyStopping(monitor='loss',\n patience=3,\n verbose=1,\n mode='min',\n restore_best_weights=True)",
"_____no_output_____"
]
],
[
[
"# Train a Decoder on Random Data\n\nFirst thing, just for fun, let's quickly see what happens when we train just the decoder on random noise. By training the decoder on random noise we force the model to make average predictions on everything so we can see the most common features throughout the dataset.",
"_____no_output_____"
]
],
[
[
"D_train_noise = random.random((X_train.shape[0], D_INPUT_SHAPE[0]))\n\nrandom_decoder = Decoder()\nrandom_decoder.compile(optimizer='adam', loss='mean_squared_error')",
"_____no_output_____"
],
[
"%%time \nrandom_decoder.fit(D_train_noise, X_train,\n epochs=5, \n batch_size=32,\n callbacks=[learning_rate_reduction, checkpoint, early_stopping])",
"_____no_output_____"
]
],
[
[
"# Sample the Random Decoder",
"_____no_output_____"
]
],
[
[
"D_test_noise = random.random((100, D_INPUT_SHAPE[0]))\n\nTest_imgs = random_decoder.predict(D_test_noise)",
"_____no_output_____"
],
[
"plt.figure(figsize=(20, 4))\nfor i in range(5):\n plt.subplot(2, 10, i + 1)\n plt.imshow(Test_imgs[i].reshape(INPUT_SHAPE))\n plt.axis('off')\n \nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"The result is the most average image the model could make. In a fairly uniform dataset like this one, we get a pretty clear face as a result with all the important features.",
"_____no_output_____"
],
[
"# Train the Autoencoder\n\nNow to train the autoencoder proper. Standard autoencoder training procedure here except that we will not use any validation splits. The loss will use the ReduceLROnPlateau a few times before it is over. Takes around 1 hour.",
"_____no_output_____"
]
],
[
[
"%%time \nmodel.fit(X_train_noisy, X_train,\n epochs=70,\n batch_size=50,\n callbacks=[learning_rate_reduction, checkpoint, early_stopping])",
"_____no_output_____"
]
],
[
[
"# Sample the Autoencoder Model",
"_____no_output_____"
]
],
[
[
"decoded_imgs = model.predict(X_train_noisy)",
"_____no_output_____"
],
[
"plt.figure(figsize=(20, 4))\nfor i in range(5):\n # original\n plt.subplot(2, 10, i + 1)\n plt.imshow(X_train[i].reshape(INPUT_SHAPE))\n plt.axis('off')\n \n # reconstruction\n plt.subplot(2, 10, i + 1 + 10)\n plt.imshow(decoded_imgs[i].reshape(INPUT_SHAPE))\n plt.axis('off')\n \nplt.tight_layout()\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Generate New Autoencoded Faces\n\nIn order to generate new faces, we will use PCA on the encoded results to make new \"random\" data that is still normally distributed in a similar way as the actual face results. I used some code found in this repository to get this part working correctly: https://github.com/HackerPoet/FaceEditor",
"_____no_output_____"
]
],
[
[
"model.save('Face_Auto_Model.hdf5')\nmodel.save_weights(\"Face_Auto_Weights.hdf5\")",
"_____no_output_____"
],
[
"encoder = Encoder()\ndecoder = Decoder()\n\nencoder.load_weights(\"Face_Auto_Weights.hdf5\", by_name=True)\ndecoder.load_weights(\"Face_Auto_Weights.hdf5\", by_name=True)",
"_____no_output_____"
],
[
"Encoder_predicts = encoder.predict(X_train)",
"_____no_output_____"
],
[
"func = K.function([decoder.input, K.learning_phase()],\n [decoder.output])\n\nrand_vecs = np.random.normal(0.0, 1.0, (50, D_INPUT_SHAPE[0]))\n\nx_mean = np.mean(Encoder_predicts, axis=0)\nx_stds = np.std(Encoder_predicts, axis=0)\nx_cov = np.cov((Encoder_predicts - x_mean).T)\ne, v = np.linalg.eig(x_cov)\n\nprint(x_mean)\nprint(x_stds)\nprint(x_cov)",
"_____no_output_____"
],
[
"e_list = e.tolist()\ne_list.sort(reverse=True)\nplt.clf()\nplt.bar(np.arange(e.shape[0]), e_list, align='center')\nplt.draw()\n\nx_vecs = x_mean + np.dot(v, (rand_vecs * e).T).T\ny_faces = func([x_vecs, 0])[0]",
"_____no_output_____"
]
],
[
[
"# Sample New Faces\n\nHere is a selection of the new random faces.",
"_____no_output_____"
]
],
[
[
"plt.figure(figsize=(50, 20))\nfor i in range(50):\n plt.subplot(5, 10, i + 1)\n plt.imshow(y_faces[i])\n plt.axis('off')",
"_____no_output_____"
]
],
[
[
"# Results\n\nThe results are pretty good, farly clear faces with a lot of variety between them. We can automatically make more or manually adjust features in the array to get a feel for key features that the neural network found to be the most important. \n\nIf you enjoyed this notebook, please like, comment, and check out some of my other notebooks on Kaggle: \n\nMaking AI Dance Videos: https://www.kaggle.com/valkling/how-to-teach-an-ai-to-dance\n\nImage Colorization: https://www.kaggle.com/valkling/image-colorization-using-autoencoders-and-resnet/notebook\n\nStar Wars Steganography: https://www.kaggle.com/valkling/steganography-hiding-star-wars-scripts-in-images",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbb2014d6f7b69f93b4adb98c171896d13168966
| 916,649 |
ipynb
|
Jupyter Notebook
|
notebooks/output/POP_gx1v7/Fe_sediment_flux_forcing.ipynb
|
marbl-ecosys/forcing-Fe-sedflux
|
df6d787148d6939dc40a624e28aca5643a62ad7b
|
[
"Apache-2.0"
] | null | null | null |
notebooks/output/POP_gx1v7/Fe_sediment_flux_forcing.ipynb
|
marbl-ecosys/forcing-Fe-sedflux
|
df6d787148d6939dc40a624e28aca5643a62ad7b
|
[
"Apache-2.0"
] | 4 |
2020-04-20T15:09:51.000Z
|
2020-04-20T17:00:27.000Z
|
notebooks/output/POP_gx1v7/Fe_sediment_flux_forcing.ipynb
|
marbl-ecosys/forcing-Fe-sedflux
|
df6d787148d6939dc40a624e28aca5643a62ad7b
|
[
"Apache-2.0"
] | 1 |
2020-06-25T17:55:21.000Z
|
2020-06-25T17:55:21.000Z
| 311.361753 | 139,604 | 0.897544 |
[
[
[
"# Compute the iron sediment forcing (`fedsedflux`) supplied to the model\n\nThis notebook implements an approach to computing `fesedflux` originally in an IDL routine by J. K. Moore.\n\n`fesedflux` includes two components:\n- `fesedflux_oxic`: a constant low background value; increased in regions of high bottom horizontal current speed (sediment resuspenion) by up to a factor of 100.\n- `fesedflux_reduce`: source everywhere linearly related to the sinking POC flux by `coef_fesedflux_POC_flux`, except: \n - source is zero below `POC_flux_gCm2yr_min` (3 gC m$^{-2}$ yr$^{-1}$ in CESM2), and \n - constant above `POC_flux_gCm2yr_max`.\n - This puts a source on the shelf, and along productive slope/margins, but has little source in the deep ocean, where almost all the remineralization is oxic right on the sediment surface.\n\n`fesedflux` is computed on subgrid-scale bathymetry, using the fraction of each cell that is ocean bottom at each depth: `fesedfrac`. `fesedfrac` is [computed from ETOPO1 bathymetry](sedfrac_compute.ipynb) and modified as follows:\n- a minimum percentage of each grid cell that is sediments (`land_adj_sedfrac_min`) is applied to all land-adjacent grid cells.\n\n\n**Arbitrary modification to this objective scheme:**\n- `fesedflux_reduce` is multiplied by 10 in the western equatorial Pacific (135-200E, 15S-15N, above 504 m). \n\n\n## Procedure\n\n1. Prepare `fesedfrac`:\n - Read pre-computed [`fesedfrac`](sedfrac_compute.ipynb);\n - Determine land-adjascent points;\n - Create `sedfrac_mod` by applying `land_adj_sedfrac_min`.\n\n\n2. Compute `fesedflux_reduce`:\n - Read `POC_flux` and convert units; \n - Where `POC_flux < POC_flux_gCm2yr_min, POC_flux = 0.`;\n - Where `POC_flux > POC_flux_gCm2yr_max, POC_flux = POC_flux_gCm2yr_max`\n - `fesedflux_reduce = POC_flux * coef_fesedflux_POC_flux * sedfrac_mod`\n - Apply ad hoc scaling in to select regions.\n\n\n3. Compute `fesedflux_oxic`:\n - Read `UVEL` and `VVEL` and compute `current_speed`\n - Where `current_speed < 1.0: current_speed = 1.0`\n - Where `current_speed > 10.0: current_speed = 10.0` \n - `fesedflux_oxic = coef_fesedflux_current_speed * sedfrac_mod * current_speed**2`\n \n\n4. Output `fesedflux_oxic` and `fesedflux_reduce` in model units: µmol/m^2/d\n ",
"_____no_output_____"
],
[
"## Preliminary setup",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport os\nimport tqdm\nimport yaml\nfrom itertools import product\n\nfrom datetime import date, datetime, timezone\n\nimport numpy as np\nimport xarray as xr\n\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\n\nimport esmlab\nimport pop_tools\n\nimport util",
"Cannot write to data cache '/glade/p/cesmdata/cseg'. Will not be able to download remote data files. Use environment variable 'CESMDATAROOT' to specify another directory.\n"
],
[
"id_string = 'Fe_sediment_flux_forcing.ipynb from github.com/marbl-ecosys/forcing-Fe-sedflux'\n\nmol_per_nmol = 1e-9 \nmol_per_µmol = 1e-6\nmol_per_mmol = 1e-3\nmol_per_Gmol = 1e9\ngC_per_mol = 12.011 \ncm2_per_m2 = 1e4 \nd_per_yr = 365.0\ns_per_yr = d_per_yr * 86400.0\nnmolCcm2s_to_gCm2yr = mol_per_nmol * gC_per_mol * cm2_per_m2 * s_per_yr\nmmolCm2d_to_gCm2yr = mol_per_mmol * gC_per_mol * d_per_yr\nmmolm2yr_to_µmolm2d = 1. / d_per_yr / mol_per_µmol * mol_per_mmol",
"_____no_output_____"
]
],
[
[
"### Specify model grid and associated parameters",
"_____no_output_____"
]
],
[
[
"dst_grid = 'POP_tx0.1v3'",
"_____no_output_____"
],
[
"# Parameters\ndst_grid = \"POP_gx1v7\"\n",
"_____no_output_____"
],
[
"POC_flux_gCm2yr_max = 20.\nPOC_flux_gCm2yr_min = 3.\n\ncurrent_speed_min = 1. # cm/s\ncurrent_speed_max = 10. # cm/s\n\nwestern_pacific_factor = 10. # scale Fe flux in W. Pacific\n\ndata_in_src_grid = dict(poc_flux='POP_gx1v7', velocity='POP_gx1v7')\n\ni_pacific = util.nlon_pacific_xsection[dst_grid]\nj_acc = util.nlat_acc_xsection[dst_grid]\n\n \nif dst_grid == 'POP_gx3v7':\n land_adj_sedfrac_min = 0.015\n coef_fesedflux_POC_flux = 0.01584 # (mmolFe/m^2/yr)/(gC/m^2/yr)\n coef_fesedflux_current_speed2 = 0.0008405 \n ltripole = False\n\nelif dst_grid == 'POP_gx1v7': \n land_adj_sedfrac_min = 0.03\n coef_fesedflux_POC_flux = 0.01614 # (mmolFe/m^2/yr)/(gC/m^2/yr) # * 1.6\n coef_fesedflux_current_speed2 = 0.0006568 # * 1.2\n ltripole = False\n \nelif dst_grid == 'POP_tx0.1v3':\n land_adj_sedfrac_min = 0.2\n coef_fesedflux_POC_flux = 0.018 # (mmolFe/m^2/yr)/(gC/m^2/yr)\n coef_fesedflux_current_speed2 = 0.0005\n ltripole = True\n data_in_src_grid['velocity'] = 'POP_tx0.1v3'\n\ndata_in_src_grid ",
"_____no_output_____"
]
],
[
[
"### Get model data `POC_FLUX_IN`, `UVEL`, `VVEL`",
"_____no_output_____"
]
],
[
[
"ds = pop_tools.get_grid(dst_grid)\n\nfor var_group, src_grid in data_in_src_grid.items():\n zarr_in = f'{util.dirwork}/{var_group}.{src_grid}_to_{dst_grid}.zarr'\n print(f'reading {zarr_in}')\n with xr.open_zarr(zarr_in) as dsv:\n dsv = dsv.drop([v for v in dsv.variables if v not in ['POC_FLUX_IN', 'UVEL', 'VVEL']]).load()\n ds = xr.merge((ds, dsv))\n\nds",
"reading /glade/work/mclong/cesm_inputdata/work/poc_flux.POP_gx1v7_to_POP_gx1v7.zarr\n"
]
],
[
[
"### Read `sedfrac` and apply `land_adj_sedfrac_min`",
"_____no_output_____"
]
],
[
[
"with xr.open_dataset(util.sedfrac_file(dst_grid)) as dstmp:\n sedfrac = dstmp.sedfrac.reset_index('z_t', drop=True).compute()\n \nland_adjacent = util.compute_topo_adjacent_points(dst_grid)\n\nsedfrac_mod = util.apply_topo_adj_sedfrac_min(\n sedfrac,\n land_adjacent,\n land_adj_sedfrac_min,\n)",
"_____no_output_____"
],
[
"plt.figure()\nsedfrac_mod.sum('z_t').where(ds.KMT > 0).plot(vmin=0, vmax=3.) \nh = plt.title('Sum of sedfrac_mod in column')\n\nplt.figure()\nsedfrac_mod.sum('z_t').where(ds.KMT > 0).plot(vmin=0, vmax=1.) \nh = plt.title('Sum of sedfrac in column, colormap scaled')",
"_____no_output_____"
]
],
[
[
"## Compute `fesedflux_reduce`\n\n### Prepare `POC_flux`: \n- convert units\n- Where `POC_flux < POC_flux_gCm2yr_min, POC_flux = 0.`; \n- Where `POC_flux > POC_flux_gCm2yr_max, POC_flux = POC_flux_gCm2yr_max`",
"_____no_output_____"
]
],
[
[
"POC_flux = ds.POC_FLUX_IN * nmolCcm2s_to_gCm2yr\nPOC_flux = xr.where(POC_flux <= POC_flux_gCm2yr_min, 0., POC_flux)\nPOC_flux = xr.where(POC_flux > POC_flux_gCm2yr_max, POC_flux_gCm2yr_max, POC_flux)\nPOC_flux = POC_flux.reset_index('z_t', drop=True)\n\nfig = plt.figure(figsize=(12,4))\nax = fig.add_subplot(1, 2, 1)\nh = POC_flux.isel(z_t=3).plot()\n\nax = fig.add_subplot(1, 2, 2)\nh = POC_flux.isel(z_t=20).plot()",
"_____no_output_____"
]
],
[
[
"### Compute `fesedflux_reduce`",
"_____no_output_____"
],
[
"Compute and apply ad hoc scaling in to select regions",
"_____no_output_____"
]
],
[
[
"# initial computation\nfesedflux_reduce = coef_fesedflux_POC_flux * POC_flux * sedfrac_mod\nfesedflux_reduce = fesedflux_reduce.fillna(0.)\n\nfesedflux_reduce = fesedflux_reduce * mmolm2yr_to_µmolm2d\n\n# plot initial values\nplt.figure()\nfesedflux_reduce.sum('z_t').plot(norm=colors.LogNorm(vmin=1e-2, vmax=20.))\nh = plt.title('fesedflux_reduce: column sum (before ad hoc adjustment)')\n\n# apply ad hoc adjustments\nregion_def = ((134. <= ds.TLONG) & (ds.TLONG <= 200) \n & (np.fabs(ds.TLAT) <= 15) & (ds.z_t <= 450e2))\n\nregion_def = region_def.where(ds.KMT > 0).reset_index('z_t', drop=True)\nregion_def = region_def.transpose('z_t', 'nlat', 'nlon')\n\nfesedflux_reduce = xr.where(region_def==1, fesedflux_reduce * western_pacific_factor, fesedflux_reduce)\nfesedflux_reduce.name = 'Fe sediment flux (reducing)'\nfesedflux_reduce.attrs['units'] = 'micromol m$^{-2}$ d$^{-1}$'\n\n\nfig = plt.figure(figsize=(12,4))\nax = fig.add_subplot(1, 2, 1)\nregion_def.isel(z_t=0).plot()\nh = plt.title('ad hoc adjustment region')\n\nax = fig.add_subplot(1, 2, 2)\nfesedflux_reduce.sum('z_t').plot(norm=colors.LogNorm(vmin=1e-2, vmax=20.))\nh = plt.title('fesedflux_reduce: column sum (after ad hoc adjustment)')",
"_____no_output_____"
]
],
[
[
"### Report global integral ",
"_____no_output_____"
]
],
[
[
"fesedflux_reduce_global = esmlab.statistics.weighted_sum(fesedflux_reduce, weights=ds.TAREA/cm2_per_m2, \n dim=('nlat', 'nlon')).sum('z_t')\n\nfesedflux_reduce_global = fesedflux_reduce_global * mol_per_µmol / mol_per_Gmol * d_per_yr\nprint(f'Global integral of `fesedflux_reduce_global` = {fesedflux_reduce_global.values:0.4f} Gmol Fe/yr')\n",
"Global integral of `fesedflux_reduce_global` = 13.5882 Gmol Fe/yr\n"
]
],
[
[
"## Compute `fesedflux_oxic`\n\n- Read `UVEL` and `VVEL` and compute `current_speed`\n- Where `current_speed < current_speed_min: current_speed = current_speed_min`\n- Where `current_speed > current_speed_max: current_speed = current_speed_max` \n- `fesedflux_oxic = coef_fesedflux_current_speed2 * sedfrac * current_speed**2`",
"_____no_output_____"
]
],
[
[
"current_speed = np.sqrt(ds.UVEL**2 + ds.VVEL**2)\ncurrent_speed = xr.where(current_speed < current_speed_min, current_speed_min, current_speed)\ncurrent_speed = xr.where(current_speed > current_speed_max, current_speed_max, current_speed)\n\nh = current_speed.isel(z_t=30).plot()\n\ncurrent_speed = current_speed.reset_index('z_t', drop=True)\ncurrent_speed",
"_____no_output_____"
],
[
"fesedflux_oxic = coef_fesedflux_current_speed2 * sedfrac_mod * current_speed**2\nfesedflux_oxic = fesedflux_oxic * mmolm2yr_to_μmolm2d\nfesedflux_oxic.name = 'Fe sediment flux (oxic)'\nfesedflux_oxic.attrs['units'] = 'micromol m$^{-2}$ d$^{-1}$'\nfesedflux_oxic.attrs['long_name'] = 'Fe sediment flux (oxic)'\n\nplt.figure()\nfesedflux_oxic.sum('z_t').plot(norm=colors.LogNorm(vmin=1e-3, vmax=fesedflux_oxic.max()))\nh = plt.title('fesedflux_oxic')",
"_____no_output_____"
],
[
"fesedflux_oxic_global = esmlab.statistics.weighted_sum(fesedflux_oxic, weights=ds.TAREA/cm2_per_m2, \n dim=('nlat', 'nlon')).sum('z_t')\n\nfesedflux_oxic_global = fesedflux_oxic_global * mol_per_µmol / mol_per_Gmol * d_per_yr\nprint(f'Global integral of `fesedflux_oxic_global` = {fesedflux_oxic_global.values:0.4f} Gmol Fe/yr')\n",
"Global integral of `fesedflux_oxic_global` = 0.6356 Gmol Fe/yr\n"
]
],
[
[
"## Compute total",
"_____no_output_____"
]
],
[
[
"fesedflux_total = (fesedflux_oxic + fesedflux_reduce)\nfesedflux_total.attrs['units'] = 'micromol/m^2/d'\nfesedflux_total.attrs['long_name'] = 'Fe sediment flux (total)'\n\nfesedflux_total_global = esmlab.statistics.weighted_sum(fesedflux_total, weights=ds.TAREA/cm2_per_m2, \n dim=('nlat', 'nlon')).sum('z_t')\n\nfesedflux_total_global = fesedflux_total_global * mol_per_µmol / mol_per_Gmol * d_per_yr\nprint(f'Global integral of `fesedflux_total_global` = {fesedflux_total_global.values:0.4f} Gmol Fe/yr')\n\n\nplt.figure()\nfesedflux_total.sum('z_t').plot(norm=colors.LogNorm(vmin=1e-2, vmax=20.))\n\nplt.figure()\nfesedflux_total.isel(nlon=i_pacific).plot(yincrease=False, norm=colors.LogNorm(vmin=1e-2, vmax=20.))\n\n",
"Global integral of `fesedflux_total_global` = 14.2238 Gmol Fe/yr\n"
]
],
[
[
"## Construct output file\n\nThe model uses a scale factor when reading in the `fesedflux`:\n`scale_factor = 1.1574e-6`; this converts from µmol/m^2/d to nmol/cm^2/s.",
"_____no_output_____"
]
],
[
[
"dso = xr.Dataset()\n\ndso['FESEDFLUXIN'] = fesedflux_total\ndso.FESEDFLUXIN.encoding = {'_FillValue': None, 'dtype': np.single}\n\ndso['FESEDFLUXIN_reduce'] = fesedflux_reduce\ndso.FESEDFLUXIN_reduce.encoding = {'_FillValue': None, 'dtype': np.single}\n\ndso['FESEDFLUXIN_oxic'] = fesedflux_oxic\ndso.FESEDFLUXIN_oxic.encoding = {'_FillValue': None, 'dtype': np.single}\n\nfor v in ['TAREA', 'TLONG', 'TLAT', 'KMT', 'z_t']:\n dso[v] = ds[v]\n dso.encoding['_FillValue'] = None\n \ndatestamp = datetime.now(timezone.utc).strftime(\"%Y-%m-%d\")\ndso.attrs['history'] = f'created by {id_string} on {datestamp}'\n\ndatestamp = date.today().strftime(\"%y%m%d\")\nfile_out = f'{util.dirout}/fesedflux_total_reduce_oxic_{dst_grid}.c{datestamp}.nc'\n\ndso.to_netcdf(file_out)\nutil.ncks_fl_fmt64bit(file_out)\n\nprint(f'wrote: {file_out}')\ndso.info()",
"wrote: /glade/work/mclong/cesm_inputdata/fesedflux_total_reduce_oxic_POP_gx1v7.c200618.nc\nxarray.Dataset {\ndimensions:\n\tnlat = 384 ;\n\tnlon = 320 ;\n\tz_t = 60 ;\n\nvariables:\n\tfloat64 z_t(z_t) ;\n\t\tz_t:units = cm ;\n\t\tz_t:long_name = depth from surface to midpoint of layer ;\n\t\tz_t:positive = down ;\n\tfloat64 FESEDFLUXIN(z_t, nlat, nlon) ;\n\t\tFESEDFLUXIN:units = micromol/m^2/d ;\n\t\tFESEDFLUXIN:long_name = Fe sediment flux (total) ;\n\tfloat64 FESEDFLUXIN_reduce(z_t, nlat, nlon) ;\n\t\tFESEDFLUXIN_reduce:units = micromol m$^{-2}$ d$^{-1}$ ;\n\tfloat64 FESEDFLUXIN_oxic(z_t, nlat, nlon) ;\n\t\tFESEDFLUXIN_oxic:units = micromol m$^{-2}$ d$^{-1}$ ;\n\t\tFESEDFLUXIN_oxic:long_name = Fe sediment flux (oxic) ;\n\tfloat64 TAREA(nlat, nlon) ;\n\t\tTAREA:units = cm^2 ;\n\t\tTAREA:long_name = area of T cells ;\n\t\tTAREA:coordinates = TLONG TLAT ;\n\tfloat64 TLONG(nlat, nlon) ;\n\t\tTLONG:units = degrees_east ;\n\t\tTLONG:long_name = T-grid longitude ;\n\tfloat64 TLAT(nlat, nlon) ;\n\t\tTLAT:units = degrees_north ;\n\t\tTLAT:long_name = T-grid latitude ;\n\tint32 KMT(nlat, nlon) ;\n\t\tKMT:long_name = k Index of Deepest Grid Cell on T Grid ;\n\t\tKMT:coordinates = TLONG TLAT ;\n\n// global attributes:\n\t:history = created by Fe_sediment_flux_forcing.ipynb from github.com/marbl-ecosys/forcing-Fe-sedflux on 2020-06-18 ;\n}"
]
],
[
[
"## Compare with CESM2 forcing dataset",
"_____no_output_____"
]
],
[
[
"cesm2_file = f'{util.inputdata}/ocn/pop/gx1v6/forcing/fesedfluxTot_gx1v6_cesm2_2018_c180618.nc'\ncesm2 = xr.open_dataset(cesm2_file).rename({'z': 'z_t', 'y': 'nlat', 'x': 'nlon'})\n\ncesm2['z_t'] = pop_tools.get_grid('POP_gx1v7').z_t\ncesm2['AREA_m2'] = pop_tools.get_grid('POP_gx1v7').TAREA * 1e-4\ncesm2.FESEDFLUXIN.attrs['units'] = 'µmol/m^2/d'\ncesm2",
"_____no_output_____"
],
[
"fesedflux_total_cesm2 = esmlab.statistics.weighted_sum(cesm2.FESEDFLUXIN, weights=cesm2.AREA_m2, \n dim=('nlat', 'nlon')).sum('z_t')\nfesedflux_total_cesm2 = fesedflux_total_cesm2 * mol_per_µmol / mol_per_Gmol * d_per_yr\n\nprint(f'Global integral of `fesedflux_total_cesm2` = {fesedflux_total_cesm2.values:0.4f} Gmol Fe/yr')",
"Global integral of `fesedflux_total_cesm2` = 19.9526 Gmol Fe/yr\n"
],
[
"fig = plt.figure(figsize=(16, 4))\nax = fig.add_subplot(1, 2, 1)\ncesm2.FESEDFLUXIN.sum('z_t').plot(norm=colors.LogNorm(vmin=1e-2, vmax=20.))\nplt.title('CESM2 Fe sedflux (vertical integral)')\n\nax = fig.add_subplot(1, 2, 2)\ndso.FESEDFLUXIN.sum('z_t').plot(norm=colors.LogNorm(vmin=1e-2, vmax=20.))\nplt.title('This dataset Fe sedflux (vertical integral)')\n\n\nfig = plt.figure(figsize=(12,4))\nax = fig.add_subplot(1, 2, 1)\ncesm2.FESEDFLUXIN.isel(nlon=200).plot(yincrease=False, norm=colors.LogNorm(vmin=1e-2, vmax=1.))\nplt.title('CESM2 Fe sedflux (Pacific transect)')\n\nax = fig.add_subplot(1, 2, 2)\ndso.FESEDFLUXIN.isel(nlon=i_pacific).plot(yincrease=False, norm=colors.LogNorm(vmin=1e-2, vmax=1.))\nplt.title('This dataset Fe sedflux (Pacific transect)')\n\nplt.figure()\nesmlab.statistics.weighted_sum(cesm2.FESEDFLUXIN, weights=cesm2.AREA_m2, dim=('nlat', 'nlon')).plot(label='CESM2')\nesmlab.statistics.weighted_sum(dso.FESEDFLUXIN, weights=ds.TAREA/cm2_per_m2, dim=('nlat', 'nlon')).plot(label='this dataset')\nplt.ylabel('Fe flux [µmol/yr]')\nplt.legend();",
"_____no_output_____"
],
[
"%load_ext watermark\n%watermark --iversion -g -m -v -u -d",
"numpy 1.18.1\nesmlab 2019.4.27.post55\nxarray 0.15.1\ntqdm 4.45.0\npop_tools 0.0.post167\nyaml 5.3.1\nlast updated: 2020-06-18 \n\nCPython 3.7.6\nIPython 7.13.0\n\ncompiler : GCC 7.3.0\nsystem : Linux\nrelease : 3.10.0-693.21.1.el7.x86_64\nmachine : x86_64\nprocessor : x86_64\nCPU cores : 72\ninterpreter: 64bit\nGit hash : 41cfb9957b578177e39fe0489171687407c91eaa\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"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"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",
"code"
],
[
"markdown"
]
] |
cbb23afe0eea0d6f96f2d708bff7cf01c1877928
| 89,731 |
ipynb
|
Jupyter Notebook
|
Longitudinal Isolates/(E) Retrieve SNPs between Longitudinal Pairs with AF change of 70% or more.ipynb
|
farhat-lab/in-host-Mtbc-dynamics
|
36e27011b5cfaed00521a38652fe2dc853832f25
|
[
"Naumen",
"Condor-1.1",
"CECILL-B",
"MS-PL"
] | null | null | null |
Longitudinal Isolates/(E) Retrieve SNPs between Longitudinal Pairs with AF change of 70% or more.ipynb
|
farhat-lab/in-host-Mtbc-dynamics
|
36e27011b5cfaed00521a38652fe2dc853832f25
|
[
"Naumen",
"Condor-1.1",
"CECILL-B",
"MS-PL"
] | null | null | null |
Longitudinal Isolates/(E) Retrieve SNPs between Longitudinal Pairs with AF change of 70% or more.ipynb
|
farhat-lab/in-host-Mtbc-dynamics
|
36e27011b5cfaed00521a38652fe2dc853832f25
|
[
"Naumen",
"Condor-1.1",
"CECILL-B",
"MS-PL"
] | null | null | null | 38.87825 | 253 | 0.469604 |
[
[
[
"from IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:100% !important; }</style>\"))",
"_____no_output_____"
]
],
[
[
"##########################################################################################################################################################################################################################################",
"_____no_output_____"
],
[
"## *Functions* for retrieving SNPs between each pair of *longitudinal* isolates (SNPs with $>= 70$% $\\Delta$ AF)",
"_____no_output_____"
],
[
"##########################################################################################################################################################################################################################################",
"_____no_output_____"
]
],
[
[
"import vcf\n\n%matplotlib inline\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport matplotlib.ticker as ticker\nfrom pylab import plot, show, savefig, xlim, figure, hold, ylim, legend, boxplot, setp, axes\nfrom itertools import compress\nfrom pylab import MaxNLocator\nimport seaborn as sns; sns.set()\nfrom matplotlib.colors import LogNorm\nfrom matplotlib import gridspec\nfrom matplotlib.gridspec import GridSpec\nimport ast\nimport itertools\nimport seaborn as sns\nfrom sklearn.preprocessing import StandardScaler\n\nimport fastcluster\nfrom sklearn import cluster, datasets\nimport scipy.cluster.hierarchy as hier\nfrom sklearn.cluster import KMeans\nimport time\nimport sys\n\nimport Bio\nfrom Bio.Alphabet import IUPAC\nfrom Bio.Blast.Applications import NcbiblastnCommandline\nfrom Bio.Blast import NCBIXML\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.SeqFeature import SeqFeature, FeatureLocation\nfrom Bio import pairwise2\nfrom Bio import SeqIO\nfrom Bio.Graphics import GenomeDiagram\nfrom Bio.SeqUtils import GC\n\nfrom Bio.Align.Applications import MuscleCommandline\nfrom StringIO import StringIO\nfrom Bio import AlignIO\nfrom Bio.Align import AlignInfo\nfrom Bio.Seq import MutableSeq\nimport itertools\n\nimport networkx as nx\nimport scipy\nimport pickle\n\n#for exporting to Adobe Illustrator\nmpl.rcParams['pdf.fonttype'] = 42\nmpl.rcParams['ps.fonttype'] = 42",
"_____no_output_____"
]
],
[
[
"### Decide on a threshold for difference in Alternate Allele Frequencies to call SNPs between two isolates",
"_____no_output_____"
]
],
[
[
"alt_AF_diff_threshold = 0.70 #x% ",
"_____no_output_____"
]
],
[
[
"### Load regions to exclude from analysis per EBR score across H37Rv (dropping sites with EBR score < 0.8)",
"_____no_output_____"
]
],
[
[
"with open('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/variant_calling/H37Rv_sites_to_drop.pkl', 'rb') as f:\n H37Rv_positions_to_drop = pickle.load(f)\n \n#convert to a set (faster to query)\nH37Rv_positions_to_drop = set(H37Rv_positions_to_drop)",
"_____no_output_____"
]
],
[
[
"### *Cell* to annotate SNPs",
"_____no_output_____"
]
],
[
[
"# Important Packages\n################################################################################################################################################################################################\nimport os\nimport pandas as pd\nimport numpy as np\nimport sys\nimport pickle\n\nimport Bio\nfrom Bio.Alphabet import IUPAC\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.SeqFeature import SeqFeature, FeatureLocation\nfrom Bio import SeqIO\nfrom StringIO import StringIO\nfrom Bio import AlignIO\nfrom Bio.Align import AlignInfo\nfrom Bio.Seq import MutableSeq\n################################################################################################################################################################################################\n\n\n# Relevant Information for H37Rv sequence SNP functional annotation\n################################################################################################################################################################################################\n####### Collect all DNA and Amino Acid sequences corresponding to genes on H37Rv #######\n#load reference genome and reference annotation\nreference_genome = '/n/data1/hms/dbmi/farhat/bin/work-horse/bin/h37rv.fasta'\nfor reference_genome in SeqIO.parse(reference_genome, \"fasta\"):\n reference_genome.seq.alphabet = IUPAC.unambiguous_dna\n\nreference_genome_annotation = pd.read_csv('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/H37Rv/h37rv_genome_summary.txt', '\\t').set_index('name')\n\n####### Function to translate coding DNA sequences ####### \ndef translate(gene_id, sequence):\n\n #find which strand the gene is located on and translate\n strand = reference_genome_annotation.loc[gene_id, 'strand']\n if strand == '+':\n protein_sequence = sequence.translate(table=\"Bacterial\", cds=False)\n elif strand == '-':\n protein_sequence = sequence.reverse_complement().translate(table=\"Bacterial\", cds=False)\n\n return protein_sequence\n\n####### Load in dictionaries for SNP annotation #######\nwith open('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/dicts_for_SNP_annotation/H37Rv_gene_seq_records.pickle', 'rb') as handle:\n ref_gene_sequences_records = pickle.load(handle)\n \nwith open('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/dicts_for_SNP_annotation/H37Rv_protein_seq_records.pickle', 'rb') as handle:\n ref_protein_sequences_records = pickle.load(handle)\n \nwith open('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/dicts_for_SNP_annotation/H37Rv_coord_gene_mapping.pickle', 'rb') as handle:\n ReferencePosition_Gene_mapping = pickle.load(handle)\n \n####### get Gene Categories #######\ngene_categories = pd.read_csv('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/CSV_files/gene_categories/gene_categories.csv').set_index('name')\ngene_categories_dict = dict([gene_id , gene_category] for gene_id, gene_category in zip(list(gene_categories.gene_id) , list(gene_categories.Gene_Category)))\n\n####### get Gene Symbols #######\ngene_symbol_dict = dict([gene_id , gene_symbol] for gene_id, gene_symbol in zip(list(reference_genome_annotation.symbol.index) , list( reference_genome_annotation.symbol )))\n################################################################################################################################################################################################\n\n\n# Function to annotate Intergenic SNPs\n################################################################################################################################################################################################\ndef find_flanking_genes_for_intergenic_region(intergenic_ref_pos): \n\n #this function finds the genes flagging an intergenic region given a reference position\n\n #find gene immediately in the 5' direction\n for i in range(0 , 100000):\n\n #move toward 5' direction\n if ReferencePosition_Gene_mapping[intergenic_ref_pos - i] != []:\n\n gene_to_left = ReferencePosition_Gene_mapping[intergenic_ref_pos - i][0]\n break\n\n #find gene immediately in the 3' direction \n for i in range(0 , 100000):\n\n #move toward 3' direction\n try:\n if ReferencePosition_Gene_mapping[intergenic_ref_pos + i] != []:\n\n gene_to_right = ReferencePosition_Gene_mapping[intergenic_ref_pos + i][0]\n break\n \n #KeyError means we have hit the 'end' of the chromosome, the intergenic region at then end of H37Rv in 5' > 3' orientation \n #since TB chromosome is circular the gene to the 'right' is Rv0001 \n except KeyError:\n \n gene_to_right = 'Rv0001'\n break\n \n return gene_to_left + '_' + gene_to_right\n################################################################################################################################################################################################\n\n\n# Function to determine whether SNPs are Synonymous or Non-Synonymous; Returns gene coordinate, codon position, AA changes, Gene Category & Symbol\n################################################################################################################################################################################################\ndef SNP_annotate(ref_seq_position , alt_allele_i):\n \n '''\n This function takes as input a reference position on H37Rv located within a \n gene and an alternate allele and returns whether the base change \n would correspond to a different Amino Acid sequence that results \n from translating the DNA sequence into an AA sequence.\n \n '''\n gene_intergenic_id_list = []\n genomic_coord_list = []\n gene_category_list = []\n gene_symbol_list = []\n Syn_NSyn_list = []\n AA_change_list = []\n \n #get the Reference Allele from the complete H37Rv reference genome, indexing starts from 0\n ref_allele_i = reference_genome.seq[int(ref_seq_position) - 1] \n \n #find the gene that SNP occurs on; check list corresponding to H37Rv coordinate to see if there are any genes associated with RefPosition\n if len(ReferencePosition_Gene_mapping[ref_seq_position]) > 0:\n\n #iterate through all genes that ReferencePosition is mapped to (i.e. SNP might correspond to 2 genes)\n for gene_intergenic_id in ReferencePosition_Gene_mapping[ref_seq_position]:\n\n #find genomic coordinate of SNP relative to gene (subtract 1 since reference seq starts counting at 1)\n gene_relative_coord = (ref_seq_position - 1) - min( reference_genome_annotation.loc[gene_intergenic_id , 'chromStart'] , reference_genome_annotation.loc[gene_intergenic_id , 'chromEnd'] )\n \n #find the genomic coordinate (relative to the gene, in the 5' to 3' direction)\n strand = reference_genome_annotation.loc[gene_intergenic_id, 'strand']\n if strand == '+':\n genomic_5_to_3_coord = (ref_seq_position) - reference_genome_annotation.loc[gene_intergenic_id , 'chromStart']\n\n elif strand == '-':\n genomic_5_to_3_coord = (reference_genome_annotation.loc[gene_intergenic_id , 'chromEnd']) - (ref_seq_position-1)\n \n #find gene category (if one exists)\n try:\n gene_category_i = gene_categories_dict[gene_intergenic_id]\n except KeyError:\n gene_category_i = 'None'\n \n #find gene symbol (if one exists)\n try:\n gene_symbol_i = gene_symbol_dict[gene_intergenic_id]\n except KeyError:\n gene_symbol_i = 'None'\n \n #alternate allele is an actual base\n if alt_allele_i in ['A','C','G','T']:\n\n #translate into protein sequence with the SNP in place if not InDel or intergenic region\n SNP_change = alt_allele_i\n\n #ALTERNATE allele (is it Syn or NSyn?)\n #get sequence from dictionary of sequences (and convert to mutable object)\n test_gene_sequence = ref_gene_sequences_records[gene_intergenic_id].seq.tomutable()\n\n #change reference gene sequence by the SNP in the query sequence\n test_gene_sequence[int(gene_relative_coord)] = SNP_change\n\n #convert back immutable object\n test_gene_sequence = test_gene_sequence.toseq()\n\n #translate sequence into amino acid seq\n test_protein_sequence = translate(gene_intergenic_id , test_gene_sequence)\n\n #store the H37Rv AA seq to compare against\n H37Rv_AA_sequence = ref_protein_sequences_records[gene_intergenic_id].seq\n\n #get the codon number where the SNP occurs within\n ## take the genomic coordinate (relative to the gene, in the 5' to 3' direction), divide by 3, then take the ceiling of this number (will be fraction if SNP occurs in 1st or 2nd position on codon)\n strand = reference_genome_annotation.loc[gene_intergenic_id, 'strand']\n if strand == '+':\n genomic_5_to_3_coord = (ref_seq_position) - reference_genome_annotation.loc[gene_intergenic_id , 'chromStart']\n\n elif strand == '-':\n genomic_5_to_3_coord = (reference_genome_annotation.loc[gene_intergenic_id , 'chromEnd']) - (ref_seq_position-1)\n\n codon_coord = int(np.ceil( float( genomic_5_to_3_coord) / 3.0 ))\n\n #compare to AA seq of original gene\n if test_protein_sequence == H37Rv_AA_sequence:\n\n SNP_type = 'S'\n\n #get the AA before & after\n AA_change = H37Rv_AA_sequence[codon_coord-1] + str(codon_coord) + test_protein_sequence[codon_coord-1]\n\n else:\n SNP_type = 'N'\n\n #get the AA before & after\n AA_change = H37Rv_AA_sequence[codon_coord-1] + str(codon_coord) + test_protein_sequence[codon_coord-1]\n \n #alternate allele is a dummy (Base Call completely supports the Reference Allele) \n else:\n \n SNP_type = 'None'\n AA_change = 'None'\n\n #store relevant info in lists \n gene_intergenic_id_list.append(gene_intergenic_id)\n genomic_coord_list.append(genomic_5_to_3_coord)\n gene_category_list.append(gene_category_i)\n gene_symbol_list.append(gene_symbol_i)\n Syn_NSyn_list.append(SNP_type)\n AA_change_list.append(AA_change)\n \n #if no gene in H37Rv corresponds to the Reference Position for SNP, then SNP must be intergenic\n else:\n \n gene_intergenic_id = find_flanking_genes_for_intergenic_region(ref_seq_position)\n genomic_5_to_3_coord = 'None'\n gene_category_i = 'None'\n gene_symbol_i = 'None'\n SNP_type = 'I'\n AA_change = 'None'\n \n #store relevant info in lists \n gene_intergenic_id_list.append(gene_intergenic_id)\n genomic_coord_list.append(genomic_5_to_3_coord)\n gene_category_list.append(gene_category_i)\n gene_symbol_list.append(gene_symbol_i)\n Syn_NSyn_list.append(SNP_type)\n AA_change_list.append(AA_change)\n \n #if there is only a single gene associated with this SNP, just return the individual elememts\n if len(gene_intergenic_id_list) == 1:\n return [ref_allele_i , gene_intergenic_id , genomic_5_to_3_coord , gene_category_i , gene_symbol_i , SNP_type , AA_change]\n \n #else if there are two genes associated with this SNP, return elements for each SNP annotation in a list\n elif len(gene_intergenic_id_list) > 1:\n return [ref_allele_i , gene_intergenic_id_list , genomic_coord_list , gene_category_list , gene_symbol_list , Syn_NSyn_list , AA_change_list]\n################################################################################################################################################################################################",
"_____no_output_____"
]
],
[
[
"### *Function* to get SNPs between paired isolates (filtered for $\\Delta AF$, MGE and low EBR score regions)",
"_____no_output_____"
]
],
[
[
"def get_filtered_SNPs_between_isolates(isolate_pair_ID , alt_AF_diff_threshold):\n\n '''\n This function only the fixed SNP variants that occur between a given isolate pair \n by loading in the pickled DataFrame for isolate pair and comparing alternate allele frequencies called in each isolate.\n (Differing Base Calls that have an Alternate Allele Frequencies >= x% different). \n This function also drops regions flagged as Mobile Genetic Elements & Regions of poor Illumina mapping / variant calling\n per Empirical Base Recall (EBR) scores across H37Rv.\n '''\n\n ################################################################################\n ### get SNPs between pair of isolates\n ################################################################################\n\n population = sample_annotation.loc[isolate_pair_ID , 'population'][0]\n\n #load in the differing Base Calls for the isolate pair from pickle\n different_base_calls_between_isolates = pd.read_pickle(SNP_variant_dir + population + '_' + isolate_pair_ID + '/base_calls_different_between_isolates.pkl')\n\n ################################################################################\n ### Drop SNPs with change in AF < x%\n ################################################################################\n\n #FILTER out paired Base Calls that have a difference in Alternate Allele Frequency of less than x%\n alt_AF_isolate_A = different_base_calls_between_isolates.loc[range(0 , np.shape(different_base_calls_between_isolates)[0] , 2) , 'alt_AF']\n alt_AF_isolate_B = different_base_calls_between_isolates.loc[range(1 , np.shape(different_base_calls_between_isolates)[0] , 2) , 'alt_AF']\n alt_AF_diff_btwn_paired_isolates = abs(alt_AF_isolate_A.values - alt_AF_isolate_B.values)\n\n isolate_A_Base_Call_indices_small_change_alt_AF = list(alt_AF_isolate_A[alt_AF_diff_btwn_paired_isolates < alt_AF_diff_threshold].index)\n isolate_B_Base_Call_indices_small_change_alt_AF = list(alt_AF_isolate_B[alt_AF_diff_btwn_paired_isolates < alt_AF_diff_threshold].index)\n Base_Call_Indices_SMALL_Alt_AF_Diff = isolate_A_Base_Call_indices_small_change_alt_AF + isolate_B_Base_Call_indices_small_change_alt_AF\n\n #drop paired Base Calls w/ corresponding change in Alterante Allele Frequency < x%\n different_base_calls_between_isolates.drop(Base_Call_Indices_SMALL_Alt_AF_Diff , axis = 0 , inplace = True)\n\n #reset index of filtered SNP DataFrame\n different_base_calls_between_isolates.reset_index(inplace = True, drop = True)\n\n ################################################################################\n ### Drop SNPs with change in regions with low EBR scores\n ################################################################################\n\n #Drop Base Calls in H37Rv sites with low EBR score (make sure there is at least 1 SNP)\n if np.shape(different_base_calls_between_isolates)[0] > 0:\n\n #create a boolean filter for SNPs to keep\n SNPs_to_keep_filter = [SNP_i_ref_pos not in H37Rv_positions_to_drop for SNP_i_ref_pos in different_base_calls_between_isolates.ref_position]\n\n #filter out SNPs in H37Rv sites with low EBR scores and reset index\n different_base_calls_between_isolates = different_base_calls_between_isolates[SNPs_to_keep_filter]\n different_base_calls_between_isolates.reset_index(inplace = True, drop = True)\n\n ################################################################################\n ### Annotate SNPs & Drop SNPs in MGE regions\n ################################################################################\n\n gene_id_list = []\n gene_coord_list = []\n gene_category_list = []\n gene_symbol_list = []\n SNP_ftype_list = []\n AA_change_list = []\n\n #Annotate Filtered Base Calls (make sure there is at least 1 SNP)\n if np.shape(different_base_calls_between_isolates)[0] > 0:\n\n for ref_position_i , alt_base_i in zip(list(different_base_calls_between_isolates.ref_position) , list(different_base_calls_between_isolates.alt_base)):\n\n #annotate SNP\n gene_id_i , gene_coord_i , gene_category_i , gene_symbol_i , SNP_ftype_i , AA_change_i = SNP_annotate(ref_position_i , alt_base_i)[1:]\n\n gene_id_list.append(gene_id_i)\n gene_coord_list.append(gene_coord_i)\n gene_category_list.append(gene_category_i)\n gene_symbol_list.append(gene_symbol_i)\n SNP_ftype_list.append(SNP_ftype_i)\n AA_change_list.append(AA_change_i)\n\n #create columns to store SNP annotation info\n different_base_calls_between_isolates['gene_id'] = gene_id_list\n different_base_calls_between_isolates['gene_coord'] = gene_coord_list\n different_base_calls_between_isolates['gene_category'] = gene_category_list\n different_base_calls_between_isolates['gene_symbol'] = gene_symbol_list\n different_base_calls_between_isolates['SNP_ftype'] = SNP_ftype_list\n different_base_calls_between_isolates['AA_change'] = AA_change_list\n\n #FILTER out Base Calls in MGE regions (Mobile Genentic Elements)\n SNPs_to_drop_filter = [] #True if SNP is located within an MGE region\n\n for gene_id_i in list(different_base_calls_between_isolates.gene_category):\n\n #only 1 or 0 genes associated with this SNP\n if (type(gene_id_i) == str) and (gene_id_i == 'Mobile Genetic Element'):\n\n SNPs_to_drop_filter.append(True)\n\n #two genes associated with this SNP\n elif (type(gene_id_i) == list) and ('Mobile Genetic Element' in gene_id_i):\n\n SNPs_to_drop_filter.append(True)\n\n #SNP not in an MGE region so don't drop\n else:\n\n SNPs_to_drop_filter.append(False)\n\n #create a boolean filter for SNPs to keep\n SNPs_to_keep_filter = [not MGE_SNP for MGE_SNP in SNPs_to_drop_filter]\n\n #filter out SNPs in MGE regions and reset index\n different_base_calls_between_isolates = different_base_calls_between_isolates[SNPs_to_keep_filter]\n different_base_calls_between_isolates.reset_index(inplace = True, drop = True)\n\n #No SNPs detected between this pair of isolates (empty DataFrame)\n else:\n\n different_base_calls_between_isolates['gene_id'] = \"\"\n different_base_calls_between_isolates['gene_coord'] = \"\"\n different_base_calls_between_isolates['gene_category'] = \"\"\n different_base_calls_between_isolates['gene_symbol'] = \"\"\n different_base_calls_between_isolates['SNP_ftype'] = \"\"\n different_base_calls_between_isolates['AA_change'] = \"\"\n \n return different_base_calls_between_isolates",
"_____no_output_____"
]
],
[
[
"##########################################################################################################################################################################################################################################",
"_____no_output_____"
],
[
"## Longitudinal Sample pairs",
"_____no_output_____"
],
[
"##########################################################################################################################################################################################################################################",
"_____no_output_____"
],
[
"#### Import Sample Annotation file",
"_____no_output_____"
]
],
[
[
"sample_annotation = pd.read_csv('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/CSV_files/sample_annotation_files/Longitudinal_fastq_path_names_and_JankyPipe_tags_filtered_final.csv' , sep = ',').set_index('patient_id')",
"_____no_output_____"
],
[
"SNP_variant_dir = '/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/variant_calling/longitudinal_SNPs/all_SNPs_between_longitudinal_pairs/'",
"_____no_output_____"
],
[
"sample_annotation.head()",
"_____no_output_____"
],
[
"num_isolate_pair_IDs = np.shape(sample_annotation)[0] / 2\nprint num_isolate_pair_IDs ",
"200\n"
],
[
"isolate_pair_ID_list = list(set(sample_annotation.index))",
"_____no_output_____"
]
],
[
[
"### Call function to collect SNPs passing Difference in Alternate Allele Frequency Threshold",
"_____no_output_____"
]
],
[
[
"Base_Call_variants_btwn_isolates_big_change_in_alt_AF = []\n\nisolate_pair_index = 0\n\n#iterate through isolate pairs, collect all SNP variants arising between each pair of isolates\nfor isolate_pair_ID in isolate_pair_ID_list:\n \n #retrieve filtered paired Base Calls with a change in Alternate Allele Frequency > threshold\n Base_Call_variants_btwn_isolates_big_change_in_alt_AF_pair_i = get_filtered_SNPs_between_isolates(isolate_pair_ID , alt_AF_diff_threshold)\n \n #store relevant Base Call info in list of DataFrames (1 for each isolate pair)\n Base_Call_variants_btwn_isolates_big_change_in_alt_AF.append(Base_Call_variants_btwn_isolates_big_change_in_alt_AF_pair_i)\n isolate_pair_index += 1\n \n if isolate_pair_index % 5 == 0:\n print isolate_pair_index\n \n#concatenate DataFrames for each subject into 1 DataFrame\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF = pd.concat(Base_Call_variants_btwn_isolates_big_change_in_alt_AF , axis = 0)\n\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.reset_index(inplace = True , drop = True)",
"5\n10\n15\n20\n25\n30\n35\n40\n45\n50\n55\n60\n65\n70\n75\n80\n85\n90\n95\n100\n105\n110\n115\n120\n125\n130\n135\n140\n145\n150\n155\n160\n165\n170\n175\n180\n185\n190\n195\n200\n"
]
],
[
[
"### *Filter*: Drop paired Base Calls if both Base Calls in a pair support *different* Alternate Alleles",
"_____no_output_____"
]
],
[
[
"#list that stores the indices of paired Base Calls with DIFFERENT Alternate Alleles\nBase_Calls_to_Drop = []\n\n#iterate through each PAIR of corresponding Base Calls from paired isolates\nfor isolate_A_Base_Call_i , isolate_B_Base_Call_i in zip(range(0 , np.shape(Base_Call_variants_btwn_isolates_big_change_in_alt_AF)[0] , 2) , range(1 , np.shape(Base_Call_variants_btwn_isolates_big_change_in_alt_AF)[0] , 2) ):\n \n #pull info that both Base Calls should have in COMMON\n isolate_A_Base_Call_info = list( Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[isolate_A_Base_Call_i , ['ref_base','ref_position','gene_id','genomic_coord','population','patient_id']] ) \n isolate_B_Base_Call_info = list( Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[isolate_B_Base_Call_i , ['ref_base','ref_position','gene_id','genomic_coord','population','patient_id']] ) \n \n #make sure Base Calls Match with respect to Reference Base, Reference Position, gene ID, Genomic Coordinate, Gene Category, Symbol, Population & Patient ID\n if isolate_A_Base_Call_info == isolate_B_Base_Call_info:\n \n #pull alternate Allele for each of the paired isolates\n isolate_A_Alt_Base = Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[isolate_A_Base_Call_i , 'alt_base']\n isolate_B_Alt_Base = Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[isolate_B_Base_Call_i , 'alt_base']\n \n #Check to see if there is a 'Z' in the pair of Alternate Alleles, if so one of the Base Calls supported the Reference Base (so there was no Alternate Allele)\n if (isolate_A_Alt_Base == 'Z') or (isolate_B_Alt_Base == 'Z'):\n pass\n \n #if neither Alternate Allele is a 'Z', then check to see that the Alternate Allele Bases Match\n elif isolate_A_Alt_Base == isolate_B_Alt_Base:\n pass\n \n #if the Alternate Alleles DON'T match and both Base Calls supported Alternate Alleles (not the Reference), then we can't compare the Allele Frequencies of these Alternate Alleles (since they're different)\n else:\n Base_Calls_to_Drop = Base_Calls_to_Drop + [isolate_A_Base_Call_i , isolate_B_Base_Call_i]\n \n #print indices of Base Calls and see what went wrong if the paired Base Calls have different information that the Calls should have in Common (Ref Position, Ref Base, Gene ID, Patient ID, etc.)\n else:\n print (isolate_A_Base_Call_i , isolate_B_Base_Call_i)\n \n#Drop Paired Base Calls that supported different Alternate Alleles\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.drop(Base_Calls_to_Drop , axis = 0 , inplace = True)\n\n#reset index\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.reset_index(inplace = True, drop = True)",
"_____no_output_____"
],
[
"Base_Call_variants_btwn_isolates_big_change_in_alt_AF.head(n = 10)",
"_____no_output_____"
],
[
"np.shape(Base_Call_variants_btwn_isolates_big_change_in_alt_AF)",
"_____no_output_____"
]
],
[
[
"### Drop any glpK mutants",
"_____no_output_____"
]
],
[
[
"Base_Call_variants_btwn_isolates_big_change_in_alt_AF[Base_Call_variants_btwn_isolates_big_change_in_alt_AF.gene_symbol == 'glpK']",
"_____no_output_____"
],
[
"#Drop glpK mutants\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF = Base_Call_variants_btwn_isolates_big_change_in_alt_AF[Base_Call_variants_btwn_isolates_big_change_in_alt_AF.gene_symbol != 'glpK']\n\n#reset index\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.reset_index(inplace = True, drop = True)",
"_____no_output_____"
],
[
"np.shape(Base_Call_variants_btwn_isolates_big_change_in_alt_AF)",
"_____no_output_____"
]
],
[
[
"### Check for SNPs that actually occurred in overlapping regions with two CDS",
"_____no_output_____"
],
[
"SNPs in these regions will be treated as 2 SNPs for downstream analysis, manually adjust DataFrame of Base Calls",
"_____no_output_____"
]
],
[
[
"SNP_overlapping_CDS_region_filter = [type(gene_id)==list for gene_id in Base_Call_variants_btwn_isolates_big_change_in_alt_AF.gene_id]\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF[SNP_overlapping_CDS_region_filter]",
"_____no_output_____"
],
[
"Base_Call_226_INFO = Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[226 , 'INFO']\nBase_Call_227_INFO = Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[227 , 'INFO']",
"_____no_output_____"
],
[
"#drop each row and replace with two additional rows, one for each CDS region\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.drop([226,227] , axis = 0 , inplace = True)\n\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[500 , :] = ['G' , 'A' , 223690 , 2045 , 'Alt_PASS' , [] , Base_Call_226_INFO , 0.99 , 59 , 'ERR181875' , 'GUERRA' , 'KPS_68' , 'Rv0192' , 127 , 'Non-Essential' , 'nan' , 'N' , 'G43R']\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[501 , :] = ['G' , 'Z' , 223690 , 1395 , 'Ref_PASS' , [] , Base_Call_227_INFO , 0.00 , 38 , 'ERR176472' , 'GUERRA' , 'KPS_68' , 'Rv0192' , 127 , 'Non-Essential' , 'nan' , 'None' , 'None']\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[502 , :] = ['G' , 'A' , 223690 , 2045 , 'Alt_PASS' , [] , Base_Call_226_INFO , 0.99 , 59 , 'ERR181875' , 'GUERRA' , 'KPS_68' , 'Rv0192A' , 84 , 'Antigen' , 'nan' , 'S' , 'L28L']\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[503 , :] = ['G' , 'Z' , 223690 , 1395 , 'Ref_PASS' , [] , Base_Call_227_INFO , 0.00 , 38 , 'ERR176472' , 'GUERRA' , 'KPS_68' , 'Rv0192A' , 84 , 'Antigen' , 'nan' , 'None' , 'None']\n\n#reset index\nBase_Call_variants_btwn_isolates_big_change_in_alt_AF.reset_index(inplace = True , drop = True)",
"_____no_output_____"
],
[
"np.shape(Base_Call_variants_btwn_isolates_big_change_in_alt_AF)",
"_____no_output_____"
]
],
[
[
"### Pickle DataFrame for Downstream analyses (Alternate Allele Frequency 1 vs. Alternate Allele Frequency 2)",
"_____no_output_____"
]
],
[
[
"Base_Call_variants_btwn_isolates_big_change_in_alt_AF.to_pickle('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/variant_calling/longitudinal_SNPs/longitudinal_SNP_variants_70_delta_in_alt_AF.pkl')",
"_____no_output_____"
]
],
[
[
"### Re-Shape Filtered DataFrame (Paired Base Calls across all isolate pairs) to store one entry per SNP",
"_____no_output_____"
]
],
[
[
"SNP_variants_between_paired_isolates = pd.DataFrame()\n\n#common information to both Base Calls (can just look at isolate A)\npopulation_dict = {}\npatient_id_dict = {}\nref_position_dict = {}\nref_allele_dict = {}\ngene_id_dict = {}\ngenomic_coord_dict = {}\ngene_category_dict = {}\ngene_symbol_dict = {}\n\n#look at info for both Base Calls\nalt_allele_dict = {}\nalt_AF_diff_dict = {}\nSNP_type_dict = {}\nAA_change_dict = {}\n\nSNP_index = 0\n#iterate through indices for isolate A (store common information for isolate pair A & B came from and Base Call), calculate different in Alternate Allele Frequencies, store Syn or NSyn info\nfor even_index in range(0 , np.shape(Base_Call_variants_btwn_isolates_big_change_in_alt_AF)[0] , 2):\n \n #Base Call info for isolate A\n Base_Call_info_isolate_A = Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[even_index , :]\n #Base Call info for isolate B\n Base_Call_info_isolate_B = Base_Call_variants_btwn_isolates_big_change_in_alt_AF.loc[even_index+1 , :]\n \n population_dict[SNP_index] = Base_Call_info_isolate_A.population\n patient_id_dict[SNP_index] = Base_Call_info_isolate_A.patient_id\n ref_position_dict[SNP_index] = Base_Call_info_isolate_A.ref_position\n ref_allele_dict[SNP_index] = Base_Call_info_isolate_A.ref_base\n gene_id_dict[SNP_index] = Base_Call_info_isolate_A.gene_id\n genomic_coord_dict[SNP_index] = Base_Call_info_isolate_A.gene_coord\n gene_category_dict[SNP_index] = Base_Call_info_isolate_A.gene_category\n gene_symbol_dict[SNP_index] = Base_Call_info_isolate_A.gene_symbol\n \n #get alternate allele\n alt_allele_calls = [Base_Call_info_isolate_A.alt_base , Base_Call_info_isolate_B.alt_base]\n try:\n alt_allele_calls.remove('Z')\n except ValueError:\n pass\n alt_allele_dict[SNP_index] = alt_allele_calls[0]\n\n #get difference in Alternate Allele Frequencies\n alt_AF_diff_dict[SNP_index] = abs(Base_Call_info_isolate_A.alt_AF - Base_Call_info_isolate_B.alt_AF)\n \n #get type of SNP \n if 'S' in [Base_Call_info_isolate_A.SNP_ftype , Base_Call_info_isolate_B.SNP_ftype]:\n SNP_type_dict[SNP_index] = 'S'\n \n elif 'N' in [Base_Call_info_isolate_A.SNP_ftype , Base_Call_info_isolate_B.SNP_ftype]:\n SNP_type_dict[SNP_index] = 'N'\n \n elif 'I' in [Base_Call_info_isolate_A.SNP_ftype , Base_Call_info_isolate_B.SNP_ftype]:\n SNP_type_dict[SNP_index] = 'I'\n \n #get AA change\n AA_change_calls = [Base_Call_info_isolate_A.AA_change , Base_Call_info_isolate_B.AA_change]\n try:\n AA_change_calls.remove('None')\n except ValueError:\n pass\n AA_change_dict[SNP_index] = AA_change_calls[0]\n \n SNP_index += 1\n \n#convert dictionaries into series\npopulation = pd.Series(population_dict)\npatient_id = pd.Series(patient_id_dict)\nref_position = pd.Series(ref_position_dict)\nref_allele = pd.Series(ref_allele_dict)\nalt_allele = pd.Series(alt_allele_dict)\ngene_id = pd.Series(gene_id_dict)\ngenomic_coord = pd.Series(genomic_coord_dict)\ngene_category = pd.Series(gene_category_dict)\ngene_symbol = pd.Series(gene_symbol_dict)\nalt_AF_diff = pd.Series(alt_AF_diff_dict)\nSNP_type = pd.Series(SNP_type_dict)\nAA_change = pd.Series(AA_change_dict)\n \n#create DataFrame\nSNP_variants_between_paired_isolates['population'] = population\nSNP_variants_between_paired_isolates['patient_id'] = patient_id\nSNP_variants_between_paired_isolates['ref_position'] = ref_position \nSNP_variants_between_paired_isolates['ref_position'] = SNP_variants_between_paired_isolates.ref_position.astype(int) #ensure ref position is a column of integers\nSNP_variants_between_paired_isolates['ref_allele'] = ref_allele\nSNP_variants_between_paired_isolates['alt_allele'] = alt_allele\nSNP_variants_between_paired_isolates['gene_id'] = gene_id\nSNP_variants_between_paired_isolates['genomic_coord'] = genomic_coord\nSNP_variants_between_paired_isolates['gene_category'] = gene_category\nSNP_variants_between_paired_isolates['gene_symbol'] = gene_symbol\nSNP_variants_between_paired_isolates['alt_AF_diff'] = alt_AF_diff\nSNP_variants_between_paired_isolates['SNP_type'] = SNP_type\nSNP_variants_between_paired_isolates['AA_change'] = AA_change",
"_____no_output_____"
],
[
"SNP_variants_between_paired_isolates.head()",
"_____no_output_____"
],
[
"np.shape(SNP_variants_between_paired_isolates)",
"_____no_output_____"
]
],
[
[
"#### Save DataFrame as CSV",
"_____no_output_____"
]
],
[
[
"SNP_variants_between_paired_isolates.to_csv('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/CSV_files/variant_calling/longitudinal_SNPs/SNPs_between_isolates_delta_70.csv' , sep = ',')",
"_____no_output_____"
]
],
[
[
"#### Pickle DataFrame for Downstream analyses",
"_____no_output_____"
]
],
[
[
"SNP_variants_between_paired_isolates.to_pickle('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/variant_calling/longitudinal_SNPs/SNPs_between_isolates_delta_70.pkl')",
"_____no_output_____"
]
],
[
[
"### Store non-redundant Filtered SNPs for use in SIMULATIONS (only simulate SNPs occuring within genes)",
"_____no_output_____"
]
],
[
[
"SNP_variants_between_paired_isolates.head()",
"_____no_output_____"
],
[
"#Drop SNPs occurring in intergenic regions\nnon_redundant_SNP_variants_between_paired_isolates = SNP_variants_between_paired_isolates[SNP_variants_between_paired_isolates.SNP_type != 'I']\n\n#reset index after dropping rows\nnon_redundant_SNP_variants_between_paired_isolates.reset_index(inplace = True , drop = True)\n\n#Find any Duplicate Base Calls ( Reference Base , Alternate Base, Reference Position , Gene ID & Genomic Coordinate identify a unique SNP )\nduplicated_Base_Calls_filter = list( non_redundant_SNP_variants_between_paired_isolates.duplicated(subset = ['ref_allele' , 'alt_allele' , 'ref_position' , 'gene_id'] , keep = 'first') )\nnon_duplicate_Base_Calls_filter = [not duplicated for duplicated in duplicated_Base_Calls_filter]\n\n#Drop any duplicate Base Calls\nnon_redundant_SNP_variants_between_paired_isolates = non_redundant_SNP_variants_between_paired_isolates[non_duplicate_Base_Calls_filter]\n\n#reset index after dropping rows\nnon_redundant_SNP_variants_between_paired_isolates.reset_index(inplace = True , drop = True)\n\n#ensure ref position is a column of integers\nnon_redundant_SNP_variants_between_paired_isolates['ref_position'] = non_redundant_SNP_variants_between_paired_isolates.ref_position.astype(int)\n\n#Drop unnecessary columns\nnon_redundant_SNP_variants_between_paired_isolates.drop(['population' , 'patient_id' , 'alt_AF_diff'] , axis = 1 , inplace = True)",
"_____no_output_____"
],
[
"np.shape(non_redundant_SNP_variants_between_paired_isolates) #all SNPs are 'non-redundant'",
"_____no_output_____"
],
[
"non_redundant_SNP_variants_between_paired_isolates.head(n=3)",
"_____no_output_____"
]
],
[
[
"#### Store as a Pickled DataFrame",
"_____no_output_____"
]
],
[
[
"non_redundant_SNP_variants_between_paired_isolates.to_pickle('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/pickled_files/variant_calling/longitudinal_SNPs/longitudinal_SNPs_to_simulate.pkl')",
"_____no_output_____"
]
],
[
[
"#### Store as a CSV file",
"_____no_output_____"
]
],
[
[
"non_redundant_SNP_variants_between_paired_isolates.to_csv('/n/data1/hms/dbmi/farhat/Roger/inhost_TB_dynamics_project/CSV_files/variant_calling/longitudinal_SNPs/longitudinal_SNPs_to_simulate.csv')",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb23bca85ef1be5d01a79772cc2c463286674ec
| 2,406 |
ipynb
|
Jupyter Notebook
|
rec_ui.ipynb
|
sepal-contrib/gwb
|
436af329ad54320b93504984c19160bca5e247b5
|
[
"MIT"
] | null | null | null |
rec_ui.ipynb
|
sepal-contrib/gwb
|
436af329ad54320b93504984c19160bca5e247b5
|
[
"MIT"
] | null | null | null |
rec_ui.ipynb
|
sepal-contrib/gwb
|
436af329ad54320b93504984c19160bca5e247b5
|
[
"MIT"
] | null | null | null | 19.403226 | 93 | 0.53325 |
[
[
[
"from sepal_ui import sepalwidgets as sw\n\nfrom component import model\nfrom component import tile\nfrom component.message import cm",
"_____no_output_____"
],
[
"rec_model = model.RecModel()",
"_____no_output_____"
],
[
"rec_title = sw.Tile(rec_model.tile_id, cm.rec.title, [sw.Markdown(cm.rec.description)])",
"_____no_output_____"
],
[
"rec_convert = tile.ConvertByte(rec_model, 0)",
"_____no_output_____"
],
[
"rec_process = tile.RecTile(rec_model, rec_convert)",
"_____no_output_____"
],
[
"rec_title",
"_____no_output_____"
],
[
"# from component import parameter as cp\n#\n# rec_model.bin_map = cp.get_result_dir(\"rec\")/\"example_bin_map.tif\"\n#\n# rec_model.__dict__",
"_____no_output_____"
],
[
"rec_convert",
"_____no_output_____"
],
[
"rec_process",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb23ce13123818559e4fdab1b40f516341b0af3
| 421,397 |
ipynb
|
Jupyter Notebook
|
Median-Combination-Pedagogy.ipynb
|
spacegal-spiff/AST341
|
cce49d730b3e6a5048549f6d777e3528b3090c13
|
[
"MIT"
] | null | null | null |
Median-Combination-Pedagogy.ipynb
|
spacegal-spiff/AST341
|
cce49d730b3e6a5048549f6d777e3528b3090c13
|
[
"MIT"
] | null | null | null |
Median-Combination-Pedagogy.ipynb
|
spacegal-spiff/AST341
|
cce49d730b3e6a5048549f6d777e3528b3090c13
|
[
"MIT"
] | 1 |
2018-02-01T17:12:44.000Z
|
2018-02-01T17:12:44.000Z
| 423.089357 | 147,608 | 0.92625 |
[
[
[
"# Median Combination Pedagogy\n### Week of 3.29.2018",
"_____no_output_____"
]
],
[
[
"# python 2/3 compatibility\nfrom __future__ import print_function\n\n# numerical python\nimport numpy as np\n\n# file management tools\nimport glob\nimport os\n\n# good module for timing tests\nimport time\n\n# plotting stuff\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib as mpl\ncmap = mpl.cm.viridis\n\n%matplotlib inline\n\n# ability to read/write fits files\nfrom astropy.io import fits\n\n# fancy image combination technique\nfrom astropy.stats import sigma_clipping\n\n# median absolute deviation: for photometry\n#from astropy.stats import mad_std\n\n# photometric utilities\n#from photutils import DAOStarFinder,aperture_photometry, CircularAperture, CircularAnnulus\n\n# import a library for generating pseudo random numbers\n# [there is great computer science theory on 'random' numbers, check it out!]\nfrom numpy import random ",
"_____no_output_____"
],
[
"# make the definitions for reading in images accessible in this notebook.\nfrom HDI_io import *",
"_____no_output_____"
],
[
"# load up shifting methods\nfrom shift_methods import *",
"_____no_output_____"
]
],
[
[
"### Part 1: Distribution Basics",
"_____no_output_____"
],
[
"Topics:\n1. Median selection\n2. Small number statistics\n\nWe'll start by imagining these in one dimension.",
"_____no_output_____"
],
[
"Draw 10000 samples from a normal distribution (an approximation of the background noise) and visualizing.",
"_____no_output_____"
]
],
[
[
"# set the parameters for the normal distribution\nmean = 0.5\nsigma = 0.1",
"_____no_output_____"
],
[
"# we'll use random.random([size]), which returns a value on the interval [0.,1.)\n# [that means 0 is allowed, but 1 is not: 'half-open']\n# scale this using a prefactor, if desired\n\n\nnsamples = 10000\n\n# draw the values and 'bin' to 0.01 increments\nrandvals = np.round(random.normal(mean,sigma,nsamples),2)\n\n\n# here's a cute method to make a pseudo histogram because of rounding\nrand_y_vals = np.zeros_like(randvals)\n\nfor x in range(1,len(randvals)):\n rand_y_vals[x] = len(np.where(randvals[0:x] == randvals[x])[0])\n\n \n# visualize\nplt.figure(figsize=(5,3))\n\n# render the points, normalizing to 1\nplt.scatter(randvals,rand_y_vals/nsamples,color='black',s=1.)\n\n# draw the median line and the theoretical median\nplt.plot([np.median(randvals),np.median(randvals)],[0.,1.2*np.max(rand_y_vals/nsamples)],color='gray',lw=1.)\nplt.plot([mean,mean],[0.,1.2*np.max(rand_y_vals/nsamples)],color='red',lw=1.)\n\n\nplt.xlim(mean-5*sigma,mean+5*sigma)\n\nplt.title('Nsamples={}'.format(nsamples),size=24)\nplt.xlabel('Pixel Value',size=24)\nplt.ylabel('# of samples',size=24)",
"_____no_output_____"
]
],
[
[
"Obviously, this is not totally smooth, even at this sample number. What happens if we decrease the number of samples?",
"_____no_output_____"
]
],
[
[
"# identical to above, but with fewer samples\n\nnsamples = 20\n\nrandvals = np.round(random.normal(mean,sigma,nsamples),2)\n\n# here's a cute method to make a pseudo histogram\nrand_y_vals = np.zeros_like(randvals)\n\nfor x in range(1,len(randvals)):\n rand_y_vals[x] = len(np.where(randvals[0:x] == randvals[x])[0])\n\n \nplt.figure(figsize=(5,3))\nplt.scatter(randvals,rand_y_vals/nsamples,color='black',s=1.)\n\n# calculated median\nplt.plot([np.median(randvals),np.median(randvals)],[0.,1.2*np.max(rand_y_vals/nsamples)],color='gray',lw=1.)\n\n# theoretical median\nplt.plot([mean,mean],[0.,1.2*np.max(rand_y_vals/nsamples)],color='red',lw=1.)\n\n\n\nplt.xlim(mean-5*sigma,mean+5*sigma)\n\nplt.title('Nsamples={}'.format(nsamples),size=24)\nplt.xlabel('Pixel Value',size=24)\nplt.ylabel('# of samples',size=24)",
"_____no_output_____"
]
],
[
[
"We can empirically check the convergence of the samples to the true value by drawing samples repeatedly and computing the median.",
"_____no_output_____"
]
],
[
[
"\nsamplenums = np.arange(1,10000,1)\nrandvals_median = np.zeros(len(samplenums))\n\nfor indx,val in enumerate(samplenums):\n randvals_median[indx] = np.median(random.normal(mean,sigma,val))\n\n\nfig = plt.figure(figsize=(5,3))\n\n\nax1 = fig.add_axes([0.2,0.6,0.6,0.35])\nax2 = fig.add_axes([0.2,0.2,0.6,0.35])\n\nax1.plot(np.log10(samplenums),randvals_median,color='black')\nax1.set_ylabel('Median',size=18)\nax1.set_xticklabels(())\n\nax2.plot(np.log10(samplenums),np.abs(randvals_median-0.5),color='red')\nax2.plot(np.log10(samplenums),0.1/(np.sqrt(samplenums)),color='gray')\n\n\n\nax2.set_xlabel('log # samples',size=18)\nax2.set_ylabel('Median\\nError',size=18)",
"_____no_output_____"
]
],
[
[
"Unfortunately, we are almost always in the very low number region (so we still have plenty of noise). But, now we can start to see why deep images will start to minimize background noise!\n\nTherefore, we want to do something like this at every point on the sky: take many observations and calculate the median. We do this at each pixel point in some fiducial image, that we have matched many other images to spatially.\n\nBut, we can do a little better. Enter sigma clipping.\n\n",
"_____no_output_____"
],
[
"### Part 1: Sigma Clipping\n\nLet's grab a well-sample histogram of values, as above:",
"_____no_output_____"
]
],
[
[
"nsamples = 10000\n\nrandvals = np.round(random.normal(0.5,0.1,nsamples),2)\n\n# here's a cute method to make a pseudo histogram\nrand_y_vals = np.zeros_like(randvals)\n\nfor x in range(1,len(randvals)):\n rand_y_vals[x] = len(np.where(randvals[0:x] == randvals[x])[0])\n\n \nplt.figure(figsize=(5,3))\n\nplt.scatter(randvals,rand_y_vals/nsamples,color='black',s=1.)\n\nmedian_value = np.median(randvals)\nstandard_deviation_value = np.std(randvals)\n\nplt.plot([median_value,median_value],[0.,1.2*np.max(rand_y_vals/nsamples)],color='red',lw=1.)\nplt.plot([median_value-3.*standard_deviation_value,median_value-3.*standard_deviation_value],\\\n [0.,0.6*np.max(rand_y_vals/nsamples)],color='blue',lw=1.)\nplt.plot([median_value+3.*standard_deviation_value,median_value+3.*standard_deviation_value],\\\n [0.,0.6*np.max(rand_y_vals/nsamples)],color='blue',lw=1.)\n\n\n# calculated median\nplt.plot([median_value,median_value],[0.,1.2*np.max(rand_y_vals/nsamples)],color='gray',lw=1.)\n\n# theoretical median\nplt.plot([mean,mean],[0.,1.2*np.max(rand_y_vals/nsamples)],color='red',lw=1.)\n\n\n\nplt.xlim(mean-5*sigma,mean+5*sigma)\n\n\n\n\n\nplt.title('Pixel Distibution\\nwith 3$\\sigma$ marked',size=24)\nplt.xlabel('Pixel Value',size=24)\nplt.ylabel('# of samples',size=24)",
"_____no_output_____"
]
],
[
[
"Now we'd elimate anything to the left and right of the 3$\\sigma$ values as being outliers.",
"_____no_output_____"
],
[
"This doesn't seem very important (and indeed, if we decrease nsample, we often won't even get fluxes out there). However, occasionally have a pixel value that is drawn from a totally different distribution. That is, another distribution may interlope with some frequency. Let's model it!",
"_____no_output_____"
]
],
[
[
"# draw the distribution as per usual\nnsamples = 1000\n\nrandvals = np.round(random.normal(0.5,0.1,nsamples),2)\n\n",
"_____no_output_____"
],
[
"\n# now, some fraction of the time, a large flux is added\n# this is a cosmic ray, with a different\ncosmic_ray_mean = 0.9\ncosmic_ray_sigma = 0.2\nprobability_of_cosmic_ray = 0.02\n\nfor x in range(0,nsamples):\n if random.random() < probability_of_cosmic_ray:\n randvals[x] += np.round(random.normal(cosmic_ray_mean,cosmic_ray_sigma),2)\n\n\n",
"_____no_output_____"
],
[
"# plot as normal\nrand_y_vals = np.zeros_like(randvals)\n\nfor x in range(1,len(randvals)):\n rand_y_vals[x] = len(np.where(randvals[0:x] == randvals[x])[0])\n\n \nplt.figure(figsize=(5,3))\nplt.scatter(randvals,rand_y_vals/nsamples,color='black',s=1.)\n\nmedian_value = np.median(randvals)\nstandard_deviation_value = np.std(randvals)\n\nplt.plot([median_value,median_value],[0.,1.2*np.max(rand_y_vals/nsamples)],color='red',lw=2.)\nplt.plot([median_value-3.*standard_deviation_value,median_value-3.*standard_deviation_value],\\\n [0.,0.6*np.max(rand_y_vals/nsamples)],color='blue',lw=2.)\nplt.plot([median_value+3.*standard_deviation_value,median_value+3.*standard_deviation_value],\\\n [0.,0.6*np.max(rand_y_vals/nsamples)],color='blue',lw=2.)\n\n\n\n\n\n\nplt.xlim(0.,2.)\nplt.title('Pixel Distribution\\nwith cosmic rays',size=24)\nplt.xlabel('Pixel Value',size=24)\nplt.ylabel('# of samples',size=24)",
"_____no_output_____"
]
],
[
[
"Even 2% can be annoying, and we'd want to eliminate them. Note that they also throw the standard deviation off! We'll exploit this principle in a minute to find cosmic rays.\n\nLuckily, it is more obvious if the added flux is large compared to the signal (as is the case for cosmic rays).",
"_____no_output_____"
],
[
"### Part 2: Real Data",
"_____no_output_____"
],
[
"Let's grab some real data and investigate how this works in practice.",
"_____no_output_____"
]
],
[
[
"data_dir = 'sample_data/'\n\nobj_files = glob.glob(data_dir+'*o00*')\nprint('Using files:',obj_files)\n\nphdr = fits.getheader(obj_files[0],0)\ndata = np.zeros([int(phdr['IMNAXIS2']),int(phdr['IMNAXIS1']),len(obj_files)])\n\nfor indx,infile in enumerate(obj_files):\n data[:,:,indx] = fits.getdata(infile)[0:phdr['IMNAXIS2'],0:phdr['IMNAXIS1']] - \\\n np.nanmedian(fits.getdata(infile)[0:4150,phdr['IMNAXIS1']:4150])\n",
"Using files: ['sample_data/c7451t0059o00.fits.gz', 'sample_data/c7451t0060o00.fits.gz', 'sample_data/c7451t0061o00.fits.gz']\n"
],
[
"#\n# do the cross correlations and shift the arrays\n#\n\nshifted_data = np.zeros([int(phdr['IMNAXIS2']),int(phdr['IMNAXIS1']),len(obj_files)])\n\n# first image is the fiducial to match to\nshifted_data[:,:,0] = data[:,:,0]\n\nfor indx in range(1,len(obj_files)):\n xshift,yshift = cross_image(data[:,:,0],data[:,:,indx],boxsize=3000)\n print('Xshift={}, Yshift={}'.format(np.round(xshift,2),np.round(yshift,2)))\n \n # note that these are reversed owing to how HDI stores axes\n shifted_data[:,:,indx] = shift_image(data[:,:,indx],xshift,yshift)\n \n \n# supersede old data:\ndata = shifted_data",
"Xshift=-0.97, Yshift=0.11\nXshift=-1.32, Yshift=-1.16\n"
]
],
[
[
"Let's take a look at a small 5x5 sample of the images to try and understand what the median is actually doing.",
"_____no_output_____"
]
],
[
[
"fig = plt.figure(figsize=(16,12))\n\nax0 = fig.add_axes([0.2,0.2,0.25,0.25])\nax1 = fig.add_axes([0.45,0.2,0.25,0.25])\nax2 = fig.add_axes([0.7,0.2,0.25,0.25])\n\nxmin = 400\nxmax = 5\n\n# set color minimum, maximum\nvmin=np.min(data[xmin:xmin+xmax,xmin:xmin+xmax,:])\nvmax=np.max(data[xmin:xmin+xmax,xmin:xmin+xmax,:])\n\nax0.imshow(data[xmin:xmin+xmax,xmin:xmin+xmax,0],origin='lower',vmin=vmin,vmax=vmax,cmap=cmap,interpolation='none')\nax1.imshow(data[xmin:xmin+xmax,xmin:xmin+xmax,1],origin='lower',vmin=vmin,vmax=vmax,cmap=cmap,interpolation='none')\nax2.imshow(data[xmin:xmin+xmax,xmin:xmin+xmax,2],origin='lower',vmin=vmin,vmax=vmax,cmap=cmap,interpolation='none')\n\nax0.set_xticks([0,2,4])\nax1.set_xticks([0,2,4])\nax2.set_xticks([0,2,4])\n\nax0.set_title('Image 0',size=24)\nax1.set_title('Image 1',size=24)\nax2.set_title('Image 2',size=24)\n\n# this is convolted, but must be like this to plot the numbers correctly!\nfor x in range(xmax-1,-1,-1):\n for y in range(0,xmax):\n ax0.text(y,x,int(data[xmin+x,xmin+y,0]),size=16,color='white',ha='center')\n ax1.text(y,x,int(data[xmin+x,xmin+y,1]),size=16,color='white',ha='center')\n ax2.text(y,x,int(data[xmin+x,xmin+y,2]),size=16,color='white',ha='center')",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(5,5))\n\nax0 = fig.add_axes([0.2,0.2,0.6,0.6])\n\n\nmedian_data = np.median(data[xmin:xmin+xmax,xmin:xmin+xmax,:],axis=2)\n\nax0.imshow(median_data,origin='lower',vmin=vmin,vmax=vmax,cmap=cmap,interpolation='none')\n\nax0.set_xticks([0,2,4])\nax0.set_yticks([0,2,4])\n\nax0.set_title('Median Image',size=24)\n\n# this is convolted, but must be like this to plot the numbers correctly!\nfor x in range(xmax-1,-1,-1):\n for y in range(0,xmax):\n ax0.text(y,x,int(median_data[x,y]),size=16,color='white',ha='center')\n",
"_____no_output_____"
]
],
[
[
"This is much closer to a uniform field!",
"_____no_output_____"
],
[
"We can go one step further and make a two-dimensional sigma map for each image.",
"_____no_output_____"
]
],
[
[
"# make a two-dimensional median and standard deviation map\nmedian_field = np.median(data,axis=2)\nstd_field = np.std(data,axis=2)\n",
"_____no_output_____"
],
[
"# make a map of the sigma values for each pixel\n\ndata_sigma = np.zeros_like(data)\n\nfor indx in range(0,len(obj_files)):\n \n data_sigma[:,:,indx] = (data[:,:,indx] - median_field)/std_field\n \n # blank out bad values\n data_sigma[:,:,indx][~np.isfinite(data_sigma[:,:,indx])] = 0.",
"_____no_output_____"
],
[
"fig = plt.figure(figsize=(16,12))\n\n\nax0 = fig.add_axes([0.2,0.2,0.25,0.25])\nax1 = fig.add_axes([0.45,0.2,0.25,0.25])\nax2 = fig.add_axes([0.7,0.2,0.25,0.25])\n\n\nvmin=np.min(data_sigma[xmin:xmin+xmax,xmin:xmin+xmax,:])\nvmax=np.max(data_sigma[xmin:xmin+xmax,xmin:xmin+xmax,:])\n\n\nax0.imshow(data_sigma[xmin:xmin+xmax,xmin:xmin+xmax,0],vmin=vmin,vmax=vmax,cmap=cmap,interpolation='none')\nax1.imshow(data_sigma[xmin:xmin+xmax,xmin:xmin+xmax,1],vmin=vmin,vmax=vmax,cmap=cmap,interpolation='none')\nax2.imshow(data_sigma[xmin:xmin+xmax,xmin:xmin+xmax,2],vmin=vmin,vmax=vmax,cmap=cmap,interpolation='none')\n\nax0.set_xticks([0,2,4])\nax1.set_xticks([0,2,4])\nax2.set_xticks([0,2,4])\n\nax0.set_title('$\\sigma$ Map 0',size=24)\nax1.set_title('$\\sigma$ Map 1',size=24)\nax2.set_title('$\\sigma$ Map 2',size=24)\n\n\nfor x in range(0,xmax):\n for y in range(0,xmax):\n ax0.text(y,x,np.round(data_sigma[xmin+x,xmin+y,0],1),size=16,color='white',ha='center')\n ax1.text(y,x,np.round(data_sigma[xmin+x,xmin+y,1],1),size=16,color='white',ha='center')\n ax2.text(y,x,np.round(data_sigma[xmin+x,xmin+y,2],1),size=16,color='white',ha='center')",
"_____no_output_____"
]
],
[
[
"The pixels with '0.0' will be the accepted pixels. Why?",
"_____no_output_____"
],
[
"Hey, did you know that you can plot in 3d?",
"_____no_output_____"
]
],
[
[
"from mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure(figsize=(16,4))\n\nxmin = 400\n\n# let's zoom out a little\nxmax = 50\n\n\nmedian_data = np.median(data[xmin:xmin+xmax,xmin:xmin+xmax,:],axis=2)\n\n\n\nxvals = np.arange(0,xmax,1)\nX,Y = np.meshgrid(xvals,xvals)\n\nvmin=np.min(data[xmin:xmin+xmax,xmin:xmin+xmax,:])\nvmax=np.max(data[xmin:xmin+xmax,xmin:xmin+xmax,:])\n\nax0 = fig.add_subplot(1,4,1)\nax0.imshow(data[xmin:xmin+xmax,xmin:xmin+xmax,0],vmin=vmin,vmax=vmax,origin='lower',cmap=cmap,interpolation='none')\nax0.set_title('Noisy Image',size=24)\n\n\nax0 = fig.add_subplot(1,4,2, projection='3d')\nax0.scatter(X,Y,data[xmin:xmin+xmax,xmin:xmin+xmax,0],c=data[xmin:xmin+xmax,xmin:xmin+xmax,1],cmap=cmap,edgecolor='none',vmin=vmin,vmax=vmax)\nax0.scatter(X,Y,data[xmin:xmin+xmax,xmin:xmin+xmax,1],c=data[xmin:xmin+xmax,xmin:xmin+xmax,1], cmap=cmap,edgecolor='none',vmin=vmin,vmax=vmax)\nax0.scatter(X,Y,data[xmin:xmin+xmax,xmin:xmin+xmax,2],c=data[xmin:xmin+xmax,xmin:xmin+xmax,2], cmap=cmap,edgecolor='none',vmin=vmin,vmax=vmax)\nax0.set_title('Data Scatter',size=24)\n\n\n\n# set the viewing angle\nax0.view_init(22, -135)\n\nax1 = fig.add_subplot(1,4,3, projection='3d')\nax1.scatter(X,Y,median_data,c=median_data,cmap=cmap,edgecolor='none',vmin=vmin,vmax=vmax)\n\nax1.view_init(22, -135)\nax1.set_title('Median Scatter',size=24)\n\nax2 = fig.add_subplot(1,4,4)\nax2.imshow(median_data,vmin=vmin,vmax=vmax,origin='lower',cmap=cmap,interpolation='none')\n_ = ax2.set_title('Medianed Image',size=24)",
"_____no_output_____"
]
],
[
[
"Does sigma clipping actually work?\n\nLet's go back to the standard deviation map and spot check some of the large values to see what exactly we are getting rid of by taking the median:",
"_____no_output_____"
]
],
[
[
"w = np.where(std_field > 10000.)\n\n# spot check 10\nfor indx in range(100,110):\n pix_vals = np.round(data[w[0][indx],w[1][indx]],0)\n print(pix_vals[pix_vals.argsort()])",
"[ 2073. 55037. 64976.]\n[ 2596. 8023. 61346.]\n[ 3110. 9159. 53838.]\n[ 13943. 25793. 57793.]\n[ 4204. 9101. 56210.]\n[ 26928. 45225. 59656.]\n[ 4488. 9781. 60405.]\n[ 4808. 10328. 57717.]\n[ 5284. 10831. 41306.]\n[ 12125. 59614. 62673.]\n"
],
[
"# spot check 10: convert to sigmas\nfor indx in range(100,110):\n \n pix_vals = data[w[0][indx],w[1][indx]]\n sigma_pix = np.std(pix_vals)\n median_pix = np.median(pix_vals)\n \n sorted_pix = pix_vals[pix_vals.argsort()]\n \n print(np.round(((sorted_pix-median_pix)/sigma_pix),2))",
"[-1.92 0. 0.36]\n[-0.2 0. 2.01]\n[-0.27 0. 1.97]\n[-0.64 0. 1.73]\n[-0.21 0. 2.01]\n[-1.37 0. 1.08]\n[-0.21 0. 2.01]\n[-0.23 0. 2. ]\n[-0.35 0. 1.92]\n[-2.05 0. 0.13]\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"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbb249bb0e318d489b45d9e238556e085404e02f
| 22,766 |
ipynb
|
Jupyter Notebook
|
Getting Split Dates.ipynb
|
PundirShivam/tradetest
|
9f62740b685c017983e33e23eaa35141b13047f1
|
[
"MIT"
] | null | null | null |
Getting Split Dates.ipynb
|
PundirShivam/tradetest
|
9f62740b685c017983e33e23eaa35141b13047f1
|
[
"MIT"
] | null | null | null |
Getting Split Dates.ipynb
|
PundirShivam/tradetest
|
9f62740b685c017983e33e23eaa35141b13047f1
|
[
"MIT"
] | 1 |
2021-12-15T13:06:37.000Z
|
2021-12-15T13:06:37.000Z
| 30.806495 | 135 | 0.320961 |
[
[
[
"import requests\nimport pandas as pd",
"_____no_output_____"
],
[
"# df = pd.read_html('https://www.moneycontrol.com/stocks/marketinfo/splits/homebody.php?sel_year=1989',header=0)\nimport os\nos.chdir('E:\\\\years\\\\')",
"_____no_output_____"
],
[
"def getFrame(df):\n for d in df:\n if len(d.columns)==4:\n return d",
"_____no_output_____"
],
[
"def getSplitFiles():\n for yr in range(1989,2020):\n try:\n df = pd.read_html('https://www.moneycontrol.com/stocks/marketinfo/splits/homebody.php?sel_year='+str(yr),header=0)\n df = getFrame(df).dropna()\n df.to_csv(str(yr)+'.csv')\n print yr,'completed '\n except:\n print yr,'not processed'\n pass",
"_____no_output_____"
],
[
"getSplitFiles()",
"1989 completed \n1990 completed \n1991 completed \n"
],
[
"def combineFiles():\n df = pd.DataFrame()\n for yr in range(1989,2020):\n temp = pd.read_csv(str(yr)+'.csv',header=1)\n df = pd.concat([df,temp],sort=False)\n return df.filter(['Company','Old FV','New FV','Split Date'])",
"_____no_output_____"
],
[
"df = combineFiles().drop_duplicates()\ndf.to_csv('split.csv')",
"_____no_output_____"
],
[
"df['Split'] = df['Old FV']/df['New FV']",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb24cea9826591636b0f0f416935e63c5864920
| 42,583 |
ipynb
|
Jupyter Notebook
|
amld2022_forecasting_meta_learning.ipynb
|
ybex/CustomModules
|
cfb463f6ed2c2cfb3d7dff0d604d494692f7c3fb
|
[
"MIT"
] | null | null | null |
amld2022_forecasting_meta_learning.ipynb
|
ybex/CustomModules
|
cfb463f6ed2c2cfb3d7dff0d604d494692f7c3fb
|
[
"MIT"
] | null | null | null |
amld2022_forecasting_meta_learning.ipynb
|
ybex/CustomModules
|
cfb463f6ed2c2cfb3d7dff0d604d494692f7c3fb
|
[
"MIT"
] | null | null | null | 37.918967 | 644 | 0.526713 |
[
[
[
"<a href=\"https://colab.research.google.com/github/ybex/CustomModules/blob/master/amld2022_forecasting_meta_learning.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# AMLD 2022 Forecasting & Meta Learning Workshop\n\nIn this notebook, we will get our hands dirty with Darts. We will do the following things:\n\n* **Part 1:** Forecasting passenger counts series for 300 airlines (`air` dataset). We will train one model per series.\n* **Part 2:** Using \"global\" models - i.e., models trained on all 300 series simultaneously. Here we split every timeseries into data from the trainset and data from the testset.\n* **Part 3:** We will try some *meta learning*, and see what happens if we train some global models on one (big) dataset (`m4` dataset) and use them on another dataset. Compared to part 2, m4 is the trainset and m3 will be our testset.\n* **Part 4:** We will reuse our pre-trained model(s) of Part 3 on another new dataset (`m3` dataset) and see how it compares to models specifically trained on this dataset.\n\n## Part 0: Setup (No code to write - execute only)\nFirst, we need to install the right libraries and make the right imports. For the deep learning models, it will help to use a GPU runtime. To get a GPU instance, click on the \"RAM/Disk\" info bars on the upper right, select \"Change runtime type\" and choose a GPU as hardware accelerator. The following command will show you the GPU available (if any). If there's no GPU available, you can still go ahead and work on CPU.",
"_____no_output_____"
]
],
[
[
"# You can run this command to see if there's a GPU:\n!nvidia-smi",
"NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.\n\n"
],
[
"!pip install darts &> /dev/null\n!pip install pyyaml==5.4.1 &> /dev/null\n!pip install xlrd==2.0.1 &> /dev/null\n!pip install matplotlib==3.1.3 &> /dev/null",
"_____no_output_____"
]
],
[
[
"Don't be afraid, we will uncover what these imports mean through the workshop :)",
"_____no_output_____"
]
],
[
[
"# filter out unecessary warnings during import\nimport warnings\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
],
[
"%matplotlib inline\n\nimport os\nimport pickle\nimport random\nimport time\nfrom datetime import datetime\nfrom typing import Dict, List, Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport requests\nimport seaborn as sns\nimport torch\nimport tqdm.notebook as tq\nfrom pytorch_lightning.callbacks import Callback, EarlyStopping\nfrom sklearn.linear_model import Ridge\nfrom sklearn.preprocessing import MaxAbsScaler, MinMaxScaler\nfrom torch import nn\n\nfrom darts import TimeSeries\nfrom darts.dataprocessing.transformers import Scaler\nfrom darts.metrics import mape, mase, smape\nfrom darts.models import *\nfrom darts.utils.data import HorizonBasedDataset\nfrom darts.utils.losses import SmapeLoss\nfrom darts.utils.utils import ModelMode, SeasonalityMode, TrendMode",
"_____no_output_____"
]
],
[
[
"We define the forecast horizon here - for all of the (monthly) time series used in this notebook, we'll be interested in forecasting 18 months in advance. We pick 18 months as this is what is used in the M3/M4 competitions for monthly series.",
"_____no_output_____"
]
],
[
[
"HORIZON = 18",
"_____no_output_____"
]
],
[
[
"### Datasets loading methods\nHere, we define some helper methods to load the three datasets we'll be playing with: `air`, `m3` and `m4`. \n\nFirst, we download the datasets (Note: we processed some of the datasets as pickle files for simplicity and speed):",
"_____no_output_____"
]
],
[
[
"# Execute this cell once to download all three datasets\n!curl -L https://github.com/unit8co/amld2022-forecasting-and-metalearning/blob/main/data/m3_dataset.xls\\?raw\\=true -o m3_dataset.xls\n!curl -L https://github.com/unit8co/amld2022-forecasting-and-metalearning/blob/main/data/passengers.pkl\\?raw\\=true -o passengers.pkl\n!curl -L https://github.com/unit8co/amld2022-forecasting-and-metalearning/blob/main/data/m4_monthly_scaled.pkl\\?raw\\=true -o m4_monthly_scaled.pkl",
" % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 159 100 159 0 0 819 0 --:--:-- --:--:-- --:--:-- 819\n100 170 100 170 0 0 258 0 --:--:-- --:--:-- --:--:-- 166k\n100 1716k 100 1716k 0 0 1753k 0 --:--:-- --:--:-- --:--:-- 1753k\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 159 100 159 0 0 815 0 --:--:-- --:--:-- --:--:-- 811\n100 178 100 178 0 0 635 0 --:--:-- --:--:-- --:--:-- 635\n100 1100k 100 1100k 0 0 1534k 0 --:--:-- --:--:-- --:--:-- 1534k\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 166 100 166 0 0 917 0 --:--:-- --:--:-- --:--:-- 917\n100 185 100 185 0 0 649 0 --:--:-- --:--:-- --:--:-- 649\n100 270M 100 270M 0 0 43.9M 0 0:00:06 0:00:06 --:--:-- 58.0M\n"
]
],
[
[
"All the methods below return two list of `TimeSeries`: one list of training series and one list of \"test\" series (of length `HORIZON`).\n\nFor convenience, all the series are already scaled here, by multiplying each of them by a constant so that the largest value is 1. Such scaling is necessary for many models to work correctly (esp. deep learning models). It does not affect the sMAPE values, so we can evaluate the accuracy of our algorithms on the scaled series. In a real application, we would have to keep the Darts `Scaler` objects somewhere in order to inverse-scale the forecasts.",
"_____no_output_____"
]
],
[
[
"def load_m3() -> Tuple[List[TimeSeries], List[TimeSeries]]:\n print('building M3 TimeSeries...')\n\n # Read DataFrame\n df_m3 = (pd.read_excel('m3_dataset.xls', 'M3Month'))\n\n # Build TimeSeries\n m3_series = []\n for row in tq.tqdm(df_m3.iterrows(), position=0, leave=True):\n s = row[1]\n start_year = int(s['Starting Year'])\n start_month = int(s['Starting Month'])\n values_series = s[6:].dropna()\n if start_month == 0:\n continue\n \n start_date = datetime(year=start_year, month=start_month, day=1)\n time_axis = pd.date_range(start_date, periods=len(values_series), freq='M')\n series = TimeSeries.from_times_and_values(time_axis, values_series.values).astype(np.float32)\n m3_series.append(series)\n\n print('\\nThere are {} monthly series in the M3 dataset'.format(len(m3_series)))\n\n # Split train/test\n print('splitting train/test...')\n m3_train = [s[:-HORIZON] for s in m3_series]\n m3_test = [s[-HORIZON:] for s in m3_series]\n\n # Scale so that the largest value is 1\n print('scaling...')\n scaler_m3 = Scaler(scaler=MaxAbsScaler())\n m3_train_scaled: List[TimeSeries] = scaler_m3.fit_transform(m3_train)\n m3_test_scaled: List[TimeSeries] = scaler_m3.transform(m3_test)\n\n print('done. There are {} series, with average training length {}'.format(\n len(m3_train_scaled), np.mean([len(s) for s in m3_train_scaled])\n ))\n return m3_train_scaled, m3_test_scaled\n\ndef load_air() -> Tuple[List[TimeSeries], List[TimeSeries]]:\n # load TimeSeries\n print('loading air TimeSeries...')\n with open('passengers.pkl', 'rb') as f:\n all_air_series = pickle.load(f)\n\n # Split train/test\n print('splitting train/test...')\n air_train = [s[:-HORIZON] for s in all_air_series]\n air_test = [s[-HORIZON:] for s in all_air_series]\n\n # Scale so that the largest value is 1\n print('scaling series...')\n scaler_air = Scaler(scaler=MaxAbsScaler())\n air_train_scaled: List[TimeSeries] = scaler_air.fit_transform(air_train)\n air_test_scaled: List[TimeSeries] = scaler_air.transform(air_test)\n\n print('done. There are {} series, with average training length {}'.format(\n len(air_train_scaled), np.mean([len(s) for s in air_train_scaled])\n ))\n return air_train_scaled, air_test_scaled\n\ndef load_m4() -> Tuple[List[TimeSeries], List[TimeSeries]]:\n # load TimeSeries - the splitting and scaling has already been done\n print('loading M4 TimeSeries...')\n with open('m4_monthly_scaled.pkl', 'rb') as f:\n m4_series = pickle.load(f)\n m4_train_scaled, m4_test_scaled = zip(*m4_series)\n\n print('done. There are {} series, with average training length {}'.format(\n len(m4_train_scaled), np.mean([len(s) for s in m4_train_scaled])\n ))\n return m4_train_scaled, m4_test_scaled",
"_____no_output_____"
]
],
[
[
"Finally, we define a handy function to tell us how good a bunch of forecasted series are:",
"_____no_output_____"
]
],
[
[
"def eval_forecasts(pred_series: List[TimeSeries], \n test_series: List[TimeSeries]) -> List[float]:\n \n print('computing sMAPEs...')\n smapes = smape(test_series, pred_series)\n mean, std = np.mean(smapes), np.std(smapes)\n print('Avg sMAPE: %.3f +- %.3f' % (mean, std))\n plt.figure(figsize=(4,4), dpi=144)\n plt.hist(smapes, bins=50)\n plt.ylabel('Count')\n plt.xlabel('sMAPE')\n plt.show()\n plt.close()\n return smapes",
"_____no_output_____"
]
],
[
[
"## Part 1: Local models on the `air` dataset\n\n### Preparing Data\n\nThe `air` dataset shows the number of air passengers that flew in or out of the USA per carrier (or airline company) from the year 2000 until 2019.\n\n**Your turn:** First, you can load the train and test series by calling `load_air()` function that we have defined above.",
"_____no_output_____"
]
],
[
[
"air_train, air_test = ...",
"_____no_output_____"
]
],
[
[
"It's a good idea to start by visualising a few of the series to get a sense of what they look like. We can plot a series by calling `series.plot()`.",
"_____no_output_____"
]
],
[
[
"for i in [1, 20, 50, 100, 250]: # Feel free to plot a few other series\n plt.figure(figsize=(4,4), dpi=144)\n air_train[i].plot()\n plt.ylabel('Passengers')\n plt.xlabel('Time')\n plt.show()\n plt.close()",
"_____no_output_____"
]
],
[
[
"We can see that most series look quite different, and they even have different time axes. \n\nQuestion: What is the shortest series available?",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"### A useful function to evaluate models\n\nBelow, we write a small function that will make our life easier for quickly trying and comparing different local models. We loop through each serie, fit a model and then evaluate on our test dataset. \n\n> ⚠️ Please note `tq.tqdm` is optional and is only there to help display the training progress (as you will see it can take some time when training 300+ time series)\n",
"_____no_output_____"
]
],
[
[
"def eval_local_model(train_series: List[TimeSeries], \n test_series: List[TimeSeries], \n model_cls, \n **kwargs) -> Tuple[List[float], float]:\n preds = []\n start_time = time.time()\n for series in tq.tqdm(train_series):\n model = model_cls(**kwargs)\n model.fit(series)\n pred = model.predict(n=HORIZON)\n preds.append(pred)\n elapsed_time = time.time() - start_time\n \n smapes = eval_forecasts(preds, test_series)\n return smapes, elapsed_time",
"_____no_output_____"
]
],
[
[
"### Building and evaluating models\n\nWe can now try a first forecasting model on this dataset. As a first step, it is usually a good practice to see how a (very) naive model blindly repeating the last value of the training series performs. This can be done in Darts using a [NaiveSeasonal](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.baselines.html#darts.models.forecasting.baselines.NaiveSeasonal) model:",
"_____no_output_____"
]
],
[
[
"naive_seasonal_last_smapes, naive_seasonal_last_elapsed_time = eval_local_model(air_train, air_test, NaiveSeasonal, K=1)",
"_____no_output_____"
]
],
[
[
"So the most naive model gives us a sMAPE of about 39.38.\n\n**Your turn:** Can we do better with a \"less naive\" model exploiting the fact that most monthly series have a seasonality of 12?",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
]
],
[
[
"All of the Darts forecasting models can be trained and used in the same way!\nSo we invite you to go over the [list of models in the API documentation](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.html) and try a few more models. Here are some suggestions:\n\n* `ExponentialSmoothing`\n* `Theta`\n* `ARIMA` - but the default parameters probably won't do very well. Using `p=12`, `d=1`, `q=0` might be a good start.\n* ... Your ideas here!\n\nWe recommend that you keep track of the SMAPEs and elapsed times for each model. Later we will use these values for quickly comparing models. Some models will take longer than others to run. Don't hesitate to interrupt the execution or run only on a subset of series.\n\n**Your turn:** Try to get the lowest possible errors with some other models of your choice.",
"_____no_output_____"
]
],
[
[
"# model_X_smapes, model_X_elapsed_time = eval_local_model(air_train, air_test, ModelX, **hyper_params_for_model_X)",
"_____no_output_____"
]
],
[
[
"### Comparing models\n\nBelow, we define a couple of functions that we will use to obtain an overview of the SMAPEs and time required to obtain the predictions.",
"_____no_output_____"
]
],
[
[
"def smapes_boxplot(method_to_smapes: Dict[str, List[float]], title: str):\n method_names = []\n smapes = []\n for curr_method_name, curr_smapes in method_to_smapes.items():\n method_names += [curr_method_name] * len(curr_smapes)\n smapes += curr_smapes\n smapes_df = pd.DataFrame({'Method': method_names, 'sMAPE': smapes})\n plt.figure(figsize=(7,4), dpi=144)\n ax = sns.boxplot(x=\"Method\", y=\"sMAPE\", data=smapes_df)\n ax.grid(False)\n # Display median score on each box\n medians = smapes_df.groupby(['Method'])['sMAPE'].median().round(decimals=2)\n vertical_offset = smapes_df['sMAPE'].median() * 0.1\n for xtick, name in enumerate(method_to_smapes.keys()):\n ax.text(xtick, medians[name] + vertical_offset, medians[name], \n horizontalalignment='center', size='x-small', color='w', weight='semibold')\n plt.xticks(rotation=90) \n plt.title(title) \n plt.show()\n plt.close()\n\ndef elapsed_time_barplot(method_to_elapsed_times: Dict[str, float], title: str):\n elapsed_times_df = pd.DataFrame({'Method': method_to_elapsed_times.keys(), 'Elapsed time [s]': method_to_elapsed_times.values()})\n ax = plt.figure(figsize=(7,4), dpi=144)\n sns.barplot(x=\"Method\", y=\"Elapsed time [s]\", data=elapsed_times_df)\n plt.xticks(rotation=90) \n plt.title(title) \n plt.show()\n plt.close()",
"_____no_output_____"
]
],
[
[
"**Your turn:** We are now ready to visualise our models. Fill in the cells below to call `smapes_boxplot()` and `elpased_time_barplot()` with the right arguments.",
"_____no_output_____"
]
],
[
[
"smapes = {\n 'naive-last': naive_seasonal_last_smapes,\n # 'model_X': model_X_smapes,\n # ...\n}\n\nsmapes_boxplot(smapes, title='sMAPEs on air passengers dataset')",
"_____no_output_____"
],
[
"elapsed_times = {\n 'naive-last': naive_seasonal_last_elapsed_time, \n # 'model_X': model_X_elapsed_time,\n # ...\n}\n\nelapsed_time_barplot(elapsed_times, title='Predict durations on air passengers dataset')",
"_____no_output_____"
]
],
[
[
"You can also try to directly predict some of the forecasts in order to visualise them.\n\nWhat are your conclusions so far?\n\nWhat are your best forecasts? Let us know!\n\n## Part 2: Global models on the `air` dataset\nIn this section we will use \"global models\" - that is, models that fit on multiple series at once. Darts has essentially two kinds of global models:\n* `RegressionModels` which are wrappers around sklearn-like regression models (Part 2.1).\n* PyTorch-based models, which offer various deep learning models (Part 2.2).\n\nBoth models can be trained on multiple series by \"tabularizing\" the data - i.e., taking many (input, output) sub-slices from all the training series, and training machine learning models in a supervised fashion to predict the output based on the input.\n\n**Your turn** We will start by defining a function `eval_global_model()` which works similarly to `eval_local_model()`, but on global models. You can complete it below (hint: you will not need the for-loop that was present in `eval_local_model()`).",
"_____no_output_____"
]
],
[
[
"def eval_global_model(train_series: List[TimeSeries], \n test_series: List[TimeSeries], \n model_cls, \n **kwargs) -> Tuple[List[float], float]:\n\n start_time = time.time()\n \n model = ... # build your model here\n\n ... # fit your model here\n\n ... # get some predictions here\n\n elapsed_time = time.time() - start_time\n \n smapes = eval_forecasts(preds, test_series)\n return smapes, elapsed_time",
"_____no_output_____"
]
],
[
[
"### Part 2.1: Using Darts `RegressionModel`s.\n`RegressionModel` in Darts are forecasting models that can wrap around any \"scikit-learn compatible\" regression model to obtain forecasts. Compared to deep learning, they represent good \"go-to\" global models because they typically don't have many hyper-parameters and can be faster to train. In addition, Darts also offers some \"pre-packaged\" regression models such as `LinearRegressionModel` and `LightGBMModel`.\n\nWe'll now use our function `eval_global_models()`. In the following cells, you can try using some regression models, for example:\n* `LinearRegressionModel`\n* `LightGBMModel`\n* `RegressionModel`(your_sklearn_model)\n\nYou can refer to [the API doc](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.regression_model.html) for how to use them.\n\nImportant parameters are `lags` and `output_chunk_length`. They determine respectively the length of the lookback and \"lookforward\" windows used by the model, and they correspond to the lengths of the input/output subslices used for training. For instance `lags=24` and `output_chunk_length=12` mean that the model will consume the past 24 lags in order to predict the next 12. In our case, because the shortest training series has length 36, we must have `lags + output_chunk_length <= 36`. (Note that `lags` can also be a list of integers representing the individual lags to be consumed by the model instead of the window length).",
"_____no_output_____"
]
],
[
[
"# model_X_smapes, model_X_elapsed_time = eval_global_model(air_train, air_test, GlobalModelX, **hyper_params_for_model_X)",
"_____no_output_____"
]
],
[
[
"### Part 2.2: Using deep learning\nBelow, we will train an N-BEATS model on our `air` dataset. Again, you can refer to [the API doc](https://unit8co.github.io/darts/generated_api/darts.models.forecasting.nbeats.html) for documentation on the hyper-parameters.\nThe following hyper-parameters should be a good starting point, and training should take in the order of a minute or two.\n\nDuring training, you can have a look at the [N-BEATS paper](https://arxiv.org/abs/1905.10437).",
"_____no_output_____"
]
],
[
[
"### Possible N-BEATS hyper-parameters\n\n# Slicing hyper-params:\nIN_LEN = 24\nOUT_LEN = 12\n\n# Architecture hyper-params:\nNUM_STACKS = 18\nNUM_BLOCKS = 3\nNUM_LAYERS = 3\nLAYER_WIDTH = 180\nCOEFFS_DIM = 6\nLOSS_FN = SmapeLoss()\n\n# Training settings:\nLR = 5e-4\nBATCH_SIZE = 1024\nNUM_EPOCHS = 4",
"_____no_output_____"
]
],
[
[
"You can now complete the skeleton below to build, train and predict using an N-BEATS model:",
"_____no_output_____"
]
],
[
[
"# reproducibility\nnp.random.seed(42)\ntorch.manual_seed(42)\n\n## Use this to specify \"optimizer_kwargs\" parameter of the N-BEATS model:\noptimizer_kwargs={'lr': LR},\n\n## In addition, when using a GPU, you should specify this for \n## the \"pl_trainer_kwargs\" parameter of the N-BEATS model:\npl_trainer_kwargs={\"enable_progress_bar\": True, \n \"accelerator\": \"gpu\",\n \"gpus\": -1,\n \"auto_select_gpus\": True}\n\nstart_time = time.time()\n\nnbeats_model_air = ... # Build the N-BEATS model here\n\nnbeats_model_air.fit(..., # fill in series to train on\n ...) # fill in number of epochs\n\n# get predictions\nnb_preds = ...\n\nnbeats_smapes = eval_forecasts(nb_preds, air_test)\nnbeats_elapsed_time = time.time() - start_time",
"_____no_output_____"
],
[
"smapes_2 = {**smapes,\n **{\n # ... Fill in here sMAPEs values of any global model you tried\n 'NBeats': nbeats_smapes,\n }\n}\nsmapes_boxplot(smapes_2, title='sMAPEs on air')",
"_____no_output_____"
],
[
"elapsed_time_2 = {**elapsed_times,\n **{\n # ... Fill in here duration values of any global model you tried\n 'NBeats': nbeats_elapsed_time,\n }\n}\nelapsed_time_barplot(elapsed_time_2, title='Durations on air')",
"_____no_output_____"
]
],
[
[
"What are your conclusions so far, and which results did you manage to get (let us know!)\n\n## Part 3: Training an N-BEATS model on `m4` dataset and use it to forecast `air` dataset\nDeep learning models often do better when trained on *large* datasets. Let's try to load all 48,000 monthly time series in the M4 dataset and train our model once more on this larger dataset.",
"_____no_output_____"
]
],
[
[
"m4_train, m4_test = load_m4()\n\n# filter to keep only those that are long enough\nm4_train = [s for s in m4_train if len(s) >= 48]\nm4_test = [s for s in m4_test if len(s) >= 48]\n\nprint('There are {} series of length >= 48.'.format(len(m4_train)))",
"loading M4 TimeSeries...\ndone. There are 48000 series, with average training length 216.30022916666667\nThere are 47992 series of length >= 48.\n"
]
],
[
[
"We can start from the same hyper-parameters as before. \n\nWith 48,000 M4 training series being on average ~200 time steps long, we would end up with ~10M training samples. With such a number of training samples, each epoch would take too long. So here, we'll limit the number of training samples used per series. This is done when calling `fit()` with the parameter `max_samples_per_ts`. We add a new hyper-parameter `MAX_SAMPLES_PER_TS` to capture this.\n\nSince the M4 training series are all >= 48 time steps long, we can also use a longer `input_chunk_length` of 36.",
"_____no_output_____"
]
],
[
[
"# Slicing hyper-params:\nIN_LEN = 36\nOUT_LEN = 12\n\n# Architecture hyper-params:\nNUM_STACKS = 18\nNUM_BLOCKS = 3\nNUM_LAYERS = 3\nLAYER_WIDTH = 180\nCOEFFS_DIM = 6\n\n# Training settings:\nLR = 5e-4\nBATCH_SIZE = 1024\nMAX_SAMPLES_PER_TS = 8 # <-- new param, limiting nr of training samples per epoch\nNUM_EPOCHS = 4",
"_____no_output_____"
]
],
[
[
"You can now build and train the model, as before.\n\nRunning this cell with the proposed hyper-parameters should take ~10 minutes on a Colab GPU. \n\n*If this is taking too long, you can also simply run the next cell, which will download and load the same N-BEATS pre-trained on M4 with these hyper-parameters.*",
"_____no_output_____"
]
],
[
[
"# reproducibility\nnp.random.seed(42)\ntorch.manual_seed(42)\n\nnbeats_model_m4 = NBEATSModel(..., # fill in hyper-params\n \n # learning rate goes here\n optimizer_kwargs={'lr': LR},\n\n # remove this one if your notebook does not have a GPU:\n pl_trainer_kwargs={\"enable_progress_bar\": True, \n \"accelerator\": \"gpu\",\n \"gpus\": -1,\n \"auto_select_gpus\": True},\n )\n\n# Train\nnbeats_model_m4.fit(..., # fill in series to train on\n ..., # fill in number of epochs\n ...) # fill in max number of samples per time series",
"_____no_output_____"
]
],
[
[
"The cell below will download a pre-trained version of this N-BEATS model - you can run this if training takes too long in your case:",
"_____no_output_____"
]
],
[
[
"## /!\\ RUNNING THIS CELL WILL DOWNLOAD AND OVERWRITE THE MODEL nbeats_model_m4\n\n# Load already trained model\n!curl -L https://github.com/unit8co/amld2022-forecasting-and-metalearning/blob/main/data/nbeats_model_m4.pth.tar\\?raw\\=true -o nbeats_model_m4.pth.tar\nnbeats_model_m4 = NBEATSModel.load_model('nbeats_model_m4.pth.tar')",
"_____no_output_____"
]
],
[
[
"We can now use our M4-trained model to get forecasts for the air passengers series. As we use the model in a \"meta learning\" (or transfer learning) way here, we will be timing only the inference part.",
"_____no_output_____"
]
],
[
[
"start_time = time.time()\npreds = ... # get forecasts\nnbeats_m4_smapes = eval_forecasts(preds, air_test)\nnbeats_m4_elapsed_time = time.time() - start_time",
"_____no_output_____"
]
],
[
[
"What are your conclusions?\n\n### Try training other global models on `m4` and applying on airline passengers\nYou can now try to train other global models on the M4 dataset in order to see if we can get similar results. If that's taking too long, it might be a good idea to take only e.g., 5000 or 10000 time series. You can do this easily by training on, say, `random.choices(m4_train, k=5000)` instead of `m4_train`. You will again need to specify some small enough value for `max_samples_per_ts` in order to limit the number of training samples.",
"_____no_output_____"
]
],
[
[
"# model_X = GlobalModelX(...)\n# model_X.fit(...,\n# max_samples_per_ts=...)",
"_____no_output_____"
],
[
"start_time = time.time()\n# preds = ... # Get predictions\n# model_X_smapes = eval_forecasts(preds, air_test) # compute errors\n# model_X_elapsed_time = time.time() - start_time # store timing",
"_____no_output_____"
]
],
[
[
"Let's now compare how our different models are doing",
"_____no_output_____"
]
],
[
[
"smapes_3 = {**smapes_2,\n **{\n 'N-BEATS M4': nbeats_m4_smapes,\n # 'model_X': model_X_smapes\n }\n}\nsmapes_boxplot(smapes_3, title='sMAPEs on air')\n\nelapsed_time_3 = {**elapsed_time_2,\n **{\n 'NBeats M4': nbeats_m4_elapsed_time,\n # 'model_X': model_X_elapsed_time\n }\n}\nelapsed_time_barplot(elapsed_time_3, title='Durations on air')",
"_____no_output_____"
]
],
[
[
"## Part 4: Forecasting the `m3` dataset\n\nUntil now, we have seen that we can use some M4-trained models to predict another dataset, namely the `air` dataset.\nBut can we try to convince ourselves a bit more, and try the same approach on a third dataset?\n\nIn this part of the notebook, we propose to consolidate all our learnings so far using the `m3` dataset:\n* Try fitting local models directly on `m3`\n* Try fitting global ML models directly on `m3` --> how far can you push it?\n* Try applying our previous M4-trained model on `m3` --> what are your conclusions?\n\nHint: The Theta model was one of the best performing model during the M3 competition.",
"_____no_output_____"
]
],
[
[
"# First, load the actual dataset\nm3_train, m3_test = load_m3()",
"_____no_output_____"
],
[
"# Then try your models :)",
"_____no_output_____"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbb26345f615e3e532f23c25048145bdebd1a947
| 13,045 |
ipynb
|
Jupyter Notebook
|
CSW/csw_unidata.ipynb
|
petercunning/notebook
|
5b26f2dc96bcb36434542b397de6ca5fa3b61a0a
|
[
"MIT"
] | 32 |
2015-01-07T01:48:05.000Z
|
2022-03-02T07:07:42.000Z
|
CSW/csw_unidata.ipynb
|
petercunning/notebook
|
5b26f2dc96bcb36434542b397de6ca5fa3b61a0a
|
[
"MIT"
] | 1 |
2015-04-13T21:00:18.000Z
|
2015-04-13T21:00:18.000Z
|
CSW/csw_unidata.ipynb
|
petercunning/notebook
|
5b26f2dc96bcb36434542b397de6ca5fa3b61a0a
|
[
"MIT"
] | 30 |
2015-01-28T09:31:29.000Z
|
2022-03-07T03:08:28.000Z
| 36.954674 | 1,986 | 0.60138 |
[
[
[
"# How to search the IOOS CSW catalog with Python tools\n\n\nThis notebook demonstrates a how to query a [Catalog Service for the Web (CSW)](https://en.wikipedia.org/wiki/Catalog_Service_for_the_Web), like the IOOS Catalog, and to parse its results into endpoints that can be used to access the data.",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\n\nioos_tools = os.path.join(os.path.pardir)\nsys.path.append(ioos_tools)",
"_____no_output_____"
]
],
[
[
"Let's start by creating the search filters.\nThe filter used here constraints the search on a certain geographical region (bounding box), a time span (last week), and some [CF](http://cfconventions.org/Data/cf-standard-names/37/build/cf-standard-name-table.html) variable standard names that represent sea surface temperature.",
"_____no_output_____"
]
],
[
[
"from datetime import datetime, timedelta\nimport dateutil.parser\n\nservice_type = 'WMS'\n\nmin_lon, min_lat = -90.0, 30.0 \nmax_lon, max_lat = -80.0, 40.0 \n\nbbox = [min_lon, min_lat, max_lon, max_lat]\ncrs = 'urn:ogc:def:crs:OGC:1.3:CRS84'\n\n# Temporal range: Last week.\nnow = datetime.utcnow()\nstart, stop = now - timedelta(days=(7)), now\n\nstart = dateutil.parser.parse('2017-03-01T00:00:00Z')\nstop = dateutil.parser.parse('2017-04-01T00:00:00Z')\n\n\n# Ocean Model Names\nmodel_names = ['NAM', 'GFS']",
"_____no_output_____"
]
],
[
[
"With these 3 elements it is possible to assemble a [OGC Filter Encoding (FE)](http://www.opengeospatial.org/standards/filter) using the `owslib.fes`\\* module.\n\n\\* OWSLib is a Python package for client programming with Open Geospatial Consortium (OGC) web service (hence OWS) interface standards, and their related content models.",
"_____no_output_____"
]
],
[
[
"from owslib import fes\nfrom ioos_tools.ioos import fes_date_filter\n\nkw = dict(wildCard='*', escapeChar='\\\\',\n singleChar='?', propertyname='apiso:AnyText')\n\nor_filt = fes.Or([fes.PropertyIsLike(literal=('*%s*' % val), **kw)\n for val in model_names])\n\nkw = dict(wildCard='*', escapeChar='\\\\',\n singleChar='?', propertyname='apiso:ServiceType')\n\nserviceType = fes.PropertyIsLike(literal=('*%s*' % service_type), **kw)\n\n\nbegin, end = fes_date_filter(start, stop)\nbbox_crs = fes.BBox(bbox, crs=crs)\n\nfilter_list = [\n fes.And(\n [\n bbox_crs, # bounding box\n begin, end, # start and end date\n or_filt, # or conditions (CF variable names)\n serviceType # search only for datasets that have WMS services\n ]\n )\n]",
"_____no_output_____"
],
[
"from owslib.csw import CatalogueServiceWeb\n\n\nendpoint = 'https://data.ioos.us/csw'\n\ncsw = CatalogueServiceWeb(endpoint, timeout=60)",
"_____no_output_____"
]
],
[
[
"The `csw` object created from `CatalogueServiceWeb` did not fetched anything yet.\nIt is the method `getrecords2` that uses the filter for the search. However, even though there is a `maxrecords` option, the search is always limited by the server side and there is the need to iterate over multiple calls of `getrecords2` to actually retrieve all records.\nThe `get_csw_records` does exactly that.",
"_____no_output_____"
]
],
[
[
"def get_csw_records(csw, filter_list, pagesize=10, maxrecords=1000):\n \"\"\"Iterate `maxrecords`/`pagesize` times until the requested value in\n `maxrecords` is reached.\n \"\"\"\n from owslib.fes import SortBy, SortProperty\n # Iterate over sorted results.\n sortby = SortBy([SortProperty('dc:title', 'ASC')])\n csw_records = {}\n startposition = 0\n nextrecord = getattr(csw, 'results', 1)\n while nextrecord != 0:\n csw.getrecords2(constraints=filter_list, startposition=startposition,\n maxrecords=pagesize, sortby=sortby)\n csw_records.update(csw.records)\n if csw.results['nextrecord'] == 0:\n break\n startposition += pagesize + 1 # Last one is included.\n if startposition >= maxrecords:\n break\n csw.records.update(csw_records)",
"_____no_output_____"
],
[
"get_csw_records(csw, filter_list, pagesize=10, maxrecords=1000)\n\nrecords = '\\n'.join(csw.records.keys())\nprint('Found {} records.\\n'.format(len(csw.records.keys())))\nfor key, value in list(csw.records.items()):\n print('[{}]\\n{}\\n'.format(value.title, key))",
"Found 17 records.\n\n[NAM CONUS 40km/Best NAM CONUS 40km Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/CONUS_40km/conduit/Best\n\n[NAM CONUS 80km/Best NAM CONUS 80km Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/CONUS_80km/Best\n\n[NAM Fireweather Nested/Best NAM Fireweather Nested Time Series/LambertConformal_622X510 (Center 38.53N 78.03W)]\nedu.ucar.unidata:grib/NCEP/NAM/Firewxnest/Best/LambertConformal_622X510-38p53N-78p03W\n\n[NAM Polar 90km/Best NAM Polar 90km Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/Polar_90km/Best\n\n[NOAA/NCEP Global Forecast System (GFS) Atmospheric Model]\nncep_global\n\n[NOAA/NCEP Global Forecast System (GFS) Atmospheric Model: Pacific]\nncep_pac\n\n[WaveWatch III (WW3) Global Wave Model]\nww3_global\n\n[NAM CONUS 12km from NOAAPORT/Best NAM CONUS 12km from NOAAPORT Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/CONUS_12km/Best\n\n[NAM CONUS 12km from CONDUIT/Best NAM CONUS 12km from CONDUIT Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/CONUS_12km/conduit/Best\n\n[NAM Alaska 45km from CONDUIT/Best NAM Alaska 45km from CONDUIT Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/Alaska_45km/conduit/Best\n\n[GFS CONUS 20km/Best GFS CONUS 20km Time Series]\nedu.ucar.unidata:grib/NCEP/GFS/CONUS_20km/Best\n\n[NAM Alaska 11km/Best NAM Alaska 11km Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/Alaska_11km/Best\n\n[GFS CONUS 80km/Best GFS CONUS 80km Time Series]\nedu.ucar.unidata:grib/NCEP/GFS/CONUS_80km/Best\n\n[NAM CONUS 20km/Best NAM CONUS 20km Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/CONUS_20km/noaaport/Best\n\n[NAM Alaska 22km/Best NAM Alaska 22km Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/Alaska_22km/Best\n\n[NAM Alaska 45km from NOAAPORT/Best NAM Alaska 45km from NOAAPORT Time Series]\nedu.ucar.unidata:grib/NCEP/NAM/Alaska_45km/noaaport/Best\n\n[GFS CONUS 95km/Best GFS CONUS 95km Time Series]\nedu.ucar.unidata:grib/NCEP/GFS/CONUS_95km/Best\n\n"
],
[
"csw.request",
"_____no_output_____"
],
[
"#write to JSON for use in TerriaJS\ncsw_request = '\"{}\": {}\"'.format('getRecordsTemplate',str(csw.request,'utf-8'))\n\nimport io\nimport json\nwith io.open('query.json', 'a', encoding='utf-8') as f:\n f.write(json.dumps(csw_request, ensure_ascii=False))\n f.write('\\n')",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
]
] |
cbb2691e837675f60fbb24ce80cfc9529d2f6d23
| 13,885 |
ipynb
|
Jupyter Notebook
|
tutorials/Creating_an_agent.ipynb
|
langner/tomsup
|
8dad2e701ef797c0a1d5ea323109efae1c527fe0
|
[
"Apache-2.0"
] | 32 |
2019-08-22T10:05:19.000Z
|
2022-03-29T15:23:40.000Z
|
tutorials/Creating_an_agent.ipynb
|
langner/tomsup
|
8dad2e701ef797c0a1d5ea323109efae1c527fe0
|
[
"Apache-2.0"
] | 16 |
2020-09-20T13:13:18.000Z
|
2022-03-16T13:29:23.000Z
|
tutorials/Creating_an_agent.ipynb
|
langner/tomsup
|
8dad2e701ef797c0a1d5ea323109efae1c527fe0
|
[
"Apache-2.0"
] | 6 |
2020-09-19T10:33:24.000Z
|
2021-12-17T22:11:02.000Z
| 40.599415 | 426 | 0.575873 |
[
[
[
"# Creating an agent\nThis notebook will go through the how to create a new agent within the tomsup framework. In this tutorial we will be making an reversed win-stay, lose-switch agent, e.g. an win-switch, lose-stay agent.\n\nThis guides assumes a basic understanding of classes in python, if you don't know these or need to recap we suggest examing this [chapter](http://hplgit.github.io/primer.html/doc/pub/class/._class-readable002.html) in the free ebook a byte of python\n\nLet us first import the package:",
"_____no_output_____"
]
],
[
[
"#assuming you are in the github folder change the path - not relevant if tomsup is installed via. pip\nimport os\nos.chdir(\"..\") # go back one folder\n\nimport tomsup as ts",
"_____no_output_____"
]
],
[
[
"Now lets first take a look at the current win-stay, lose-switch (WSLS) agent:",
"_____no_output_____"
]
],
[
[
"sigmund = ts.WSLS() #create agent\n\n# inspect sigmund\nprint(f\"sigmund is an class of type: {type(sigmund)}\") #f is for format\nif isinstance(sigmund, ts.Agent):\n print(f\"but sigmund is also of has the parent class ts.Agent\")\n",
"sigmund is an class of type: <class 'tomsup.agent.WSLS'>\nbut sigmund is also of has the parent class ts.Agent\n"
]
],
[
[
"As we can see sigmund is a WSLS agent with the parent class tsAgent. This us some benefits as WSLS inherit some of the attributes of the parent class, such as the ability to save play history and the ability to reset the agents. To see more of the inherited methods see help(ts.WSLS).\n\n## Creating a new class\nNow let's try to create our own agent one bit at a time (if you are confortable with classes simply jump to 'The final reversed WSLS):",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n\nclass ReversedWSLS(ts.Agent): # make sure that the parent class is ts.Agent\n \"\"\"\n ReversedWSLS: Win-switch, lose-stay.\n\n This agent is a reversed win-stay, lose-switch agent, which ...\n \"\"\"\n # add a docstring which explains the agent \n pass # we will later replace this pass with something else\n\n\nfreud = ReversedWSLS()\nprint(f\"is freud an Agent? {isinstance(freud, ts.Agent)}\")",
"is freud an Agent? True\n"
]
],
[
[
"### Add initialization\nLet's add an initalization of the agent. These are things which should be created prior to the agent competing.",
"_____no_output_____"
]
],
[
[
"\nclass ReversedWSLS(ts.Agent):\n \"\"\"\n ReversedWSLS: Win-switch, lose-stay.\n\n This agent is a reversed win-stay, lose-switch agent, which ...\n \"\"\"\n def __init__(self, first_move, **kwargs): #initalize the agent\n self.strategy = \"ReversedWSLS\" # set the strategy name\n\n # set internal parameters\n self.first_move = first_move\n\n super().__init__(**kwargs) # pass additional argument the ts.Agent class (could e.g. include 'save_history = True')\n self._start_params = {'first_move': first_move, **kwargs} # save any starting parameters used when the agent is reset\n\nfreud = ReversedWSLS(first_move = 1)\nprint(f\"what is freud's first move? {freud.first_move}\")\nprint(f\"what is freud's an starting parameters? {freud.get_start_params()}\")\nprint(f\"what is freud's strategy? {freud.get_strategy()}\")",
"what is freud's first move? 1\nwhat is freud's an starting parameters? {'first_move': 1}\nwhat is freud's strategy? ReversedWSLS\n"
]
],
[
[
"In the above you sucessfully created an freud as an agent and that his first move is 1. We also see that functions such as the ```get_start_params()``` from the ts.Agent is inherited by the new agent. \n\n\n**Note** that we have set ```**kwargs```, this simply means that function accept additional arguments, e.g. ```save_history = True```.\nThese arguments are then passed to the ```super()__init__()```, which initialize the parent class (in this case the ts.Agent class) as well as the ```_start_params``` which is the starting parameters. The starting parameter are used when resetting the agent, which is relevant e.g. when setting up a tournament settings. \n\n#### Add a compete function\nAll agent naturally need a compete function. Let us add one to the agent",
"_____no_output_____"
]
],
[
[
"\nclass ReversedWSLS(ts.Agent):\n \"\"\"\n ReversedWSLS: Win-switch, lose-stay.\n\n This agent is a reversed win-stay, lose-switch agent, which ...\n \"\"\"\n def __init__(self, first_move, **kwargs): #initalize the agent\n self.strategy = \"ReversedWSLS\" # set the strategy name\n\n # set internal parameters\n self.first_move = first_move\n\n super().__init__(**kwargs) # pass additional argument the ts.Agent class (could e.g. include 'save_history = True')\n self._start_params = {'first_move': first_move, **kwargs} # save any starting parameters used when the agent is reset\n\n\n def compete(self, p_matrix, op_choice = None, agent = 0):\n \"\"\"\n win-switch, lose-stay strategy, with the first move being set when the class is initilized (__init__())\n \n p_matrix is a PayoffMatrix\n op_choice is either 1 or 0\n agent is either 0 or 1 and indicated the perpective of the agent in the game (whether it is player 1 og 2)\n \"\"\"\n if self.choice is None: # if a choice haven't been made: Choose the redifined first move\n self.choice = self.first_move #fetch from self\n else: # if a choice have been made:\n payoff = p_matrix.payoff(self.choice, op_choice, agent) # calculate payoff of last round\n if payoff == 1: # if the agent won then switch\n self.choice = 1-self.choice # save the choice in self (for next round)\n # also save any other internal states which you might \n # want the agent to keep for next round in self\n self._add_to_history(choice = self.choice) # save action and (if any) internal states in history\n # note that _add_to_history() is not intented for \n # later use within the agent\n return self.choice # return choice which is either 1 or 0\n \nfreud = ReversedWSLS(first_move = 1) #create the agent \n\n# fetch payoff matrix for the pennygame\npenny = ts.PayoffMatrix(name = \"penny_competitive\") \nprint(\"This is the payoffmatrix for the game (seen from freud's perspective):\", penny()[0,:,:], sep = \"\\n\")\n\n# have freud compete\nchoice = freud.compete(penny)\nprint(f\"what is freud's choice the first round? {choice}\")\nchoice = freud.compete(penny, op_choice = 1)\nprint(f\"what is freud's choice the second round if his opponent chose 1? {choice}\")",
"This is the payoffmatrix for the game (seen from freud's perspective):\n[[-1 1]\n [ 1 -1]]\nwhat is freud's choice the first round? 1\nwhat is freud's choice the second round if his opponent chose 1? 1\n"
]
],
[
[
"In the above script we add freud's compete function, which for the first round choses his own move and for future moves it uses the win-switch, lose-stay strategy. It then return either a 0 or 1 depending on whether is choses e.g. right or left hand in the penny game. It is important that the agent does only return 0 or 1 in its compete function otherwise the agent will not function in the context of the package. \n\n**Note** the ```self._add_to_history(choice = self.choice)```, which indicated which variables I would like to add to the agent history, assuming save history is set to ```True```. In this case we would like to.\n\nFinally when you have the ```__init__()``` and the ```compete()``` working you can add any additional function you might want your agent to have, for example you will se that we have added the ```get_first_move()```, which is a helper function to extract the first move of the agent.",
"_____no_output_____"
],
[
"## The final reversed WSLS\nThe following is the finalized version of the win-switch, lose-stay agent.",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\n\nclass ReversedWSLS(ts.Agent):\n \"\"\"\n ReversedWSLS: Win-switch, lose-stay.\n\n This agent is a reversed win-stay, lose-switch agent, which ...\n\n Examples:\n >>> waade = ReversedWSLS(first_move = 1)\n >>> waade.compete(op_choice = None, p_matrix = penny)\n 1\n \"\"\"\n def __init__(self, first_move, **kwargs): \n self.strategy = \"ReversedWSLS\" \n\n # set internal parameters\n self.first_move = first_move\n\n super().__init__(**kwargs) # pass additional argument the ts.Agent class (could e.g. include 'save_history = True')\n self._start_params = {'first_move': first_move, **kwargs} # save any starting parameters used when the agent is reset\n\n \n def compete(self, p_matrix, op_choice = None):\n if self.choice is None: # if a choice haven't been made: Choose the redifined first move\n self.choice = self.first_move #fetch from self\n else: # if a choice have been made:\n payoff = p_matrix.payoff(self.choice, op_choice, 0) # calculate payoff of last round\n if payoff == 1: # if the agent won then switch\n self.choice = 1-self.choice # save the choice in self (for next round)\n # also save any other internal states which you might \n # want the agent to keep for next round in self\n self._add_to_history(choice = self.choice) # save action and (if any) internal states in history\n # note that _add_to_history() is not intented for \n # later use within the agent\n return self.choice # return choice\n\n \n # define any additional function you wish the class should have\n def get_first_move(self):\n return self.first_move",
"_____no_output_____"
]
],
[
[
"## Test your knowlegde\n\n1) Create an agent called Random, which simply choose randomly\n\n2) Check that it is an agent and that the compete function work\n\n3) Have the agent compete against another agent within the package using the ```ts.compete()```, which one win?",
"_____no_output_____"
],
[
"# FAQ\n\n- I have developed an agent which I would like to include in your package\nSounds lovely, we would love to include the agent. Feel free to make a pull request on Github or contact us at [email protected].",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbb26a592b9f4f680dfba3ddb562eb6053e565ac
| 461,055 |
ipynb
|
Jupyter Notebook
|
tennis_ball_detection.ipynb
|
Muzzamal-Hameed/Deep-Learning-Models
|
6f5735ac18cf52e3c3e455b68adad5c2a41cd465
|
[
"MIT"
] | null | null | null |
tennis_ball_detection.ipynb
|
Muzzamal-Hameed/Deep-Learning-Models
|
6f5735ac18cf52e3c3e455b68adad5c2a41cd465
|
[
"MIT"
] | null | null | null |
tennis_ball_detection.ipynb
|
Muzzamal-Hameed/Deep-Learning-Models
|
6f5735ac18cf52e3c3e455b68adad5c2a41cd465
|
[
"MIT"
] | null | null | null | 190.518595 | 326,702 | 0.848732 |
[
[
[
"<a href=\"https://colab.research.google.com/github/Muzzamal-Hameed/Deep-Learning-Models/blob/main/tennis_ball_detection.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
"from google.colab import drive",
"_____no_output_____"
],
[
"drive.mount('/content/gdrive')",
"Mounted at /content/gdrive\n"
],
[
"! mkdir ~/.kaggle",
"_____no_output_____"
],
[
"! cp kaggle.json ~/.kaggle/",
"_____no_output_____"
],
[
"! chmod 600 ~/.kaggle/kaggle.json",
"_____no_output_____"
],
[
"! kaggle datasets download -d domhenjes/ballsemtpytt",
"Downloading ballsemtpytt.zip to /content\n 99% 193M/195M [00:05<00:00, 30.5MB/s]\n100% 195M/195M [00:05<00:00, 40.2MB/s]\n"
],
[
"! unzip ballsemtpytt.zip",
"Archive: ballsemtpytt.zip\n inflating: emptyballs/test/balls/ball100.jpg \n inflating: emptyballs/test/balls/ball116.jpg \n inflating: emptyballs/test/balls/ball118.jpg \n inflating: emptyballs/test/balls/ball129.jpg \n inflating: emptyballs/test/balls/ball152.jpg \n inflating: emptyballs/test/balls/ball166.jpg \n inflating: emptyballs/test/balls/ball169.jpg \n inflating: emptyballs/test/balls/ball187.jpg \n inflating: emptyballs/test/balls/ball19.jpg \n inflating: emptyballs/test/balls/ball194.jpg \n inflating: emptyballs/test/balls/ball200.jpg \n inflating: emptyballs/test/balls/ball203.jpg \n inflating: emptyballs/test/balls/ball21.jpg \n inflating: emptyballs/test/balls/ball232.jpg \n inflating: emptyballs/test/balls/ball300.jpg \n inflating: emptyballs/test/balls/ball301.jpg \n inflating: emptyballs/test/balls/ball324.jpg \n inflating: emptyballs/test/balls/ball327.jpg \n inflating: emptyballs/test/balls/ball328.jpg \n inflating: emptyballs/test/balls/ball342.jpg \n inflating: emptyballs/test/balls/ball401.jpg \n inflating: emptyballs/test/balls/ball402.jpg \n inflating: emptyballs/test/balls/ball428.jpg \n inflating: emptyballs/test/balls/ball432.jpg \n inflating: emptyballs/test/balls/ball436.jpg \n inflating: emptyballs/test/balls/ball459.jpg \n inflating: emptyballs/test/balls/ball479.jpg \n inflating: emptyballs/test/balls/ball48.jpg \n inflating: emptyballs/test/balls/ball482.jpg \n inflating: emptyballs/test/balls/ball5.jpg \n inflating: emptyballs/test/balls/ball508.jpg \n inflating: emptyballs/test/balls/ball517.jpg \n inflating: emptyballs/test/balls/ball525.jpg \n inflating: emptyballs/test/balls/ball536.jpg \n inflating: emptyballs/test/balls/ball537.jpg \n inflating: emptyballs/test/balls/ball542.jpg \n inflating: emptyballs/test/balls/ball68.jpg \n inflating: emptyballs/test/balls/ball69.jpg \n inflating: emptyballs/test/balls/ball72.jpg \n inflating: emptyballs/test/balls/ball97.jpg \n inflating: emptyballs/test/empty/empty128.jpg \n inflating: emptyballs/test/empty/empty14.jpg \n inflating: emptyballs/test/empty/empty142.jpg \n inflating: emptyballs/test/empty/empty146.jpg \n inflating: emptyballs/test/empty/empty167.jpg \n inflating: emptyballs/test/empty/empty179.jpg \n inflating: emptyballs/test/empty/empty184.jpg \n inflating: emptyballs/test/empty/empty186.jpg \n inflating: emptyballs/test/empty/empty202.jpg \n inflating: emptyballs/test/empty/empty21.jpg \n inflating: emptyballs/test/empty/empty211.jpg \n inflating: emptyballs/test/empty/empty220.jpg \n inflating: emptyballs/test/empty/empty225.jpg \n inflating: emptyballs/test/empty/empty243.jpg \n inflating: emptyballs/test/empty/empty33.jpg \n inflating: emptyballs/test/empty/empty330.jpg \n inflating: emptyballs/test/empty/empty340.jpg \n inflating: emptyballs/test/empty/empty348.jpg \n inflating: emptyballs/test/empty/empty351.jpg \n inflating: emptyballs/test/empty/empty365.jpg \n inflating: emptyballs/test/empty/empty374.jpg \n inflating: emptyballs/test/empty/empty396.jpg \n inflating: emptyballs/test/empty/empty40.jpg \n inflating: emptyballs/test/empty/empty418.jpg \n inflating: emptyballs/test/empty/empty423.jpg \n inflating: emptyballs/test/empty/empty462.jpg \n inflating: emptyballs/test/empty/empty479.jpg \n inflating: emptyballs/test/empty/empty491.jpg \n inflating: emptyballs/test/empty/empty495.jpg \n inflating: emptyballs/test/empty/empty497.jpg \n inflating: emptyballs/test/empty/empty504.jpg \n inflating: emptyballs/test/empty/empty517.jpg \n inflating: emptyballs/test/empty/empty54.jpg \n inflating: emptyballs/test/empty/empty59.jpg \n inflating: emptyballs/test/empty/empty6.jpg \n inflating: emptyballs/test/empty/empty60.jpg \n inflating: emptyballs/test/empty/empty66.jpg \n inflating: emptyballs/test/empty/empty74.jpg \n inflating: emptyballs/test/empty/empty97.jpg \n inflating: emptyballs/test/empty/empty99.jpg \n inflating: emptyballs/train/balls/ball0.jpg \n inflating: emptyballs/train/balls/ball1.jpg \n inflating: emptyballs/train/balls/ball10.jpg \n inflating: emptyballs/train/balls/ball101.jpg \n inflating: emptyballs/train/balls/ball102.jpg \n inflating: emptyballs/train/balls/ball103.jpg \n inflating: emptyballs/train/balls/ball104.jpg \n inflating: emptyballs/train/balls/ball105.jpg \n inflating: emptyballs/train/balls/ball106.jpg \n inflating: emptyballs/train/balls/ball107.jpg \n inflating: emptyballs/train/balls/ball108.jpg \n inflating: emptyballs/train/balls/ball109.jpg \n inflating: emptyballs/train/balls/ball11.jpg \n inflating: emptyballs/train/balls/ball110.jpg \n inflating: emptyballs/train/balls/ball111.jpg \n inflating: emptyballs/train/balls/ball112.jpg \n inflating: emptyballs/train/balls/ball113.jpg \n inflating: emptyballs/train/balls/ball114.jpg \n inflating: emptyballs/train/balls/ball115.jpg \n inflating: emptyballs/train/balls/ball117.jpg \n inflating: emptyballs/train/balls/ball119.jpg \n inflating: emptyballs/train/balls/ball12.jpg \n inflating: emptyballs/train/balls/ball120.jpg \n inflating: emptyballs/train/balls/ball121.jpg \n inflating: emptyballs/train/balls/ball122.jpg \n inflating: emptyballs/train/balls/ball123.jpg \n inflating: emptyballs/train/balls/ball124.jpg \n inflating: emptyballs/train/balls/ball125.jpg \n inflating: emptyballs/train/balls/ball126.jpg \n inflating: emptyballs/train/balls/ball127.jpg \n inflating: emptyballs/train/balls/ball128.jpg \n inflating: emptyballs/train/balls/ball13.jpg \n inflating: emptyballs/train/balls/ball130.jpg \n inflating: emptyballs/train/balls/ball131.jpg \n inflating: emptyballs/train/balls/ball132.jpg \n inflating: emptyballs/train/balls/ball133.jpg \n inflating: emptyballs/train/balls/ball134.jpg \n inflating: emptyballs/train/balls/ball135.jpg \n inflating: emptyballs/train/balls/ball136.jpg \n inflating: emptyballs/train/balls/ball137.jpg \n inflating: emptyballs/train/balls/ball138.jpg \n inflating: emptyballs/train/balls/ball139.jpg \n inflating: emptyballs/train/balls/ball14.jpg \n inflating: emptyballs/train/balls/ball140.jpg \n inflating: emptyballs/train/balls/ball141.jpg \n inflating: emptyballs/train/balls/ball142.jpg \n inflating: emptyballs/train/balls/ball143.jpg \n inflating: emptyballs/train/balls/ball144.jpg \n inflating: emptyballs/train/balls/ball145.jpg \n inflating: emptyballs/train/balls/ball146.jpg \n inflating: emptyballs/train/balls/ball147.jpg \n inflating: emptyballs/train/balls/ball148.jpg \n inflating: emptyballs/train/balls/ball149.jpg \n inflating: emptyballs/train/balls/ball15.jpg \n inflating: emptyballs/train/balls/ball150.jpg \n inflating: emptyballs/train/balls/ball151.jpg \n inflating: emptyballs/train/balls/ball153.jpg \n inflating: emptyballs/train/balls/ball154.jpg \n inflating: emptyballs/train/balls/ball155.jpg \n inflating: emptyballs/train/balls/ball156.jpg \n inflating: emptyballs/train/balls/ball157.jpg \n inflating: emptyballs/train/balls/ball158.jpg \n inflating: emptyballs/train/balls/ball159.jpg \n inflating: emptyballs/train/balls/ball16.jpg \n inflating: emptyballs/train/balls/ball160.jpg \n inflating: emptyballs/train/balls/ball161.jpg \n inflating: emptyballs/train/balls/ball162.jpg \n inflating: emptyballs/train/balls/ball163.jpg \n inflating: emptyballs/train/balls/ball164.jpg \n inflating: emptyballs/train/balls/ball165.jpg \n inflating: emptyballs/train/balls/ball167.jpg \n inflating: emptyballs/train/balls/ball168.jpg \n inflating: emptyballs/train/balls/ball17.jpg \n inflating: emptyballs/train/balls/ball170.jpg \n inflating: emptyballs/train/balls/ball171.jpg \n inflating: emptyballs/train/balls/ball172.jpg \n inflating: emptyballs/train/balls/ball173.jpg \n inflating: emptyballs/train/balls/ball174.jpg \n inflating: emptyballs/train/balls/ball175.jpg \n inflating: emptyballs/train/balls/ball176.jpg \n inflating: emptyballs/train/balls/ball177.jpg \n inflating: emptyballs/train/balls/ball178.jpg \n inflating: emptyballs/train/balls/ball179.jpg \n inflating: emptyballs/train/balls/ball18.jpg \n inflating: emptyballs/train/balls/ball180.jpg \n inflating: emptyballs/train/balls/ball181.jpg \n inflating: emptyballs/train/balls/ball182.jpg \n inflating: emptyballs/train/balls/ball183.jpg \n inflating: emptyballs/train/balls/ball184.jpg \n inflating: emptyballs/train/balls/ball185.jpg \n inflating: emptyballs/train/balls/ball186.jpg \n inflating: emptyballs/train/balls/ball188.jpg \n inflating: emptyballs/train/balls/ball189.jpg \n inflating: emptyballs/train/balls/ball190.jpg \n inflating: emptyballs/train/balls/ball191.jpg \n inflating: emptyballs/train/balls/ball192.jpg \n inflating: emptyballs/train/balls/ball193.jpg \n inflating: emptyballs/train/balls/ball195.jpg \n inflating: emptyballs/train/balls/ball196.jpg \n inflating: emptyballs/train/balls/ball197.jpg \n inflating: emptyballs/train/balls/ball198.jpg \n inflating: emptyballs/train/balls/ball199.jpg \n inflating: emptyballs/train/balls/ball2.jpg \n inflating: emptyballs/train/balls/ball20.jpg \n inflating: emptyballs/train/balls/ball201.jpg \n inflating: emptyballs/train/balls/ball202.jpg \n inflating: emptyballs/train/balls/ball204.jpg \n inflating: emptyballs/train/balls/ball205.jpg \n inflating: emptyballs/train/balls/ball206.jpg \n inflating: emptyballs/train/balls/ball207.jpg \n inflating: emptyballs/train/balls/ball208.jpg \n inflating: emptyballs/train/balls/ball209.jpg \n inflating: emptyballs/train/balls/ball210.jpg \n inflating: emptyballs/train/balls/ball211.jpg \n inflating: emptyballs/train/balls/ball212.jpg \n inflating: emptyballs/train/balls/ball213.jpg \n inflating: emptyballs/train/balls/ball214.jpg \n inflating: emptyballs/train/balls/ball215.jpg \n inflating: emptyballs/train/balls/ball216.jpg \n inflating: emptyballs/train/balls/ball217.jpg \n inflating: emptyballs/train/balls/ball218.jpg \n inflating: emptyballs/train/balls/ball219.jpg \n inflating: emptyballs/train/balls/ball22.jpg \n inflating: emptyballs/train/balls/ball220.jpg \n inflating: emptyballs/train/balls/ball221.jpg \n inflating: emptyballs/train/balls/ball222.jpg \n inflating: emptyballs/train/balls/ball223.jpg \n inflating: emptyballs/train/balls/ball224.jpg \n inflating: emptyballs/train/balls/ball225.jpg \n inflating: emptyballs/train/balls/ball226.jpg \n inflating: emptyballs/train/balls/ball227.jpg \n inflating: emptyballs/train/balls/ball228.jpg \n inflating: emptyballs/train/balls/ball229.jpg \n inflating: emptyballs/train/balls/ball23.jpg \n inflating: emptyballs/train/balls/ball230.jpg \n inflating: emptyballs/train/balls/ball231.jpg \n inflating: emptyballs/train/balls/ball233.jpg \n inflating: emptyballs/train/balls/ball234.jpg \n inflating: emptyballs/train/balls/ball235.jpg \n inflating: emptyballs/train/balls/ball236.jpg \n inflating: emptyballs/train/balls/ball237.jpg \n inflating: emptyballs/train/balls/ball238.jpg \n inflating: emptyballs/train/balls/ball239.jpg \n inflating: emptyballs/train/balls/ball24.jpg \n inflating: emptyballs/train/balls/ball240.jpg \n inflating: emptyballs/train/balls/ball241.jpg \n inflating: emptyballs/train/balls/ball242.jpg \n inflating: emptyballs/train/balls/ball243.jpg \n inflating: emptyballs/train/balls/ball244.jpg \n inflating: emptyballs/train/balls/ball245.jpg \n inflating: emptyballs/train/balls/ball246.jpg \n inflating: emptyballs/train/balls/ball247.jpg \n inflating: emptyballs/train/balls/ball248.jpg \n inflating: emptyballs/train/balls/ball249.jpg \n inflating: emptyballs/train/balls/ball25.jpg \n inflating: emptyballs/train/balls/ball250.jpg \n inflating: emptyballs/train/balls/ball251.jpg \n inflating: emptyballs/train/balls/ball252.jpg \n inflating: emptyballs/train/balls/ball253.jpg \n inflating: emptyballs/train/balls/ball254.jpg \n inflating: emptyballs/train/balls/ball255.jpg \n inflating: emptyballs/train/balls/ball256.jpg \n inflating: emptyballs/train/balls/ball257.jpg \n inflating: emptyballs/train/balls/ball258.jpg \n inflating: emptyballs/train/balls/ball26.jpg \n inflating: emptyballs/train/balls/ball27.jpg \n inflating: emptyballs/train/balls/ball28.jpg \n inflating: emptyballs/train/balls/ball29.jpg \n inflating: emptyballs/train/balls/ball3.jpg \n inflating: emptyballs/train/balls/ball30.jpg \n inflating: emptyballs/train/balls/ball302.jpg \n inflating: emptyballs/train/balls/ball303.jpg \n inflating: emptyballs/train/balls/ball304.jpg \n inflating: emptyballs/train/balls/ball305.jpg \n inflating: emptyballs/train/balls/ball306.jpg \n inflating: emptyballs/train/balls/ball307.jpg \n inflating: emptyballs/train/balls/ball308.jpg \n inflating: emptyballs/train/balls/ball309.jpg \n inflating: emptyballs/train/balls/ball31.jpg \n inflating: emptyballs/train/balls/ball310.jpg \n inflating: emptyballs/train/balls/ball311.jpg \n inflating: emptyballs/train/balls/ball312.jpg \n inflating: emptyballs/train/balls/ball313.jpg \n inflating: emptyballs/train/balls/ball314.jpg \n inflating: emptyballs/train/balls/ball315.jpg \n inflating: emptyballs/train/balls/ball317.jpg \n inflating: emptyballs/train/balls/ball318.jpg \n inflating: emptyballs/train/balls/ball319.jpg \n inflating: emptyballs/train/balls/ball32.jpg \n inflating: emptyballs/train/balls/ball320.jpg \n inflating: emptyballs/train/balls/ball321.jpg \n inflating: emptyballs/train/balls/ball322.jpg \n inflating: emptyballs/train/balls/ball323.jpg \n inflating: emptyballs/train/balls/ball325.jpg \n inflating: emptyballs/train/balls/ball326.jpg \n inflating: emptyballs/train/balls/ball329.jpg \n inflating: emptyballs/train/balls/ball33.jpg \n inflating: emptyballs/train/balls/ball330.jpg \n inflating: emptyballs/train/balls/ball331.jpg \n inflating: emptyballs/train/balls/ball332.jpg \n inflating: emptyballs/train/balls/ball333.jpg \n inflating: emptyballs/train/balls/ball334.jpg \n inflating: emptyballs/train/balls/ball335.jpg \n inflating: emptyballs/train/balls/ball336.jpg \n inflating: emptyballs/train/balls/ball337.jpg \n inflating: emptyballs/train/balls/ball338.jpg \n inflating: emptyballs/train/balls/ball34.jpg \n inflating: emptyballs/train/balls/ball340.jpg \n inflating: emptyballs/train/balls/ball341.jpg \n inflating: emptyballs/train/balls/ball343.jpg \n inflating: emptyballs/train/balls/ball344.jpg \n inflating: emptyballs/train/balls/ball345.jpg \n inflating: emptyballs/train/balls/ball35.jpg \n inflating: emptyballs/train/balls/ball36.jpg \n inflating: emptyballs/train/balls/ball37.jpg \n inflating: emptyballs/train/balls/ball38.jpg \n inflating: emptyballs/train/balls/ball39.jpg \n inflating: emptyballs/train/balls/ball4.jpg \n inflating: emptyballs/train/balls/ball40.jpg \n inflating: emptyballs/train/balls/ball400.jpg \n inflating: emptyballs/train/balls/ball403.jpg \n inflating: emptyballs/train/balls/ball404.jpg \n inflating: emptyballs/train/balls/ball405.jpg \n inflating: emptyballs/train/balls/ball406.jpg \n inflating: emptyballs/train/balls/ball407.jpg \n inflating: emptyballs/train/balls/ball408.jpg \n inflating: emptyballs/train/balls/ball409.jpg \n inflating: emptyballs/train/balls/ball41.jpg \n inflating: emptyballs/train/balls/ball410.jpg \n inflating: emptyballs/train/balls/ball411.jpg \n inflating: emptyballs/train/balls/ball412.jpg \n inflating: emptyballs/train/balls/ball413.jpg \n inflating: emptyballs/train/balls/ball414.jpg \n inflating: emptyballs/train/balls/ball415.jpg \n inflating: emptyballs/train/balls/ball416.jpg \n inflating: emptyballs/train/balls/ball417.jpg \n inflating: emptyballs/train/balls/ball418.jpg \n inflating: emptyballs/train/balls/ball419.jpg \n inflating: emptyballs/train/balls/ball42.jpg \n inflating: emptyballs/train/balls/ball420.jpg \n inflating: emptyballs/train/balls/ball421.jpg \n inflating: emptyballs/train/balls/ball422.jpg \n inflating: emptyballs/train/balls/ball423.jpg \n inflating: emptyballs/train/balls/ball424.jpg \n inflating: emptyballs/train/balls/ball425.jpg \n inflating: emptyballs/train/balls/ball426.jpg \n inflating: emptyballs/train/balls/ball427.jpg \n inflating: emptyballs/train/balls/ball429.jpg \n inflating: emptyballs/train/balls/ball43.jpg \n inflating: emptyballs/train/balls/ball430.jpg \n inflating: emptyballs/train/balls/ball431.jpg \n inflating: emptyballs/train/balls/ball433.jpg \n inflating: emptyballs/train/balls/ball434.jpg \n inflating: emptyballs/train/balls/ball435.jpg \n inflating: emptyballs/train/balls/ball437.jpg \n inflating: emptyballs/train/balls/ball438.jpg \n inflating: emptyballs/train/balls/ball439.jpg \n inflating: emptyballs/train/balls/ball44.jpg \n inflating: emptyballs/train/balls/ball440.jpg \n inflating: emptyballs/train/balls/ball441.jpg \n inflating: emptyballs/train/balls/ball442.jpg \n inflating: emptyballs/train/balls/ball443.jpg \n inflating: emptyballs/train/balls/ball444.jpg \n inflating: emptyballs/train/balls/ball445.jpg \n inflating: emptyballs/train/balls/ball446.jpg \n inflating: emptyballs/train/balls/ball447.jpg \n inflating: emptyballs/train/balls/ball448.jpg \n inflating: emptyballs/train/balls/ball449.jpg \n inflating: emptyballs/train/balls/ball45.jpg \n inflating: emptyballs/train/balls/ball450.jpg \n inflating: emptyballs/train/balls/ball451.jpg \n inflating: emptyballs/train/balls/ball452.jpg \n inflating: emptyballs/train/balls/ball453.jpg \n inflating: emptyballs/train/balls/ball454.jpg \n inflating: emptyballs/train/balls/ball455.jpg \n inflating: emptyballs/train/balls/ball456.jpg \n inflating: emptyballs/train/balls/ball457.jpg \n inflating: emptyballs/train/balls/ball458.jpg \n inflating: emptyballs/train/balls/ball46.jpg \n inflating: emptyballs/train/balls/ball460.jpg \n inflating: emptyballs/train/balls/ball461.jpg \n inflating: emptyballs/train/balls/ball462.jpg \n inflating: emptyballs/train/balls/ball463.jpg \n inflating: emptyballs/train/balls/ball464.jpg \n inflating: emptyballs/train/balls/ball465.jpg \n inflating: emptyballs/train/balls/ball466.jpg \n inflating: emptyballs/train/balls/ball467.jpg \n inflating: emptyballs/train/balls/ball468.jpg \n inflating: emptyballs/train/balls/ball469.jpg \n inflating: emptyballs/train/balls/ball47.jpg \n inflating: emptyballs/train/balls/ball470.jpg \n inflating: emptyballs/train/balls/ball471.jpg \n inflating: emptyballs/train/balls/ball472.jpg \n inflating: emptyballs/train/balls/ball473.jpg \n inflating: emptyballs/train/balls/ball474.jpg \n inflating: emptyballs/train/balls/ball475.jpg \n inflating: emptyballs/train/balls/ball476.jpg \n inflating: emptyballs/train/balls/ball477.jpg \n inflating: emptyballs/train/balls/ball478.jpg \n inflating: emptyballs/train/balls/ball480.jpg \n inflating: emptyballs/train/balls/ball481.jpg \n inflating: emptyballs/train/balls/ball483.jpg \n inflating: emptyballs/train/balls/ball484.jpg \n inflating: emptyballs/train/balls/ball485.jpg \n inflating: emptyballs/train/balls/ball486.jpg \n inflating: emptyballs/train/balls/ball487.jpg \n inflating: emptyballs/train/balls/ball488.jpg \n inflating: emptyballs/train/balls/ball489.jpg \n inflating: emptyballs/train/balls/ball49.jpg \n inflating: emptyballs/train/balls/ball490.jpg \n inflating: emptyballs/train/balls/ball491.jpg \n inflating: emptyballs/train/balls/ball492.jpg \n inflating: emptyballs/train/balls/ball493.jpg \n inflating: emptyballs/train/balls/ball494.jpg \n inflating: emptyballs/train/balls/ball495.jpg \n inflating: emptyballs/train/balls/ball496.jpg \n inflating: emptyballs/train/balls/ball497.jpg \n inflating: emptyballs/train/balls/ball498.jpg \n inflating: emptyballs/train/balls/ball499.jpg \n inflating: emptyballs/train/balls/ball50.jpg \n inflating: emptyballs/train/balls/ball500.jpg \n inflating: emptyballs/train/balls/ball501.jpg \n inflating: emptyballs/train/balls/ball502.jpg \n inflating: emptyballs/train/balls/ball503.jpg \n inflating: emptyballs/train/balls/ball504.jpg \n inflating: emptyballs/train/balls/ball505.jpg \n inflating: emptyballs/train/balls/ball506.jpg \n inflating: emptyballs/train/balls/ball507.jpg \n inflating: emptyballs/train/balls/ball509.jpg \n inflating: emptyballs/train/balls/ball51.jpg \n inflating: emptyballs/train/balls/ball510.jpg \n inflating: emptyballs/train/balls/ball511.jpg \n inflating: emptyballs/train/balls/ball512.jpg \n inflating: emptyballs/train/balls/ball513.jpg \n inflating: emptyballs/train/balls/ball514.jpg \n inflating: emptyballs/train/balls/ball515.jpg \n inflating: emptyballs/train/balls/ball516.jpg \n inflating: emptyballs/train/balls/ball518.jpg \n inflating: emptyballs/train/balls/ball519.jpg \n inflating: emptyballs/train/balls/ball52.jpg \n inflating: emptyballs/train/balls/ball520.jpg \n inflating: emptyballs/train/balls/ball521.jpg \n inflating: emptyballs/train/balls/ball522.jpg \n inflating: emptyballs/train/balls/ball523.jpg \n inflating: emptyballs/train/balls/ball524.jpg \n inflating: emptyballs/train/balls/ball526.jpg \n inflating: emptyballs/train/balls/ball527.jpg \n inflating: emptyballs/train/balls/ball528.jpg \n inflating: emptyballs/train/balls/ball529.jpg \n inflating: emptyballs/train/balls/ball53.jpg \n inflating: emptyballs/train/balls/ball530.jpg \n inflating: emptyballs/train/balls/ball531.jpg \n inflating: emptyballs/train/balls/ball532.jpg \n inflating: emptyballs/train/balls/ball533.jpg \n inflating: emptyballs/train/balls/ball534.jpg \n inflating: emptyballs/train/balls/ball535.jpg \n inflating: emptyballs/train/balls/ball538.jpg \n inflating: emptyballs/train/balls/ball539.jpg \n inflating: emptyballs/train/balls/ball54.jpg \n inflating: emptyballs/train/balls/ball540.jpg \n inflating: emptyballs/train/balls/ball541.jpg \n inflating: emptyballs/train/balls/ball55.jpg \n inflating: emptyballs/train/balls/ball56.jpg \n inflating: emptyballs/train/balls/ball57.jpg \n inflating: emptyballs/train/balls/ball58.jpg \n inflating: emptyballs/train/balls/ball59.jpg \n inflating: emptyballs/train/balls/ball6.jpg \n inflating: emptyballs/train/balls/ball60.jpg \n inflating: emptyballs/train/balls/ball61.jpg \n inflating: emptyballs/train/balls/ball62.jpg \n inflating: emptyballs/train/balls/ball63.jpg \n inflating: emptyballs/train/balls/ball64.jpg \n inflating: emptyballs/train/balls/ball65.jpg \n inflating: emptyballs/train/balls/ball66.jpg \n inflating: emptyballs/train/balls/ball67.jpg \n inflating: emptyballs/train/balls/ball7.jpg \n inflating: emptyballs/train/balls/ball70.jpg \n inflating: emptyballs/train/balls/ball71.jpg \n inflating: emptyballs/train/balls/ball73.jpg \n inflating: emptyballs/train/balls/ball74.jpg \n inflating: emptyballs/train/balls/ball75.jpg \n inflating: emptyballs/train/balls/ball76.jpg \n inflating: emptyballs/train/balls/ball77.jpg \n inflating: emptyballs/train/balls/ball78.jpg \n inflating: emptyballs/train/balls/ball79.jpg \n inflating: emptyballs/train/balls/ball8.jpg \n inflating: emptyballs/train/balls/ball80.jpg \n inflating: emptyballs/train/balls/ball81.jpg \n inflating: emptyballs/train/balls/ball82.jpg \n inflating: emptyballs/train/balls/ball83.jpg \n inflating: emptyballs/train/balls/ball84.jpg \n inflating: emptyballs/train/balls/ball85.jpg \n inflating: emptyballs/train/balls/ball86.jpg \n inflating: emptyballs/train/balls/ball87.jpg \n inflating: emptyballs/train/balls/ball88.jpg \n inflating: emptyballs/train/balls/ball89.jpg \n inflating: emptyballs/train/balls/ball9.jpg \n inflating: emptyballs/train/balls/ball90.jpg \n inflating: emptyballs/train/balls/ball91.jpg \n inflating: emptyballs/train/balls/ball92.jpg \n inflating: emptyballs/train/balls/ball93.jpg \n inflating: emptyballs/train/balls/ball94.jpg \n inflating: emptyballs/train/balls/ball95.jpg \n inflating: emptyballs/train/balls/ball96.jpg \n inflating: emptyballs/train/balls/ball98.jpg \n inflating: emptyballs/train/balls/ball99.jpg \n inflating: emptyballs/train/empty/empty0.jpg \n inflating: emptyballs/train/empty/empty1.jpg \n inflating: emptyballs/train/empty/empty10.jpg \n inflating: emptyballs/train/empty/empty100.jpg \n inflating: emptyballs/train/empty/empty101.jpg \n inflating: emptyballs/train/empty/empty102.jpg \n inflating: emptyballs/train/empty/empty103.jpg \n inflating: emptyballs/train/empty/empty104.jpg \n inflating: emptyballs/train/empty/empty105.jpg \n inflating: emptyballs/train/empty/empty106.jpg \n inflating: emptyballs/train/empty/empty107.jpg \n inflating: emptyballs/train/empty/empty108.jpg \n inflating: emptyballs/train/empty/empty109.jpg \n inflating: emptyballs/train/empty/empty11.jpg \n inflating: emptyballs/train/empty/empty110.jpg \n inflating: emptyballs/train/empty/empty111.jpg \n inflating: emptyballs/train/empty/empty112.jpg \n inflating: emptyballs/train/empty/empty113.jpg \n inflating: emptyballs/train/empty/empty114.jpg \n inflating: emptyballs/train/empty/empty115.jpg \n inflating: emptyballs/train/empty/empty116.jpg \n inflating: emptyballs/train/empty/empty117.jpg \n inflating: emptyballs/train/empty/empty118.jpg \n inflating: emptyballs/train/empty/empty119.jpg \n inflating: emptyballs/train/empty/empty12.jpg \n inflating: emptyballs/train/empty/empty120.jpg \n inflating: emptyballs/train/empty/empty121.jpg \n inflating: emptyballs/train/empty/empty122.jpg \n inflating: emptyballs/train/empty/empty123.jpg \n inflating: emptyballs/train/empty/empty124.jpg \n inflating: emptyballs/train/empty/empty125.jpg \n inflating: emptyballs/train/empty/empty126.jpg \n inflating: emptyballs/train/empty/empty127.jpg \n inflating: emptyballs/train/empty/empty129.jpg \n inflating: emptyballs/train/empty/empty13.jpg \n inflating: emptyballs/train/empty/empty130.jpg \n inflating: emptyballs/train/empty/empty131.jpg \n inflating: emptyballs/train/empty/empty132.jpg \n inflating: emptyballs/train/empty/empty133.jpg \n inflating: emptyballs/train/empty/empty134.jpg \n inflating: emptyballs/train/empty/empty135.jpg \n inflating: emptyballs/train/empty/empty136.jpg \n inflating: emptyballs/train/empty/empty137.jpg \n inflating: emptyballs/train/empty/empty138.jpg \n inflating: emptyballs/train/empty/empty139.jpg \n inflating: emptyballs/train/empty/empty140.jpg \n inflating: emptyballs/train/empty/empty141.jpg \n inflating: emptyballs/train/empty/empty143.jpg \n inflating: emptyballs/train/empty/empty144.jpg \n inflating: emptyballs/train/empty/empty145.jpg \n inflating: emptyballs/train/empty/empty147.jpg \n inflating: emptyballs/train/empty/empty148.jpg \n inflating: emptyballs/train/empty/empty149.jpg \n inflating: emptyballs/train/empty/empty15.jpg \n inflating: emptyballs/train/empty/empty150.jpg \n inflating: emptyballs/train/empty/empty151.jpg \n inflating: emptyballs/train/empty/empty152.jpg \n inflating: emptyballs/train/empty/empty153.jpg \n inflating: emptyballs/train/empty/empty154.jpg \n inflating: emptyballs/train/empty/empty155.jpg \n inflating: emptyballs/train/empty/empty156.jpg \n inflating: emptyballs/train/empty/empty157.jpg \n inflating: emptyballs/train/empty/empty158.jpg \n inflating: emptyballs/train/empty/empty159.jpg \n inflating: emptyballs/train/empty/empty16.jpg \n inflating: emptyballs/train/empty/empty160.jpg \n inflating: emptyballs/train/empty/empty161.jpg \n inflating: emptyballs/train/empty/empty162.jpg \n inflating: emptyballs/train/empty/empty163.jpg \n inflating: emptyballs/train/empty/empty164.jpg \n inflating: emptyballs/train/empty/empty165.jpg \n inflating: emptyballs/train/empty/empty166.jpg \n inflating: emptyballs/train/empty/empty168.jpg \n inflating: emptyballs/train/empty/empty169.jpg \n inflating: emptyballs/train/empty/empty17.jpg \n inflating: emptyballs/train/empty/empty170.jpg \n inflating: emptyballs/train/empty/empty171.jpg \n inflating: emptyballs/train/empty/empty172.jpg \n inflating: emptyballs/train/empty/empty173.jpg \n inflating: emptyballs/train/empty/empty174.jpg \n inflating: emptyballs/train/empty/empty175.jpg \n inflating: emptyballs/train/empty/empty176.jpg \n inflating: emptyballs/train/empty/empty177.jpg \n inflating: emptyballs/train/empty/empty178.jpg \n inflating: emptyballs/train/empty/empty18.jpg \n inflating: emptyballs/train/empty/empty180.jpg \n inflating: emptyballs/train/empty/empty181.jpg \n inflating: emptyballs/train/empty/empty182.jpg \n inflating: emptyballs/train/empty/empty183.jpg \n inflating: emptyballs/train/empty/empty185.jpg \n inflating: emptyballs/train/empty/empty187.jpg \n inflating: emptyballs/train/empty/empty188.jpg \n inflating: emptyballs/train/empty/empty189.jpg \n inflating: emptyballs/train/empty/empty19.jpg \n inflating: emptyballs/train/empty/empty190.jpg \n inflating: emptyballs/train/empty/empty191.jpg \n inflating: emptyballs/train/empty/empty192.jpg \n inflating: emptyballs/train/empty/empty193.jpg \n inflating: emptyballs/train/empty/empty194.jpg \n inflating: emptyballs/train/empty/empty195.jpg \n inflating: emptyballs/train/empty/empty196.jpg \n inflating: emptyballs/train/empty/empty197.jpg \n inflating: emptyballs/train/empty/empty198.jpg \n inflating: emptyballs/train/empty/empty199.jpg \n inflating: emptyballs/train/empty/empty2.jpg \n inflating: emptyballs/train/empty/empty20.jpg \n inflating: emptyballs/train/empty/empty200.jpg \n inflating: emptyballs/train/empty/empty201.jpg \n inflating: emptyballs/train/empty/empty203.jpg \n inflating: emptyballs/train/empty/empty204.jpg \n inflating: emptyballs/train/empty/empty205.jpg \n inflating: emptyballs/train/empty/empty206.jpg \n inflating: emptyballs/train/empty/empty207.jpg \n inflating: emptyballs/train/empty/empty208.jpg \n inflating: emptyballs/train/empty/empty209.jpg \n inflating: emptyballs/train/empty/empty210.jpg \n inflating: emptyballs/train/empty/empty212.jpg \n inflating: emptyballs/train/empty/empty213.jpg \n inflating: emptyballs/train/empty/empty214.jpg \n inflating: emptyballs/train/empty/empty215.jpg \n inflating: emptyballs/train/empty/empty216.jpg \n inflating: emptyballs/train/empty/empty217.jpg \n inflating: emptyballs/train/empty/empty218.jpg \n inflating: emptyballs/train/empty/empty219.jpg \n inflating: emptyballs/train/empty/empty22.jpg \n inflating: emptyballs/train/empty/empty221.jpg \n inflating: emptyballs/train/empty/empty222.jpg \n inflating: emptyballs/train/empty/empty223.jpg \n inflating: emptyballs/train/empty/empty224.jpg \n inflating: emptyballs/train/empty/empty226.jpg \n inflating: emptyballs/train/empty/empty227.jpg \n inflating: emptyballs/train/empty/empty228.jpg \n inflating: emptyballs/train/empty/empty229.jpg \n inflating: emptyballs/train/empty/empty23.jpg \n inflating: emptyballs/train/empty/empty230.jpg \n inflating: emptyballs/train/empty/empty231.jpg \n inflating: emptyballs/train/empty/empty232.jpg \n inflating: emptyballs/train/empty/empty233.jpg \n inflating: emptyballs/train/empty/empty234.jpg \n inflating: emptyballs/train/empty/empty235.jpg \n inflating: emptyballs/train/empty/empty236.jpg \n inflating: emptyballs/train/empty/empty237.jpg \n inflating: emptyballs/train/empty/empty238.jpg \n inflating: emptyballs/train/empty/empty239.jpg \n inflating: emptyballs/train/empty/empty24.jpg \n inflating: emptyballs/train/empty/empty240.jpg \n inflating: emptyballs/train/empty/empty241.jpg \n inflating: emptyballs/train/empty/empty242.jpg \n inflating: emptyballs/train/empty/empty244.jpg \n inflating: emptyballs/train/empty/empty245.jpg \n inflating: emptyballs/train/empty/empty25.jpg \n inflating: emptyballs/train/empty/empty26.jpg \n inflating: emptyballs/train/empty/empty27.jpg \n inflating: emptyballs/train/empty/empty28.jpg \n inflating: emptyballs/train/empty/empty29.jpg \n inflating: emptyballs/train/empty/empty3.jpg \n inflating: emptyballs/train/empty/empty30.jpg \n inflating: emptyballs/train/empty/empty300.jpg \n inflating: emptyballs/train/empty/empty301.jpg \n inflating: emptyballs/train/empty/empty302.jpg \n inflating: emptyballs/train/empty/empty303.jpg \n inflating: emptyballs/train/empty/empty304.jpg \n inflating: emptyballs/train/empty/empty305.jpg \n inflating: emptyballs/train/empty/empty306.jpg \n inflating: emptyballs/train/empty/empty307.jpg \n inflating: emptyballs/train/empty/empty308.jpg \n inflating: emptyballs/train/empty/empty309.jpg \n inflating: emptyballs/train/empty/empty31.jpg \n inflating: emptyballs/train/empty/empty310.jpg \n inflating: emptyballs/train/empty/empty311.jpg \n inflating: emptyballs/train/empty/empty312.jpg \n inflating: emptyballs/train/empty/empty32.jpg \n inflating: emptyballs/train/empty/empty320.jpg \n inflating: emptyballs/train/empty/empty321.jpg \n inflating: emptyballs/train/empty/empty322.jpg \n inflating: emptyballs/train/empty/empty323.jpg \n inflating: emptyballs/train/empty/empty324.jpg \n inflating: emptyballs/train/empty/empty325.jpg \n inflating: emptyballs/train/empty/empty326.jpg \n inflating: emptyballs/train/empty/empty327.jpg \n inflating: emptyballs/train/empty/empty328.jpg \n inflating: emptyballs/train/empty/empty329.jpg \n inflating: emptyballs/train/empty/empty331.jpg \n inflating: emptyballs/train/empty/empty332.jpg \n inflating: emptyballs/train/empty/empty333.jpg \n inflating: emptyballs/train/empty/empty334.jpg \n inflating: emptyballs/train/empty/empty335.jpg \n inflating: emptyballs/train/empty/empty336.jpg \n inflating: emptyballs/train/empty/empty337.jpg \n inflating: emptyballs/train/empty/empty338.jpg \n inflating: emptyballs/train/empty/empty339.jpg \n inflating: emptyballs/train/empty/empty34.jpg \n inflating: emptyballs/train/empty/empty341.jpg \n inflating: emptyballs/train/empty/empty342.jpg \n inflating: emptyballs/train/empty/empty343.jpg \n inflating: emptyballs/train/empty/empty344.jpg \n inflating: emptyballs/train/empty/empty345.jpg \n inflating: emptyballs/train/empty/empty346.jpg \n inflating: emptyballs/train/empty/empty347.jpg \n inflating: emptyballs/train/empty/empty349.jpg \n inflating: emptyballs/train/empty/empty35.jpg \n inflating: emptyballs/train/empty/empty350.jpg \n inflating: emptyballs/train/empty/empty352.jpg \n inflating: emptyballs/train/empty/empty353.jpg \n inflating: emptyballs/train/empty/empty354.jpg \n inflating: emptyballs/train/empty/empty355.jpg \n inflating: emptyballs/train/empty/empty356.jpg \n inflating: emptyballs/train/empty/empty357.jpg \n inflating: emptyballs/train/empty/empty358.jpg \n inflating: emptyballs/train/empty/empty359.jpg \n inflating: emptyballs/train/empty/empty36.jpg \n inflating: emptyballs/train/empty/empty360.jpg \n inflating: emptyballs/train/empty/empty361.jpg \n inflating: emptyballs/train/empty/empty362.jpg \n inflating: emptyballs/train/empty/empty363.jpg \n inflating: emptyballs/train/empty/empty364.jpg \n inflating: emptyballs/train/empty/empty366.jpg \n inflating: emptyballs/train/empty/empty367.jpg \n inflating: emptyballs/train/empty/empty368.jpg \n inflating: emptyballs/train/empty/empty369.jpg \n inflating: emptyballs/train/empty/empty37.jpg \n inflating: emptyballs/train/empty/empty370.jpg \n inflating: emptyballs/train/empty/empty371.jpg \n inflating: emptyballs/train/empty/empty372.jpg \n inflating: emptyballs/train/empty/empty373.jpg \n inflating: emptyballs/train/empty/empty375.jpg \n inflating: emptyballs/train/empty/empty376.jpg \n inflating: emptyballs/train/empty/empty377.jpg \n inflating: emptyballs/train/empty/empty378.jpg \n inflating: emptyballs/train/empty/empty379.jpg \n inflating: emptyballs/train/empty/empty38.jpg \n inflating: emptyballs/train/empty/empty380.jpg \n inflating: emptyballs/train/empty/empty381.jpg \n inflating: emptyballs/train/empty/empty382.jpg \n inflating: emptyballs/train/empty/empty383.jpg \n inflating: emptyballs/train/empty/empty384.jpg \n inflating: emptyballs/train/empty/empty385.jpg \n inflating: emptyballs/train/empty/empty386.jpg \n inflating: emptyballs/train/empty/empty387.jpg \n inflating: emptyballs/train/empty/empty388.jpg \n inflating: emptyballs/train/empty/empty389.jpg \n inflating: emptyballs/train/empty/empty39.jpg \n inflating: emptyballs/train/empty/empty390.jpg \n inflating: emptyballs/train/empty/empty391.jpg \n inflating: emptyballs/train/empty/empty392.jpg \n inflating: emptyballs/train/empty/empty393.jpg \n inflating: emptyballs/train/empty/empty394.jpg \n inflating: emptyballs/train/empty/empty395.jpg \n inflating: emptyballs/train/empty/empty397.jpg \n inflating: emptyballs/train/empty/empty398.jpg \n inflating: emptyballs/train/empty/empty399.jpg \n inflating: emptyballs/train/empty/empty4.jpg \n inflating: emptyballs/train/empty/empty400.jpg \n inflating: emptyballs/train/empty/empty401.jpg \n inflating: emptyballs/train/empty/empty402.jpg \n inflating: emptyballs/train/empty/empty403.jpg \n inflating: emptyballs/train/empty/empty404.jpg \n inflating: emptyballs/train/empty/empty405.jpg \n inflating: emptyballs/train/empty/empty406.jpg \n inflating: emptyballs/train/empty/empty407.jpg \n inflating: emptyballs/train/empty/empty408.jpg \n inflating: emptyballs/train/empty/empty409.jpg \n inflating: emptyballs/train/empty/empty41.jpg \n inflating: emptyballs/train/empty/empty410.jpg \n inflating: emptyballs/train/empty/empty411.jpg \n inflating: emptyballs/train/empty/empty412.jpg \n inflating: emptyballs/train/empty/empty413.jpg \n inflating: emptyballs/train/empty/empty414.jpg \n inflating: emptyballs/train/empty/empty415.jpg \n inflating: emptyballs/train/empty/empty416.jpg \n inflating: emptyballs/train/empty/empty417.jpg \n inflating: emptyballs/train/empty/empty419.jpg \n inflating: emptyballs/train/empty/empty42.jpg \n inflating: emptyballs/train/empty/empty420.jpg \n inflating: emptyballs/train/empty/empty421.jpg \n inflating: emptyballs/train/empty/empty422.jpg \n inflating: emptyballs/train/empty/empty424.jpg \n inflating: emptyballs/train/empty/empty425.jpg \n inflating: emptyballs/train/empty/empty426.jpg \n inflating: emptyballs/train/empty/empty427.jpg \n inflating: emptyballs/train/empty/empty428.jpg \n inflating: emptyballs/train/empty/empty429.jpg \n inflating: emptyballs/train/empty/empty43.jpg \n inflating: emptyballs/train/empty/empty430.jpg \n inflating: emptyballs/train/empty/empty431.jpg \n inflating: emptyballs/train/empty/empty432.jpg \n inflating: emptyballs/train/empty/empty433.jpg \n inflating: emptyballs/train/empty/empty434.jpg \n inflating: emptyballs/train/empty/empty435.jpg \n inflating: emptyballs/train/empty/empty436.jpg \n inflating: emptyballs/train/empty/empty437.jpg \n inflating: emptyballs/train/empty/empty438.jpg \n inflating: emptyballs/train/empty/empty439.jpg \n inflating: emptyballs/train/empty/empty44.jpg \n inflating: emptyballs/train/empty/empty440.jpg \n inflating: emptyballs/train/empty/empty441.jpg \n inflating: emptyballs/train/empty/empty442.jpg \n inflating: emptyballs/train/empty/empty443.jpg \n inflating: emptyballs/train/empty/empty444.jpg \n inflating: emptyballs/train/empty/empty445.jpg \n inflating: emptyballs/train/empty/empty446.jpg \n inflating: emptyballs/train/empty/empty447.jpg \n inflating: emptyballs/train/empty/empty448.jpg \n inflating: emptyballs/train/empty/empty449.jpg \n inflating: emptyballs/train/empty/empty45.jpg \n inflating: emptyballs/train/empty/empty450.jpg \n inflating: emptyballs/train/empty/empty451.jpg \n inflating: emptyballs/train/empty/empty452.jpg \n inflating: emptyballs/train/empty/empty453.jpg \n inflating: emptyballs/train/empty/empty454.jpg \n inflating: emptyballs/train/empty/empty455.jpg \n inflating: emptyballs/train/empty/empty456.jpg \n inflating: emptyballs/train/empty/empty457.jpg \n inflating: emptyballs/train/empty/empty458.jpg \n inflating: emptyballs/train/empty/empty459.jpg \n inflating: emptyballs/train/empty/empty46.jpg \n inflating: emptyballs/train/empty/empty460.jpg \n inflating: emptyballs/train/empty/empty461.jpg \n inflating: emptyballs/train/empty/empty463.jpg \n inflating: emptyballs/train/empty/empty464.jpg \n inflating: emptyballs/train/empty/empty465.jpg \n inflating: emptyballs/train/empty/empty466.jpg \n inflating: emptyballs/train/empty/empty467.jpg \n inflating: emptyballs/train/empty/empty468.jpg \n inflating: emptyballs/train/empty/empty469.jpg \n inflating: emptyballs/train/empty/empty47.jpg \n inflating: emptyballs/train/empty/empty470.jpg \n inflating: emptyballs/train/empty/empty471.jpg \n inflating: emptyballs/train/empty/empty472.jpg \n inflating: emptyballs/train/empty/empty473.jpg \n inflating: emptyballs/train/empty/empty474.jpg \n inflating: emptyballs/train/empty/empty475.jpg \n inflating: emptyballs/train/empty/empty476.jpg \n inflating: emptyballs/train/empty/empty477.jpg \n inflating: emptyballs/train/empty/empty478.jpg \n inflating: emptyballs/train/empty/empty48.jpg \n inflating: emptyballs/train/empty/empty480.jpg \n inflating: emptyballs/train/empty/empty481.jpg \n inflating: emptyballs/train/empty/empty482.jpg \n inflating: emptyballs/train/empty/empty483.jpg \n inflating: emptyballs/train/empty/empty484.jpg \n inflating: emptyballs/train/empty/empty485.jpg \n inflating: emptyballs/train/empty/empty486.jpg \n inflating: emptyballs/train/empty/empty487.jpg \n inflating: emptyballs/train/empty/empty488.jpg \n inflating: emptyballs/train/empty/empty489.jpg \n inflating: emptyballs/train/empty/empty49.jpg \n inflating: emptyballs/train/empty/empty490.jpg \n inflating: emptyballs/train/empty/empty492.jpg \n inflating: emptyballs/train/empty/empty493.jpg \n inflating: emptyballs/train/empty/empty494.jpg \n inflating: emptyballs/train/empty/empty496.jpg \n inflating: emptyballs/train/empty/empty498.jpg \n inflating: emptyballs/train/empty/empty499.jpg \n inflating: emptyballs/train/empty/empty5.jpg \n inflating: emptyballs/train/empty/empty50.jpg \n inflating: emptyballs/train/empty/empty500.jpg \n inflating: emptyballs/train/empty/empty501.jpg \n inflating: emptyballs/train/empty/empty502.jpg \n inflating: emptyballs/train/empty/empty503.jpg \n inflating: emptyballs/train/empty/empty505.jpg \n inflating: emptyballs/train/empty/empty506.jpg \n inflating: emptyballs/train/empty/empty507.jpg \n inflating: emptyballs/train/empty/empty508.jpg \n inflating: emptyballs/train/empty/empty509.jpg \n inflating: emptyballs/train/empty/empty51.jpg \n inflating: emptyballs/train/empty/empty510.jpg \n inflating: emptyballs/train/empty/empty511.jpg \n inflating: emptyballs/train/empty/empty512.jpg \n inflating: emptyballs/train/empty/empty513.jpg \n inflating: emptyballs/train/empty/empty514.jpg \n inflating: emptyballs/train/empty/empty515.jpg \n inflating: emptyballs/train/empty/empty516.jpg \n inflating: emptyballs/train/empty/empty52.jpg \n inflating: emptyballs/train/empty/empty53.jpg \n inflating: emptyballs/train/empty/empty55.jpg \n inflating: emptyballs/train/empty/empty56.jpg \n inflating: emptyballs/train/empty/empty57.jpg \n inflating: emptyballs/train/empty/empty58.jpg \n inflating: emptyballs/train/empty/empty61.jpg \n inflating: emptyballs/train/empty/empty62.jpg \n inflating: emptyballs/train/empty/empty63.jpg \n inflating: emptyballs/train/empty/empty64.jpg \n inflating: emptyballs/train/empty/empty65.jpg \n inflating: emptyballs/train/empty/empty67.jpg \n inflating: emptyballs/train/empty/empty68.jpg \n inflating: emptyballs/train/empty/empty69.jpg \n inflating: emptyballs/train/empty/empty7.jpg \n inflating: emptyballs/train/empty/empty70.jpg \n inflating: emptyballs/train/empty/empty71.jpg \n inflating: emptyballs/train/empty/empty72.jpg \n inflating: emptyballs/train/empty/empty73.jpg \n inflating: emptyballs/train/empty/empty75.jpg \n inflating: emptyballs/train/empty/empty76.jpg \n inflating: emptyballs/train/empty/empty77.jpg \n inflating: emptyballs/train/empty/empty78.jpg \n inflating: emptyballs/train/empty/empty79.jpg \n inflating: emptyballs/train/empty/empty8.jpg \n inflating: emptyballs/train/empty/empty80.jpg \n inflating: emptyballs/train/empty/empty81.jpg \n inflating: emptyballs/train/empty/empty82.jpg \n inflating: emptyballs/train/empty/empty83.jpg \n inflating: emptyballs/train/empty/empty84.jpg \n inflating: emptyballs/train/empty/empty85.jpg \n inflating: emptyballs/train/empty/empty86.jpg \n inflating: emptyballs/train/empty/empty87.jpg \n inflating: emptyballs/train/empty/empty88.jpg \n inflating: emptyballs/train/empty/empty89.jpg \n inflating: emptyballs/train/empty/empty9.jpg \n inflating: emptyballs/train/empty/empty90.jpg \n inflating: emptyballs/train/empty/empty91.jpg \n inflating: emptyballs/train/empty/empty92.jpg \n inflating: emptyballs/train/empty/empty93.jpg \n inflating: emptyballs/train/empty/empty94.jpg \n inflating: emptyballs/train/empty/empty95.jpg \n inflating: emptyballs/train/empty/empty96.jpg \n inflating: emptyballs/train/empty/empty98.jpg \n inflating: test/balls/ball100.jpg \n inflating: test/balls/ball116.jpg \n inflating: test/balls/ball118.jpg \n inflating: test/balls/ball129.jpg \n inflating: test/balls/ball152.jpg \n inflating: test/balls/ball166.jpg \n inflating: test/balls/ball169.jpg \n inflating: test/balls/ball187.jpg \n inflating: test/balls/ball19.jpg \n inflating: test/balls/ball194.jpg \n inflating: test/balls/ball200.jpg \n inflating: test/balls/ball203.jpg \n inflating: test/balls/ball21.jpg \n inflating: test/balls/ball232.jpg \n inflating: test/balls/ball300.jpg \n inflating: test/balls/ball301.jpg \n inflating: test/balls/ball324.jpg \n inflating: test/balls/ball327.jpg \n inflating: test/balls/ball328.jpg \n inflating: test/balls/ball342.jpg \n inflating: test/balls/ball401.jpg \n inflating: test/balls/ball402.jpg \n inflating: test/balls/ball428.jpg \n inflating: test/balls/ball432.jpg \n inflating: test/balls/ball436.jpg \n inflating: test/balls/ball459.jpg \n inflating: test/balls/ball479.jpg \n inflating: test/balls/ball48.jpg \n inflating: test/balls/ball482.jpg \n inflating: test/balls/ball5.jpg \n inflating: test/balls/ball508.jpg \n inflating: test/balls/ball517.jpg \n inflating: test/balls/ball525.jpg \n inflating: test/balls/ball536.jpg \n inflating: test/balls/ball537.jpg \n inflating: test/balls/ball542.jpg \n inflating: test/balls/ball68.jpg \n inflating: test/balls/ball69.jpg \n inflating: test/balls/ball72.jpg \n inflating: test/balls/ball97.jpg \n inflating: test/empty/empty128.jpg \n inflating: test/empty/empty14.jpg \n inflating: test/empty/empty142.jpg \n inflating: test/empty/empty146.jpg \n inflating: test/empty/empty167.jpg \n inflating: test/empty/empty179.jpg \n inflating: test/empty/empty184.jpg \n inflating: test/empty/empty186.jpg \n inflating: test/empty/empty202.jpg \n inflating: test/empty/empty21.jpg \n inflating: test/empty/empty211.jpg \n inflating: test/empty/empty220.jpg \n inflating: test/empty/empty225.jpg \n inflating: test/empty/empty243.jpg \n inflating: test/empty/empty33.jpg \n inflating: test/empty/empty330.jpg \n inflating: test/empty/empty340.jpg \n inflating: test/empty/empty348.jpg \n inflating: test/empty/empty351.jpg \n inflating: test/empty/empty365.jpg \n inflating: test/empty/empty374.jpg \n inflating: test/empty/empty396.jpg \n inflating: test/empty/empty40.jpg \n inflating: test/empty/empty418.jpg \n inflating: test/empty/empty423.jpg \n inflating: test/empty/empty462.jpg \n inflating: test/empty/empty479.jpg \n inflating: test/empty/empty491.jpg \n inflating: test/empty/empty495.jpg \n inflating: test/empty/empty497.jpg \n inflating: test/empty/empty504.jpg \n inflating: test/empty/empty517.jpg \n inflating: test/empty/empty54.jpg \n inflating: test/empty/empty59.jpg \n inflating: test/empty/empty6.jpg \n inflating: test/empty/empty60.jpg \n inflating: test/empty/empty66.jpg \n inflating: test/empty/empty74.jpg \n inflating: test/empty/empty97.jpg \n inflating: test/empty/empty99.jpg \n inflating: train/balls/ball0.jpg \n inflating: train/balls/ball1.jpg \n inflating: train/balls/ball10.jpg \n inflating: train/balls/ball101.jpg \n inflating: train/balls/ball102.jpg \n inflating: train/balls/ball103.jpg \n inflating: train/balls/ball104.jpg \n inflating: train/balls/ball105.jpg \n inflating: train/balls/ball106.jpg \n inflating: train/balls/ball107.jpg \n inflating: train/balls/ball108.jpg \n inflating: train/balls/ball109.jpg \n inflating: train/balls/ball11.jpg \n inflating: train/balls/ball110.jpg \n inflating: train/balls/ball111.jpg \n inflating: train/balls/ball112.jpg \n inflating: train/balls/ball113.jpg \n inflating: train/balls/ball114.jpg \n inflating: train/balls/ball115.jpg \n inflating: train/balls/ball117.jpg \n inflating: train/balls/ball119.jpg \n inflating: train/balls/ball12.jpg \n inflating: train/balls/ball120.jpg \n inflating: train/balls/ball121.jpg \n inflating: train/balls/ball122.jpg \n inflating: train/balls/ball123.jpg \n inflating: train/balls/ball124.jpg \n inflating: train/balls/ball125.jpg \n inflating: train/balls/ball126.jpg \n inflating: train/balls/ball127.jpg \n inflating: train/balls/ball128.jpg \n inflating: train/balls/ball13.jpg \n inflating: train/balls/ball130.jpg \n inflating: train/balls/ball131.jpg \n inflating: train/balls/ball132.jpg \n inflating: train/balls/ball133.jpg \n inflating: train/balls/ball134.jpg \n inflating: train/balls/ball135.jpg \n inflating: train/balls/ball136.jpg \n inflating: train/balls/ball137.jpg \n inflating: train/balls/ball138.jpg \n inflating: train/balls/ball139.jpg \n inflating: train/balls/ball14.jpg \n inflating: train/balls/ball140.jpg \n inflating: train/balls/ball141.jpg \n inflating: train/balls/ball142.jpg \n inflating: train/balls/ball143.jpg \n inflating: train/balls/ball144.jpg \n inflating: train/balls/ball145.jpg \n inflating: train/balls/ball146.jpg \n inflating: train/balls/ball147.jpg \n inflating: train/balls/ball148.jpg \n inflating: train/balls/ball149.jpg \n inflating: train/balls/ball15.jpg \n inflating: train/balls/ball150.jpg \n inflating: train/balls/ball151.jpg \n inflating: train/balls/ball153.jpg \n inflating: train/balls/ball154.jpg \n inflating: train/balls/ball155.jpg \n inflating: train/balls/ball156.jpg \n inflating: train/balls/ball157.jpg \n inflating: train/balls/ball158.jpg \n inflating: train/balls/ball159.jpg \n inflating: train/balls/ball16.jpg \n inflating: train/balls/ball160.jpg \n inflating: train/balls/ball161.jpg \n inflating: train/balls/ball162.jpg \n inflating: train/balls/ball163.jpg \n inflating: train/balls/ball164.jpg \n inflating: train/balls/ball165.jpg \n inflating: train/balls/ball167.jpg \n inflating: train/balls/ball168.jpg \n inflating: train/balls/ball17.jpg \n inflating: train/balls/ball170.jpg \n inflating: train/balls/ball171.jpg \n inflating: train/balls/ball172.jpg \n inflating: train/balls/ball173.jpg \n inflating: train/balls/ball174.jpg \n inflating: train/balls/ball175.jpg \n inflating: train/balls/ball176.jpg \n inflating: train/balls/ball177.jpg \n inflating: train/balls/ball178.jpg \n inflating: train/balls/ball179.jpg \n inflating: train/balls/ball18.jpg \n inflating: train/balls/ball180.jpg \n inflating: train/balls/ball181.jpg \n inflating: train/balls/ball182.jpg \n inflating: train/balls/ball183.jpg \n inflating: train/balls/ball184.jpg \n inflating: train/balls/ball185.jpg \n inflating: train/balls/ball186.jpg \n inflating: train/balls/ball188.jpg \n inflating: train/balls/ball189.jpg \n inflating: train/balls/ball190.jpg \n inflating: train/balls/ball191.jpg \n inflating: train/balls/ball192.jpg \n inflating: train/balls/ball193.jpg \n inflating: train/balls/ball195.jpg \n inflating: train/balls/ball196.jpg \n inflating: train/balls/ball197.jpg \n inflating: train/balls/ball198.jpg \n inflating: train/balls/ball199.jpg \n inflating: train/balls/ball2.jpg \n inflating: train/balls/ball20.jpg \n inflating: train/balls/ball201.jpg \n inflating: train/balls/ball202.jpg \n inflating: train/balls/ball204.jpg \n inflating: train/balls/ball205.jpg \n inflating: train/balls/ball206.jpg \n inflating: train/balls/ball207.jpg \n inflating: train/balls/ball208.jpg \n inflating: train/balls/ball209.jpg \n inflating: train/balls/ball210.jpg \n inflating: train/balls/ball211.jpg \n inflating: train/balls/ball212.jpg \n inflating: train/balls/ball213.jpg \n inflating: train/balls/ball214.jpg \n inflating: train/balls/ball215.jpg \n inflating: train/balls/ball216.jpg \n inflating: train/balls/ball217.jpg \n inflating: train/balls/ball218.jpg \n inflating: train/balls/ball219.jpg \n inflating: train/balls/ball22.jpg \n inflating: train/balls/ball220.jpg \n inflating: train/balls/ball221.jpg \n inflating: train/balls/ball222.jpg \n inflating: train/balls/ball223.jpg \n inflating: train/balls/ball224.jpg \n inflating: train/balls/ball225.jpg \n inflating: train/balls/ball226.jpg \n inflating: train/balls/ball227.jpg \n inflating: train/balls/ball228.jpg \n inflating: train/balls/ball229.jpg \n inflating: train/balls/ball23.jpg \n inflating: train/balls/ball230.jpg \n inflating: train/balls/ball231.jpg \n inflating: train/balls/ball233.jpg \n inflating: train/balls/ball234.jpg \n inflating: train/balls/ball235.jpg \n inflating: train/balls/ball236.jpg \n inflating: train/balls/ball237.jpg \n inflating: train/balls/ball238.jpg \n inflating: train/balls/ball239.jpg \n inflating: train/balls/ball24.jpg \n inflating: train/balls/ball240.jpg \n inflating: train/balls/ball241.jpg \n inflating: train/balls/ball242.jpg \n inflating: train/balls/ball243.jpg \n inflating: train/balls/ball244.jpg \n inflating: train/balls/ball245.jpg \n inflating: train/balls/ball246.jpg \n inflating: train/balls/ball247.jpg \n inflating: train/balls/ball248.jpg \n inflating: train/balls/ball249.jpg \n inflating: train/balls/ball25.jpg \n inflating: train/balls/ball250.jpg \n inflating: train/balls/ball251.jpg \n inflating: train/balls/ball252.jpg \n inflating: train/balls/ball253.jpg \n inflating: train/balls/ball254.jpg \n inflating: train/balls/ball255.jpg \n inflating: train/balls/ball256.jpg \n inflating: train/balls/ball257.jpg \n inflating: train/balls/ball258.jpg \n inflating: train/balls/ball26.jpg \n inflating: train/balls/ball27.jpg \n inflating: train/balls/ball28.jpg \n inflating: train/balls/ball29.jpg \n inflating: train/balls/ball3.jpg \n inflating: train/balls/ball30.jpg \n inflating: train/balls/ball302.jpg \n inflating: train/balls/ball303.jpg \n inflating: train/balls/ball304.jpg \n inflating: train/balls/ball305.jpg \n inflating: train/balls/ball306.jpg \n inflating: train/balls/ball307.jpg \n inflating: train/balls/ball308.jpg \n inflating: train/balls/ball309.jpg \n inflating: train/balls/ball31.jpg \n inflating: train/balls/ball310.jpg \n inflating: train/balls/ball311.jpg \n inflating: train/balls/ball312.jpg \n inflating: train/balls/ball313.jpg \n inflating: train/balls/ball314.jpg \n inflating: train/balls/ball315.jpg \n inflating: train/balls/ball317.jpg \n inflating: train/balls/ball318.jpg \n inflating: train/balls/ball319.jpg \n inflating: train/balls/ball32.jpg \n inflating: train/balls/ball320.jpg \n inflating: train/balls/ball321.jpg \n inflating: train/balls/ball322.jpg \n inflating: train/balls/ball323.jpg \n inflating: train/balls/ball325.jpg \n inflating: train/balls/ball326.jpg \n inflating: train/balls/ball329.jpg \n inflating: train/balls/ball33.jpg \n inflating: train/balls/ball330.jpg \n inflating: train/balls/ball331.jpg \n inflating: train/balls/ball332.jpg \n inflating: train/balls/ball333.jpg \n inflating: train/balls/ball334.jpg \n inflating: train/balls/ball335.jpg \n inflating: train/balls/ball336.jpg \n inflating: train/balls/ball337.jpg \n inflating: train/balls/ball338.jpg \n inflating: train/balls/ball34.jpg \n inflating: train/balls/ball340.jpg \n inflating: train/balls/ball341.jpg \n inflating: train/balls/ball343.jpg \n inflating: train/balls/ball344.jpg \n inflating: train/balls/ball345.jpg \n inflating: train/balls/ball35.jpg \n inflating: train/balls/ball36.jpg \n inflating: train/balls/ball37.jpg \n inflating: train/balls/ball38.jpg \n inflating: train/balls/ball39.jpg \n inflating: train/balls/ball4.jpg \n inflating: train/balls/ball40.jpg \n inflating: train/balls/ball400.jpg \n inflating: train/balls/ball403.jpg \n inflating: train/balls/ball404.jpg \n inflating: train/balls/ball405.jpg \n inflating: train/balls/ball406.jpg \n inflating: train/balls/ball407.jpg \n inflating: train/balls/ball408.jpg \n inflating: train/balls/ball409.jpg \n inflating: train/balls/ball41.jpg \n inflating: train/balls/ball410.jpg \n inflating: train/balls/ball411.jpg \n inflating: train/balls/ball412.jpg \n inflating: train/balls/ball413.jpg \n inflating: train/balls/ball414.jpg \n inflating: train/balls/ball415.jpg \n inflating: train/balls/ball416.jpg \n inflating: train/balls/ball417.jpg \n inflating: train/balls/ball418.jpg \n inflating: train/balls/ball419.jpg \n inflating: train/balls/ball42.jpg \n inflating: train/balls/ball420.jpg \n inflating: train/balls/ball421.jpg \n inflating: train/balls/ball422.jpg \n inflating: train/balls/ball423.jpg \n inflating: train/balls/ball424.jpg \n inflating: train/balls/ball425.jpg \n inflating: train/balls/ball426.jpg \n inflating: train/balls/ball427.jpg \n inflating: train/balls/ball429.jpg \n inflating: train/balls/ball43.jpg \n inflating: train/balls/ball430.jpg \n inflating: train/balls/ball431.jpg \n inflating: train/balls/ball433.jpg \n inflating: train/balls/ball434.jpg \n inflating: train/balls/ball435.jpg \n inflating: train/balls/ball437.jpg \n inflating: train/balls/ball438.jpg \n inflating: train/balls/ball439.jpg \n inflating: train/balls/ball44.jpg \n inflating: train/balls/ball440.jpg \n inflating: train/balls/ball441.jpg \n inflating: train/balls/ball442.jpg \n inflating: train/balls/ball443.jpg \n inflating: train/balls/ball444.jpg \n inflating: train/balls/ball445.jpg \n inflating: train/balls/ball446.jpg \n inflating: train/balls/ball447.jpg \n inflating: train/balls/ball448.jpg \n inflating: train/balls/ball449.jpg \n inflating: train/balls/ball45.jpg \n inflating: train/balls/ball450.jpg \n inflating: train/balls/ball451.jpg \n inflating: train/balls/ball452.jpg \n inflating: train/balls/ball453.jpg \n inflating: train/balls/ball454.jpg \n inflating: train/balls/ball455.jpg \n inflating: train/balls/ball456.jpg \n inflating: train/balls/ball457.jpg \n inflating: train/balls/ball458.jpg \n inflating: train/balls/ball46.jpg \n inflating: train/balls/ball460.jpg \n inflating: train/balls/ball461.jpg \n inflating: train/balls/ball462.jpg \n inflating: train/balls/ball463.jpg \n inflating: train/balls/ball464.jpg \n inflating: train/balls/ball465.jpg \n inflating: train/balls/ball466.jpg \n inflating: train/balls/ball467.jpg \n inflating: train/balls/ball468.jpg \n inflating: train/balls/ball469.jpg \n inflating: train/balls/ball47.jpg \n inflating: train/balls/ball470.jpg \n inflating: train/balls/ball471.jpg \n inflating: train/balls/ball472.jpg \n inflating: train/balls/ball473.jpg \n inflating: train/balls/ball474.jpg \n inflating: train/balls/ball475.jpg \n inflating: train/balls/ball476.jpg \n inflating: train/balls/ball477.jpg \n inflating: train/balls/ball478.jpg \n inflating: train/balls/ball480.jpg \n inflating: train/balls/ball481.jpg \n inflating: train/balls/ball483.jpg \n inflating: train/balls/ball484.jpg \n inflating: train/balls/ball485.jpg \n inflating: train/balls/ball486.jpg \n inflating: train/balls/ball487.jpg \n inflating: train/balls/ball488.jpg \n inflating: train/balls/ball489.jpg \n inflating: train/balls/ball49.jpg \n inflating: train/balls/ball490.jpg \n inflating: train/balls/ball491.jpg \n inflating: train/balls/ball492.jpg \n inflating: train/balls/ball493.jpg \n inflating: train/balls/ball494.jpg \n inflating: train/balls/ball495.jpg \n inflating: train/balls/ball496.jpg \n inflating: train/balls/ball497.jpg \n inflating: train/balls/ball498.jpg \n inflating: train/balls/ball499.jpg \n inflating: train/balls/ball50.jpg \n inflating: train/balls/ball500.jpg \n inflating: train/balls/ball501.jpg \n inflating: train/balls/ball502.jpg \n inflating: train/balls/ball503.jpg \n inflating: train/balls/ball504.jpg \n inflating: train/balls/ball505.jpg \n inflating: train/balls/ball506.jpg \n inflating: train/balls/ball507.jpg \n inflating: train/balls/ball509.jpg \n inflating: train/balls/ball51.jpg \n inflating: train/balls/ball510.jpg \n inflating: train/balls/ball511.jpg \n inflating: train/balls/ball512.jpg \n inflating: train/balls/ball513.jpg \n inflating: train/balls/ball514.jpg \n inflating: train/balls/ball515.jpg \n inflating: train/balls/ball516.jpg \n inflating: train/balls/ball518.jpg \n inflating: train/balls/ball519.jpg \n inflating: train/balls/ball52.jpg \n inflating: train/balls/ball520.jpg \n inflating: train/balls/ball521.jpg \n inflating: train/balls/ball522.jpg \n inflating: train/balls/ball523.jpg \n inflating: train/balls/ball524.jpg \n inflating: train/balls/ball526.jpg \n inflating: train/balls/ball527.jpg \n inflating: train/balls/ball528.jpg \n inflating: train/balls/ball529.jpg \n inflating: train/balls/ball53.jpg \n inflating: train/balls/ball530.jpg \n inflating: train/balls/ball531.jpg \n inflating: train/balls/ball532.jpg \n inflating: train/balls/ball533.jpg \n inflating: train/balls/ball534.jpg \n inflating: train/balls/ball535.jpg \n inflating: train/balls/ball538.jpg \n inflating: train/balls/ball539.jpg \n inflating: train/balls/ball54.jpg \n inflating: train/balls/ball540.jpg \n inflating: train/balls/ball541.jpg \n inflating: train/balls/ball55.jpg \n inflating: train/balls/ball56.jpg \n inflating: train/balls/ball57.jpg \n inflating: train/balls/ball58.jpg \n inflating: train/balls/ball59.jpg \n inflating: train/balls/ball6.jpg \n inflating: train/balls/ball60.jpg \n inflating: train/balls/ball61.jpg \n inflating: train/balls/ball62.jpg \n inflating: train/balls/ball63.jpg \n inflating: train/balls/ball64.jpg \n inflating: train/balls/ball65.jpg \n inflating: train/balls/ball66.jpg \n inflating: train/balls/ball67.jpg \n inflating: train/balls/ball7.jpg \n inflating: train/balls/ball70.jpg \n inflating: train/balls/ball71.jpg \n inflating: train/balls/ball73.jpg \n inflating: train/balls/ball74.jpg \n inflating: train/balls/ball75.jpg \n inflating: train/balls/ball76.jpg \n inflating: train/balls/ball77.jpg \n inflating: train/balls/ball78.jpg \n inflating: train/balls/ball79.jpg \n inflating: train/balls/ball8.jpg \n inflating: train/balls/ball80.jpg \n inflating: train/balls/ball81.jpg \n inflating: train/balls/ball82.jpg \n inflating: train/balls/ball83.jpg \n inflating: train/balls/ball84.jpg \n inflating: train/balls/ball85.jpg \n inflating: train/balls/ball86.jpg \n inflating: train/balls/ball87.jpg \n inflating: train/balls/ball88.jpg \n inflating: train/balls/ball89.jpg \n inflating: train/balls/ball9.jpg \n inflating: train/balls/ball90.jpg \n inflating: train/balls/ball91.jpg \n inflating: train/balls/ball92.jpg \n inflating: train/balls/ball93.jpg \n inflating: train/balls/ball94.jpg \n inflating: train/balls/ball95.jpg \n inflating: train/balls/ball96.jpg \n inflating: train/balls/ball98.jpg \n inflating: train/balls/ball99.jpg \n inflating: train/empty/empty0.jpg \n inflating: train/empty/empty1.jpg \n inflating: train/empty/empty10.jpg \n inflating: train/empty/empty100.jpg \n inflating: train/empty/empty101.jpg \n inflating: train/empty/empty102.jpg \n inflating: train/empty/empty103.jpg \n inflating: train/empty/empty104.jpg \n inflating: train/empty/empty105.jpg \n inflating: train/empty/empty106.jpg \n inflating: train/empty/empty107.jpg \n inflating: train/empty/empty108.jpg \n inflating: train/empty/empty109.jpg \n inflating: train/empty/empty11.jpg \n inflating: train/empty/empty110.jpg \n inflating: train/empty/empty111.jpg \n inflating: train/empty/empty112.jpg \n inflating: train/empty/empty113.jpg \n inflating: train/empty/empty114.jpg \n inflating: train/empty/empty115.jpg \n inflating: train/empty/empty116.jpg \n inflating: train/empty/empty117.jpg \n inflating: train/empty/empty118.jpg \n inflating: train/empty/empty119.jpg \n inflating: train/empty/empty12.jpg \n inflating: train/empty/empty120.jpg \n inflating: train/empty/empty121.jpg \n inflating: train/empty/empty122.jpg \n inflating: train/empty/empty123.jpg \n inflating: train/empty/empty124.jpg \n inflating: train/empty/empty125.jpg \n inflating: train/empty/empty126.jpg \n inflating: train/empty/empty127.jpg \n inflating: train/empty/empty129.jpg \n inflating: train/empty/empty13.jpg \n inflating: train/empty/empty130.jpg \n inflating: train/empty/empty131.jpg \n inflating: train/empty/empty132.jpg \n inflating: train/empty/empty133.jpg \n inflating: train/empty/empty134.jpg \n inflating: train/empty/empty135.jpg \n inflating: train/empty/empty136.jpg \n inflating: train/empty/empty137.jpg \n inflating: train/empty/empty138.jpg \n inflating: train/empty/empty139.jpg \n inflating: train/empty/empty140.jpg \n inflating: train/empty/empty141.jpg \n inflating: train/empty/empty143.jpg \n inflating: train/empty/empty144.jpg \n inflating: train/empty/empty145.jpg \n inflating: train/empty/empty147.jpg \n inflating: train/empty/empty148.jpg \n inflating: train/empty/empty149.jpg \n inflating: train/empty/empty15.jpg \n inflating: train/empty/empty150.jpg \n inflating: train/empty/empty151.jpg \n inflating: train/empty/empty152.jpg \n inflating: train/empty/empty153.jpg \n inflating: train/empty/empty154.jpg \n inflating: train/empty/empty155.jpg \n inflating: train/empty/empty156.jpg \n inflating: train/empty/empty157.jpg \n inflating: train/empty/empty158.jpg \n inflating: train/empty/empty159.jpg \n inflating: train/empty/empty16.jpg \n inflating: train/empty/empty160.jpg \n inflating: train/empty/empty161.jpg \n inflating: train/empty/empty162.jpg \n inflating: train/empty/empty163.jpg \n inflating: train/empty/empty164.jpg \n inflating: train/empty/empty165.jpg \n inflating: train/empty/empty166.jpg \n inflating: train/empty/empty168.jpg \n inflating: train/empty/empty169.jpg \n inflating: train/empty/empty17.jpg \n inflating: train/empty/empty170.jpg \n inflating: train/empty/empty171.jpg \n inflating: train/empty/empty172.jpg \n inflating: train/empty/empty173.jpg \n inflating: train/empty/empty174.jpg \n inflating: train/empty/empty175.jpg \n inflating: train/empty/empty176.jpg \n inflating: train/empty/empty177.jpg \n inflating: train/empty/empty178.jpg \n inflating: train/empty/empty18.jpg \n inflating: train/empty/empty180.jpg \n inflating: train/empty/empty181.jpg \n inflating: train/empty/empty182.jpg \n inflating: train/empty/empty183.jpg \n inflating: train/empty/empty185.jpg \n inflating: train/empty/empty187.jpg \n inflating: train/empty/empty188.jpg \n inflating: train/empty/empty189.jpg \n inflating: train/empty/empty19.jpg \n inflating: train/empty/empty190.jpg \n inflating: train/empty/empty191.jpg \n inflating: train/empty/empty192.jpg \n inflating: train/empty/empty193.jpg \n inflating: train/empty/empty194.jpg \n inflating: train/empty/empty195.jpg \n inflating: train/empty/empty196.jpg \n inflating: train/empty/empty197.jpg \n inflating: train/empty/empty198.jpg \n inflating: train/empty/empty199.jpg \n inflating: train/empty/empty2.jpg \n inflating: train/empty/empty20.jpg \n inflating: train/empty/empty200.jpg \n inflating: train/empty/empty201.jpg \n inflating: train/empty/empty203.jpg \n inflating: train/empty/empty204.jpg \n inflating: train/empty/empty205.jpg \n inflating: train/empty/empty206.jpg \n inflating: train/empty/empty207.jpg \n inflating: train/empty/empty208.jpg \n inflating: train/empty/empty209.jpg \n inflating: train/empty/empty210.jpg \n inflating: train/empty/empty212.jpg \n inflating: train/empty/empty213.jpg \n inflating: train/empty/empty214.jpg \n inflating: train/empty/empty215.jpg \n inflating: train/empty/empty216.jpg \n inflating: train/empty/empty217.jpg \n inflating: train/empty/empty218.jpg \n inflating: train/empty/empty219.jpg \n inflating: train/empty/empty22.jpg \n inflating: train/empty/empty221.jpg \n inflating: train/empty/empty222.jpg \n inflating: train/empty/empty223.jpg \n inflating: train/empty/empty224.jpg \n inflating: train/empty/empty226.jpg \n inflating: train/empty/empty227.jpg \n inflating: train/empty/empty228.jpg \n inflating: train/empty/empty229.jpg \n inflating: train/empty/empty23.jpg \n inflating: train/empty/empty230.jpg \n inflating: train/empty/empty231.jpg \n inflating: train/empty/empty232.jpg \n inflating: train/empty/empty233.jpg \n inflating: train/empty/empty234.jpg \n inflating: train/empty/empty235.jpg \n inflating: train/empty/empty236.jpg \n inflating: train/empty/empty237.jpg \n inflating: train/empty/empty238.jpg \n inflating: train/empty/empty239.jpg \n inflating: train/empty/empty24.jpg \n inflating: train/empty/empty240.jpg \n inflating: train/empty/empty241.jpg \n inflating: train/empty/empty242.jpg \n inflating: train/empty/empty244.jpg \n inflating: train/empty/empty245.jpg \n inflating: train/empty/empty25.jpg \n inflating: train/empty/empty26.jpg \n inflating: train/empty/empty27.jpg \n inflating: train/empty/empty28.jpg \n inflating: train/empty/empty29.jpg \n inflating: train/empty/empty3.jpg \n inflating: train/empty/empty30.jpg \n inflating: train/empty/empty300.jpg \n inflating: train/empty/empty301.jpg \n inflating: train/empty/empty302.jpg \n inflating: train/empty/empty303.jpg \n inflating: train/empty/empty304.jpg \n inflating: train/empty/empty305.jpg \n inflating: train/empty/empty306.jpg \n inflating: train/empty/empty307.jpg \n inflating: train/empty/empty308.jpg \n inflating: train/empty/empty309.jpg \n inflating: train/empty/empty31.jpg \n inflating: train/empty/empty310.jpg \n inflating: train/empty/empty311.jpg \n inflating: train/empty/empty312.jpg \n inflating: train/empty/empty32.jpg \n inflating: train/empty/empty320.jpg \n inflating: train/empty/empty321.jpg \n inflating: train/empty/empty322.jpg \n inflating: train/empty/empty323.jpg \n inflating: train/empty/empty324.jpg \n inflating: train/empty/empty325.jpg \n inflating: train/empty/empty326.jpg \n inflating: train/empty/empty327.jpg \n inflating: train/empty/empty328.jpg \n inflating: train/empty/empty329.jpg \n inflating: train/empty/empty331.jpg \n inflating: train/empty/empty332.jpg \n inflating: train/empty/empty333.jpg \n inflating: train/empty/empty334.jpg \n inflating: train/empty/empty335.jpg \n inflating: train/empty/empty336.jpg \n inflating: train/empty/empty337.jpg \n inflating: train/empty/empty338.jpg \n inflating: train/empty/empty339.jpg \n inflating: train/empty/empty34.jpg \n inflating: train/empty/empty341.jpg \n inflating: train/empty/empty342.jpg \n inflating: train/empty/empty343.jpg \n inflating: train/empty/empty344.jpg \n inflating: train/empty/empty345.jpg \n inflating: train/empty/empty346.jpg \n inflating: train/empty/empty347.jpg \n inflating: train/empty/empty349.jpg \n inflating: train/empty/empty35.jpg \n inflating: train/empty/empty350.jpg \n inflating: train/empty/empty352.jpg \n inflating: train/empty/empty353.jpg \n inflating: train/empty/empty354.jpg \n inflating: train/empty/empty355.jpg \n inflating: train/empty/empty356.jpg \n inflating: train/empty/empty357.jpg \n inflating: train/empty/empty358.jpg \n inflating: train/empty/empty359.jpg \n inflating: train/empty/empty36.jpg \n inflating: train/empty/empty360.jpg \n inflating: train/empty/empty361.jpg \n inflating: train/empty/empty362.jpg \n inflating: train/empty/empty363.jpg \n inflating: train/empty/empty364.jpg \n inflating: train/empty/empty366.jpg \n inflating: train/empty/empty367.jpg \n inflating: train/empty/empty368.jpg \n inflating: train/empty/empty369.jpg \n inflating: train/empty/empty37.jpg \n inflating: train/empty/empty370.jpg \n inflating: train/empty/empty371.jpg \n inflating: train/empty/empty372.jpg \n inflating: train/empty/empty373.jpg \n inflating: train/empty/empty375.jpg \n inflating: train/empty/empty376.jpg \n inflating: train/empty/empty377.jpg \n inflating: train/empty/empty378.jpg \n inflating: train/empty/empty379.jpg \n inflating: train/empty/empty38.jpg \n inflating: train/empty/empty380.jpg \n inflating: train/empty/empty381.jpg \n inflating: train/empty/empty382.jpg \n inflating: train/empty/empty383.jpg \n inflating: train/empty/empty384.jpg \n inflating: train/empty/empty385.jpg \n inflating: train/empty/empty386.jpg \n inflating: train/empty/empty387.jpg \n inflating: train/empty/empty388.jpg \n inflating: train/empty/empty389.jpg \n inflating: train/empty/empty39.jpg \n inflating: train/empty/empty390.jpg \n inflating: train/empty/empty391.jpg \n inflating: train/empty/empty392.jpg \n inflating: train/empty/empty393.jpg \n inflating: train/empty/empty394.jpg \n inflating: train/empty/empty395.jpg \n inflating: train/empty/empty397.jpg \n inflating: train/empty/empty398.jpg \n inflating: train/empty/empty399.jpg \n inflating: train/empty/empty4.jpg \n inflating: train/empty/empty400.jpg \n inflating: train/empty/empty401.jpg \n inflating: train/empty/empty402.jpg \n inflating: train/empty/empty403.jpg \n inflating: train/empty/empty404.jpg \n inflating: train/empty/empty405.jpg \n inflating: train/empty/empty406.jpg \n inflating: train/empty/empty407.jpg \n inflating: train/empty/empty408.jpg \n inflating: train/empty/empty409.jpg \n inflating: train/empty/empty41.jpg \n inflating: train/empty/empty410.jpg \n inflating: train/empty/empty411.jpg \n inflating: train/empty/empty412.jpg \n inflating: train/empty/empty413.jpg \n inflating: train/empty/empty414.jpg \n inflating: train/empty/empty415.jpg \n inflating: train/empty/empty416.jpg \n inflating: train/empty/empty417.jpg \n inflating: train/empty/empty419.jpg \n inflating: train/empty/empty42.jpg \n inflating: train/empty/empty420.jpg \n inflating: train/empty/empty421.jpg \n inflating: train/empty/empty422.jpg \n inflating: train/empty/empty424.jpg \n inflating: train/empty/empty425.jpg \n inflating: train/empty/empty426.jpg \n inflating: train/empty/empty427.jpg \n inflating: train/empty/empty428.jpg \n inflating: train/empty/empty429.jpg \n inflating: train/empty/empty43.jpg \n inflating: train/empty/empty430.jpg \n inflating: train/empty/empty431.jpg \n inflating: train/empty/empty432.jpg \n inflating: train/empty/empty433.jpg \n inflating: train/empty/empty434.jpg \n inflating: train/empty/empty435.jpg \n inflating: train/empty/empty436.jpg \n inflating: train/empty/empty437.jpg \n inflating: train/empty/empty438.jpg \n inflating: train/empty/empty439.jpg \n inflating: train/empty/empty44.jpg \n inflating: train/empty/empty440.jpg \n inflating: train/empty/empty441.jpg \n inflating: train/empty/empty442.jpg \n inflating: train/empty/empty443.jpg \n inflating: train/empty/empty444.jpg \n inflating: train/empty/empty445.jpg \n inflating: train/empty/empty446.jpg \n inflating: train/empty/empty447.jpg \n inflating: train/empty/empty448.jpg \n inflating: train/empty/empty449.jpg \n inflating: train/empty/empty45.jpg \n inflating: train/empty/empty450.jpg \n inflating: train/empty/empty451.jpg \n inflating: train/empty/empty452.jpg \n inflating: train/empty/empty453.jpg \n inflating: train/empty/empty454.jpg \n inflating: train/empty/empty455.jpg \n inflating: train/empty/empty456.jpg \n inflating: train/empty/empty457.jpg \n inflating: train/empty/empty458.jpg \n inflating: train/empty/empty459.jpg \n inflating: train/empty/empty46.jpg \n inflating: train/empty/empty460.jpg \n inflating: train/empty/empty461.jpg \n inflating: train/empty/empty463.jpg \n inflating: train/empty/empty464.jpg \n inflating: train/empty/empty465.jpg \n inflating: train/empty/empty466.jpg \n inflating: train/empty/empty467.jpg \n inflating: train/empty/empty468.jpg \n inflating: train/empty/empty469.jpg \n inflating: train/empty/empty47.jpg \n inflating: train/empty/empty470.jpg \n inflating: train/empty/empty471.jpg \n inflating: train/empty/empty472.jpg \n inflating: train/empty/empty473.jpg \n inflating: train/empty/empty474.jpg \n inflating: train/empty/empty475.jpg \n inflating: train/empty/empty476.jpg \n inflating: train/empty/empty477.jpg \n inflating: train/empty/empty478.jpg \n inflating: train/empty/empty48.jpg \n inflating: train/empty/empty480.jpg \n inflating: train/empty/empty481.jpg \n inflating: train/empty/empty482.jpg \n inflating: train/empty/empty483.jpg \n inflating: train/empty/empty484.jpg \n inflating: train/empty/empty485.jpg \n inflating: train/empty/empty486.jpg \n inflating: train/empty/empty487.jpg \n inflating: train/empty/empty488.jpg \n inflating: train/empty/empty489.jpg \n inflating: train/empty/empty49.jpg \n inflating: train/empty/empty490.jpg \n inflating: train/empty/empty492.jpg \n inflating: train/empty/empty493.jpg \n inflating: train/empty/empty494.jpg \n inflating: train/empty/empty496.jpg \n inflating: train/empty/empty498.jpg \n inflating: train/empty/empty499.jpg \n inflating: train/empty/empty5.jpg \n inflating: train/empty/empty50.jpg \n inflating: train/empty/empty500.jpg \n inflating: train/empty/empty501.jpg \n inflating: train/empty/empty502.jpg \n inflating: train/empty/empty503.jpg \n inflating: train/empty/empty505.jpg \n inflating: train/empty/empty506.jpg \n inflating: train/empty/empty507.jpg \n inflating: train/empty/empty508.jpg \n inflating: train/empty/empty509.jpg \n inflating: train/empty/empty51.jpg \n inflating: train/empty/empty510.jpg \n inflating: train/empty/empty511.jpg \n inflating: train/empty/empty512.jpg \n inflating: train/empty/empty513.jpg \n inflating: train/empty/empty514.jpg \n inflating: train/empty/empty515.jpg \n inflating: train/empty/empty516.jpg \n inflating: train/empty/empty52.jpg \n inflating: train/empty/empty53.jpg \n inflating: train/empty/empty55.jpg \n inflating: train/empty/empty56.jpg \n inflating: train/empty/empty57.jpg \n inflating: train/empty/empty58.jpg \n inflating: train/empty/empty61.jpg \n inflating: train/empty/empty62.jpg \n inflating: train/empty/empty63.jpg \n inflating: train/empty/empty64.jpg \n inflating: train/empty/empty65.jpg \n inflating: train/empty/empty67.jpg \n inflating: train/empty/empty68.jpg \n inflating: train/empty/empty69.jpg \n inflating: train/empty/empty7.jpg \n inflating: train/empty/empty70.jpg \n inflating: train/empty/empty71.jpg \n inflating: train/empty/empty72.jpg \n inflating: train/empty/empty73.jpg \n inflating: train/empty/empty75.jpg \n inflating: train/empty/empty76.jpg \n inflating: train/empty/empty77.jpg \n inflating: train/empty/empty78.jpg \n inflating: train/empty/empty79.jpg \n inflating: train/empty/empty8.jpg \n inflating: train/empty/empty80.jpg \n inflating: train/empty/empty81.jpg \n inflating: train/empty/empty82.jpg \n inflating: train/empty/empty83.jpg \n inflating: train/empty/empty84.jpg \n inflating: train/empty/empty85.jpg \n inflating: train/empty/empty86.jpg \n inflating: train/empty/empty87.jpg \n inflating: train/empty/empty88.jpg \n inflating: train/empty/empty89.jpg \n inflating: train/empty/empty9.jpg \n inflating: train/empty/empty90.jpg \n inflating: train/empty/empty91.jpg \n inflating: train/empty/empty92.jpg \n inflating: train/empty/empty93.jpg \n inflating: train/empty/empty94.jpg \n inflating: train/empty/empty95.jpg \n inflating: train/empty/empty96.jpg \n inflating: train/empty/empty98.jpg \n"
],
[
"%matplotlib inline\nimport pandas as pd\nimport os,shutil,math,scipy,cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom sklearn.metrics import confusion_matrix,roc_curve,auc\n\nfrom PIL import Image\nfrom PIL import Image as pil_image\nfrom time import time\nfrom PIL import ImageDraw\nfrom glob import glob\nfrom tqdm import tqdm\nfrom skimage.io import imread\nfrom IPython.display import SVG\n\nfrom scipy import misc,ndimage\nfrom scipy.ndimage.interpolation import zoom\n\nfrom keras import backend as K\nfrom keras import layers\nfrom keras.preprocessing.image import save_img\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.applications.vgg16 import VGG16,preprocess_input\nfrom keras.applications.xception import Xception\nfrom keras.applications.nasnet import NASNetMobile\nfrom keras.models import Sequential,Input,Model\nfrom keras.layers import Dense,Flatten,Dropout,Concatenate,GlobalAveragePooling2D,Lambda,ZeroPadding2D\nfrom keras.layers import SeparableConv2D,BatchNormalization,MaxPooling2D,Conv2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.vis_utils import plot_model\nfrom keras.callbacks import ModelCheckpoint,EarlyStopping,TensorBoard,CSVLogger,ReduceLROnPlateau,LearningRateScheduler",
"_____no_output_____"
],
[
"def show_final_history(history):\n fig, ax = plt.subplots(1, 2, figsize=(15,5))\n ax[0].set_title('loss')\n ax[0].plot(history.epoch, history.history[\"loss\"], label=\"Train loss\")\n ax[0].plot(history.epoch, history.history[\"val_loss\"], label=\"Validation loss\")\n ax[1].set_title('acc')\n ax[1].plot(history.epoch, history.history[\"acc\"], label=\"Train acc\")\n ax[1].plot(history.epoch, history.history[\"val_acc\"], label=\"Validation acc\")\n ax[0].legend()\n ax[1].legend()",
"_____no_output_____"
],
[
"augs = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2, \n zoom_range=0.2, \n horizontal_flip=True,\n validation_split=0.3) \n\ntrain_gen = augs.flow_from_directory(\n '/content/emptyballs/train/',\n target_size = (150,150),\n batch_size=8,\n class_mode = 'binary')\n\ntest_gen = augs.flow_from_directory(\n '/content/emptyballs/test/',\n target_size=(150,150),\n batch_size=8,\n class_mode='binary',\n subset='validation')",
"Found 823 images belonging to 2 classes.\nFound 24 images belonging to 2 classes.\n"
],
[
"base_model = VGG16(include_top=False,\n input_shape = (150,150,3),\n weights = 'imagenet')\n\nfor layer in base_model.layers[:-12]:\n layer.trainable = False\n \nfor layer in base_model.layers:\n print(layer,layer.trainable)\n\nmodel = Sequential()\nmodel.add(base_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(1024,activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1,activation='sigmoid'))\nmodel.summary()\n\nSVG(model_to_dot(model).create(prog='dot', format='svg'))\nplot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True, expand_nested=True)",
"Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5\n58892288/58889256 [==============================] - 0s 0us/step\n58900480/58889256 [==============================] - 0s 0us/step\n<keras.engine.input_layer.InputLayer object at 0x7f94b5370c50> False\n<keras.layers.convolutional.Conv2D object at 0x7f94b22ca710> False\n<keras.layers.convolutional.Conv2D object at 0x7f94afdc5390> False\n<keras.layers.pooling.MaxPooling2D object at 0x7f94afd94890> False\n<keras.layers.convolutional.Conv2D object at 0x7f94afd55250> False\n<keras.layers.convolutional.Conv2D object at 0x7f94b22c2f90> False\n<keras.layers.pooling.MaxPooling2D object at 0x7f94afd5b7d0> False\n<keras.layers.convolutional.Conv2D object at 0x7f94afd63850> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afd6b950> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afd75b90> True\n<keras.layers.pooling.MaxPooling2D object at 0x7f94b4643110> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afd74310> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afe04a90> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afcfd210> True\n<keras.layers.pooling.MaxPooling2D object at 0x7f94afd0ba90> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afd10e90> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afd13110> True\n<keras.layers.convolutional.Conv2D object at 0x7f94afd0b610> True\n<keras.layers.pooling.MaxPooling2D object at 0x7f94afd1cb10> True\nModel: \"sequential\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n vgg16 (Functional) (None, 4, 4, 512) 14714688 \n \n global_average_pooling2d (G (None, 512) 0 \n lobalAveragePooling2D) \n \n dense (Dense) (None, 1024) 525312 \n \n dropout (Dropout) (None, 1024) 0 \n \n dense_1 (Dense) (None, 1) 1025 \n \n=================================================================\nTotal params: 15,241,025\nTrainable params: 14,980,865\nNon-trainable params: 260,160\n_________________________________________________________________\n"
],
[
"checkpoint = ModelCheckpoint(\n './base.model',\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n mode='min',\n save_weights_only=False,\n period=1\n)\nearlystop = EarlyStopping(\n monitor='val_loss',\n min_delta=0.01,\n patience=30,\n verbose=1,\n mode='auto'\n)\ntensorboard = TensorBoard(\n log_dir = './logs',\n histogram_freq=0,\n batch_size=16,\n write_graph=True,\n write_grads=True,\n write_images=False,\n)\n\ncsvlogger = CSVLogger(\n filename= \"training_csv.log\",\n separator = \",\",\n append = False\n)\n\nreduce = ReduceLROnPlateau(\n monitor='val_loss',\n factor=0.1,\n patience=1,\n verbose=1, \n mode='auto'\n)\n\ncallbacks = [checkpoint,tensorboard,csvlogger,reduce]",
"WARNING:tensorflow:`period` argument is deprecated. Please use `save_freq` to specify the frequency in number of batches seen.\nWARNING:tensorflow:`write_grads` will be ignored in TensorFlow 2.0 for the `TensorBoard` Callback.\nWARNING:tensorflow:`batch_size` is no longer needed in the `TensorBoard` Callback and will be ignored in TensorFlow 2.0.\n"
],
[
"import tensorflow as tf\n\nopt = tf.keras.optimizers.SGD(lr=1e-5,momentum=0.95)\nopt1 = tf.keras.optimizers.Adam(lr=1e-4)\n\n\nmodel.compile(\n loss='binary_crossentropy',\n optimizer=opt1,\n metrics=['accuracy']\n)\n \nhistory = model.fit_generator(\n train_gen, \n steps_per_epoch = 150, \n validation_data = test_gen,\n validation_steps = 150,\n epochs = 30, \n verbose = 1,\n callbacks=callbacks)",
"/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/gradient_descent.py:102: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n super(SGD, self).__init__(name, **kwargs)\n/usr/local/lib/python3.7/dist-packages/keras/optimizer_v2/adam.py:105: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n super(Adam, self).__init__(name, **kwargs)\n/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:20: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.\n"
],
[
"predictions = np.rint(model.predict(x_test))",
"_____no_output_____"
],
[
"print( classification_report(y_test, predictions) )",
"_____no_output_____"
],
[
"# show_final_history(history)\nmodel.load_weights('./base.model')\nmodel_score = model.evaluate_generator(test_gen)\nprint(\"Model Test Loss:\",model_score[0])\nprint(\"Model Test Accuracy:\",model_score[1])\n\nmodel_json = model.to_json()\nwith open(\"model.json\",\"w\") as json_file:\n json_file.write(model_json)\n \nmodel.save(\"model_tennis.h5\")\nprint(\"Weights Saved\")",
"/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: UserWarning: `Model.evaluate_generator` is deprecated and will be removed in a future version. Please use `Model.evaluate`, which supports generators.\n This is separate from the ipykernel package so we can avoid doing imports until\n"
],
[
"!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\n!unzip ngrok-stable-linux-amd64.zip\nLOG_DIR = './logs' # Here you have to put your log directory\nget_ipython().system_raw(\n 'tensorboard --logdir {} --host 0.0.0.0 --port 8080 &'\n .format(LOG_DIR)\n)\nget_ipython().system_raw('./ngrok http 8080 &')\n! curl -s http://localhost:4040/api/tunnels | python3 -c \\\n \"import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])\"",
"--2022-01-05 06:38:00-- https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip\nResolving bin.equinox.io (bin.equinox.io)... 52.202.168.65, 54.161.241.46, 18.205.222.128, ...\nConnecting to bin.equinox.io (bin.equinox.io)|52.202.168.65|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 13832437 (13M) [application/octet-stream]\nSaving to: ‘ngrok-stable-linux-amd64.zip.1’\n\nngrok-stable-linux- 100%[===================>] 13.19M 3.38MB/s in 6.7s \n\n2022-01-05 06:38:07 (1.97 MB/s) - ‘ngrok-stable-linux-amd64.zip.1’ saved [13832437/13832437]\n\nArchive: ngrok-stable-linux-amd64.zip\nreplace ngrok? [y]es, [n]o, [A]ll, [N]one, [r]ename: Y\n inflating: ngrok \nhttps://5336-34-91-44-196.ngrok.io\n"
],
[
"",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb270e8dd7b671c1263e1d742b450099c6f6c3e
| 1,492 |
ipynb
|
Jupyter Notebook
|
Example 1.6.ipynb
|
mfkiwl/GMPE340
|
3602b8ba859a2c7db2cab96862472597dc1ac793
|
[
"MIT"
] | 1 |
2021-09-07T09:36:36.000Z
|
2021-09-07T09:36:36.000Z
|
Example 1.6.ipynb
|
mfkiwl/GMPE340
|
3602b8ba859a2c7db2cab96862472597dc1ac793
|
[
"MIT"
] | null | null | null |
Example 1.6.ipynb
|
mfkiwl/GMPE340
|
3602b8ba859a2c7db2cab96862472597dc1ac793
|
[
"MIT"
] | 1 |
2021-09-20T18:48:20.000Z
|
2021-09-20T18:48:20.000Z
| 21.623188 | 71 | 0.506032 |
[
[
[
"# Mean, Variance and Standard Deviation {-}\n\nLet $X$ be uniformly distributed in the interval $(0, 2\\pi)$.\n\nCompute the mean, variance and standard deviation of $X$:",
"_____no_output_____"
]
],
[
[
"from numpy import pi, sqrt\nfrom scipy.integrate import quad\n\n# Probability density\nfx = 1/(2*pi)\n\n# Expectation\nEX = quad(lambda x: x*fx, 0, 2*pi)\nprint(\"Expectation: %.2f (%.2e)\" % EX)\n\n# Variance\nVarX = quad(lambda x: x**2*fx, 0, 2*pi)[0] - EX[0]**2\nprint(\"Variance: %.2f\" % VarX)\nprint(\"Standard deviation: %.2f\" % sqrt(VarX))",
"Expectation: 3.14 (3.49e-14)\nVariance: 3.29\nStandard deviation: 1.81\n"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
]
] |
cbb27b8b5e2935e50639f57079efcfe47d6a0916
| 37,815 |
ipynb
|
Jupyter Notebook
|
lectures/Day4-FourierMethods/1_Introduction_to_pulsar_timing.ipynb
|
carmensg/IAA_School2019
|
e07274d0b3437ccedc5d306b7f86f4a12535b1a2
|
[
"BSD-2-Clause"
] | null | null | null |
lectures/Day4-FourierMethods/1_Introduction_to_pulsar_timing.ipynb
|
carmensg/IAA_School2019
|
e07274d0b3437ccedc5d306b7f86f4a12535b1a2
|
[
"BSD-2-Clause"
] | null | null | null |
lectures/Day4-FourierMethods/1_Introduction_to_pulsar_timing.ipynb
|
carmensg/IAA_School2019
|
e07274d0b3437ccedc5d306b7f86f4a12535b1a2
|
[
"BSD-2-Clause"
] | 4 |
2019-10-18T05:11:00.000Z
|
2021-11-23T13:42:04.000Z
| 33.793566 | 331 | 0.513606 |
[
[
[
"%matplotlib inline\nimport warnings\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import gridspec\n\nwarnings.filterwarnings('ignore')",
"_____no_output_____"
]
],
[
[
"<style type=\"text/css\">\n.input, .output_prompt {\ndisplay:none !important;\n}\n</style>\n\n \n",
"_____no_output_____"
]
],
[
[
"# Introduction to Pulsar Timing\n\n[](http://mybinder.org/repo/matteobachetti/timing-lectures)\n\n<img src=\"0737.png\" alt=\"0737\" style=\"height: 300px;margin: auto;\"/>\n\n(These slides are obtained from the iPython notebook that can be found [here](https://github.com/matteobachetti/timing-lectures))",
"_____no_output_____"
],
[
"## Contents\n\n* Finding pulsars: the buried clock\n\n* Frequency analysis: the Fourier Transform and the Power Density Spectrum\n\n* Refine the search: Folding search (+ $Z^2_n$, $H$-test, ...)\n\n* Getting pulse arrival times ",
"_____no_output_____"
],
[
"# Finding pulsars: the buried clock\n\n<img src=\"buriedclock.jpg\" alt=\"Buried Clock\" style=\"height: 300px;margin: auto;\"/>\n\n",
"_____no_output_____"
],
[
"# Finding pulsars: the buried clock\n\n* Pulsars are stable rotators: very predictable \"clocks\"\n\n<img src=\"smallmodpulsar.gif\" alt=\"Pulsar\" style=\"height: 300px;margin: auto;\"/>",
"_____no_output_____"
],
[
"# Finding pulsars: the buried clock\n\n* Pulsars are stable rotators: very predictable \"clocks\"\n\n* Often signal buried in noise (below: a 0.853-Hz sinusoidal pulse buried in noise ~30 times stronger)",
"_____no_output_____"
]
],
[
[
"def pulsar(time, period=1):\n return (1 + np.sin(2 * np.pi / period * time)) / 2.\n\ntime_bin = 0.009\n\n# --- Parameters ----\nperiod = 0.8532\npulsar_amp = 0.5\npulsar_stdev = 0.05\nnoise_amp = 15\nnoise_stdev = 1.5\n# --------------------\n\n# refer to the center of the time bin\ntime = np.arange(0, 100, time_bin) + time_bin / 2\n\nsignal = np.random.normal(pulsar_amp * pulsar(time, period), pulsar_stdev)\nnoise = np.random.normal(noise_amp, noise_stdev, len(time))\ntotal = signal + noise\n\n# PLOTTING -------------------------\nplt.plot(time, signal, 'r-', label='signal')\nplt.plot(time, noise, 'b-', label='noise')\nplt.plot(time, total, 'k-', label='total')\nplt.xlim(0, 30)\nplt.xlabel('Time')\nplt.ylabel('Flux')\na = plt.legend()\n# -----------------------------------",
"_____no_output_____"
]
],
[
[
"# Frequency analysis: the Fourier Transform\n\nThrough the Fourier transform, we can decompose a function of time into a series of functions of frequency:\n\n\\begin{equation}\n\\mathcal{F}(\\omega) = \\int^{\\infty}_{-\\infty} e^{-i\\omega t} f(t)\n\\end{equation}\n\nor, more appropriate to our case, in the discrete form, we can decompose a time series into a frequency series:\n\n\\begin{equation}\nF_k = \\sum^{N-1}_{k=0} e^{-2\\pi i k n/N} t_n\n\\end{equation}\n\nit is, in general, a **complex** function.\n\nThe Fourier transform of a sinusoid will give a high (in absolute terms) value of the $F_k$ corresponding to the frequency of the sinusoid. Other periodic functions will produce high contribution at the fundamental frequency plus one or more multiples of the fundamental, called *harmonics*.\n",
"_____no_output_____"
],
[
"## Our example\n\nLet's take the Fourier transform of the signal we simulated above (only taking *positive* frequencies)",
"_____no_output_____"
]
],
[
[
"ft = np.fft.fft(total)\nfreqs = np.fft.fftfreq(len(total), time[1] - time[0])\ngood = freqs >0\nfreqs = freqs[good]\nft = ft[good]\n\n# PLOTTING ---------------------------\nplt.plot(freqs, ft.real, 'r-', label='real')\nplt.plot(freqs, ft.imag, 'b-', label='imag')\nplt.xlim([-0.1, 10])\na = plt.legend()\n_ = plt.xlabel('Frequency (Hz)')\n_ = plt.ylabel('FT')\n# -------------------------------------",
"_____no_output_____"
]
],
[
[
"Note that the imaginary part and real part of the Fourier transform have different contributions at the pulsar frequency (1/0.85 s ~ 1.2 Hz). This is because they depend strongly on the phase of the signal [Exercise: **why?**].",
"_____no_output_____"
],
[
"## Our example - 2\n\n If we applied a shift of 240 ms (just any value) to the signal:",
"_____no_output_____"
]
],
[
[
"shift = 0.240\nsignal_shift = np.roll(total, int(shift / time_bin))\nft_shift = np.fft.fft(signal_shift)\nfreqs_shift = np.fft.fftfreq(len(total), time[1] - time[0])\ngood = freqs_shift >0\nfreqs_shift = freqs_shift[good]\nft_shift = ft_shift[good]\n\n# PLOTTING -------------------------------------\nplt.plot(freqs_shift, ft_shift.real, 'r-', label='real')\nplt.plot(freqs_shift, ft_shift.imag, 'b-', label='imag')\nplt.xlim([-0.1, 10])\na = plt.legend()\n_ = plt.xlabel('Frequency (Hz)')\n_ = plt.ylabel('FT')\n# ----------------------------------------------",
"_____no_output_____"
]
],
[
[
"we would clearly have non-zero values at ~0.85 Hz both in the real and the imaginary parts.",
"_____no_output_____"
],
[
"# The Power Density Spectrum\n\nTo solve these issues with real and imaginary parts, we can instead take the *squared modulus* of the Fourier transform. This is called **Periodogram**, but most people use the word **Power Density Spectrum** (a periodogram is actually a single realization of the underlying PDS).\n\n\\begin{equation}\n\\mathcal{P}(\\omega) = \\mathcal{F}(\\omega) \\cdot \\mathcal{F}^*(\\omega)\n\\end{equation}\n\nThis function is positive-definite and in our case results in a clear peak at the pulse frequency, *consistent* between original and shifted signal:",
"_____no_output_____"
]
],
[
[
"pds = np.abs(ft*ft.conj())\npds_shift = np.abs(ft_shift*ft_shift.conj())\n\nfmax = freqs[np.argmax(pds)]\npmax = 1 / fmax\n\n# PLOTTING ---------------------------------\nplt.plot(freqs, pds, 'r-', label='PDS of signal')\nplt.plot(freqs_shift, pds_shift, 'b-', label='PDS of shifted signal')\na = plt.legend()\na = plt.xlabel('Frequency (Hz)')\na = plt.ylabel('PDS')\nplt.xlim([-0.1, 3.5])\n_ = plt.gca().annotate('max = {:.2f} s ({:.2f} Hz)'.format(pmax, fmax), xy=(2., max(pds) / 2))\n# -------------------------------------------",
"_____no_output_____"
]
],
[
[
"## The Power Density Spectrum -2\n\nThe PDS of a generic non-sinusoidal pulse profile will, in general, contain more than one harmonic, with the fundamental not always predominant.",
"_____no_output_____"
]
],
[
[
"def gaussian_periodic(x, x0, amp, width):\n '''Approximates a Gaussian periodic function by summing the contributions in the phase\n range 0--1 with those in the phase range -1--0 and 1--2'''\n phase = x - np.floor(x)\n lc = np.zeros_like(x)\n for shift in [-1, 0, 1]:\n lc += amp * np.exp(-(phase + shift - x0)**2 / width ** 2)\n \n return lc\n\ndef generate_profile(time, period):\n '''Simulate a given profile with 1-3 Gaussian components'''\n total_phase = time / period\n ngauss = np.random.randint(1, 3)\n lc = np.zeros_like(total_phase)\n for i in range(ngauss):\n ph0 = np.random.uniform(0, 1)\n amp = np.random.uniform(0.1, 1)\n width = np.random.uniform(0.01, 0.2)\n lc += gaussian_periodic(total_phase, ph0, amp, width)\n \n return lc\n\n# PLOTTING -------------------------\nncols = 2\nnrows = 3\nfig = plt.figure(figsize=(12, 8))\nfig.suptitle('Profiles and their PDSs')\n\ngs = gridspec.GridSpec(nrows, ncols)\n\nfor c in range(ncols):\n for r in range(nrows):\n# ----------------------------------\n noise = np.random.normal(noise_amp, noise_stdev, len(time))\n\n lc = generate_profile(time, period)\n lc_noisy = np.random.normal(2 * lc, 0.2) + noise\n \n lcft = np.fft.fft(lc_noisy)\n lcfreq = np.fft.fftfreq(len(lc_noisy), time[1] - time[0])\n lcpds = np.absolute(lcft) ** 2 \n\n # PLOTTING -------------------------\n\n gs_2 = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs[r, c])\n ax = plt.subplot(gs_2[0])\n good = time < period * 3\n ax.plot(time[good] / period, lc[good])\n \n ax.set_xlim([0,3])\n ax.set_xlabel('Phase')\n \n ax = plt.subplot(gs_2[1])\n ax.plot(lcfreq[lcfreq > 0], lcpds[lcfreq > 0] / max(lcpds[lcfreq > 0]))\n ax.set_xlabel('Frequency')\n ax.set_xlim([0, 10])\n\n # ----------------------------------",
"_____no_output_____"
]
],
[
[
"## Pulsation?\n\nHere are some examples of power density spectra. In some cases, it might look like a pulsation is present in the data. How do we assess this?\n",
"_____no_output_____"
]
],
[
[
"# PLOTTING -------------------------\nncols = 2\nnrows = 3\nfig = plt.figure(figsize=(12, 8))\nfig.suptitle('Profiles and their PDSs')\n\ngs = gridspec.GridSpec(nrows, ncols)\n\nfor c in range(ncols):\n for r in range(nrows):\n# ----------------------------------\n\n noise = np.random.normal(noise_amp, noise_stdev, len(time))\n lc = np.zeros_like(time)\n lc_noisy = np.random.normal(2 * lc, 0.2) + noise\n \n lcft = np.fft.fft(lc_noisy)\n lcfreq = np.fft.fftfreq(len(lc_noisy), time[1] - time[0])\n lcpds = np.absolute(lcft) ** 2 \n\n # PLOTTING -------------------------\n\n gs_2 = gridspec.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs[r, c])\n ax = plt.subplot(gs_2[0])\n good = time < period * 3\n ax.plot(time[good] / period, lc[good])\n \n ax.set_xlim([0,3])\n ax.set_xlabel('Phase')\n \n ax = plt.subplot(gs_2[1])\n ax.plot(lcfreq[lcfreq > 0], lcpds[lcfreq > 0] / max(lcpds[lcfreq > 0]))\n ax.set_xlabel('Frequency')\n ax.set_xlim([0, 10])\n\n # ----------------------------------",
"_____no_output_____"
]
],
[
[
"# Epoch folding\n\nEpoch folding consists of summing equal, one pulse period-long, chunks of data. If the period is just right, the crests will sum up in phase, gaining signal over noise [Exercise: **how much will we gain** by summing up in phase $N$ chunks of data at the right period?].",
"_____no_output_____"
]
],
[
[
"def epoch_folding(time, signal, period, nperiods=3, nbin=16):\n # The phase of the pulse is always between 0 and 1.\n phase = time / period\n phase -= phase.astype(int)\n \n # First histogram: divide phase range in nbin bins, and count how many signal bins\n # fall in each histogram bin. The sum is weighted by the value of the signal at \n # each phase\n prof_raw, bins = np.histogram(\n phase, bins=np.linspace(0, 1, nbin + 1),\n weights=signal)\n # \"Exposure\": how many signal bins have been summed in each histogram bin\n expo, bins = np.histogram(phase, bins=np.linspace(0, 1, nbin + 1))\n \n # ---- Evaluate errors -------\n prof_sq, bins = np.histogram(\n phase, bins=np.linspace(0, 1, nbin + 1),\n weights=signal ** 2)\n # Variance of histogram bin: \"Mean of squares minus square of mean\" X N\n hist_var = (prof_sq / expo - (prof_raw / expo) ** 2) * expo\n # Then, take square root -> Stdev, then normalize / N. \n prof_err = np.sqrt(hist_var)\n #-----------------------------\n # Normalize by exposure\n prof = prof_raw / expo\n prof_err = prof_err / expo\n \n # histogram returns all bin edges, including last one. Here we take the\n # center of each bin.\n phase_bins = (bins[1:] + bins[:-1]) / 2\n \n # ---- Return the same pattern 'nperiods' times, for visual purposes -----\n final_prof = np.array([])\n final_phase = np.array([])\n final_prof_err = np.array([])\n for n in range(nperiods):\n final_prof = np.append(final_prof, prof)\n final_phase = np.append(final_phase, phase_bins + n)\n final_prof_err = np.append(final_prof_err, prof_err)\n # ---------------------------\n return final_phase, final_prof, final_prof_err\n\nphase, profile, profile_err = epoch_folding(time, total, period)\nphase_shift, profile_shift, profile_shift_err = epoch_folding(time, signal_shift, period)\n\n# PLOTTING -------------------------------------------------------------\nplt.errorbar(\n phase, profile, yerr=profile_err, drawstyle='steps-mid',\n label='Signal')\nplt.errorbar(\n phase_shift, profile_shift, yerr=profile_shift_err,\n drawstyle='steps-mid', label='Shifted signal')\n\n_ = plt.legend()\n_ = plt.xlabel('Phase')\n_ = plt.ylabel('Counts/bin')\n# -------------------------------------------------------------------",
"_____no_output_____"
]
],
[
[
"# Epoch folding search\n\nNow, let's run epoch folding at a number of trial periods around the pulse period. To evaluate how much a given profile \"looks pulsar-y\", we can use the $\\chi^2$ statistics, as follows:\n\n\\begin{equation}\n\\mathcal{S} = \\sum_{i=0}^N \\frac{(p_i - \\bar{p})^2}{\\sigma_p^2}\n\\end{equation}\n\nfor each profile obtained for each trial value of the pulse frequency and look for peaks$^1$. [Exercise: do you know what statistics this is? And why does that statistics work for our case? Exercise-2: Note the very large number of trials. Can we optimize the search so that we use less trials without losing sensitivity?]\n\n$^1$ 1.\tLeahy, D. A. et al. On searches for pulsed emission with application to four globular cluster X-ray sources - NGC 1851, 6441, 6624, and 6712. _ApJ_ **266**, 160 (1983).",
"_____no_output_____"
]
],
[
[
"def pulse_profile_stat(profile, profile_err):\n return np.sum(\n (profile - np.mean(profile)) ** 2 / profile_err ** 2)\n\ntrial_periods = np.arange(0.7, 1.0, 0.0002)\nstats = np.zeros_like(trial_periods)\nfor i, p in enumerate(trial_periods):\n phase, profile, profile_err = epoch_folding(time, total, p)\n stats[i] = pulse_profile_stat(profile, profile_err)\n\nbestp = trial_periods[np.argmax(stats)]\n\nphase_search, profile_search, profile_search_err = \\\n epoch_folding(time, total, bestp)\nphase, profile, profile_err = epoch_folding(time, total, period)\n\n# PLOTTING -------------------------------\nfig = plt.figure(figsize=(10, 3))\ngs = gridspec.GridSpec(1, 2)\nax = plt.subplot(gs[0])\nax.plot(trial_periods, stats)\nax.set_xlim([0.7, 1])\nax.set_xlabel('Period (s)')\nax.set_ylabel('$\\chi^2$')\nax.axvline(period, color='r', label=\"True value\")\n_ = ax.legend()\nax.annotate('max = {:.5f} s'.format(pmax), xy=(.9, max(stats) / 2))\n\nax2 = plt.subplot(gs[1])\n\nax2.errorbar(phase_search, profile_search, yerr=profile_search_err,\n drawstyle='steps-mid', label='Search')\nax2.errorbar(phase, profile, yerr=profile_err, drawstyle='steps-mid',\n label='True period')\nax2.set_xlabel('Phase')\nax2.set_ylabel('Counts/bin')\n\n_ = ax2.legend()\n# ------------------------------------------",
"_____no_output_____"
]
],
[
[
"# Times of arrival (TOA)\nTo calculate the time of arrival of the pulses, we need to:\n\n* Choose what **part of the pulse** is the reference (e.g., the maximum). Once we know that, if $\\phi_{max}$ is the phase of the maximum of the pulse, $t_{start}$ the time at the start of the folded light curve, and $p$ is the folding period,\n\n$TOA = t_{start} + \\phi_{max} \\cdot p$\n\n* Choose a **method** to calculate the TOA: \n\n + The maximum bin?\n \n + The phase of a sinusoidal fit?\n \n + The phase of a more complicated fit?\n \nHereafter, we are going to use the maximum of the pulse as a reference, and we will calculate the TOA with the three methods above. ",
"_____no_output_____"
],
[
"## TOA from the maximum bin\n\n**Advantage**\n\n* Very fast and easy to implement\n\n**Disadvantages**\n\n* Very rough (maximum precision, the width of the bin)\n\n* Very uncertain (if statistics is low and/or the pulse is broad, many close-by bins can randomly be the maximum)",
"_____no_output_____"
]
],
[
[
"phase_bin = 1 / 32.\nph = np.arange(phase_bin / 2, phase_bin / 2 + 1, phase_bin)\nshape = np.sin(2 * np.pi * ph) + 2\npr_1 = np.random.poisson(shape * 10000) / 10000\npr_2 = np.random.poisson(shape * 10) / 10\n\n# PLOTTING -----------------------------\nplt.plot(ph, shape, label='Theoretical shape', color='k')\nplt.plot(\n ph, pr_1, drawstyle='steps-mid', color='r',\n label='Shape - good stat')\nplt.plot(\n ph, pr_2, drawstyle='steps-mid', color='b',\n label='Shape - bad stat')\nplt.axvline(0.25, ls=':', color='k', lw=2, label='Real maximum')\nplt.axvline(\n ph[np.argmax(pr_1)], ls='--', color='r', lw=2,\n label='Maximum - good stat')\nplt.axvline(\n ph[np.argmax(pr_2)], ls='--', color='b', lw=2,\n label='Maximum - bad stat')\n\n_ = plt.legend()\n# --------------------------------------",
"_____no_output_____"
]
],
[
[
"## TOA from single sinusoidal fit\n\n**Advantage**\n\n* Relatively easy task (fitting with a sinusoid)\n\n* Errors are well determined provided that the pulse is broad\n\n**Disadvantages**\n\n* If profile is not sinusoidal, might not be well determined\n\nBelow, the phase of the pulse is always 0.25",
"_____no_output_____"
]
],
[
[
"def sinusoid(phase, phase0, amplitude, offset):\n return offset + np.cos(2 * np.pi * (phase - phase0))\n\nfrom scipy.optimize import curve_fit\n\n# PLOTTING ------------------\nfig = plt.figure(figsize=(12, 3))\ngs = gridspec.GridSpec(1, 4)\nax1 = plt.subplot(gs[0])\nax1.set_title('Theoretical')\nax2 = plt.subplot(gs[1])\nax2.set_title('Sinusoidal, good stat')\nax3 = plt.subplot(gs[2])\nax3.set_title('Sinusoidal, noisy')\nax4 = plt.subplot(gs[3])\nax4.set_title('Complicated profile')\n# ---------------------------\n\n# Fit sinusoid to theoretical shape\npar, pcov = curve_fit(sinusoid, ph, shape)\n\n# PLOTTING -----------------------------------------------\nax1.plot(ph, sinusoid(ph, *par))\nax1.plot(ph, shape)\npar[0] -= np.floor(par[0])\nax1.annotate('phase = {:.2f}'.format(par[0]), xy=(.5, .3))\nax1.set_ylim([0, 4])\n\n# Fit to good-stat line\n# ---------------------------------------------------------\n\npar, pcov = curve_fit(sinusoid, ph, pr_1)\n\n# PLOTTING -----------------------------------------------\n\nax2.plot(ph, sinusoid(ph, *par))\nax2.plot(ph, pr_1)\npar[0] -= np.floor(par[0])\nax2.annotate('phase = {:.2f}'.format(par[0]), xy=(.5, .3))\nax2.set_ylim([0, 4])\n\n# Fit to bad-stat line\n# ---------------------------------------------------------\n\npar, pcov = curve_fit(sinusoid, ph, pr_2)\n\n# PLOTTING -----------------------------------------------\n\nax3.plot(ph, sinusoid(ph, *par))\nax3.plot(ph, pr_2, drawstyle='steps-mid')\npar[0] -= np.floor(par[0])\nax3.annotate('phase = {:.2f}'.format(par[0]), xy=(.5, .3))\nax3.set_ylim([0, 4])\n\n# Now try with a complicated profile (a double Gaussian)\n# ---------------------------------------------------------\n\npr_3_clean = 0.3 + np.exp(- (ph - 0.25) ** 2 / 0.001) + 0.5 * np.exp(- (ph - 0.75) ** 2 / 0.01)\npr_3 = np.random.poisson(pr_3_clean * 100) / 50\n# Let us normalize the template with the same factor (100 / 50) of the randomized one. It will be helpful later\npr_3_clean *= 2\n\npar, pcov = curve_fit(sinusoid, ph, pr_3, maxfev=10000)\n\n# PLOTTING -----------------------------------------------\n\nax4.plot(ph, sinusoid(ph, *par), label='Fit')\nax4.plot(ph, pr_3, drawstyle='steps-mid', label='Noisy profile')\nax4.plot(ph, pr_3_clean, label='Real profile')\n\npar[0] -= np.floor(par[0])\nax4.annotate('phase = {:.2f}'.format(par[0]), xy=(.5, .3))\nax4.set_ylim([0, 4])\n_ = ax4.legend()\n# ---------------------------------------------------------",
"_____no_output_____"
]
],
[
[
"## TOA from non-sinusoidal fit: multiple harmonic fitting\n\n**Multiple harmonic fitting**$^1$ (the profile is described by a sum of sinusoids) is just an extension of the single-harmonic fit by adding additional sinusoidal components at multiple frequencies.\n\n**Advantages**\n\n* Still conceptually easy, but more robust and reliable\n\n**Disadvantages**\n\n* The phase is not determined by the fit (in general, it isn't he phase of any of the sinusoids [Exercise: why?]) and needs to be determined from the maximum of the profile. Errors are not straightforward to implement.\n\n$^1$e.g. Riggio, A. et al. Timing of the accreting millisecond pulsar IGR J17511-3057. _A&A_ **526**, 95 (2011).\n",
"_____no_output_____"
],
[
"## TOA from non-sinusoidal fit: Template pulse shapes\n\n* **Cross-correlation** of template pulse shape\n\n* **Fourier-domain fitting (FFTFIT)**$^1$ -> the usual choice. Consists of taking the Fourier transform of the profile $\\mathcal{P}$ and of the template $\\mathcal{T}$ and minimizing the following objective function (similar to $\\chi^2$):\n\\begin{equation}\nF = \\sum_k \\frac{|\\mathcal{P}_k - a\\mathcal{T}_k e^{-2\\pi i k\\phi}|^2}{\\sigma^2}\n\\end{equation}\n\n**Advantages**\n\n* Much more robust and reliable\n\n* Errors well determined whatever the pulse shape\n\n**Disadvantages**\n\n* Relatively trickier to implement\n\n* Needs good template pulse profile\n\n$^1$Taylor, J. H. Pulsar Timing and Relativistic Gravity. _Philosophical Transactions: Physical Sciences and Engineering_ **341**, 117–134 (1992).",
"_____no_output_____"
]
],
[
[
"def fftfit_fun(profile, template, amplitude, phase):\n '''Objective function to be minimized - \\'a la Taylor (1992).'''\n \n prof_ft = np.fft.fft(profile)\n temp_ft = np.fft.fft(template)\n freq = np.fft.fftfreq(len(profile))\n good = freq > 0\n idx = np.arange(0, prof_ft.size, dtype=int)\n sigma = np.std(prof_ft[good])\n return np.sum(np.absolute(prof_ft - temp_ft*amplitude*np.exp(-2*np.pi*1.0j*idx*phase))**2 / sigma)\n\ndef obj_fun(pars, data):\n '''Wrap parameters and input data up in order to be used with minimization\n algorithms.'''\n amplitude, phase = pars\n profile, template = data\n return fftfit_fun(profile, template, amplitude, phase)\n\n# Produce 16 realizations of pr_3, at different amplitudes and phases, and reconstruct the phase\nfrom scipy.optimize import fmin, basinhopping\n\n# PLOTTING --------------------------\n\nfig = plt.figure(figsize=(10, 10))\nfig.suptitle('FFTfit results')\ngs = gridspec.GridSpec(4, 4)\n\n# -----------------------------------\namp0 = 1\nphase0 = 0\np0 = [amp0, phase0]\nfor i in range(16):\n # PLOTTING --------------------------\n col = i % 4\n row = i // 4\n # -----------------------------------\n\n factor = 10 ** np.random.uniform(1, 3)\n pr_orig = np.random.poisson(pr_3_clean * factor)\n roll_len = np.random.randint(0, len(pr_orig) - 1)\n pr = np.roll(pr_orig, roll_len)\n\n# # Using generic minimization algorithms is faster, but local minima can be a problem\n# res = fmin(obj_fun, p0, args=([pr, pr_3_clean],), disp=False, full_output=True)\n# amplitude_res, phase_res = res[0]\n\n # The basinhopping algorithm is very slow but very effective in finding \n # the global minimum of functions with local minima.\n res = basinhopping(obj_fun, p0, minimizer_kwargs={'args':([pr, pr_3_clean],)})\n amplitude_res, phase_res = res.x\n \n phase_res -= np.floor(phase_res)\n newphase = ph + phase_res\n newphase -= np.floor(newphase)\n \n # Sort arguments of phase so that they are ordered in plot\n # (avoids ugly lines traversing the plot)\n order = np.argsort(newphase)\n\n # PLOTTING --------------------------\n\n ax = plt.subplot(gs[row, col])\n ax.plot(ph, pr, 'k-')\n \n ax.plot(newphase[order], amplitude_res * pr_3_clean[order], 'r-')\n # -------------------------------------",
"_____no_output_____"
]
],
[
[
"## The Z_n search\n\n$Z_n^2$ is another widely used statistics for high-energy pulsar searches.\nIt measures how the probability of photons in a given phase is proportional to a given combination of $n$ harmonics. Or in other words, how well the pulse profile is described by a combination of sinusoidal harmonics.\nThe definition of this statistical indicator is (Buccheri+1983):\n\n$$\nZ^2_n = \\dfrac{2}{N} \\sum_{k=1}^n \\left[{\\left(\\sum_{j=1}^N \\cos k \\phi_j\\right)}^2 + {\\left(\\sum_{j=1}^N \\sin k \\phi_j\\right)}^2\\right] \\; ,\n$$\n\nThe formula can be slightly modified for binned data, by introducing a `weight` quantity giving the number of photons (or another measure of flux) in a given bin (Huppenkothen+2019):\n\n$$\nZ^2_n \\approx \\dfrac{2}{\\sum_j{w_j}} \\sum_{k=1}^n \\left[{\\left(\\sum_{j=1}^m w_j \\cos k \\phi_j\\right)}^2 + {\\left(\\sum_{j=1}^m w_j \\sin k \\phi_j\\right)}^2\\right]\n$$",
"_____no_output_____"
]
],
[
[
"def z_n(time, p, n=2, weight=1):\n '''Z^2_n statistics, a` la Buccheri+03, A&A, 128, 245, eq. 2.\n\n Parameters\n ----------\n phase : array of floats\n The phases of the events\n n : int, default 2\n Number of harmonics, including the fundamental\n\n Other Parameters\n ----------------\n norm : float or array of floats\n A normalization factor that gets multiplied as a weight.\n\n Returns\n -------\n z2_n : float\n The Z^2_n statistics of the events.\n '''\n phase = time / p\n \n nbin = len(phase)\n\n if nbin == 0:\n return 0\n\n weight = np.asarray(weight)\n if weight.size == 1:\n total_weight = nbin * weight\n else:\n total_weight = np.sum(weight)\n phase = phase * 2 * np.pi\n return 2 / total_weight * \\\n np.sum([np.sum(np.cos(k * phase) * weight) ** 2 +\n np.sum(np.sin(k * phase) * weight) ** 2\n for k in range(1, n + 1)])\n\ntrial_periods = np.arange(0.7, 1.0, 0.0002)\nstats = np.zeros_like(trial_periods)\nfor i, p in enumerate(trial_periods):\n stats[i] = z_n(time, p, weight=total)\n\nbestp = trial_periods[np.argmax(stats)]\n\nphase_search, profile_search, profile_search_err = \\\n epoch_folding(time, total, bestp)\nphase, profile, profile_err = epoch_folding(time, total, period)\n\n# PLOTTING -------------------------------\nfig = plt.figure(figsize=(10, 3))\ngs = gridspec.GridSpec(1, 2)\nax = plt.subplot(gs[0])\nax.plot(trial_periods, stats)\nax.set_xlim([0.7, 1])\nax.set_xlabel('Period (s)')\nax.set_ylabel('$\\chi^2$')\nax.axvline(period, color='r', label=\"True value\")\n_ = ax.legend()\nax.annotate('max = {:.5f} s'.format(pmax), xy=(.9, max(stats) / 2))\n\nax2 = plt.subplot(gs[1])\n\nax2.errorbar(phase_search, profile_search, yerr=profile_search_err,\n drawstyle='steps-mid', label='Search')\nax2.errorbar(phase, profile, yerr=profile_err, drawstyle='steps-mid',\n label='True period')\nax2.set_xlabel('Phase')\nax2.set_ylabel('Counts/bin')\n\n_ = ax2.legend()\n# ------------------------------------------",
"_____no_output_____"
]
],
[
[
"## Pulsation searches with HENDRICS\n\n1. To read a fits file into an event list file:\n\n```\n$ HENreadevents file.evt.gz\n```\na file called something like `file_mission_instr_ev.nc` appears\n\n2. To calculate the light curve (binning the events) with a sample time of 1 s:\n\n```\n$ HENlcurve file_mission_instr_ev.nc -b 1\n```\n\n3. To calculate the averaged power density spectrum cutting the data by chunks of 128 s:\n\n```\n$ HENfspec file_mission_instr_lc.nc -f 128\n```\n\n4. To watch the power density spectrum:\n\n```\n$ HENplot file_mission_instr_pds.nc\n```\n\n5. To run a $Z^2_4$ search, e.g. between frequencies 0.5 and 0.6:\n\n```\n$ HENzsearch file_mission_instr_ev.nc -f 0.5 -F 0.6 -N 4\n```\n\n6. To run a $Z^2_2$ search searching in the frequency -- fdot space\n\n```\n$ HENzsearch file_mission_instr_ev.nc -f 0.5 -F 0.6 -N 2 --fast\n$ HENplot file_mission_instr_Z2n.nc\n```\n\n7. Then... follow the instructions...\n\n### BONUS\n\n8. Calculate the TOAs and create a parameter and timing file (can you find how?)\n\n9. Use `pintk` (from `github.com/nanograv/PINT`) to fit the pulse solution\n\n```\n$ pintk parfile.par timfile.tim\n```\n\nNB: due to a bug to PINT (under investigation), you might need to add the line\n```\nTZRMJD 55555\n```\n\nSubstitute 55555 with the value of PEPOCH in the parameter file.\n",
"_____no_output_____"
]
]
] |
[
"code",
"raw",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"code"
],
[
"raw"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbb294e76826ddb4ca1a1d5f3cf47030ad9b47c0
| 202,260 |
ipynb
|
Jupyter Notebook
|
klue_roberta_kornli_simcse_tpu.ipynb
|
jeongukjae/distilkobert-sentence-encoder
|
40b282bf3bf38e5d08b456a87ef2a1f179232dcb
|
[
"Apache-2.0"
] | null | null | null |
klue_roberta_kornli_simcse_tpu.ipynb
|
jeongukjae/distilkobert-sentence-encoder
|
40b282bf3bf38e5d08b456a87ef2a1f179232dcb
|
[
"Apache-2.0"
] | null | null | null |
klue_roberta_kornli_simcse_tpu.ipynb
|
jeongukjae/distilkobert-sentence-encoder
|
40b282bf3bf38e5d08b456a87ef2a1f179232dcb
|
[
"Apache-2.0"
] | null | null | null | 37.016837 | 700 | 0.480812 |
[
[
[
"<a href=\"https://colab.research.google.com/github/jeongukjae/distilkobert-sentence-encoder/blob/main/klue_roberta_kornli_simcse_tpu.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# Train supervised SimCSE on KorNLI dataset using KLUE-RoBERTa large",
"_____no_output_____"
]
],
[
[
"BATCH_SIZE = 128\nLEARNING_RATE = 2e-5\nEPOCHS = 3\nWARMUP_RATE = 0.1\nTEMPERATURE = 0.05",
"_____no_output_____"
]
],
[
[
"## Prepare environments",
"_____no_output_____"
]
],
[
[
"import os\n\nos.environ[\"TFHUB_MODEL_LOAD_FORMAT\"] = \"UNCOMPRESSED\"\nprint(os.environ['COLAB_TPU_ADDR'])",
"10.124.168.194:8470\n"
],
[
"!pip install -U -q tensorflow-text tensorflow-datasets tfds-korean",
"\u001b[K |████████████████████████████████| 4.9 MB 5.6 MB/s \n\u001b[K |████████████████████████████████| 4.0 MB 31.5 MB/s \n\u001b[K |████████████████████████████████| 161 kB 47.9 MB/s \n\u001b[?25h"
],
[
"import tensorflow as tf\nimport tensorflow_text as text\nimport tensorflow_hub as hub\nimport tensorflow_datasets as tfds\nfrom tfds_korean import korsts, kornli, klue_sts\nfrom tqdm import tqdm",
"_____no_output_____"
],
[
"cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')\ntf.config.experimental_connect_to_cluster(cluster_resolver)\ntf.tpu.experimental.initialize_tpu_system(cluster_resolver)\nstrategy = tf.distribute.TPUStrategy(cluster_resolver)",
"INFO:tensorflow:Deallocate tpu buffers before initializing tpu system.\n"
]
],
[
[
"## Prepare models",
"_____no_output_____"
]
],
[
[
"def create_preprocessing_model():\n preproecssor_layer = hub.KerasLayer(\"https://tfhub.dev/jeongukjae/klue_roberta_cased_preprocess/1\")\n\n sentences = tf.keras.layers.Input(shape=(), dtype=tf.string, name=\"sentences\")\n encoder_inputs = preproecssor_layer(sentences)\n preprocessor_model = tf.keras.Model(sentences, encoder_inputs)\n return preprocessor_model",
"_____no_output_____"
],
[
"def create_model():\n encoder = hub.KerasLayer(\"https://tfhub.dev/jeongukjae/klue_roberta_cased_L-24_H-1024_A-16/1\", trainable=True)\n inputs = {\n \"input_word_ids\": tf.keras.Input([None], dtype=tf.int32, name=\"input_word_ids\"),\n \"input_type_ids\": tf.keras.Input([None], dtype=tf.int32, name=\"input_type_ids\"),\n \"input_mask\": tf.keras.Input([None], dtype=tf.int32, name=\"input_mask\"),\n }\n logit = encoder(inputs)['pooled_output']\n model = tf.keras.Model(inputs, logit)\n model.summary()\n return model",
"_____no_output_____"
],
[
"class BertScheduler(tf.keras.optimizers.schedules.LearningRateSchedule):\n def __init__(self, rate, warmup_ratio, total_steps, name=None):\n super().__init__()\n\n self.rate = rate\n self.warmup_ratio = warmup_ratio\n self.total_steps = float(total_steps)\n self.warmup_steps = warmup_ratio * total_steps\n self.name = name\n\n def __call__(self, step):\n with tf.name_scope(\"BertScheduler\"):\n total_steps = tf.convert_to_tensor(self.total_steps, name=\"total_steps\")\n warmup_steps = tf.convert_to_tensor(self.warmup_steps, name=\"warmup_steps\")\n\n current_step = step + 1.0\n\n return self.rate * tf.cond(\n current_step < warmup_steps,\n lambda: self.warmup(current_step, warmup_steps),\n lambda: self.decay(current_step, total_steps, warmup_steps),\n )\n\n @tf.function\n def warmup(self, step, warmup_steps):\n return step / tf.math.maximum(tf.constant(1.0), warmup_steps)\n\n @tf.function\n def decay(self, step, total_steps, warmup_steps):\n return tf.math.maximum(\n tf.constant(0.0), (total_steps - step) / tf.math.maximum(tf.constant(1.0), total_steps - warmup_steps)\n )\n\n def get_config(self):\n return {\n \"warmup_ratio\": self.warmup_ratio,\n \"total_steps\": self.total_steps,\n \"warmup_steps\": self.warmup_steps,\n \"name\": self.name,\n }",
"_____no_output_____"
],
[
"class ModelForSimCSE(tf.keras.Model):\n def __init__(self, model, temperature, **kwargs):\n super().__init__(**kwargs)\n self.model = model\n self.temperature = temperature\n\n def call(self, data, training=None):\n anchors, positives, negatives = data\n batch_size = tf.shape(anchors['input_word_ids'])[0]\n\n sentences = {key: tf.concat([anchors[key], positives[key], negatives[key]], axis=0) for key in positives.keys()}\n sentences_embedding = tf.nn.l2_normalize(self.model(sentences, training=training), axis=-1)\n\n anchor_embeddings = sentences_embedding[:batch_size]\n positive_embeddings = sentences_embedding[batch_size:-batch_size]\n negative_embeddings = sentences_embedding[-batch_size:]\n\n ctx = tf.distribute.get_replica_context()\n positive_embeddings, negative_embeddings = ctx.all_gather([positive_embeddings, negative_embeddings], axis=0)\n candidate_embeddings = tf.concat([positive_embeddings, negative_embeddings], axis=0)\n\n scores = tf.tensordot(anchor_embeddings, candidate_embeddings, axes=[[1], [1]])\n scores /= self.temperature\n\n local_batch_size = tf.shape(scores)[0]\n label = tf.range(local_batch_size) + (local_batch_size * ctx.replica_id_in_sync_group)\n\n return scores, label\n\n def train_step(self, data):\n with tf.GradientTape() as tape:\n logits, label = self(data, training=True)\n loss = self.compiled_loss(label, logits, regularization_losses=self.losses)\n\n self.optimizer.minimize(loss, self.trainable_variables, tape=tape)\n self.compiled_metrics.update_state(label, logits)\n return {m.name: m.result() for m in self.metrics}\n\n def test_step(self, data):\n logits, label = self(data, training=None)\n\n loss = self.compiled_loss(label, logits, regularization_losses=self.losses)\n self.compiled_metrics.update_state(label, logits)\n return {m.name: m.result() for m in self.metrics}\n",
"_____no_output_____"
]
],
[
[
"## Prepare datasets",
"_____no_output_____"
]
],
[
[
"def get_kornli_dataset(preprocessor, batch_size):\n def _get_ds_from_split(split) -> tf.data.Dataset:\n with tf.device('/job:localhost'):\n # batch_size=-1 is a way to load the dataset into memory\n in_memory_ds = tfds.load(\"kornli\", split=split, batch_size=-1, shuffle_files=True)\n\n sentence1_list = in_memory_ds[\"sentence1\"].numpy()\n sentence2_list = in_memory_ds[\"sentence2\"].numpy()\n gold_label_list = in_memory_ds[\"gold_label\"].numpy()\n\n # label: [entailment, neutral, contradiction] => [0, 1, 2]\n sentences = {}\n for index in tqdm(range(len(sentence1_list)), desc=f\"reading {split}\"):\n sentence1 = sentence1_list[index]\n sentence2 = sentence2_list[index]\n gold_label = gold_label_list[index]\n\n if sentence1 not in sentences:\n sentences[sentence1] = {}\n\n if gold_label != 1: # not neutral\n sentences[sentence1][gold_label] = sentence2\n\n dataset_input = [(key, val[0], val[2]) for key, val in sentences.items() if 0 in val and 2 in val]\n print(f\"dataset length of split {split}: {len(dataset_input)}\")\n return tf.data.Dataset.from_tensor_slices(dataset_input), len(dataset_input)\n\n mnli_train, num_mnli_train = _get_ds_from_split(\"mnli_train\")\n snli_train, num_snli_train = _get_ds_from_split(\"snli_train\")\n xnli_dev, num_xnli_dev = _get_ds_from_split(\"xnli_dev\")\n num_examples = num_mnli_train + num_snli_train\n\n train_ds = (\n mnli_train.concatenate(snli_train)\n .shuffle(num_mnli_train + num_snli_train, reshuffle_each_iteration=True)\n .batch(batch_size, drop_remainder=True)\n .map(lambda x: (preprocessor(x[:, 0]), preprocessor(x[:, 1]), preprocessor(x[:, 2])), num_parallel_calls=tf.data.AUTOTUNE)\n )\n dev_ds = (\n xnli_dev\n .shuffle(num_xnli_dev)\n .batch(batch_size, drop_remainder=True)\n .map(lambda x: (preprocessor(x[:, 0]), preprocessor(x[:, 1]), preprocessor(x[:, 2])), num_parallel_calls=tf.data.AUTOTUNE)\n )\n return (train_ds, dev_ds), num_examples",
"_____no_output_____"
]
],
[
[
"## Run train",
"_____no_output_____"
]
],
[
[
"preprocessor = create_preprocessing_model()\npreprocessor.summary()",
"Model: \"model\"\n_________________________________________________________________\n Layer (type) Output Shape Param # \n=================================================================\n sentences (InputLayer) [(None,)] 0 \n \n keras_layer (KerasLayer) {'input_word_ids': (None 0 \n , 128), \n 'input_type_ids': (None \n , 128), \n 'input_mask': (None, 12 \n 8)} \n \n=================================================================\nTotal params: 0\nTrainable params: 0\nNon-trainable params: 0\n_________________________________________________________________\n"
],
[
"import math\n\n\nwith strategy.scope():\n (train_ds, dev_ds), num_examples = get_kornli_dataset(preprocessor, BATCH_SIZE)\n print(\"Element spec:\", train_ds.element_spec)\n print(\"Num examples:\", num_examples)\n steps_per_epoch = math.ceil(num_examples / BATCH_SIZE)\n print(\"steps per epoch:\", steps_per_epoch)\n num_train_steps = steps_per_epoch * EPOCHS\n print(\"total num steps:\", num_train_steps)\n\n encoder = create_model()\n model = ModelForSimCSE(encoder, TEMPERATURE)\n model.compile(\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['acc'],\n optimizer=tf.keras.optimizers.Adam(learning_rate=BertScheduler(LEARNING_RATE, WARMUP_RATE, num_train_steps)),\n )\n\n model.fit(\n train_ds,\n epochs=EPOCHS,\n validation_data=dev_ds,\n )",
"\u001b[1mDownloading and preparing dataset Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to /root/tensorflow_datasets/kornli/1.0.1...\u001b[0m\n"
]
],
[
[
"## Run evaluation on KorSTS and KLUE STS",
"_____no_output_____"
]
],
[
[
"from scipy import stats\nfrom tqdm import tqdm\n\n\[email protected]\ndef calculate_similarity(sentence1, sentence2):\n representation1 = tf.nn.l2_normalize(encoder(preprocessor(sentence1)), axis=-1)\n representation2 = tf.nn.l2_normalize(encoder(preprocessor(sentence2)), axis=-1)\n\n return tf.reduce_sum(representation1 * representation2, axis=-1)\n\ndef eval_korsts(ds):\n label_score = []\n pred_score = []\n\n for item in tqdm(ds):\n label_score.append(item[\"score\"].numpy())\n pred_score.append(calculate_similarity(item[\"sentence1\"], item[\"sentence2\"]).numpy())\n\n label_score = tf.concat(label_score, axis=0)\n pred_score = tf.concat(pred_score, axis=0)\n print(stats.spearmanr(label_score, pred_score))\n\n\nwith tf.device('/job:localhost'):\n korsts_ds = tfds.load(\"korsts\", split=[\"dev\", \"test\"], batch_size=32)\n korsts_ds = {split: [item for item in korsts_ds[index]] for index, split in ((0, \"dev\"), (1, \"test\"))}\n\nprint(\"Evaluate dev\")\neval_korsts(korsts_ds['dev'])\nprint(\"Evaluate test\")\neval_korsts(korsts_ds['test'])",
"\u001b[1mDownloading and preparing dataset Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to /root/tensorflow_datasets/korsts/1.0.0...\u001b[0m\n"
],
[
"def eval_klue_sts(ds):\n label_score = []\n pred_score = []\n\n for item in tqdm(ds):\n label_score.append(item[\"label\"].numpy())\n pred_score.append(calculate_similarity(item[\"sentence1\"], item[\"sentence2\"]).numpy())\n\n label_score = tf.concat(label_score, axis=0)\n pred_score = tf.concat(pred_score, axis=0)\n print(stats.pearsonr(label_score, pred_score))\n\nwith tf.device('/job:localhost'):\n klue_sts = tfds.load(\"klue_sts\", split=\"dev\", batch_size=32)\n klue_sts = [item for item in klue_sts]\n\nprint(\"Evaluate dev\")\neval_klue_sts(klue_sts)",
"\u001b[1mDownloading and preparing dataset Unknown size (download: Unknown size, generated: Unknown size, total: Unknown size) to /root/tensorflow_datasets/klue_sts/1.1.0...\u001b[0m\n"
]
],
[
[
"## Save model",
"_____no_output_____"
]
],
[
[
"save_options = tf.saved_model.SaveOptions(experimental_io_device='/job:localhost')\nencoder.save(\"klue-roberta-large-simcse\", include_optimizer=False, options=save_options)",
"WARNING:tensorflow:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.\n"
],
[
"!zip -r klue-roberta-large-simcse.zip klue-roberta-large-simcse",
" adding: klue-roberta-large-simcse/ (stored 0%)\n adding: klue-roberta-large-simcse/variables/ (stored 0%)\n adding: klue-roberta-large-simcse/variables/variables.index (deflated 83%)\n adding: klue-roberta-large-simcse/variables/variables.data-00000-of-00001 (deflated 8%)\n adding: klue-roberta-large-simcse/keras_metadata.pb (deflated 87%)\n adding: klue-roberta-large-simcse/saved_model.pb (deflated 93%)\n adding: klue-roberta-large-simcse/assets/ (stored 0%)\n"
],
[
"!ls -alh",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbb29e12b2b7ccb7218fb2a197135388b9dd91a6
| 219,736 |
ipynb
|
Jupyter Notebook
|
LOL_bottomduotier_dataanalysis.ipynb
|
Bonseong/LOL_bottomduotier_dataanalysis
|
ebda6821ee711c286476f28f09b8670737bdb8d3
|
[
"MIT"
] | null | null | null |
LOL_bottomduotier_dataanalysis.ipynb
|
Bonseong/LOL_bottomduotier_dataanalysis
|
ebda6821ee711c286476f28f09b8670737bdb8d3
|
[
"MIT"
] | null | null | null |
LOL_bottomduotier_dataanalysis.ipynb
|
Bonseong/LOL_bottomduotier_dataanalysis
|
ebda6821ee711c286476f28f09b8670737bdb8d3
|
[
"MIT"
] | null | null | null | 37.472033 | 5,776 | 0.405914 |
[
[
[
"# 과제1, 바텀듀오의 티어",
"_____no_output_____"
],
[
"## 라이브러리, 데이터 로드",
"_____no_output_____"
]
],
[
[
"import requests\nimport json\nimport pandas as pd\nimport numpy as np\nfrom pandas.io.json import json_normalize\n\nimport warnings\nwarnings.filterwarnings(action='ignore')\n\nfrom sklearn.preprocessing import StandardScaler,MinMaxScaler\nfrom sklearn.cluster import KMeans\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits import mplot3d\nimport math",
"_____no_output_____"
],
[
"url='*****************************************************'",
"_____no_output_____"
],
[
"adc_sup_pick_red",
"_____no_output_____"
],
[
"lol_data=data.text\nlol_data=lol_data.replace('\\n', ',\\n')\nlol_data='['+lol_data+']'\nlol_data=lol_data.replace(']},\\n]',']}\\n]')",
"_____no_output_____"
],
[
"f = open(\"data.txt\", 'w')\nf.write(lol_data)\nf.close()",
"_____no_output_____"
],
[
"lol_data=json.loads(lol_data)",
"_____no_output_____"
],
[
"output_df=json_normalize(lol_data)",
"_____no_output_____"
],
[
"sample=output_df\nsample.reset_index(inplace=True)\ndel sample['index']\ndel sample['Unnamed: 0']\nsample",
"_____no_output_____"
]
],
[
[
"## 데이터 전처리",
"_____no_output_____"
],
[
"### teams\n#### 밴, 오브젝트에 대한 간략한 정보",
"_____no_output_____"
]
],
[
[
"def array_on_duplicate_keys(ordered_pairs):\n d = {}\n for k, v in ordered_pairs:\n if k in d:\n if type(d[k]) is list:\n d[k].append(v)\n else:\n d[k] = [d[k],v]\n else:\n d[k] = v\n return d",
"_____no_output_____"
],
[
"teams_output = pd.DataFrame(columns = ['firstdragon', 'firstinhibitor', 'pickturn', 'championid', 'baronkills',\n 'firstriftherald', 'firstbaron', 'riftheraldkills', 'firstblood',\n 'teamid', 'firsttower', 'vilemawkills', 'inhibitorkills', 'towerkills',\n 'dominionvictoryscore', 'win', 'dragonkills'])\ndef split_list(a_list):\n half = len(a_list)//2\n return a_list[:][:half], a_list[:][half:]",
"_____no_output_____"
],
[
"for i in range(len(sample)):\n test=sample['teams'][i]\n test=test.replace(\"'\", \"\\\"\").replace('[{','').replace('}]','').replace('}, {', ', ').replace(' \"bans\":','').replace('False','\\\"False\\\"').replace('True','\\\"True\\\"')\n test='[{' + test+ '}]'\n test=json.loads(test, object_pairs_hook=array_on_duplicate_keys)\n test=json_normalize(test)\n \n teams_output=pd.concat([teams_output,test])\n \nteams_output.reset_index(inplace=True)\ndel teams_output['index']\nteams_output.head()\n\n",
"_____no_output_____"
],
[
"a=[]\nb=[]\n\nteams_output_blue=pd.DataFrame()\nteams_output_red=pd.DataFrame()\n\n\nfor i in range(teams_output.shape[0]):\n for j in range(teams_output.shape[1]):\n \n A,B=split_list(teams_output.iloc[i][j])\n\n a.append(A)\n b.append(B)\n \n teams_output_blue=pd.concat([teams_output_blue,pd.DataFrame(pd.Series(a)).transpose()])\n teams_output_red=pd.concat([teams_output_red,pd.DataFrame(pd.Series(b)).transpose()])\n a=[]\n b=[]\n \nteams_output_blue.columns=teams_output.columns\nteams_output_red.columns=teams_output.columns\n\nteams_output_blue.reset_index(inplace=True)\nteams_output_red.reset_index(inplace=True)\n\nteams_output_blue=teams_output_blue.rename({'championid':'championid_ban'},axis='columns')\nteams_output_red=teams_output_blue.rename({'championid':'championid_ban'},axis='columns')\n\ndel teams_output_blue['index']\ndel teams_output_red['index']",
"_____no_output_____"
],
[
"teams_output_blue.head()",
"_____no_output_____"
]
],
[
[
"### participants\n#### 팀 챔피언, 오브젝트, 킬에 대한 상세한 정보",
"_____no_output_____"
]
],
[
[
"participants_output=pd.DataFrame()\n\nfor i in range(len(sample)):\n test=sample['participants'][i]\n test=test.replace(\"'\", \"\\\"\").replace('[{','').replace('}]','').replace('}, {', ', ').replace(' \"bans\":','').replace('False','\\\"False\\\"').replace('True','\\\"True\\\"')\n test='[{' + test+ '}]'\n test=json.loads(test, object_pairs_hook=array_on_duplicate_keys)\n test=json_normalize(test)\n \n participants_output=pd.concat([participants_output,test])\nparticipants_output.reset_index(inplace=True)\ndel participants_output['index']\nparticipants_output.head()",
"_____no_output_____"
],
[
"participants_output_if=pd.DataFrame(columns=['championid', 'kills', 'deaths', 'assists'])\n\nfor i in range(len(participants_output)):\n participants_output_if = participants_output_if.append(pd.DataFrame([[participants_output['championid'][i],\n list(json_normalize(participants_output['stats'][i])['kills']),\n list(json_normalize(participants_output['stats'][i])['deaths']),\n list(json_normalize(participants_output['stats'][i])['assists'])]], columns=['championid', 'kills', 'deaths', 'assists']), ignore_index=True)\n",
"_____no_output_____"
],
[
"a=[]\nb=[]\n\nparticipants_output_if_blue=pd.DataFrame()\nparticipants_output_if_red=pd.DataFrame()\n\nfor i in range(participants_output_if.shape[0]):\n for j in range(participants_output_if.shape[1]):\n \n A,B=split_list(participants_output_if.iloc[i][j])\n\n a.append(A)\n b.append(B)\n \n participants_output_if_blue=pd.concat([participants_output_if_blue,pd.DataFrame(pd.Series(a)).transpose()])\n participants_output_if_red=pd.concat([participants_output_if_red,pd.DataFrame(pd.Series(b)).transpose()])\n a=[]\n b=[]\n \nparticipants_output_if_blue.columns=participants_output_if.columns\nparticipants_output_if_red.columns=participants_output_if.columns\n\nparticipants_output_if_blue.reset_index(inplace=True)\nparticipants_output_if_red.reset_index(inplace=True)\n\ndel participants_output_if_blue['index']\ndel participants_output_if_red['index']",
"_____no_output_____"
],
[
"participants_output_if_blue.head()",
"_____no_output_____"
]
],
[
[
"### gameduration\n#### 게임 시간",
"_____no_output_____"
]
],
[
[
"sample['gameduration'].head()",
"_____no_output_____"
]
],
[
[
"### participantextendedstats\n#### 게임 플레이어들의 티어",
"_____no_output_____"
]
],
[
[
"participantextendedstats_output=pd.DataFrame()\n\nfor i in range(len(sample)):\n test=sample['participantextendedstats'][i]\n test=test.replace(\"'\", \"\\\"\").replace('[{','').replace('}]','').replace('}, {', ', ').replace(' \"bans\":','').replace('False','\\\"False\\\"').replace('True','\\\"True\\\"')\n test='[{' + test+ '}]'\n test=json.loads(test, object_pairs_hook=array_on_duplicate_keys)\n test=json_normalize(test)\n \n participantextendedstats_output=pd.concat([participantextendedstats_output,test])",
"_____no_output_____"
],
[
"a=[]\nb=[]\n\nparticipantextendedstats_output_blue=pd.DataFrame()\nparticipantextendedstats_output_red=pd.DataFrame()\n\n\nfor i in range(participantextendedstats_output.shape[0]):\n for j in range(participantextendedstats_output.shape[1]):\n \n A,B=split_list(participantextendedstats_output.iloc[i][j])\n\n a.append(A)\n b.append(B)\n \n participantextendedstats_output_blue=pd.concat([participantextendedstats_output_blue,pd.DataFrame(pd.Series(a)).transpose()])\n participantextendedstats_output_red=pd.concat([participantextendedstats_output_red,pd.DataFrame(pd.Series(b)).transpose()])\n a=[]\n b=[]\n \nparticipantextendedstats_output_blue.columns=participantextendedstats_output.columns\nparticipantextendedstats_output_red.columns=participantextendedstats_output.columns\n\nparticipantextendedstats_output_blue.reset_index(inplace=True)\nparticipantextendedstats_output_red.reset_index(inplace=True)\n\ndel participantextendedstats_output_blue['index']\ndel participantextendedstats_output_red['index']",
"_____no_output_____"
],
[
"participantextendedstats_output_blue.head()",
"_____no_output_____"
]
],
[
[
"### champion info\n#### 챔피언들의 코드, 영문명, 한글명",
"_____no_output_____"
]
],
[
[
"api_key = '**************************************************************'\nr = requests.get('https://ddragon.leagueoflegends.com/api/versions.json') # version data 확인\ncurrent_version = r.json()[0] # 가장 최신 버전 확인\ncurrent_version",
"_____no_output_____"
],
[
"r = requests.get('http://ddragon.leagueoflegends.com/cdn/{}/data/ko_KR/champion.json'.format(current_version))\nparsed_data = r.json() \nch_if = pd.DataFrame(parsed_data)",
"_____no_output_____"
],
[
"ch_if_df=pd.DataFrame(columns=['key','name','id'])\nfor i in range(len(ch_if)):\n temp_df=ch_if['data'][i]\n temp_df=json_normalize(temp_df)[['key','name','id']]\n \n ch_if_df=pd.concat([ch_if_df,temp_df])\n\nch_if_df.reset_index(inplace=True)\ndel ch_if_df['index']",
"_____no_output_____"
],
[
"ch_if_df",
"_____no_output_____"
]
],
[
[
"### 픽률 계산",
"_____no_output_____"
],
[
"#### BLUE TEAM",
"_____no_output_____"
]
],
[
[
"adc_sup_pick_blue=pd.DataFrame(participants_output_if_blue['championid'])\nadc_sup_pick_blue['adc_champ']=\"\"\nadc_sup_pick_blue['adc_champ_name']=\"\"\nadc_sup_pick_blue['adc_champ_kill']=''\nadc_sup_pick_blue['adc_champ_deaths']=''\nadc_sup_pick_blue['adc_champ_assists']=''\nadc_sup_pick_blue['sup_champ']=\"\"\nadc_sup_pick_blue['sup_champ_name']=\"\"\nadc_sup_pick_blue['sup_champ_kill']=''\nadc_sup_pick_blue['sup_champ_deaths']=''\nadc_sup_pick_blue['sup_champ_assists']=''\nadc_sup_pick_blue['win']=teams_output_blue['win']\n",
"_____no_output_____"
],
[
"def champ_name_korean(x): \n if x!=-1: return ch_if_df.loc[ch_if_df['key'] == str(x), 'name'].values[0]\n return",
"_____no_output_____"
],
[
"for i in range(len(adc_sup_pick_blue)):\n adc_sup_pick_blue['adc_champ'][i]=adc_sup_pick_blue['championid'][i][participantextendedstats_output_blue['position'][i].index('ADC')]\n adc_sup_pick_blue['adc_champ_name'][i]=champ_name_korean(adc_sup_pick_blue['adc_champ'][i])\n adc_sup_pick_blue['adc_champ_kill'][i]=participants_output_if_blue['kills'][i][participantextendedstats_output_blue['position'][i].index('ADC')]\n adc_sup_pick_blue['adc_champ_deaths'][i]=participants_output_if_blue['deaths'][i][participantextendedstats_output_blue['position'][i].index('ADC')]\n adc_sup_pick_blue['adc_champ_assists'][i]=participants_output_if_blue['assists'][i][participantextendedstats_output_blue['position'][i].index('ADC')]\n \n adc_sup_pick_blue['sup_champ'][i]=adc_sup_pick_blue['championid'][i][participantextendedstats_output_blue['position'][i].index('SUPPORT')]\n adc_sup_pick_blue['sup_champ_name'][i]=champ_name_korean(adc_sup_pick_blue['sup_champ'][i])\n adc_sup_pick_blue['sup_champ_kill'][i]=participants_output_if_blue['kills'][i][participantextendedstats_output_blue['position'][i].index('SUPPORT')]\n adc_sup_pick_blue['sup_champ_deaths'][i]=participants_output_if_blue['deaths'][i][participantextendedstats_output_blue['position'][i].index('SUPPORT')]\n adc_sup_pick_blue['sup_champ_assists'][i]=participants_output_if_blue['assists'][i][participantextendedstats_output_blue['position'][i].index('SUPPORT')]\n\ndel adc_sup_pick_blue['championid']",
"_____no_output_____"
]
],
[
[
"#### RED TEAM",
"_____no_output_____"
]
],
[
[
"adc_sup_pick_red=pd.DataFrame(participants_output_if_red['championid'])\nadc_sup_pick_red['adc_champ']=\"\"\nadc_sup_pick_red['adc_champ_name']=\"\"\nadc_sup_pick_red['adc_champ_kill']=''\nadc_sup_pick_red['adc_champ_deaths']=''\nadc_sup_pick_red['adc_champ_assists']=''\nadc_sup_pick_red['sup_champ']=\"\"\nadc_sup_pick_red['sup_champ_name']=\"\"\nadc_sup_pick_red['sup_champ_kill']=''\nadc_sup_pick_red['sup_champ_deaths']=''\nadc_sup_pick_red['sup_champ_assists']=''\nadc_sup_pick_red['win']=teams_output_red['win']\n",
"_____no_output_____"
],
[
"for i in range(len(adc_sup_pick_red)):\n adc_sup_pick_red['adc_champ'][i]=adc_sup_pick_red['championid'][i][participantextendedstats_output_red['position'][i].index('ADC')]\n adc_sup_pick_red['adc_champ_name'][i]=champ_name_korean(adc_sup_pick_red['adc_champ'][i])\n adc_sup_pick_red['adc_champ_kill'][i]=participants_output_if_red['kills'][i][participantextendedstats_output_red['position'][i].index('ADC')]\n adc_sup_pick_red['adc_champ_deaths'][i]=participants_output_if_red['deaths'][i][participantextendedstats_output_red['position'][i].index('ADC')]\n adc_sup_pick_red['adc_champ_assists'][i]=participants_output_if_red['assists'][i][participantextendedstats_output_red['position'][i].index('ADC')]\n \n adc_sup_pick_red['sup_champ'][i]=adc_sup_pick_red['championid'][i][participantextendedstats_output_red['position'][i].index('SUPPORT')]\n adc_sup_pick_red['sup_champ_name'][i]=champ_name_korean(adc_sup_pick_red['sup_champ'][i])\n adc_sup_pick_red['sup_champ_kill'][i]=participants_output_if_red['kills'][i][participantextendedstats_output_red['position'][i].index('SUPPORT')]\n adc_sup_pick_red['sup_champ_deaths'][i]=participants_output_if_red['deaths'][i][participantextendedstats_output_red['position'][i].index('SUPPORT')]\n adc_sup_pick_red['sup_champ_assists'][i]=participants_output_if_red['assists'][i][participantextendedstats_output_red['position'][i].index('SUPPORT')]\n\ndel adc_sup_pick_red['championid']",
"_____no_output_____"
],
[
"adsup_pick=pd.concat([adc_sup_pick_blue,adc_sup_pick_red])\nadsup_pick.reset_index(inplace=True)\ndel adsup_pick['index']",
"_____no_output_____"
],
[
"adsup_pick.head()",
"_____no_output_____"
],
[
"adsup_pickrate=pd.DataFrame(adsup_pick.groupby(['adc_champ_name','sup_champ_name']).count()['adc_champ']).sort_values(by='adc_champ',axis=0,ascending=False)",
"_____no_output_____"
],
[
"adsup_pickrate['duo_pickrate']=''\nadsup_pickrate['duo_pickrate']=adsup_pickrate['adc_champ']/len(sample)",
"_____no_output_____"
],
[
"adsup_pickrate=adsup_pickrate.rename({'adc_champ':'duo_pickcount'},axis='columns')",
"_____no_output_____"
],
[
"adsup_pickrate.reset_index(inplace=True)",
"_____no_output_____"
],
[
"adsup_pickrate",
"_____no_output_____"
]
],
[
[
"### 승률 계산",
"_____no_output_____"
]
],
[
[
"adsup_winrate=adsup_pick\nadsup_winrate = adsup_winrate.astype({'win': 'str'})\nadsup_winrate[\"win\"] = adsup_winrate[\"win\"].apply(lambda x: 1 if x==\"['Win']\" else 0)",
"_____no_output_____"
],
[
"adsup_winrate=adsup_winrate.groupby(['adc_champ_name','sup_champ_name']).mean().sort_values(by='win',axis=0,ascending=False)",
"_____no_output_____"
],
[
"adsup_winrate\nadsup_winrate.reset_index(inplace=True)\nadsup_winrate=adsup_winrate.rename({'win':'duo_winrate'},axis='columns')",
"_____no_output_____"
],
[
"adsup_winrate",
"_____no_output_____"
]
],
[
[
"### KDA 평균 계산",
"_____no_output_____"
]
],
[
[
"adsup_kdamean=adsup_pick",
"_____no_output_____"
],
[
"adsup_kdamean['adc_kda']=''\nadsup_kdamean['sup_kda']=''",
"_____no_output_____"
],
[
"for i in range(0,100):\n if adsup_kdamean['adc_champ_deaths'][i]!=0:\n adsup_kdamean['adc_kda'][i]=(adsup_kdamean['adc_champ_kill'][i]+adsup_kdamean['adc_champ_assists'][i])/adsup_kdamean['adc_champ_deaths'][i] \n else:\n adsup_kdamean['adc_kda'][i]=(adsup_kdamean['adc_champ_kill'][i]+adsup_kdamean['adc_champ_assists'][i])*1.2\n \n if adsup_kdamean['sup_champ_deaths'][i]!=0:\n adsup_kdamean['sup_kda'][i]=(adsup_kdamean['sup_champ_kill'][i]+adsup_kdamean['sup_champ_assists'][i])/adsup_kdamean['sup_champ_deaths'][i]\n else:\n adsup_kdamean['sup_kda'][i]=(adsup_kdamean['sup_champ_kill'][i]+adsup_kdamean['sup_champ_assists'][i])*1.2\n ",
"_____no_output_____"
],
[
"adsup_kdamean['duo_kda']=(adsup_kdamean['adc_kda']+adsup_kdamean['sup_kda'])/2",
"_____no_output_____"
],
[
"adsup_kdamean.head()",
"_____no_output_____"
],
[
"adsup_kdamean = adsup_kdamean.astype({'duo_kda': 'int'})",
"_____no_output_____"
],
[
"adsup_kdamean=adsup_kdamean.groupby(['adc_champ_name','sup_champ_name']).mean()",
"_____no_output_____"
],
[
"adsup_kdamean.reset_index(inplace=True)",
"_____no_output_____"
],
[
"adsup_kdamean",
"_____no_output_____"
]
],
[
[
"## 데이터 합치기",
"_____no_output_____"
]
],
[
[
"adsup_stat=pd.merge(adsup_winrate,adsup_pickrate,on=['adc_champ_name','sup_champ_name'])\nadsup_stat=pd.merge(adsup_stat,adsup_kdamean,on=['adc_champ_name','sup_champ_name'])\nadsup_stat=adsup_stat.rename({'win':'duo_winrate'},axis='columns')",
"_____no_output_____"
]
],
[
[
"## 최종 데이터",
"_____no_output_____"
]
],
[
[
"adsup_stat",
"_____no_output_____"
]
],
[
[
"# 데이터 분석",
"_____no_output_____"
],
[
"## 주제 : 픽률, 승률, KDA를 기준으로 한 바텀듀오 티어\n1. 가장 많이 픽된 듀오는?\n2. 가장 승률이 높은 듀오는?\n3. 가장 티어 (픽률, 승률, KDA 기준) 가 높은 듀오는?",
"_____no_output_____"
],
[
"LOL을 하면서 뜻하지 않게 서포터나 원거리 딜러 포지션에 배정받을 경우가 있다. 바텀 듀오는 바텀 라인에서 마치 둘이 한 몸이 된 것처럼 행동해야 CS나 적 챔피언을 잡을 수 있고 이는 곧 게임의 승패까지 연관된다.\n이 분석을 통해 고랭크 유저들의 바텀듀오 조합을 바탕으로 티어를 책정했으며, 바텀 유저가 아니거나 저랭크 유저들이 데이터 분석 결과를 바탕으로 조합을 구성하는데 조금 더 도움이 됐으면 하는 목적이다.",
"_____no_output_____"
],
[
"사용데이터\n- teams_output_blue , red : 팀에 대한 정보 (밴, 오브젝트 등)\n- participants_output_if_blue , red : 플레이어 챔피언에 대한 정보\n- gameduration : 게임 시간\n- participantextendedstats_output_blue , red : 플레이어 포지션, 티어\n- ch_if_df : 챔피언 정보\n",
"_____no_output_____"
],
[
"## 1. 가장 많이 픽된 듀오는?",
"_____no_output_____"
]
],
[
[
"adsup_stat['duo_pickcount'].mean()",
"_____no_output_____"
],
[
"plt.hist(adsup_stat['duo_pickcount'])",
"_____no_output_____"
]
],
[
[
"- LOL에는 수많은 원딜과 서포터들이 있고, 그 중 비원딜이나 다른 라인에서 잠시 내려온 서포터도 존재하기 때문에 모든 경우의 수를 고려할 수가 없다.\n- 너무 데이터가 없는 값은 삭제하기로 한다.\n- 평균 66회의 듀오픽이지만, 데이터가 좌측에 극단적으로 몰려있으므로, 임의적으로 300회 이상의 듀오 카운트를 가진 데이터만 사용하고자 한다.\n",
"_____no_output_____"
]
],
[
[
"adsup_stat_cut=adsup_stat[adsup_stat['duo_pickcount']>1000]",
"_____no_output_____"
],
[
"plt.hist(adsup_stat_cut['duo_pickcount']) # 나름 고른 모습을 보여줌.",
"_____no_output_____"
],
[
"len(adsup_stat_cut) # 17만건 게임의 95개의 듀오 대상",
"_____no_output_____"
],
[
"adsup_stat_cut.sort_values(by='duo_pickcount',axis=0,ascending=False)[0:10]",
"_____no_output_____"
]
],
[
[
"- 이즈리얼, 유미 듀오가 가장 많이 나왔다. 유미는 원거리 딜러의 몸에 달라붙어 있기 때문에 생존기가 우월한 이즈리얼이 자주 등장한다.\n- 그 뒤로 케이틀린, 럭스 & 케이틀린, 모르가나이다. 케이틀린은 덫을 활용하여 헤드샷을 최대한 쏴 라인전을 강하게 가져가야 하기 때문에 원거리 속박기가 있는 럭스, 모르가나가 선호되었다.\n- 그 뒤로 이즈리얼, 카르마이다. 역시 하드포킹 조합이다.\n- 모두 솔로랭크에서 자주 볼 수 있는 조합이며, 승률도 대부분 50%를 넘는 모습을 보여주었다.",
"_____no_output_____"
],
[
"## 2. 가장 승률이 높은 듀오는?\n",
"_____no_output_____"
]
],
[
[
"adsup_stat_cut.sort_values(by='duo_winrate',axis=0,ascending=False)[0:10]",
"_____no_output_____"
]
],
[
[
"- 애쉬, 노틸러스는 CC에 맞을경우 한방에 갈 확률이 매우 높은 듀오이다. 두 챔프 모두 많은 CC기를 보유하고 있으며, 애쉬의 긴 사거리와 노틸러스의 닻줄을 통해 라인전을 강하게 가져간다.\n- 진, 세나는 원거리 딜링, CC지원으로 상체의 캐리를 돕는 픽이다. 역시 궁합이 좋은 편이라고 할 수 있따.\n- 루시안, 파이크는 사거리는 짧지만 파이크의 CC가 한번 닿을 경우, 상대 듀오를 모두 잡아낼 수 있는 픽이다.\n- 그 외에 솔로랭크에서 궁합이 좋은 챔피언들이 구성되었다.",
"_____no_output_____"
],
[
"## 3. 가장 티어 (픽률, 승률, KDA 기준) 가 높은 듀오는?\n- 듀오 픽률, 듀오 승률, 듀오 KDA를 기준으로 티어를 5티어까지 나눠보고자 한다.\n- 세 변수를 기준으로 K-means 군집분석을 실시하여 군집을 나눈 후, 군집에 따라 티어를 책정했다.",
"_____no_output_____"
]
],
[
[
"adsup_stat_clustering=adsup_stat_cut[['adc_champ_name','sup_champ_name','duo_winrate','duo_pickrate','duo_kda']]\nadsup_stat_clustering.reset_index(inplace=True)\ndel adsup_stat_clustering['index']\nadsup_stat_clustering",
"_____no_output_____"
],
[
"X=np.array(adsup_stat_clustering.iloc[:,2:5])\nX[0:5]",
"_____no_output_____"
],
[
"scaler=StandardScaler()\nX_train_scale=scaler.fit_transform(X)",
"_____no_output_____"
],
[
"adsup_stat_clustering",
"_____no_output_____"
],
[
"X=pd.DataFrame(X_train_scale,columns=adsup_stat_clustering.columns[2:5])\nX.head()",
"_____no_output_____"
],
[
"model = KMeans(n_clusters=5,algorithm='auto')\nfeature = X[['duo_winrate','duo_pickrate','duo_kda']]",
"_____no_output_____"
],
[
"model.fit(feature)\npredict = pd.DataFrame(model.predict(feature))\npredict.columns=['predict']",
"_____no_output_____"
],
[
"adsup_stat_clustering_output=pd.concat([adsup_stat_clustering,predict], axis=1)",
"_____no_output_____"
],
[
"adsup_stat_clustering_output.head()",
"_____no_output_____"
],
[
"count=adsup_stat_clustering_output.groupby('predict').count()['adc_champ_name']\ncount ",
"_____no_output_____"
],
[
"X=pd.concat([X,predict],axis=1)",
"_____no_output_____"
],
[
"X.groupby('predict').mean().mean(axis=1)\n# 2 -> 1티어, 4 -> 2티어, 0 -> 3티어, 3 -> 4티어, 4 -> 5티어",
"_____no_output_____"
],
[
"adsup_stat_clustering_output['tier']=''\nfor i in range(len(adsup_stat_clustering_output)):\n if adsup_stat_clustering_output['predict'][i]==2:\n adsup_stat_clustering_output['tier'][i]='1티어'\n elif adsup_stat_clustering_output['predict'][i]==4:\n adsup_stat_clustering_output['tier'][i]='2티어'\n elif adsup_stat_clustering_output['predict'][i]==0:\n adsup_stat_clustering_output['tier'][i]='3티어'\n elif adsup_stat_clustering_output['predict'][i]==3:\n adsup_stat_clustering_output['tier'][i]='4티어'\n else:\n adsup_stat_clustering_output['tier'][i]='5티어'\ndel adsup_stat_clustering_output['predict']",
"_____no_output_____"
],
[
"adsup_stat_clustering_output.head()",
"_____no_output_____"
],
[
"adsup_stat_clustering_output[adsup_stat_clustering_output['tier']=='1티어'] #1티어 바텀듀오",
"_____no_output_____"
]
],
[
[
"- 1티어 바텀듀오는 위와 같다.\n- 대부분의 경기에서 등장했으며, 승률과 픽률 모두 높은 양상을 띈다.\n- 솔로랭크에서 대부분 한 번쯤 봤던 조합이며, 이따금 대회에서 나오기도 하는 조합이다.",
"_____no_output_____"
]
],
[
[
"adsup_stat_clustering_output[adsup_stat_clustering_output['tier']=='2티어'] #2티어 바텀듀오",
"_____no_output_____"
],
[
"adsup_stat_clustering_output[adsup_stat_clustering_output['tier']=='3티어'] #3티어 바텀듀오",
"_____no_output_____"
],
[
"adsup_stat_clustering_output[adsup_stat_clustering_output['tier']=='4티어'] #4티어 바텀듀오",
"_____no_output_____"
],
[
"adsup_stat_clustering_output[adsup_stat_clustering_output['tier']=='5티어'] #5티어 바텀듀오",
"_____no_output_____"
]
],
[
[
"- 5티어 바텀조합이다. 주의해야 할 것은 1000회 이상 데이터가 기록된 데이터를 바탕으로 분석을 진행한 것이기 때문에 이 조합이 꼭 나쁘다는 것은 아니다.\n- 상위티어 챔피언 구성에 비해 다소 지표가 떨어진다.",
"_____no_output_____"
],
[
"# 한계점\n- 듀오승률, 듀오픽률, KDA 만 고려했을 뿐, 데미지 딜링이나 골드 수급 등 많은 변수를 고려하지 않은 분석이다. 특히 KDA라는 지표는 허점이 많은 지표이기 때문에 보정이나 다른 데이터 대체가 필요할 수도 있다.\n- 픽률이 군집분석에서 너무 높은 부분을 가져 간듯 하다. 케이틀린, 이즈리얼같은 국민픽이라고 해서 반드시 상위티어 일수는 없다.\n- 다른 고차원적인 분석이 분명 존재할 것이다.",
"_____no_output_____"
],
[
"# 보완해야 할 점\n- JSON 파일을 다루는 데에 좀 더 익숙해져야 한다. JSON 파일 로드에 굉장히 많은 시간을 쏟았고, 결국 내부를 임의적으로 바꿔 로드하는데 그치고 말았다. 결과위주의 분석이기 때문에 추후 코드최적화가 반드시 필요하다.\n- 리그오브레전드에 대한 이해도가 더욱 필요하다. 게임 상세정보에 분명 더 좋은 인사이트를 추출할 부분이 있을 것이다.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cbb2b2bc28459dbf7dddf942df6669bfb9a5fb27
| 9,186 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
|
jtpeters963/sqlalchemy-challenge
|
8b52db1fab239ff61cefa21082253d9b3ba23412
|
[
"ADSL"
] | null | null | null |
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
|
jtpeters963/sqlalchemy-challenge
|
8b52db1fab239ff61cefa21082253d9b3ba23412
|
[
"ADSL"
] | null | null | null |
.ipynb_checkpoints/climate_starter-checkpoint.ipynb
|
jtpeters963/sqlalchemy-challenge
|
8b52db1fab239ff61cefa21082253d9b3ba23412
|
[
"ADSL"
] | null | null | null | 25.445983 | 131 | 0.562813 |
[
[
[
"%matplotlib inline\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\nimport matplotlib.pyplot as plt",
"_____no_output_____"
],
[
"import numpy as np\nimport pandas as pd",
"_____no_output_____"
],
[
"import datetime as dt",
"_____no_output_____"
]
],
[
[
"# Reflect Tables into SQLAlchemy ORM",
"_____no_output_____"
]
],
[
[
"# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func",
"_____no_output_____"
],
[
"engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")",
"_____no_output_____"
],
[
"# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables",
"_____no_output_____"
],
[
"# We can view all of the classes that automap found\n",
"_____no_output_____"
],
[
"# Save references to each table\n",
"_____no_output_____"
],
[
"# Create our session (link) from Python to the DB\n",
"_____no_output_____"
]
],
[
[
"# Exploratory Climate Analysis",
"_____no_output_____"
]
],
[
[
"# Design a query to retrieve the last 12 months of precipitation data and plot the results\n\n# Calculate the date 1 year ago from the last data point in the database\n\n# Perform a query to retrieve the data and precipitation scores\n\n# Save the query results as a Pandas DataFrame and set the index to the date column\n\n# Sort the dataframe by date\n\n# Use Pandas Plotting with Matplotlib to plot the data\n",
"_____no_output_____"
],
[
"# Use Pandas to calcualte the summary statistics for the precipitation data",
"_____no_output_____"
],
[
"# Design a query to show how many stations are available in this dataset?\n",
"_____no_output_____"
],
[
"# What are the most active stations? (i.e. what stations have the most rows)?\n# List the stations and the counts in descending order.\n",
"_____no_output_____"
],
[
"# Using the station id from the previous query, calculate the lowest temperature recorded, \n# highest temperature recorded, and average temperature of the most active station?\n",
"_____no_output_____"
],
[
"# Choose the station with the highest number of temperature observations.\n# Query the last 12 months of temperature observation data for this station and plot the results as a histogram\n",
"_____no_output_____"
]
],
[
[
"## Bonus Challenge Assignment",
"_____no_output_____"
]
],
[
[
"# This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' \n# and return the minimum, average, and maximum temperatures for that range of dates\ndef calc_temps(start_date, end_date):\n \"\"\"TMIN, TAVG, and TMAX for a list of dates.\n \n Args:\n start_date (string): A date string in the format %Y-%m-%d\n end_date (string): A date string in the format %Y-%m-%d\n \n Returns:\n TMIN, TAVE, and TMAX\n \"\"\"\n \n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()\n\n# function usage example\nprint(calc_temps('2012-02-28', '2012-03-05'))",
"_____no_output_____"
],
[
"# Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax \n# for your trip using the previous year's data for those same dates.\n",
"_____no_output_____"
],
[
"# Plot the results from your previous query as a bar chart. \n# Use \"Trip Avg Temp\" as your Title\n# Use the average temperature for the y value\n# Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr)\n",
"_____no_output_____"
],
[
"# Calculate the total amount of rainfall per weather station for your trip dates using the previous year's matching dates.\n# Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation\n\n",
"_____no_output_____"
],
[
"# Create a query that will calculate the daily normals \n# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)\n\ndef daily_normals(date):\n \"\"\"Daily Normals.\n \n Args:\n date (str): A date string in the format '%m-%d'\n \n Returns:\n A list of tuples containing the daily normals, tmin, tavg, and tmax\n \n \"\"\"\n \n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n return session.query(*sel).filter(func.strftime(\"%m-%d\", Measurement.date) == date).all()\n \ndaily_normals(\"01-01\")",
"_____no_output_____"
],
[
"# calculate the daily normals for your trip\n# push each tuple of calculations into a list called `normals`\n\n# Set the start and end date of the trip\n\n# Use the start and end date to create a range of dates\n\n# Stip off the year and save a list of %m-%d strings\n\n# Loop through the list of %m-%d strings and calculate the normals for each date\n",
"_____no_output_____"
],
[
"# Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index\n",
"_____no_output_____"
],
[
"# Plot the daily normals as an area plot with `stacked=False`\n",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb2b3e282cabebc5dcba912b3c29a24589b9823
| 88,672 |
ipynb
|
Jupyter Notebook
|
docs/tutorials/george.ipynb
|
tronsgaard/tinygp
|
11e9c869fd2a62d7c0292db3b6fa9eab46e296e5
|
[
"MIT"
] | null | null | null |
docs/tutorials/george.ipynb
|
tronsgaard/tinygp
|
11e9c869fd2a62d7c0292db3b6fa9eab46e296e5
|
[
"MIT"
] | null | null | null |
docs/tutorials/george.ipynb
|
tronsgaard/tinygp
|
11e9c869fd2a62d7c0292db3b6fa9eab46e296e5
|
[
"MIT"
] | null | null | null | 283.297125 | 77,222 | 0.916806 |
[
[
[
"try:\n import tinygp\nexcept ImportError:\n %pip install -q tinygp\n\ntry:\n import george\nexcept ImportError:\n %pip install -q george\n\nfrom jax.config import config\n\nconfig.update(\"jax_enable_x64\", True)",
"_____no_output_____"
]
],
[
[
"(george)=\n\n# Comparison With george\n\nOne of the `tinygp` design decisions was to provide a high-level API similar to the one provided by the [george](https://george.readthedocs.io) GP library.\nThis was partly because I (as the lead developer of `george`) wanted to ease users' transitions away from `george` to something more modern (like `tinygp`).\nI also quite like the `george` API and don't think that there exist other similar tools.\nThe defining feature is `tinygp` does not include built-in implementations of inference algorithms.\nInstead, it provides an expressive model-building interface that makes it easy to experiement with different kernels while still integrating with your favorite inference engine.\n\nIn this document, we compare the interfaces and computational performance of `george` and `tinygp` for constructing kernel models and evaluating the GP marginalized likelihood.\nSince `tinygp` supports GPU-acceleration, we have executed this notebook on a machine with the following GPU:",
"_____no_output_____"
]
],
[
[
"!nvidia-smi --query-gpu=gpu_name --format=csv",
"name\nNVIDIA A100-PCIE-40GB\n"
]
],
[
[
"By default, the CPU versions of both `george` and `tinygp` will also use parellelized linear algebra libraries to take advantage of multiple CPU threads, however to make the benchmarks more replicable, we'll disable this parallelization for the remainder of this notebook:",
"_____no_output_____"
]
],
[
[
"import os\n\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\nos.environ[\"XLA_FLAGS\"] = (\n os.environ.get(\"XLA_FLAGS\", \"\")\n + \" --xla_cpu_multi_thread_eigen=false intra_op_parallelism_threads=1\"\n)",
"_____no_output_____"
]
],
[
[
"Then we generate some simulated data and define functions for computing the GP log likelihood using `george` and `tinygp` (with separate CPU and GPU version).\nAs mentioned above, the syntax of these functions is quite similar, but there are a few differences.\nMost notably, the units of the \"metric\" or \"length scale\" parameter in the kernel is different (length-squared in `george` and not squared in `tinygp`).\nAlso, the `gp.compute` method no longer exists in `tinygp` since this would be less compatible with `jax`'s preference for pure functional programming.",
"_____no_output_____"
]
],
[
[
"from functools import partial\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport jax\nimport jax.numpy as jnp\n\nimport george\nimport tinygp\n\nsigma = 1.5\nrho = 2.5\njitter = 0.1\n\nrandom = np.random.default_rng(49382)\nx = np.sort(random.uniform(0, 10, 20_000))\ny = np.sin(x) + jitter * random.normal(0, 1, len(x))\n\n\ndef george_loglike(x, y, **kwargs):\n kernel = sigma**2 * george.kernels.Matern32Kernel(rho**2)\n gp = george.GP(kernel, **kwargs)\n gp.compute(x, jitter)\n return gp.log_likelihood(y)\n\n\ndef tinygp_loglike(x, y):\n kernel = sigma**2 * tinygp.kernels.Matern32(rho)\n gp = tinygp.GaussianProcess(kernel, x, diag=jitter**2)\n return gp.condition(y)\n\n\nhodlr_loglike = partial(\n george_loglike, solver=george.solvers.HODLRSolver, tol=0.5\n)\ntinygp_loglike_cpu = jax.jit(tinygp_loglike, backend=\"cpu\")\ntinygp_loglike_gpu = jax.jit(tinygp_loglike, backend=\"gpu\")",
"_____no_output_____"
]
],
[
[
"Now we benchmark the computational cost of computing the log likelihood using each of these methods:",
"_____no_output_____"
]
],
[
[
"ns = [10, 20, 100, 200, 1_000, 2_000, 10_000, len(x)]\ngeorge_time = []\nhodlr_time = []\ncpu_time = []\ngpu_time = []\nfor n in ns:\n print(f\"\\nN = {n}:\")\n\n args = x[:n], y[:n]\n gpu_args = jax.device_put(x[:n]), jax.device_put(y[:n])\n\n if n < 10_000:\n results = %timeit -o george_loglike(*args)\n george_time.append(results.average)\n\n tinygp_loglike_cpu(*args).block_until_ready()\n results = %timeit -o tinygp_loglike_cpu(*args).block_until_ready()\n cpu_time.append(results.average)\n\n results = %timeit -o hodlr_loglike(*args)\n hodlr_time.append(results.average)\n\n tinygp_loglike_gpu(*gpu_args).block_until_ready()\n results = %timeit -o tinygp_loglike_gpu(*gpu_args).block_until_ready()\n gpu_time.append(results.average)",
"\nN = 10:\n387 µs ± 6.61 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n14.2 µs ± 14 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n304 µs ± 6.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n73.5 µs ± 368 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\nN = 20:\n403 µs ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n23.9 µs ± 78.9 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n318 µs ± 6.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n75.6 µs ± 86.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\nN = 100:\n781 µs ± 757 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n398 µs ± 701 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n592 µs ± 3.78 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n180 µs ± 2.02 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\nN = 200:\n2.42 ms ± 5.15 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n2.01 ms ± 8.43 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n919 µs ± 674 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n266 µs ± 222 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\nN = 1000:\n198 ms ± 1.09 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n155 ms ± 429 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n4.42 ms ± 7.32 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n1.54 ms ± 1.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nN = 2000:\n1.56 s ± 1.98 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n1.18 s ± 2.91 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n8.81 ms ± 10.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n3.65 ms ± 1.25 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nN = 10000:\n59.5 ms ± 228 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n49.1 ms ± 55.3 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\nN = 20000:\n126 ms ± 519 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n263 ms ± 898 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
]
],
[
[
"In the plot of this benchmark, you'll notice several features:\n\n1. For very small datasets, the `tinygp` CPU implementation is significantly faster than any of the other implementations. This is because `jax.jit` removes a lot of the Python overhead that is encountered when chaining `numpy` functions.\n2. For medium to large datasets, `tinygp` is generally faster than `george`, with the GPU version seeing a significant advantage.\n3. The CPU implementations approach the expected asymptotic complexity of $\\mathcal{O}(N^3)$ only for the largest values of $N$. This is probably caused by memory allocation overhead or other operations with better scaling than the Cholesky factorization.\n4. The approximate \"HODLR\" solver from `george` outperforms the GPU-enabled `tinygp` exact solver, but only for very large datasets, and it's important to note that the HODLR method does not scale well to larger input dimensions. Any existing or future approximate solvers like this that are implemented in `jax` could be easily used in conjunction with `tinygp`, but such things have not yet been implemented.",
"_____no_output_____"
]
],
[
[
"plt.loglog(ns[: len(george_time)], george_time, \"o-\", label=\"george (basic)\")\nplt.loglog(ns, hodlr_time, \"o-\", label=\"george (HODLR)\")\nplt.loglog(ns[: len(cpu_time)], cpu_time, \"o-\", label=\"tinygp (CPU)\")\nplt.loglog(ns, gpu_time, \"o-\", label=\"tinygp (GPU)\")\nylim = plt.ylim()\nplt.loglog(\n ns,\n 0.5 * np.array(ns) ** 3 / ns[len(cpu_time) - 1] ** 3 * cpu_time[-1],\n \":k\",\n label=\"O($N^3$)\",\n)\nplt.ylim(ylim)\nplt.legend()\nplt.xlabel(\"number of data points\")\nplt.ylabel(\"runtime [s]\");",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb2e1b14888cf1172af9d6f13347b4d2fb57efb
| 206,818 |
ipynb
|
Jupyter Notebook
|
sandbox/jupyter notebooks/Make realistic spectra.ipynb
|
jamessdixon/hypedsearch
|
e294208cd5e66b897527d7d819c337b61ea7dde8
|
[
"MIT"
] | null | null | null |
sandbox/jupyter notebooks/Make realistic spectra.ipynb
|
jamessdixon/hypedsearch
|
e294208cd5e66b897527d7d819c337b61ea7dde8
|
[
"MIT"
] | null | null | null |
sandbox/jupyter notebooks/Make realistic spectra.ipynb
|
jamessdixon/hypedsearch
|
e294208cd5e66b897527d7d819c337b61ea7dde8
|
[
"MIT"
] | 1 |
2021-07-09T19:45:46.000Z
|
2021-07-09T19:45:46.000Z
| 149.219336 | 781 | 0.703899 |
[
[
[
"# Make realistic spectra\nMake our generated data look more like real data",
"_____no_output_____"
]
],
[
[
"import os\nimport sys\nmodule_path = os.path.abspath(os.path.join('..'))\nif module_path not in sys.path:\n sys.path.append(module_path)\nmodule_path = os.path.abspath(os.path.join('../..'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n \nfrom src.spectra.gen_spectra import gen_spectrum\nfrom random import randint\nfrom collections import namedtuple\nimport numpy as np",
"_____no_output_____"
],
[
"RealisticSpectrum = namedtuple('RealisticSpectrum', ['spectrum', 'abundance', 'precursor_mass'])\n\ndef gen_realistic_spectra(sequences: list) -> list:\n '''\n '''\n realistic_spectra = []\n for seq in sequences:\n spec_props = gen_spectrum(seq)\n spec = spec_props['spectrum']\n precursor = spec_props['precursor_mass']\n # Mess with it\n # 1. Drop out peaks\n dropout_rate = randint(60, 85)\n dropouts = [randint(0, 100) < dropout_rate for _ in range(len(spec))]\n leftover_peaks = [spec[i] for i in range(len(spec)) if not dropouts[i]]\n\n # 2. introduce mass errors\n for i in range(len(leftover_peaks)):\n factor = 1 if randint(0, 10) < 5 else -1\n leftover_peaks[i] += factor * np.random.pareto(600) # found from experiments\n\n # 3. pick the abundance\n abundances = points = np.random.pareto(1, len(leftover_peaks)) * 2000\n \n realistic_spectra.append(RealisticSpectrum(leftover_peaks, abundances, precursor))\n \n return realistic_spectra",
"_____no_output_____"
]
],
[
[
"## Make sequences",
"_____no_output_____"
]
],
[
[
"from src.file_io import fasta\n\nfasta_file = '../../testing framework/data/databases/100prots.fasta'\ndatabase = fasta.read(fasta_file, True)\n\ndatabase = {x['name']: x for x in database}\n\nfrom modules.sequence_generation import proteins, peptides\ntest_directory = '../data/testing_output/'\n\nnum_hybs = 5\nmin_length= 5\nmax_length = 20\nnum_peptides = 100\nmin_cont = 3 #min contribution for each side of a hybrid\n\n# make hybrid proteins\nhyb_prots = proteins.generate_hybrids([x for _, x in database.items()], num_hybs, min_contribution=max_length)\n# create peptides\nnon_hybrid_peps = peptides.gen_peptides([x for _, x in database.items()], num_peptides, min_length=min_length, max_length=max_length, digest='random', dist='beta')\n# create hybrid peptides\nhyb_peps = peptides.gen_peptides(hyb_prots, num_hybs, min_length=min_length, max_length=max_length, digest='random', min_contribution=min_cont, hybrid_list=True)\n\nall_proteins_raw = [x for _,x in database.items()] + hyb_prots\nall_peptides_raw = non_hybrid_peps + hyb_peps\n\npeptides = {}\nfor i, pep in enumerate(all_peptides_raw):\n peptides[i] = pep\n peptides[i]['scan_no'] = i\n \nimport json\nexperiment_info_file_name = 'experiment_info.json'\n\nexp = {'database': fasta_file, 'peptides': peptides}\nwith open(test_directory + experiment_info_file_name, 'w') as o:\n json.dump(exp, o)",
"Generating hybrid protein 0/5[0%]\rGenerating hybrid protein 1/5[20%]\rGenerating hybrid protein 2/5[40%]\rGenerating hybrid protein 3/5[60%]\rGenerating hybrid protein 4/5[80%]\r\nFinished generating hybrid proteins\n"
],
[
"from modules.sequence_generation import write_spectra\n\nspectra = gen_realistic_spectra([p['sequence'] for p in all_peptides_raw])\n\nwrite_spectra.write_mzml('realisticSpectra', [x._asdict() for x in spectra], output_dir=test_directory)\n",
"OrderedDict([('spectrum', [357.2256498775485, 44.520513505549914, 293.1700303856042, 341.69761393056916, 628.3776794578276, 741.4610881266184, 236.6435904886326, 414.74785371744997]), ('abundance', array([3540.46265055, 1389.32465648, 5535.55425355, 1142.16033593,\n 5781.09010783, 802.9783693 , 626.45684955, 4024.82585276])), ('precursor_mass', 414.75052725000006)])\nOrderedDict([('spectrum', [865.4826648232279, 79.05744663768904, 164.11165660978418, 317.6921468366993, 433.24993550186673, 500.2648996785691, 442.25040246654754]), ('abundance', array([ 4688.57463888, 129528.58731226, 741.50250775, 10538.6294523 ,\n 5227.31840581, 2370.33902375, 2687.30810016])), ('precursor_mass', 442.25017225000005)])\nOrderedDict([('spectrum', [314.20223181217347, 90.05630853091401, 397.1198417676071, 609.2768953693503, 97.0344734511997, 305.1352733975159]), ('abundance', array([3703.97926093, 1149.04628358, 4672.49426808, 2779.47100458,\n 4276.63535847, 2366.43391687])), ('precursor_mass', 305.14037925)])\nOrderedDict([('spectrum', [355.1991577243947, 65.05743074541752, 484.28113518683523, 518.2933973191601, 631.3715518997628, 728.4291722211984, 67.0340270608539, 131.08337504222303, 493.2853004309223]), ('abundance', array([2.91545592e+03, 1.15867378e+04, 1.04530744e+04, 2.20027421e+02,\n 3.20773458e+03, 3.53792964e+04, 1.39385707e+03, 2.43637100e+05,\n 4.40394812e+03])), ('precursor_mass', 493.28747375000006)])\nOrderedDict([('spectrum', [273.1515577154952, 137.08203097094685, 175.106704367586, 360.22057831408597, 88.0575609348218]), ('abundance', array([34236.53201843, 5765.29100371, 1070.98997824, 99586.3701341 ,\n 5522.72798406])), ('precursor_mass', 224.13172525000002)])\nOrderedDict([('spectrum', [114.09482770823998, 211.1441923878683, 308.19942872903704, 1168.6635719702024, 154.59892204184504, 527.3220112026877, 182.08267584384294, 539.2456739270182, 872.3951054797212, 1156.5886961382284, 1463.778973757785, 91.54556828728815, 270.1279086026836, 436.6981497331641]), ('abundance', array([1.61251175e+04, 7.23078731e+02, 3.29297888e+03, 1.62524708e+03,\n 1.35915407e+03, 2.02179387e+02, 5.23306863e+01, 5.30556362e+05,\n 5.01736344e+03, 3.34297296e+03, 1.10215741e+03, 8.01844792e+04,\n 7.04118447e+02, 4.26460746e+04])), ('precursor_mass', 732.3933317499999)])\nOrderedDict([('spectrum', [415.23571299208874, 116.06216417326291, 151.5828222073001, 272.169116207128, 147.12122837361792, 260.2004803546548, 331.23642536579075, 281.1777065606662]), ('abundance', array([ 1545.67307852, 1715.80732431, 792.39005574, 5921.51798851,\n 7072.73206219, 1839.75055345, 15150.47694417, 6501.83395701])), ('precursor_mass', 281.17507875)])\nOrderedDict([('spectrum', [98.06440445226079, 286.1382053736841, 400.18180685141755, 687.3349030132457, 100.06054358663144, 257.13378332846804, 220.09312739003485, 621.2856526708711, 708.3160187842869, 809.3635557508507, 53.530526038062895, 197.58102646318775, 311.14497155703896, 453.71030111717124]), ('abundance', array([ 1905.03243283, 139.32556423, 2785.26499801, 537.92310637,\n 2994.84082237, 18857.59926575, 163.76095878, 71312.95082359,\n 5001.88764793, 188.89939803, 5399.27775491, 261.46343335,\n 1935.24059305, 2643.61735872])), ('precursor_mass', 453.71179524999997)])\nOrderedDict([('spectrum', [104.02223924986947, 52.508727620696426, 118.08202404177062, 59.55121665214983, 117.06023121154509]), ('abundance', array([1091.11062741, 1127.93313998, 1318.8911591 , 419.84354096,\n 1797.36025444])), ('precursor_mass', 318.63651475)])\nOrderedDict([('spectrum', [201.12296192729886, 101.06665226276262]), ('abundance', array([ 383.18859948, 11664.50753123])), ('precursor_mass', 303.67649725)])\nOrderedDict([('spectrum', [522.1844707235616, 961.4804303321656, 204.0810434799758, 297.10929832003865, 274.1866537919549, 458.30816749859156, 850.4399415241911, 979.4857960536281, 425.7237755068856]), ('abundance', array([ 4260.9994502 , 27553.77569376, 961.35538046, 1396.65056065,\n 1494.23515368, 79321.71382854, 745.84147595, 2075.10942099,\n 1486.55106756])), ('precursor_mass', 490.24580175)])\nOrderedDict([('spectrum', [783.4396273253057, 237.15771358340314, 392.2232440405651, 313.1204173181366, 230.59725535738562, 304.13335597681623, 360.67491080501213]), ('abundance', array([ 1737.64839474, 40101.0061871 , 1100.07624231, 2399.77631263,\n 111.42686291, 3981.13369712, 2440.18438048])), ('precursor_mass', 466.75114625)])\nOrderedDict([('spectrum', [372.18631254466874, 501.2314188983857, 65.03746894670716, 186.59836918747195, 359.15652559354703, 148.0607363897711, 235.09235562562185, 735.3163652498987, 246.61962239764952, 304.12207077630956, 368.1621743609325]), ('abundance', array([ 3530.15055854, 1202.44597503, 10253.00503309, 79431.95224919,\n 7414.84739458, 512.48985507, 902.93370821, 20110.61692814,\n 7373.6901462 , 2899.19692459, 15948.4361727 ])), ('precursor_mass', 368.16140775)])\nOrderedDict([('spectrum', [58.022883093304564, 685.3392241772223, 207.11619368030728, 242.63461720733616, 53.52801750907369, 352.1775072931363]), ('abundance', array([ 87.76499298, 14752.09284329, 1279.22552043, 46963.08562119,\n 4295.39657017, 404.73299603])), ('precursor_mass', 352.17772675)])\nOrderedDict([('spectrum', [203.08328331339925, 393.1261471719006, 232.5862486220947, 90.05657185292738, 280.0910401289933, 383.1048061205001, 482.17411893429295, 89.04539194759737]), ('abundance', array([1254.8244432 , 1749.97233845, 643.74120615, 1645.98999239,\n 1856.38511017, 7825.10047284, 1617.60565769, 5098.07981723])), ('precursor_mass', 241.59052174999997)])\nOrderedDict([('spectrum', [129.10197299629493, 654.3072634655201, 1092.6253997330775, 1499.8486568496487, 138.58209458241353, 212.1215587947565, 555.2868915680593, 781.4483642580983, 993.6095207462273, 278.14511994085694, 440.7603730331668, 686.3727073893538]), ('abundance', array([1.44017937e+03, 3.75545368e+01, 2.86239284e+03, 1.65205232e+04,\n 3.27928837e+03, 3.25505429e+03, 2.31958737e+04, 1.75507253e+03,\n 5.51739486e+02, 2.16471848e+04, 3.40349838e+04, 6.89576785e+04])), ('precursor_mass', 823.95438125)])\nOrderedDict([('spectrum', [100.07572823466741, 213.159502896303, 342.2009896574599, 528.2832085022975, 107.08317628693713, 264.64125246623877, 514.7365938826373, 148.0622631394627, 277.10192762911146, 405.1636040833724, 705.2860299172626, 1046.4768197166504, 74.53448351425482, 139.05366622258398, 353.14470409341794, 417.6661420939988, 474.2091988062687]), ('abundance', array([10056.08504979, 345.23112593, 2624.55947272, 8190.94412073,\n 3790.30255687, 1540.70679668, 593.74145982, 76.16313318,\n 105.18601908, 4632.73084893, 106.78061431, 3119.32863053,\n 3716.84827995, 535.98481878, 218.50051149, 11883.46112605,\n 420.35985819])), ('precursor_mass', 523.7430962500001)])\nOrderedDict([('spectrum', [229.11512812701235, 148.06267445791877, 546.2863978697878, 195.59772385363135, 558.295426373914]), ('abundance', array([1.62409174e+03, 1.63400822e+00, 4.09925862e+03, 1.44955551e+03,\n 2.41394611e+04])), ('precursor_mass', 558.29582625)])\nOrderedDict([('spectrum', [312.15437094112093, 875.4152239934225, 50.54291423971908, 438.2135653909115, 106.04967555638764, 441.19719816057136, 669.3089461953123, 881.3875149155137, 980.4554122586129, 53.52935317203642, 89.04655507342673, 139.57317155896007, 221.10164937716542, 277.64300278310486]), ('abundance', array([5.44007977e+03, 1.89551193e+03, 3.55022763e+05, 2.07243749e+02,\n 3.11313510e+04, 3.68593907e+03, 9.05376365e+02, 7.65778826e+02,\n 1.25439626e+03, 1.28664020e+03, 3.58177976e+03, 2.20423932e+03,\n 2.31974859e+01, 2.90039169e+03])), ('precursor_mass', 490.73219324999997)])\nOrderedDict([('spectrum', [114.08674265436697, 251.66962619743504, 302.19687050180613, 358.74259746796236, 361.24449407891143]), ('abundance', array([ 3393.62152614, 14429.57072749, 4767.5458675 , 581.81346936,\n 3341.15399325])), ('precursor_mass', 431.79166425000005)])\nOrderedDict([('spectrum', [203.09994363899554, 137.5736948413103, 181.09361157275293, 366.16371797094496, 182.08094502009985, 494.28216835034124, 565.3180290401029, 169.59071211428568]), ('abundance', array([ 5400.73266417, 1443.73712834, 1742.07655802, 129.67550108,\n 6463.51515975, 6997.85898926, 2378.89787245, 45774.65116865])), ('precursor_mass', 698.84440125)])\nOrderedDict([('spectrum', [164.06960835037444, 491.2276467545729, 900.3569539274724, 118.05811880283076, 246.1158542700848, 501.20281778788166, 366.12901696151977, 60.53564960697144, 265.10252682493376, 329.13410421366405, 428.6788623179173]), ('abundance', array([6.58568057e+03, 1.06149678e+04, 1.81893372e+03, 3.81164039e+01,\n 4.20345620e+03, 7.60056567e+03, 1.05763087e+03, 4.74049800e+04,\n 8.75044807e+02, 2.44596491e+02, 5.76379080e+03])), ('precursor_mass', 510.21056725)])\nOrderedDict([('spectrum', [386.20280269320665, 542.293706331179, 599.3130423592679, 106.05000201353523, 53.5281673600337, 210.61417274838837]), ('abundance', array([22428.5984146 , 660.33700427, 27590.60543285, 7916.73394428,\n 3265.51766028, 755.155817 ])), ('precursor_mass', 352.68231075000006)])\nOrderedDict([('spectrum', [930.5201515769938, 1059.5611168566331, 1173.6046594302102, 65.0436145472829, 129.08288112051738, 202.6170396515829, 349.14055489209886, 761.381286002056, 110.54832298972323, 288.1605424565177, 438.22141042653624, 575.7984101997249]), ('abundance', array([26847.55178733, 602.0765046 , 1780.37910284, 259.61290733,\n 5197.32236393, 7846.15305753, 438.88717804, 1157.53035247,\n 814.02157322, 1691.83561621, 528.92909809, 160.15951334])), ('precursor_mass', 639.8274942500001)])\nOrderedDict([('spectrum', [129.1017212475677, 500.33111067504086, 884.567521934101, 286.1885449123433, 442.7872783909636, 233.14918918798656, 433.2652607501923, 1003.6246613054365, 117.0788947664552, 438.2699277112793, 502.3234799412792]), ('abundance', array([14700.06799369, 835.03641996, 4028.63949357, 795.42836261,\n 8462.13180349, 1610.84615569, 7715.92461934, 2451.99458422,\n 1436.00756959, 7540.428542 , 1312.01937098])), ('precursor_mass', 502.31656575)])\nOrderedDict([('spectrum', [306.14291660760523, 74.54757243032103, 221.07635256573278, 334.1610930305823, 249.11651191107455]), ('abundance', array([ 744.45612805, 205.74601465, 652.81941484, 3900.00201817,\n 545.7449064 ])), ('precursor_mass', 401.68451425)])\nOrderedDict([('spectrum', [132.04811225390117, 716.3289554155906, 66.52602173694494, 231.10669860174076, 281.628712921902, 274.13852262537625, 603.2971761560366, 137.56841315707837, 194.115252119077, 244.6386658221377, 367.67355930203746]), ('abundance', array([24317.52529023, 1181.49901995, 2161.236205 , 1937.7777408 ,\n 11425.14103116, 19699.58335703, 445.10378334, 655.09428952,\n 520.27863983, 389.45792685, 4916.23673527])), ('precursor_mass', 367.67309775000007)])\nOrderedDict([('spectrum', [356.21664242418916, 236.1274369703756, 877.4291044094731, 117.07825819149208, 167.60400948788606, 260.6483627796286]), ('abundance', array([ 817.85445712, 1973.3074663 , 51.54905373, 472.87374288,\n 3003.90632168, 5139.14462925])), ('precursor_mass', 495.76075825000004)])\nOrderedDict([('spectrum', [100.07426305885099, 50.540092816582955, 229.64059478663475, 295.1633247426514, 380.1652783968115, 607.3314893185986, 75.53317635806732, 254.63508080937888]), ('abundance', array([ 172.44380969, 2336.84108312, 2722.13342381, 82.17202644,\n 303.11877183, 9376.4041222 , 2226.41813546, 1654.65726454])), ('precursor_mass', 304.16893925)])\nOrderedDict([('spectrum', [258.14236784990396, 474.21849821187436, 731.3573258648437, 860.3978111425462, 1086.5664458475053, 65.52484152775047, 430.7033085388455, 132.10263747782957, 245.18791059419615, 631.3646162735229, 1104.5739522517815, 66.55595825145055, 187.62230469133044, 252.13925597539458, 424.2202026834611]), ('abundance', array([ 285.58921097, 3299.46449952, 16544.96891218, 12752.91293267,\n 8321.99726342, 823.35257484, 32408.70770388, 3713.59801911,\n 3255.17463329, 238.99804785, 994.79076969, 22893.08411375,\n 16389.44409675, 2315.43552283, 2206.02830078])), ('precursor_mass', 552.7927862500001)])\nOrderedDict([('spectrum', [271.15233449490546, 399.24564437548526, 715.3843395817428, 58.02905338391712, 136.08237407740782, 358.1970533430236, 733.3931523774992, 74.04393031689382]), ('abundance', array([1.59214879e+02, 9.72273156e+02, 3.40668567e+03, 1.75454680e+03,\n 1.18703432e+02, 6.80943469e+05, 1.92579283e+03, 7.75527967e+02])), ('precursor_mass', 367.20120175000005)])\nOrderedDict([('spectrum', [416.7175856629717]), ('abundance', array([1243.02871609])), ('precursor_mass', 416.7192277500001)])\nOrderedDict([('spectrum', [116.0300769591426, 230.081135482453, 377.14510550849405, 189.07359745888178, 253.1236138033872, 360.1897688160929, 253.12021080889548, 366.20253215113405, 595.3449670410674, 856.4567459059733]), ('abundance', array([24951.85201261, 2490.91770114, 6921.43488649, 47105.39732409,\n 3379.46721615, 17896.52000285, 1736.65525006, 1743.49151331,\n 491.18030758, 1025.51883076])), ('precursor_mass', 486.24527475)])\nOrderedDict([('spectrum', [88.03412501350911, 494.23432484495925, 817.3279874247279, 166.09133857724774, 247.62102697300935, 409.1677724273806, 437.674356084445, 189.12748523998712, 292.1322608726578, 675.2820796292546, 831.3814509925945, 1005.4466806892926, 175.0812148270609, 503.22751020064027]), ('abundance', array([11172.70405004, 2048.60080418, 545.00316678, 4093.56100472,\n 4500.4254638 , 1081.69654958, 1504.22595407, 862.44181648,\n 2529.0586807 , 10934.35121377, 7341.33033149, 2644.04804447,\n 4241.42264633, 1695.47153877])), ('precursor_mass', 503.22655075000006)])\nOrderedDict([('spectrum', [72.04626325586482, 171.1137814777671, 242.15152189859882, 513.3008556045534, 86.05983978094521, 121.57528049554936, 257.1556528711927, 335.2035077275312, 175.11995214476303, 446.26936814027994, 517.306642923222, 687.4143573461068, 144.6049071540825, 188.1214259532785, 259.1585552524887]), ('abundance', array([2.25747048e+04, 1.20967614e+03, 1.87933299e+02, 1.78951241e+03,\n 2.02961776e+03, 1.12401068e+03, 6.68399118e+02, 3.82659201e+04,\n 2.07204884e+03, 3.14621356e+03, 1.56413051e+04, 2.58910301e+03,\n 1.76259669e+04, 2.44175143e+02, 3.72623259e+01])), ('precursor_mass', 344.21103825)])\nOrderedDict([('spectrum', [138.06714614279932, 713.3163614797038, 183.5941467464788, 291.63908087843373, 118.08487332507461, 249.12692655678947, 362.21056963156576, 693.3302842480546, 830.3906286407969, 59.54550771559121, 233.11346676540316, 297.6348149026073, 415.70003479956335]), ('abundance', array([9.54883279e+04, 3.45319064e+02, 5.49370490e+02, 2.79765665e+02,\n 3.95631810e+02, 1.21194594e+03, 4.43678599e+03, 1.74663758e+03,\n 1.03013316e+04, 3.05489852e+02, 4.74964311e+03, 2.83454894e+02,\n 7.69014253e+05])), ('precursor_mass', 415.69859225)])\nOrderedDict([('spectrum', [157.10996515890128, 600.2850422523185, 243.13191652916328, 300.64838096179244, 329.15617326082764, 275.17007936137645, 546.2964411306524, 718.3448773666956, 138.08871583793808, 302.1636952945536, 359.67700645051724, 437.72736198772606]), ('abundance', array([9.44880610e+03, 5.96858977e+03, 1.17699419e+03, 9.01522384e+03,\n 8.97413618e+02, 3.91200517e+01, 2.37785620e+03, 6.50874818e+04,\n 8.44175430e+02, 5.07786819e+02, 5.98070784e+03, 1.39506845e+03])), ('precursor_mass', 437.72811525000003)])\nOrderedDict([('spectrum', [241.6400820803269, 872.4766546316214, 196.1096010637069]), ('abundance', array([4701.46642398, 212.19717017, 659.98251177])), ('precursor_mass', 436.74217975)])\nOrderedDict([('spectrum', [185.09029814764412, 658.3014162928274, 329.656980052791, 106.04817482983502, 492.22818103802325, 589.2831257148232, 53.52747011017782, 110.07656596139806]), ('abundance', array([10255.08849257, 353.58997074, 6476.59616967, 2019.75994801,\n 4968.33814989, 658.76737297, 210.38078298, 972.84503631])), ('precursor_mass', 338.66104325000003)])\nOrderedDict([('spectrum', [373.1714481579409, 486.2556699213323, 243.63092672257454, 292.15507535724413, 229.15525324979694, 486.29531751942227, 601.3191133013536, 115.07898544893027, 179.12942810525865]), ('abundance', array([ 1158.58948122, 3120.34517516, 903.71146345, 6261.2008978 ,\n 601.5806227 , 458.15645749, 6880.35908399, 3341.41974282,\n 12431.91750519])), ('precursor_mass', 301.16322225000005)])\nOrderedDict([('spectrum', [201.1251616964539, 587.3225918403983, 337.6798557128975, 106.04958587782235, 322.14306941488434, 492.25302153430215]), ('abundance', array([3533.63995898, 5240.59316957, 4823.07917809, 5350.41177814,\n 680.11529195, 2227.54336581])), ('precursor_mass', 346.68600775)])\nOrderedDict([('spectrum', [114.09182591423368, 622.378688396368, 934.5942507338506, 233.64610593579067, 132.09830438935214, 487.3344760408819, 574.3674978366677, 952.6046870159785, 356.21647870016284]), ('abundance', array([5.26319313e+02, 1.32081002e+04, 1.94908066e+02, 3.94419460e+03,\n 1.08612366e+03, 7.53430025e+05, 1.94404705e+02, 3.20464714e+03,\n 1.98486260e+03])), ('precursor_mass', 476.80616825)])\nOrderedDict([('spectrum', [378.1152424651495, 959.4133468887497, 1016.4308140040799, 66.52530486062186, 363.1554501195737, 552.23941786482, 300.12866482718556, 859.3947403281787, 1121.4776558739443, 82.03622148078934, 495.7209458430092]), ('abundance', array([ 3203.35688923, 9971.16680848, 1550.6631417 , 3765.03833784,\n 877.18874058, 14823.36375906, 5422.77408104, 2202.817752 ,\n 386.22838567, 421.25129887, 678.44912837])), ('precursor_mass', 561.2413522500001)])\nOrderedDict([('spectrum', [905.4005308487951, 992.4306489943542, 236.60974697075395, 134.04238579184516, 221.0762326342182, 768.3216892966716, 1125.4751010691532, 513.7036060764815]), ('abundance', array([4821.58357807, 1482.29660198, 2328.77142147, 19.23602777,\n 1260.11744084, 1853.5529439 , 326.49238869, 39.58368787])), ('precursor_mass', 563.24005975)])\nOrderedDict([('spectrum', [214.12383730718074, 165.08184160366858, 238.6153345446199, 343.6817051741101, 116.07020573706448, 229.1575358949956, 58.54050358451953, 188.61881671141686]), ('abundance', array([ 2168.40678369, 189.4511769 , 7219.33420183, 2354.24433785,\n 2623.72759601, 5445.10152501, 2538.12567312, 10163.56106615])), ('precursor_mass', 352.68993875000007)])\nOrderedDict([('spectrum', [304.1788787463881, 545.2845350424667, 658.3663114066687, 152.59588091478037, 201.11625295974747, 132.09889812445516, 189.12273840485338, 676.3781964713099]), ('abundance', array([ 259.93553887, 1670.78935665, 1823.18075686, 1711.899831 ,\n 946.7541409 , 867.6004714 , 807.78511258, 2986.43363095])), ('precursor_mass', 338.69248125)])\nOrderedDict([('spectrum', [217.07741695417246, 345.17874953763646, 804.40264579155, 1046.506024550808, 58.520575717376296, 402.7053722926684, 122.02499369838283, 910.386480440388, 1254.5583623481646, 105.03336304709113, 304.13041026019, 519.7459331231732, 627.7820621532294]), ('abundance', array([4.27444704e+01, 1.15262698e+03, 5.98488213e+03, 1.75981497e+04,\n 2.27096422e+03, 9.34103187e+05, 3.20508834e+04, 2.64584448e+03,\n 2.44901741e+03, 1.69041506e+02, 4.23699151e+04, 3.48524797e+03,\n 7.57167892e+02])), ('precursor_mass', 627.7819047500001)])\nOrderedDict([('spectrum', [355.23545908894476, 36.53407445827834, 128.5840922258213, 206.63225214991704, 427.2354104844734, 267.1293966219967, 618.2918681273419, 134.07222630850396, 486.76099917830294]), ('abundance', array([ 4746.32361608, 1313.38018377, 2340.78327454, 203.47562482,\n 1790.40964363, 15718.91661371, 299.12751317, 2184.53132528,\n 4299.11142692])), ('precursor_mass', 486.76310424999997)])\nOrderedDict([('spectrum', [308.17216941163196, 535.2986865896962, 733.4355257448204, 1101.6697834811814, 268.1535691183815, 317.6866478241377, 501.80230776928306, 486.3272822387435, 911.5928502508484, 293.2027057939251, 456.29574908016224, 560.344320495474]), ('abundance', array([3.72516767e+03, 2.12838485e+00, 1.80384719e+05, 1.29138831e+05,\n 1.17065805e+02, 2.74718131e+04, 2.39838330e+03, 1.30999613e+05,\n 1.53507252e+03, 5.42513610e+03, 2.62140085e+04, 1.42091936e+03])), ('precursor_mass', 560.34786675)])\nOrderedDict([('spectrum', [104.01860975797369, 615.3370434701004, 52.51203995796761, 88.02755759701373, 166.07224120428174, 372.20138349165626, 464.2448835645749, 203.1001510837185, 487.262142628303, 945.4939054428792, 58.53854107805505, 244.1333534726529]), ('abundance', array([6.46022891e+03, 9.09440848e+03, 5.24377322e+03, 1.15627768e+03,\n 5.59547723e+00, 3.29249414e+03, 1.54725934e+02, 1.52566813e+04,\n 5.33284138e+03, 1.34457361e+03, 2.78790906e+02, 2.98110270e+03])), ('precursor_mass', 473.25036925000006)])\nOrderedDict([('spectrum', [145.0630164371365, 442.2280629465026, 739.4333481355828, 44.53053372861535, 221.62044522007963, 203.1423295473176, 484.3110978863848, 741.4551988980156, 828.4859612003041, 137.5902519327614, 371.2290126193504, 414.7442439015535]), ('abundance', array([ 3116.09468833, 6765.23111374, 136.66654521, 85.55110814,\n 3614.82617456, 5044.31897399, 2411.77067428, 31149.19712037,\n 3484.09836533, 4978.54275965, 9303.14075348, 6675.91997537])), ('precursor_mass', 414.74491075000003)])\nOrderedDict([('spectrum', [115.58790439326216, 165.10902053337873, 132.10134789426888, 598.3675084703893]), ('abundance', array([ 478.76564663, 10677.55156882, 73710.3368457 , 7305.37128872])), ('precursor_mass', 414.25851975000006)])\nOrderedDict([('spectrum', [242.14089672866018, 223.10895162138854, 427.19612753741484, 112.05665889389273, 334.67895077193646]), ('abundance', array([ 830.17785746, 10624.06300857, 3029.47795299, 137.61438235,\n 3065.93041853])), ('precursor_mass', 334.67375775)])\nOrderedDict([('spectrum', [585.3014055064447, 924.4768613446839, 732.3346515287686, 1045.4982331657109, 110.03733057312871]), ('abundance', array([ 228.11839568, 415.83476967, 110.9942212 , 754.67348604,\n 50842.23617222])), ('precursor_mass', 523.25277425)])\nOrderedDict([('spectrum', [490.265651478368, 646.3653591437637, 774.461437415537, 1114.674397748106, 50.54205055862966, 245.63706633907216, 493.8123782969841, 557.8421500154402, 345.2177015183069, 458.2958290066367, 586.3930821572495, 856.5389303073495, 969.6208171115969, 123.58083210932728, 428.7709093871229, 616.3750716699252]), ('abundance', array([1.27820228e+03, 2.34746895e+02, 6.00855377e+02, 1.58478847e+03,\n 1.50724522e+02, 1.05044744e+03, 9.40168361e+02, 1.54025779e+05,\n 5.35309749e+01, 2.69707408e+02, 2.82177876e+02, 2.94167763e+02,\n 1.17918248e+04, 1.60650410e+03, 3.07231076e+02, 3.71604294e+02])), ('precursor_mass', 616.3796932500002)])\nOrderedDict([('spectrum', [679.3545646495518, 118.06251295208024, 235.11324224887406, 291.6549524029167, 463.25529360032635, 697.3647449257553, 58.5380214002644, 300.66158382568705, 349.1866140394695]), ('abundance', array([ 29.53088464, 7267.14687505, 845.1472016 , 15103.78502253,\n 2860.64588976, 256.70368991, 27579.07217337, 632.67077552,\n 3360.38690283])), ('precursor_mass', 349.18703175)])\nOrderedDict([('spectrum', [316.1239375357561, 531.2127476617813, 731.3352230385419, 917.3954755188295, 988.4328192652159, 58.02793733891221, 309.6278527218434, 494.7194579827097, 90.0509376570237, 205.08282910963547, 805.3725923856946, 1006.4462267601297, 103.04521110926696, 503.72533093124804]), ('abundance', array([ 6364.18636085, 4718.81829102, 2930.8799858 , 483.66539578,\n 523.57884754, 851.08772999, 1754.58275537, 10440.03397191,\n 381.79120027, 821.82658053, 834.1294898 , 1085.47184273,\n 8983.12221915, 2408.67286938])), ('precursor_mass', 503.72543425)])\nOrderedDict([('spectrum', [203.0858942625037, 441.1913181793243, 597.2944479066373, 221.1000754679749, 355.6945275084316, 391.2108077151931, 205.07835222417435, 318.16499058115704, 611.3254601926335, 811.4415673239663, 406.22299384427316]), ('abundance', array([4.38355971e+02, 2.11247185e+02, 1.87829975e+04, 7.05917984e+02,\n 2.48516260e+02, 9.37897233e+02, 1.05017551e+01, 8.01951831e+02,\n 9.24838602e+03, 2.87787588e+02, 1.28804677e+04])), ('precursor_mass', 457.72926974999996)])\nOrderedDict([('spectrum', [413.2451007223994, 500.28361011643733, 114.58379523619061, 178.61656370711447, 211.60584772409274]), ('abundance', array([ 6292.20208705, 3649.22053628, 995.15797839, 1188.81662021,\n 16242.70996538])), ('precursor_mass', 389.21800625000003)])\nOrderedDict([('spectrum', [372.2332564399773, 868.5493301351943, 143.1059958835337, 300.18438856407596, 132.09887600981352, 416.26946416742265, 515.3281857491046, 602.3641585120608, 886.5586211073473, 208.63610186862755]), ('abundance', array([ 15.01221521, 1839.22515987, 1247.58377394, 2436.25133778,\n 2728.09758345, 8034.00443854, 697.08894963, 3605.07103475,\n 4060.13743118, 4616.23286924])), ('precursor_mass', 443.78269325)])\nOrderedDict([('spectrum', [100.07586450818225, 237.1333872333707, 478.3170028151212, 749.4325443358539, 862.5135562212639, 1030.6042090365358, 50.53899425458488, 175.61206467818488, 480.28738442507404, 515.8061152971205, 387.22112897435073, 699.4059236754633, 286.15724636324467, 350.20315303891346, 406.74600397787066]), ('abundance', array([15736.31912252, 807.07498206, 919.12851087, 2711.99189709,\n 3994.55341142, 385.96816055, 1202.12813598, 1106.74087761,\n 9190.12474128, 10495.74501074, 3715.30598747, 14135.29651275,\n 5760.03964382, 544.33299348, 31.99235753])), ('precursor_mass', 524.81111625)])\nOrderedDict([('spectrum', [164.06868587341424, 842.3676625214982, 82.53904227172623, 340.15658497132483, 421.69513510502276, 697.3161551199588, 298.6398167928335, 349.1572170948475]), ('abundance', array([ 46.1554673 , 285.2764254 , 30986.09329941, 3407.05756982,\n 4705.49861752, 1163.56131517, 748.00700122, 1342.50330391])), ('precursor_mass', 430.69286675000006)])\nOrderedDict([('spectrum', [286.14176075318767, 442.2350052194809, 543.2908636131497, 646.2975110232842, 223.07743051580283, 664.3108675717665, 332.65844563228194]), ('abundance', array([ 299.74950646, 4818.16183875, 3245.36111788, 412.11089605,\n 3445.29420837, 274.48768363, 2131.01716069])), ('precursor_mass', 332.65778175)])\nOrderedDict([('spectrum', [545.2545805903858, 1018.495834611993, 221.62658255804095, 321.65837396361735, 239.10245051236313, 395.202314274951, 120.05407733206462, 518.7538270321096]), ('abundance', array([ 2384.9462096 , 5606.76316254, 165.25909174, 1809.06244466,\n 7900.79887247, 49355.41112676, 721.61279637, 2177.11931573])), ('precursor_mass', 518.7569687499999)])\nOrderedDict([('spectrum', [244.13992984696898, 448.1995956962196, 604.2991704180645, 174.0782315030063, 224.6012563299764, 302.6545332952724, 175.11939679329495, 379.17430259651684, 622.308926291241, 88.0611979206302, 190.09239993177943, 233.61217819675144]), ('abundance', array([1.41247834e+03, 1.90846660e+03, 2.17005076e+04, 1.68990062e+02,\n 3.27834689e+02, 5.65747253e+02, 1.01975306e+03, 4.32155716e+03,\n 4.58331627e+03, 1.87379509e+01, 6.99717541e+03, 1.31277750e+03])), ('precursor_mass', 311.65811575000004)])\nOrderedDict([('spectrum', [676.3166926359754, 66.52829881269531, 166.5870701252954, 223.12825166117352, 338.6621160974722, 557.7738841289281, 560.2568051887915, 902.4471881903776, 229.12513724336722, 344.66302299744905, 401.20294458741074, 451.7257476013031, 501.25334504693006]), ('abundance', array([ 692.37213301, 5809.36032936, 763.27717772, 11195.86316419,\n 18088.40331891, 4600.24661135, 369.29692915, 2613.64234998,\n 352.65536345, 1052.61841081, 3045.91595352, 467.07638422,\n 657.08125711])), ('precursor_mass', 566.7801097500001)])\nOrderedDict([('spectrum', [464.19692209539056, 1442.6600256154477, 110.05762736563906, 612.8064357647679, 721.8298679606005, 237.08880834181468, 423.1670859735091, 570.2434709936622, 1313.6050202646652, 53.528407072696425, 119.05018052163722]), ('abundance', array([4.50570023e+04, 1.00640467e+03, 6.62171586e+02, 7.38706975e+02,\n 1.06134809e+04, 7.08148386e+02, 3.33317221e+02, 1.70612459e+02,\n 3.39099875e+03, 2.52857197e+01, 6.65796015e+02])), ('precursor_mass', 730.83869075)])\nOrderedDict([('spectrum', [86.05978147389088, 129.57520360407364, 106.05135138206187, 462.2541563912075, 159.60784390115268, 231.63122299822507]), ('abundance', array([1804.76745481, 4294.3344738 , 7858.48031708, 2795.8385291 ,\n 1084.23594526, 1957.12074996])), ('precursor_mass', 288.17358975)])\nOrderedDict([('spectrum', [352.1453821562072, 608.3038387404023, 240.61024100008092, 304.6555717814397, 218.15022969802877, 298.6559277404687]), ('abundance', array([ 409.85590409, 806.68555881, 1267.79072635, 2766.04212245,\n 1348.91667311, 1257.14981807])), ('precursor_mass', 349.17939975)])\nOrderedDict([('spectrum', [157.10599378427074, 311.1828803409086, 637.3871705027043, 887.4860193149082, 234.14166629244562, 229.15269796912654, 536.2729702161146, 480.27094003028463]), ('abundance', array([23223.0826313 , 1136.65710361, 5114.79749119, 448.11223922,\n 29268.83761032, 7452.62960826, 605.89046122, 7392.09489383])), ('precursor_mass', 558.31963575)])\nOrderedDict([('spectrum', [203.0702183349994, 58.52007704617515, 223.1007762439648, 375.1918987198689, 74.0434165019349]), ('abundance', array([53876.77534014, 2623.3539161 , 401.61649909, 10869.89900633,\n 612.66501868])), ('precursor_mass', 353.64813325)])\nOrderedDict([('spectrum', [132.046182196668, 439.21279633423285, 568.2532285775187, 786.3598506580681, 873.3901693682756, 184.59121280869505, 106.04898596470738, 253.11725506992684, 453.201457242742, 661.2948656979067, 891.4042078855749, 262.62160880611737, 331.15002116090403, 380.68535742210037, 446.20644060951446]), ('abundance', array([ 531.05500132, 166.28993995, 1773.85609658, 9799.38197574,\n 53716.70436763, 3316.27009782, 55767.80905198, 6201.85579737,\n 1269.63151781, 1538.49321555, 2934.03862981, 102.90466548,\n 2459.38961253, 233.82342302, 640.17038151])), ('precursor_mass', 446.20509574999994)])\nOrderedDict([('spectrum', [72.04452516754274, 483.20213558917885, 36.52481237914335, 242.1090989262719, 291.63842977745094, 433.71574631181244, 175.12095518245096, 303.1804470827226, 505.25421567781723, 716.3516482404499, 813.4047465776327, 152.09006976907162, 310.151484570484, 358.684252130217, 407.2042343880217, 442.7312177038938]), ('abundance', array([9.01848261e+03, 2.83829952e+03, 3.07467036e+03, 1.92871258e+02,\n 6.45137969e+04, 1.16129069e+02, 3.99632551e+03, 2.03761131e+05,\n 3.22700459e+03, 7.00704950e+02, 3.00567002e+03, 1.01602262e+02,\n 9.98237170e+02, 1.10972332e+03, 7.36473161e+02, 2.12812355e+04])), ('precursor_mass', 442.72398725000005)])\nOrderedDict([('spectrum', [488.2596727195308, 662.3212764880307, 981.4777852514885, 44.525369542156795, 360.1778558870149, 409.70751856039897, 540.7778814141302, 205.11966386613986, 467.24753398815864, 611.3015307037776, 1098.5578950086008, 53.5234238404556, 103.05991592273851]), ('abundance', array([ 2367.55495746, 26.62130226, 1409.38923793, 5431.29923022,\n 913.38462126, 152.25234114, 370.43128903, 12562.60045014,\n 831.41218061, 10616.40954127, 3972.61612289, 299.75853386,\n 329.91578742])), ('precursor_mass', 593.29856525)])\nOrderedDict([('spectrum', [399.22487875953357, 58.51722521534051, 147.10640661542791, 273.1653351187033]), ('abundance', array([ 527.99780254, 23743.6607807 , 5351.78266296, 384.01334801])), ('precursor_mass', 273.16830775000005)])\nOrderedDict([('spectrum', [356.22785045996864, 854.5300978887407, 1012.5938210698787, 58.027864364673974, 235.1636698826679, 363.71530546728275, 427.76578188346656, 506.7939859173343, 556.3342013423984, 118.08472874191179, 219.13091392424673, 902.5485838126342, 1129.6732336344926, 202.62686264433532, 508.3182507918492]), ('abundance', array([ 721.60766204, 5893.9754463 , 169.82633856, 7475.52910676,\n 846.31380778, 5477.27036499, 117.13490423, 276.96414442,\n 2645.38024052, 978.44828605, 1019.56391602, 19142.42521026,\n 660.64397157, 70437.55506782, 850.67912903])), ('precursor_mass', 565.34004125)])\nOrderedDict([('spectrum', [645.3951964512411, 760.4241709953504, 36.528033206692264, 110.06222744612725, 323.1994731475855, 437.2539368418264, 889.5071302543553, 118.05903846075971, 174.60138015035017]), ('abundance', array([ 505.31362332, 1316.87409436, 1061.63670914, 5034.84645432,\n 18.82547811, 2538.67714455, 1298.54494714, 658.62100812,\n 13277.64343714])), ('precursor_mass', 554.30956075)])\nOrderedDict([('spectrum', [729.4425724970378, 828.5087139882299, 915.53816760336, 164.11125301494556, 458.27300183017377, 106.04187132368506, 494.26161254591926, 607.3470942160496, 720.4282800764136, 103.06340100664572, 304.17722958069834, 360.71829904237455, 438.7654589912359, 467.2806500703078]), ('abundance', array([93714.94891841, 576.84463651, 10075.84643289, 333.69350892,\n 4488.7334137 , 20063.87784361, 1199.29773144, 1104.53489316,\n 3196.16434883, 1266.89632787, 2046.97021743, 19585.09693327,\n 2948.21309191, 548.74950294])), ('precursor_mass', 467.27945224999996)])\nOrderedDict([('spectrum', [718.3440172242441, 849.3841597540755, 172.59287619624547, 236.6373388593732, 294.15448484591144, 425.19603110880604, 281.0996197703801, 396.12591446142557, 524.2262136181042, 738.3527969759722, 141.0541358657761, 262.61389888533705]), ('abundance', array([19587.21526899, 348.5279833 , 1001.11705985, 2011.70418083,\n 149.50605173, 281.29634236, 1006.01743131, 942.19569523,\n 126.5089502 , 3752.72952556, 6373.28547954, 136.10119356])), ('precursor_mass', 434.20116475000003)])\nOrderedDict([('spectrum', [500.2315133355111, 147.0773699200302, 248.1226445860455, 349.1687563203371, 74.04108412206506, 124.56538828561067, 267.12801632698046, 323.67365451304653]), ('abundance', array([ 528.56427663, 2809.87196495, 3255.65508431, 408.57527335,\n 3070.75073003, 3102.98220637, 101746.34244273, 703.21570522])), ('precursor_mass', 424.70344025)])\nOrderedDict([('spectrum', [173.09218918498502, 51.5315836509974, 172.10401574207634, 471.183989090258, 813.3731146806101, 285.62938766402794]), ('abundance', array([1.32699240e+03, 4.14582417e+03, 1.72608343e+01, 1.09650825e+05,\n 3.87200225e+03, 7.09445632e+04])), ('precursor_mass', 407.19050025)])\nOrderedDict([('spectrum', [186.08713395446364, 301.1160820561658, 93.55004040376141, 151.06136619922268, 179.56967974223008, 253.10541178027972, 309.64860618848013, 132.10178340749744, 279.1688255858968, 636.299578978359, 66.55412773164537]), ('abundance', array([ 2313.46121404, 2606.16230081, 475.25418173, 3618.48991411,\n 737.44934164, 1124.65036361, 1767.28129839, 1369.51918662,\n 1425.75136956, 180133.28875565, 5165.04597337])), ('precursor_mass', 318.65302175)])\nOrderedDict([('spectrum', [215.14028704498222, 459.2631554192991, 833.4565732050384, 108.07428427716793, 164.61401123887876, 230.13653377113326, 287.1576960575059, 417.2324585832211, 465.27099890280357, 970.5057849560523, 1083.5902097138014, 151.6073550620892, 420.2380007887319, 542.296548722574]), ('abundance', array([2.05429820e+02, 3.09455296e+03, 5.71768926e+03, 5.42901458e+04,\n 4.62902328e+02, 2.37463617e+03, 6.56764303e+02, 1.08189771e+05,\n 5.04787299e+02, 2.63410786e+02, 1.23352975e+04, 5.16039911e+01,\n 1.07691679e+03, 5.96006357e+04])), ('precursor_mass', 649.3648632499999)])\nOrderedDict([('spectrum', [98.06208600445908, 254.16828395738185, 290.6646392617678, 602.3126846040249]), ('abundance', array([3847.26093029, 2348.88223335, 656.35465013, 2007.15888007])), ('precursor_mass', 463.75634174999993)])\nOrderedDict([('spectrum', [649.3201214741882, 746.3729739693424, 902.4720797453164, 276.6373045224346, 325.1651203668472, 451.73721947192803, 563.3346866517238, 136.5917825730532, 282.1671104140516, 331.70550309005864]), ('abundance', array([2.20231608e+04, 9.76844296e+02, 9.20173145e+02, 4.27482941e+03,\n 2.21358009e+04, 2.07081608e+01, 7.60707197e+02, 1.69391832e+03,\n 4.44999839e+03, 6.09253163e+03])), ('precursor_mass', 460.7454422500001)])\nOrderedDict([('spectrum', [218.14923150647698]), ('abundance', array([262.38236863])), ('precursor_mass', 344.21103825)])\nOrderedDict([('spectrum', [314.20414741331786, 385.2457208381504, 499.2867134067265, 101.0661397393782, 193.12431252640042, 318.67406611414447, 287.11371074511413, 472.2006036191867, 686.3300518178282, 201.08603737134584]), ('abundance', array([ 116.48359433, 2135.70110297, 47928.89858547, 16506.18985516,\n 74.65246864, 891.12615471, 8527.44802279, 1697.61324988,\n 5094.89541942, 4603.38394491])), ('precursor_mass', 393.20235625)])\nOrderedDict([('spectrum', [277.1183668397578, 580.2410283724732, 679.3131876611342, 65.52747331574247, 290.6267968846821, 118.08478012775983, 421.21020526172435, 568.2817868755511, 697.3226435103005, 59.54978467517702, 145.5863001770097, 211.10945627831265]), ('abundance', array([11523.24271948, 2035.78838141, 7128.07534238, 484.37492835,\n 8004.50675639, 707.54402037, 9535.54650339, 491.86252098,\n 601.98877681, 39199.96488628, 2475.43215385, 2082.07186594])), ('precursor_mass', 349.16490825)])\nOrderedDict([('spectrum', [683.3207525468565, 853.4271559607872, 981.5249132678035, 1210.5958184175877, 433.20400200906374, 490.2249677895493, 1186.5581402524508, 245.61490462970133]), ('abundance', array([ 3523.34846686, 3911.79143818, 858.76107249, 519.69201248,\n 7580.91077749, 12415.91625018, 8224.8980728 , 2161.00658077])), ('precursor_mass', 643.3171567500001)])\nOrderedDict([('spectrum', [1248.6582738602674, 208.1047021926739, 526.773378925357, 730.8652333823886, 233.11219012682673, 740.3811804955375, 1037.513952310864, 1278.6585077342882, 1692.8450565940645, 67.52049880767106, 370.6909396432977]), ('abundance', array([3.89122119e+04, 5.82612942e+03, 6.04685992e+03, 1.72333615e+03,\n 3.84525670e+03, 4.37804708e+00, 1.20730413e+03, 3.77086025e+03,\n 6.61730344e+03, 5.19936966e+03, 2.59679582e+03])), ('precursor_mass', 846.9255917500002)])\nOrderedDict([('spectrum', [104.01139750832044, 175.0547489752996, 430.2228833379216, 593.2868274657752, 664.3228946358672, 793.3577206875051, 52.51288795510044, 215.61445450585484, 297.14411640113485, 332.6659785541603, 708.3671909305637, 74.5349008752739, 241.11817990551262, 319.1691531743925]), ('abundance', array([1.19611746e+03, 5.03199658e+00, 3.17729355e+03, 5.56332454e+04,\n 6.83066586e+03, 2.53281128e+03, 6.34924549e+03, 6.34435922e+02,\n 1.76540076e+03, 1.34629766e+03, 2.98229389e+02, 7.93132169e+02,\n 7.45496401e+03, 3.34079353e+03])), ('precursor_mass', 406.19198425)])\nOrderedDict([('spectrum', [115.05063661572788, 545.276380110559, 703.3479651073984, 114.56511177010908, 352.1777975566798, 406.22798939056145, 622.3252398860233, 260.16145508961773, 368.20605124717866]), ('abundance', array([11100.30177079, 1441.13055322, 2422.74240795, 1946.9111969 ,\n 1166.63309765, 1944.30939506, 1244.13256972, 28112.87997152,\n 1711.60581478])), ('precursor_mass', 425.2285712500001)])\nOrderedDict([('spectrum', [129.0655487881485, 357.17635314308126, 628.3301911890837, 715.3603946405677, 929.4915047950864, 121.58254445444624, 179.09599636183103, 207.60219730124837, 314.6680078994429, 358.1802845145996, 423.1886041274717, 536.2658533000523, 938.4865256722954, 995.5052878589306, 1110.5335113500528, 1223.6168041577737, 319.16081645780815, 362.6792314432936, 419.2193811683077, 469.7501423936134, 676.336276626636]), ('abundance', array([1.83143717e+03, 1.56574621e+02, 1.03909199e+04, 1.34072066e+03,\n 7.38342927e+02, 7.19787588e+03, 4.12047216e+03, 1.01081991e+04,\n 5.54093297e+02, 3.70699028e+03, 1.72852666e+01, 9.99750466e+04,\n 1.03154342e+04, 1.46782672e+03, 2.93515049e+02, 4.16446567e+02,\n 3.17237283e+03, 6.28875209e+04, 1.08306447e+03, 4.08079651e+04,\n 2.79584111e+04])), ('precursor_mass', 676.34063275)])\nOrderedDict([('spectrum', [649.2578704385294, 1077.4881136906452, 108.55515311775761, 325.1373313955792, 562.2713534525161, 880.4066161400982, 66.55383029229613]), ('abundance', array([ 332.86754551, 1274.9279165 , 16071.82972803, 3553.13442323,\n 1000.24591156, 3532.83110898, 22409.78709117])), ('precursor_mass', 548.2529707499999)])\nOrderedDict([('spectrum', [513.2777796722786, 798.4188987332158, 927.4666916024764, 1056.505294807851, 335.1867666831854, 464.22987067309276, 148.06159328399224, 277.10260893327, 406.14480982845555, 918.416135708232, 139.05595644732242, 402.1958431205643]), ('abundance', array([36513.14786875, 390.59238434, 581.64492594, 1291.23647528,\n 134.10478879, 1052.23129798, 598.40822682, 1387.7351118 ,\n 7687.51815596, 6559.71410365, 95.4491521 , 1398.21504277])), ('precursor_mass', 537.76235175)])\nOrderedDict([('spectrum', [424.223110439338, 537.3059053229972, 1142.5929484195133, 334.6791488425548, 997.5453701795822, 1160.6085104550789, 425.7391578440628, 580.8075738126064]), ('abundance', array([5013.47163335, 214.46086954, 474.89161718, 1120.32763174,\n 949.01766594, 4976.06276487, 783.67975454, 1693.3973062 ])), ('precursor_mass', 580.80664975)])\nOrderedDict([('spectrum', [102.05397721818457, 432.19127996094426, 838.3868754055399, 1081.5180231789536, 101.06569002868096, 165.0937374098121, 294.6504196617749, 376.18093325660067, 463.2171805835547, 541.2578531821761, 131.57627293380804, 175.09581919214926, 550.2687127344482]), ('abundance', array([ 2671.92133919, 4220.5348273 , 4608.47306589, 29746.58792216,\n 21918.31516072, 258.62424052, 3599.12583748, 97.13561706,\n 920.18182986, 9357.74420476, 5067.387595 , 1616.55814432,\n 1722.92679606])), ('precursor_mass', 550.26928575)])\nOrderedDict([('spectrum', [260.1044777789447, 664.3256958480358, 848.4170362892507, 29.519642998729296, 130.55666950648657, 381.19124369584006, 260.12361180186195, 397.18607903768066, 510.2666896154587, 607.3233539260134, 255.63544129620107, 405.20570216840093, 433.7123510985299]), ('abundance', array([ 4387.39302537, 16592.4620942 , 510.84415622, 1951.11882338,\n 2919.85625611, 4129.02599948, 314.1115745 , 1319.39778712,\n 2411.71178106, 1966.98053738, 156.43052387, 2265.03066554,\n 2012.41205084])), ('precursor_mass', 433.71308825000006)])\nOrderedDict([('spectrum', [982.4701221980131, 195.11036501243774, 251.65936095650056, 557.2594855808467, 181.57346642565298, 420.68464078239316]), ('abundance', array([12249.50547898, 585.09032859, 2134.03049357, 312.05353596,\n 20723.3623272 , 11864.30110074])), ('precursor_mass', 614.79067825)])\nOrderedDict([('spectrum', [259.09239354511476, 301.16351473433343, 401.2012484667717, 90.05220322898516, 320.1386893033163, 690.3606200787289, 45.53004193690172, 281.1693180380125, 410.21246176589796]), ('abundance', array([1.21934624e+03, 9.14064572e+03, 1.23293271e+02, 7.87810676e+02,\n 7.60192407e+02, 1.27811235e+03, 5.87776558e+04, 4.44981036e+02,\n 4.22840827e+06])), ('precursor_mass', 410.20835825000006)])\nOrderedDict([('spectrum', [774.3642936717741, 144.57066834975066, 402.2447438625003, 253.12805615839855, 303.6499706575564]), ('abundance', array([ 45448.40217964, 9106.16937848, 127194.44176158, 6221.14747207,\n 4298.83391361])), ('precursor_mass', 396.69469875000004)])\nOrderedDict([('spectrum', [391.1430644234736, 875.4165526842775, 94.0466437173735, 144.5691474815804, 196.07568908105966, 274.1244337925436, 323.66066235815634, 438.21204817740005, 248.12521220379588, 503.29133529432414, 606.3021595758809, 60.534697963167304, 124.56701766396051, 303.6581982277005, 354.17667980128624]), ('abundance', array([29806.95657549, 786.77356424, 3623.33134169, 520.27405394,\n 583.59914842, 4457.47954461, 38717.44731634, 14159.34336323,\n 1147.10752293, 138.2606671 , 377.59949658, 2885.84679981,\n 2101.28478692, 528.09118975, 1861.61262199])), ('precursor_mass', 447.21853825000005)])\nOrderedDict([('spectrum', [547.2452100043728, 875.4146203369621, 196.07805043657615, 323.65883725363534, 481.7320700936497, 794.3830404885814, 980.4620013477718]), ('abundance', array([1457.17436102, 258.67510726, 2500.98275479, 6605.64648997,\n 1531.49346012, 128.81343553, 1007.15694281])), ('precursor_mass', 490.73455225000004)])\nOrderedDict([('spectrum', [274.12680182665235, 481.729307833562, 235.10057131360227, 336.14342684037626, 719.3661203971768]), ('abundance', array([ 701.9500007 , 10793.59505414, 73.00487559, 173.49922925,\n 5350.34358623])), ('precursor_mass', 555.25584875)])\nOrderedDict([('spectrum', [288.13046701319394, 962.4498576821541, 387.6917559283712, 277.1016466715803, 182.57040830657164, 297.1224243458346]), ('abundance', array([ 4943.67686661, 485.24957885, 937.10512614, 10399.23332497,\n 3227.39923465, 819.67128196])), ('precursor_mass', 619.77714525)])\nOrderedDict([('spectrum', [187.085268749382, 547.2456055317581, 646.3115371266725, 387.68930243716625, 481.73069623039356, 546.2507037939288, 639.2799784802407, 522.2045150461759, 650.2632494567308, 749.3309279615939, 1109.4865912349637, 1295.5681669900237, 167.56701089915282, 375.17030177715867, 555.2474711037328]), ('abundance', array([ 2720.20645167, 994.40407843, 2159.24478081, 49284.49441168,\n 4558.28397016, 2961.10170822, 21969.10522395, 6710.14308449,\n 554.67144454, 997.72363145, 1294.48480028, 925.74904994,\n 2379.88336454, 4275.13502646, 896.93907715])), ('precursor_mass', 648.28787725)])\nOrderedDict([('spectrum', [391.14637542549053, 547.2454826275159, 481.72931078122195, 207.0809296931737, 465.1653773061123, 1426.6185340961297, 570.2430935809167, 620.7672560577587]), ('abundance', array([1.35310758e+02, 1.32921392e+06, 3.25143391e+03, 6.17487509e+03,\n 3.82590177e+03, 1.30694409e+04, 6.84937636e+02, 2.05577311e+03])), ('precursor_mass', 713.80811975)])\nOrderedDict([('spectrum', [315.18220037330485, 416.2289461324472, 675.3357635641588, 505.25499771527967, 792.3833802138744, 920.4818034461119, 123.57068755487838, 303.6573194953781]), ('abundance', array([ 9019.12656138, 792.66040158, 20127.9187283 , 301.24136032,\n 300.63252967, 2378.05101512, 2269.49343122, 513.13368652])), ('precursor_mass', 460.74218025000005)])\nOrderedDict([('spectrum', [519.239641634291, 1003.5130523500209, 65.05416117746147, 451.7413360470084, 502.26188617828836, 606.3026492714638, 174.1039735638927, 252.15313313628488, 354.1805061237959, 447.22188667761077]), ('abundance', array([13355.10633647, 3012.41639293, 55.40342022, 220.53501313,\n 21201.8562857 , 1099.04683019, 4004.76367794, 1049.09714891,\n 491.99738874, 539.13932274])), ('precursor_mass', 511.26601975000005)])\nOrderedDict([('spectrum', [129.10383943880865, 416.2282545427197, 519.2478719709906, 902.467261391937, 1090.5447717889465, 65.05517452454103, 338.1736914098723, 451.7392123920511, 106.0485442995263, 207.09565779823885, 335.1579256393803, 980.4608437104398, 168.09191542810663, 217.61280558057743, 490.7378973504104]), ('abundance', array([2.38020348e+02, 3.75708604e+02, 2.05706759e+06, 5.93741072e+02,\n 1.37035253e+02, 5.63493829e+03, 1.84490857e+04, 2.92035557e+01,\n 4.55688612e+04, 2.20079759e+03, 1.44750567e+07, 2.55617004e+02,\n 1.58037602e+03, 1.53725102e+04, 8.29326909e+02])), ('precursor_mass', 554.7820337500001)])\nOrderedDict([('spectrum', [519.2381401824679, 1090.5460466614616, 208.60963359840304, 260.1203873630469, 338.16604631759714, 451.7340042384643, 336.13904142378044, 563.264548377197, 822.3763277575144, 923.4249041808781, 1109.5021485940922, 74.53258524697488, 232.60217398406022, 411.6924884725569, 619.3032392191285]), ('abundance', array([ 160.3971756 , 966.99380874, 836.56218662, 10252.68265971,\n 2550.12470528, 2244.68272869, 13245.41609218, 119.96576615,\n 482.19662023, 7647.85089142, 3789.22245047, 28812.75524197,\n 521.32726505, 157.87189878, 69001.24214401])), ('precursor_mass', 619.3033302500002)])\nOrderedDict([('spectrum', [416.22910857784814, 1003.5130751552194, 1219.589446431876, 260.1246849976063, 387.70787126019644, 451.7364707968415, 610.2961734346642, 148.05581768778254, 277.1029677215164, 593.2415399988864, 848.4076762522108, 1238.5456040790784, 74.53353992135027, 139.05465236385922, 619.7751833446023]), ('abundance', array([1.18953153e+06, 5.45921979e+03, 9.99395696e+02, 1.24428422e+04,\n 1.92683667e+03, 1.49291583e+03, 1.11449700e+02, 2.25955116e+02,\n 3.52147039e+02, 1.04433921e+04, 3.36410172e+02, 2.15130738e+03,\n 1.16367583e+02, 1.95283795e+03, 1.70311236e+04])), ('precursor_mass', 683.8246267500002)])\nOrderedDict([('spectrum', [129.10232936374044, 315.1853754493984, 416.2279073726162, 519.2400289937661, 675.339996592082, 902.4691523564492, 1003.5110265911921, 1405.6516668678466, 338.1744993551507, 421.1567728145904, 1109.490652765439, 38.52065667125014, 261.6112240891286, 375.16948900526097, 648.2872959147379]), ('abundance', array([10406.1908817 , 397.3551159 , 1121.75284414, 32567.40496385,\n 1869.82011207, 101.74153557, 534.06172953, 35780.81410308,\n 1766.98346793, 1270.73084656, 1582.53071196, 46.63186586,\n 14426.27158271, 4234.44758967, 362.93222573])), ('precursor_mass', 712.3353587500002)])\nOrderedDict([('spectrum', [519.2415332287491, 675.3384957930951, 1090.5437145758033, 1219.5877017712514, 158.09458085547075, 338.17560697246427, 703.3234738255132, 207.07952097727141, 465.1644682953141, 781.3056516008506, 1036.4735103675869, 168.56484684144368, 233.08231664575305, 327.12690889682807, 391.15323375011263, 440.6903966836543, 620.7613169124002, 713.8111955752408, 777.8556965300029]), ('abundance', array([8.23843195e+01, 4.94749489e+03, 1.64297218e+03, 1.73642799e+03,\n 3.34062162e+03, 2.70328506e+03, 7.68651556e+02, 1.70448788e+03,\n 4.52262735e+02, 1.17491450e+05, 1.35455108e+04, 7.15454587e+02,\n 1.51020945e+02, 5.18004623e+03, 9.48839212e+02, 2.37959065e+04,\n 1.64983181e+03, 5.88513314e+03, 3.17681910e+02])), ('precursor_mass', 777.8556012500002)])\nOrderedDict([('spectrum', [871.4608862366525, 257.1452400789644, 386.6978705155007, 436.2390771010214, 147.0773443431589, 246.14404294374305, 792.3831352300161, 920.4781137822341, 1017.5277980323841, 201.62719001792013]), ('abundance', array([3542.27231972, 68.9602073 , 470.31694211, 3187.69542837,\n 1445.31334294, 2213.95665567, 774.35063767, 2404.20287168,\n 26.07151502, 2866.2355371 ])), ('precursor_mass', 509.26856225000006)])\nOrderedDict([('spectrum', [412.235861910317, 113.58099534088521, 550.7873216868347, 1021.5245034592795]), ('abundance', array([ 839.08832516, 19602.34497059, 1714.62211752, 534.28497142])), ('precursor_mass', 559.7924017500001)])\nOrderedDict([('spectrum', [1100.5669460469849, 1187.600627014786, 257.1434153855668, 386.6995847178129, 500.2631714004723, 794.3826853965982, 980.4587288885093, 168.08210689378046, 217.61596227783912, 554.7838695080465]), ('abundance', array([ 724.37754581, 45686.6256711 , 1636.52265426, 734.02018707,\n 452.44057631, 1426.30401401, 5244.34484935, 2232.3702039 ,\n 4703.6600839 , 3784.19031589])), ('precursor_mass', 603.3084157500001)])\nOrderedDict([('spectrum', [871.4630915910558, 1187.598152981827, 257.1438986544164, 550.7858129868124, 360.1879506288572, 411.6895433780087, 619.30082465504]), ('abundance', array([ 145.99549429, 644.35555902, 16.75742707, 208.67876374,\n 3246.32129397, 7.26102563, 1770.92429082])), ('precursor_mass', 667.8297122500002)])\nOrderedDict([('spectrum', [871.4608837092486, 999.5207142726576, 386.7017205165206, 594.3002648217963, 658.8267394856846, 1463.6934401253463, 182.57066380493896, 297.1292592069521]), ('abundance', array([ 2222.57342818, 8508.38124272, 21305.69485358, 16162.80083315,\n 3925.39061695, 1481.61522968, 201.56241021, 1088.8087285 ])), ('precursor_mass', 732.3510087500002)])\nOrderedDict([('spectrum', [98.05883315330566, 412.23507321637493, 513.2847937526924, 999.5217799338395, 1502.704221749512, 49.53374722317916, 206.61950309406808, 257.1432577710779, 308.6493272291337, 436.23744145405817, 594.3048063193589, 658.8234287231514, 76.03928054513621, 205.08370303963306, 650.2619572610978, 1008.4403963244573, 1109.4908338175994, 1295.5658296275315, 1423.6684389319696, 38.524264791718906, 103.03847050996592, 167.5652905272986, 325.6363771981792, 504.7252871164933, 555.2521117892436]), ('abundance', array([4.27342339e+04, 8.37072661e+02, 2.04403968e+04, 9.61695074e+04,\n 2.20856934e+03, 3.52264605e+03, 6.53362495e+02, 1.75007782e+04,\n 1.90961683e+03, 1.14774833e+03, 7.74094921e+04, 9.65845511e+03,\n 4.01010380e+04, 1.74031275e+04, 1.15373677e+04, 5.47151333e+02,\n 1.10556837e+03, 2.26007767e+03, 8.95712447e+02, 5.09343357e+02,\n 9.76984975e+02, 7.16433844e+01, 1.96032917e+03, 1.31348996e+03,\n 8.50129400e+02])), ('precursor_mass', 760.8617407500002)])\nOrderedDict([('spectrum', [98.06269902782658, 226.15282645399523, 412.23381051437434, 513.2808605515519, 871.4592431976785, 1445.6850284115108, 49.53115209266779, 308.6507961339184, 500.2618742444991, 550.7864668350342, 594.3041906773551, 207.07637706177897, 653.2476518978335, 781.3016875307342, 327.12705171549084, 440.6894144274062, 518.7381064722344, 570.2468170241783, 713.810731962329, 777.8553106095236]), ('abundance', array([ 19691.36444254, 3150.38840216, 417.55225461, 175.56922969,\n 1528.53379842, 5786.87909676, 926.96398006, 3105.21935073,\n 766.91257194, 63679.0544987 , 3893.05299029, 4679.42226657,\n 411.72277752, 1441.09042764, 103353.61667429, 8234.43047821,\n 1841.35898867, 867.10195646, 198.76463973, 1378.52954116])), ('precursor_mass', 826.3819832500002)])\nOrderedDict([('spectrum', [628.3096027755722, 986.4837265068925, 264.1366022187981, 493.7462713446778, 147.0749559503628, 246.14604783736635, 402.2460098963843, 1132.5576659136213, 201.626108703292, 303.6532603373905, 566.7817329326766]), ('abundance', array([9.22801046e+03, 9.28047031e+02, 1.71073731e+03, 1.06342906e+03,\n 9.87617128e+03, 1.38931172e+01, 1.54172213e+04, 2.21774282e+03,\n 5.81574547e+02, 4.06363121e+03, 4.74728987e+01])), ('precursor_mass', 566.7820337500001)])\nOrderedDict([('spectrum', [213.0921952172397, 341.18164227060385, 628.3063067020942, 887.4174839065896, 986.4884335636154, 107.0510725195698, 171.09626971138422, 557.7771188382333, 608.3010608569616, 120.06492553231469, 347.19091502549514, 606.3023220521573, 707.3475984155426, 1021.523341807263, 1233.6053289102279, 617.3053073699792]), ('abundance', array([ 5862.48443024, 1045.39509151, 1145.91398812, 320.79168719,\n 2990.68673541, 609.01090403, 4189.24633642, 48.30946046,\n 8272.36528772, 766.23798505, 1480.96688341, 16767.4830669 ,\n 2635.29511685, 8155.2343529 , 131.4910982 , 262.96399624])), ('precursor_mass', 617.3058732500001)])\nOrderedDict([('spectrum', [116.03272268071876, 527.2628193029803, 171.09623344675833, 264.13424686142787, 366.1585190097194, 444.2130762892441, 493.74755606829893, 557.7771945451411, 106.04959588143882, 434.22484389465, 980.4609217414237, 53.527437296377826, 347.1703020448555, 397.6948043510707, 603.3077088681696, 660.821096381007]), ('abundance', array([ 3578.26079052, 2628.78738828, 4853.54304742, 842.4478323 ,\n 1288.39410448, 52995.93940162, 28358.0846751 , 4654.08425712,\n 4748.41542763, 485.1512317 , 1132.50906004, 184.80562379,\n 704.84568517, 12204.4573974 , 59534.32723985, 4361.66783259])), ('precursor_mass', 660.8218872500001)])\nOrderedDict([('spectrum', [116.03518122031848, 213.0861864992153, 527.2578231095729, 731.320230217897, 887.4182498912721, 986.4864910435751, 1431.6685202848607, 58.52107472876712, 107.04700821764354, 444.21483815856624, 716.3377916894934, 235.09386754090102, 563.2657095488895, 719.3716753969649, 822.3815780933285, 1449.6787242068415, 74.53185701433715, 118.0528177911044, 411.6854196678639, 555.2569433608237, 667.8323968862381]), ('abundance', array([9.87520492e+02, 1.15605273e+03, 8.84872439e+04, 1.63700534e+03,\n 2.46417573e+02, 4.42619364e+01, 1.52719820e+02, 4.99000413e+03,\n 6.02464668e+02, 1.34666723e+04, 5.74618304e+02, 5.38960299e+03,\n 5.55006835e+02, 2.84199277e+02, 7.35033939e+02, 3.02344352e+03,\n 1.27595953e+05, 1.19577275e+03, 2.44736165e+03, 3.04824269e+03,\n 1.85634830e+02])), ('precursor_mass', 725.3431837500001)])\nOrderedDict([('spectrum', [527.262344303409, 986.486198822123, 1114.5466637100515, 1215.594952233431, 557.774791707236, 364.13975807272993, 1366.6417308686084, 139.05306838236464, 233.09495859151096, 476.2095970701966, 789.8644943488305]), ('abundance', array([6.34141375e+03, 2.83001410e+05, 1.53987519e+02, 2.94431902e+02,\n 1.70674895e+03, 1.27673776e+03, 1.47400533e+03, 3.94668927e+03,\n 9.66321513e+01, 4.40273752e+03, 4.16245708e+02])), ('precursor_mass', 789.8644802500002)])\nOrderedDict([('spectrum', [1215.596113461838, 1431.6672099122466, 557.7760967366245, 334.1215115954871, 749.3312728499272, 1008.4418454596772, 211.08526660776113, 453.2200654004805, 712.3355709087604]), ('abundance', array([ 649.35863907, 1116.03356014, 1829.77184251, 368.28712049,\n 159803.25549958, 9642.94960373, 2216.91959567, 720.64048754,\n 674.98935009])), ('precursor_mass', 818.3752122500001)])\nOrderedDict([('spectrum', [1302.6263910282673, 1431.6673620767904, 58.52064846893804, 107.04838438761104, 264.13361744218855, 608.3011410410983, 651.8019880565035, 780.857034334953, 781.301294389593, 880.3720999462917, 440.68846335281546, 713.8072406700867]), ('abundance', array([ 3699.56881771, 7230.34751051, 3537.80807196, 664.76510521,\n 19771.26488252, 312.39933735, 5658.03280602, 3856.91295011,\n 5485.99793097, 469.23479243, 5135.65659272, 772.46388342])), ('precursor_mass', 883.8954547500001)])\nOrderedDict([('spectrum', [114.09943688584329, 454.26688199534493, 640.3407062888239, 741.3923370143963, 57.5488593332598, 227.63993224787538, 320.67550548554857, 371.20111538355, 422.70406880691996, 246.14617147192968, 402.24648729948467, 606.3019487464928, 920.4766274787416, 1017.5297750293129, 74.04096813338674, 253.13362359215887, 303.6545335908122, 396.6947431579069, 566.7828551714204]), ('abundance', array([ 105.96640467, 14818.2375917 , 25193.12900737, 2883.34556458,\n 5837.61610276, 355.11487131, 2451.91795915, 5776.08778107,\n 798.7959874 , 9583.16244367, 996.28992901, 11447.61078228,\n 71.30139395, 7132.16657231, 1099.96780909, 298.31299807,\n 1006.77560249, 6014.43134974, 1855.81494537])), ('precursor_mass', 623.3240657500002)])\nOrderedDict([('spectrum', [114.09216788909266, 844.4008059575939, 1099.5692093528428, 1328.6734171846706, 115.06243499880277, 422.7055732417044, 614.3191092839525, 664.8457699874947, 347.19168898267793, 707.347859388575, 1118.578600776656, 1346.685357953632, 447.21984946684324, 511.2649971664945]), ('abundance', array([1.72975403e+03, 1.16189735e+04, 8.72642096e+01, 2.63389368e+02,\n 1.42227623e+03, 2.50799764e+02, 6.65499022e+03, 1.05425083e+05,\n 1.19385196e+04, 9.84206269e+02, 1.05391519e+03, 8.54000207e+02,\n 8.92862937e+03, 3.79697415e+03])), ('precursor_mass', 673.8479052500002)])\nOrderedDict([('spectrum', [741.3945483990624, 844.4023384556141, 1000.5043512131637, 1227.6292096263635, 57.54928678157528, 550.2821587990128, 335.15710996025587, 794.3873653404829, 347.17227445258345, 490.7366131062604]), ('abundance', array([ 193.64990624, 1970.59100107, 333.33932171, 1186.41479664,\n 8644.69404381, 6663.12549277, 3149.60103238, 2143.68381792,\n 1612.93745893, 2180.00849944])), ('precursor_mass', 717.3639192500002)])\nOrderedDict([('spectrum', [1000.5086122447693, 1099.5714988463956, 163.58790885547765, 227.63525562512476, 708.3571843493264, 772.880138780097, 235.08970957630527, 719.3672018658242, 1109.503640330061, 1562.7623990392747, 74.53210259420173, 282.1345038128313, 411.6923390298578, 555.2551072823238]), ('abundance', array([5.96449993e+02, 1.49780052e+03, 1.77616224e+03, 1.07873128e+01,\n 3.58174918e+02, 1.32964004e+03, 6.23827784e+04, 1.01590654e+03,\n 1.00562103e+04, 4.11759642e+02, 4.76254472e+03, 1.52495935e+02,\n 1.10607594e-01, 4.14430743e+02])), ('precursor_mass', 781.8852157500002)])\nOrderedDict([('spectrum', [454.26513758803446, 741.3989502502415, 1328.6759609076064, 1544.752470591777, 163.59052901043898, 500.75514347561233, 664.8409990017268, 277.09851168132496, 364.1327634275651, 465.1829336742862, 593.2408398213835, 692.3077686030722, 1691.8029495286141, 182.574396481246, 233.09558583885666, 424.7089022324479, 789.8643689885755]), ('abundance', array([ 199.30836875, 694.60235378, 6795.34388315, 535.38928233,\n 1363.87396318, 10146.15109572, 962.70392224, 1048.22235389,\n 1266.24682732, 809.08443882, 7478.12558573, 46630.26829783,\n 18415.60459323, 1533.90953039, 730.76576804, 4933.32891581,\n 803.85824023])), ('precursor_mass', 846.4065122500002)])\nOrderedDict([('spectrum', [114.08966845081949, 1099.5722034151524, 1544.7553384416276, 1673.7938321747697, 500.75904922436365, 708.3569137291786, 76.03892085014418, 650.2633596837521, 1423.6614924565806, 167.56830577736113, 712.3427229559985]), ('abundance', array([15113.22650516, 13846.97826339, 333.48570665, 392.42937381,\n 12288.11240108, 8273.35168129, 563.08732967, 1437.71599303,\n 117.62808712, 3459.09518781, 1634.41045086])), ('precursor_mass', 874.9172442500002)])\nOrderedDict([('spectrum', [114.0897406398264, 454.2676367853271, 1099.5725386411348, 1227.6294374948661, 1544.7520345401517, 57.54834122284505, 371.20132076661866, 500.75340140876216, 614.3174702754201, 772.8839293089723, 837.4000333535236, 207.0805723112491, 336.1179207739181, 552.198070477011, 880.3749572772833, 1554.7042309733824, 233.0860721023676, 327.12394213818294, 440.6900150042078, 518.7443350370899, 620.76773725296]), ('abundance', array([1030.46703239, 586.93011218, 1689.62364636, 1678.86049327,\n 9918.22033766, 313.36547041, 2704.51084036, 447.78880944,\n 381.51969662, 2512.8332638 , 2736.59786048, 4439.77179721,\n 750.2694842 , 455.95459291, 5019.08285755, 565.14732998,\n 1681.05770612, 7110.46083756, 2651.81029277, 1504.75056823,\n 642.13804692])), ('precursor_mass', 940.4374867500002)])\nOrderedDict([('spectrum', [439.25473572278537, 567.3494891302266, 753.4297143315641, 1212.653847549669, 57.548656973385306, 114.08616141834082, 171.60420246924534, 284.1777297693125, 377.2191687946894, 479.2449167475209, 557.297353851974, 246.14377051468256, 505.255153635831, 606.3039028802714, 792.3835765559645, 1017.5380569336977, 74.042984934652, 566.7820194914501]), ('abundance', array([1.09095224e+03, 1.77962157e+03, 2.53489661e+03, 1.02401792e+04,\n 4.78182677e+03, 1.57476741e+03, 6.63979711e+03, 4.70216421e+02,\n 6.79195700e+03, 4.15266200e+04, 4.79265173e+03, 9.74308850e+02,\n 5.74899374e+02, 1.15417159e+03, 1.41684806e+03, 4.74368238e+01,\n 1.34407856e+05, 9.50097864e+03])), ('precursor_mass', 679.8660977500002)])\nOrderedDict([('spectrum', [567.3473498044807, 1441.7651183262055, 284.18002148058656, 606.3016002045805, 1346.6882685831074]), ('abundance', array([6.45146657e+03, 1.91457713e+04, 6.55533358e+02, 6.33835759e+03,\n 1.87805632e+01])), ('precursor_mass', 730.3899372500002)])\nOrderedDict([('spectrum', [114.09574093896235, 567.3513186684755, 957.4880693887246, 1340.7075136944095, 1441.7630764241358, 114.08680894299162, 171.60635261321656, 606.828404881059, 670.8605810382741, 721.3843247317814, 106.04991605329593, 794.387430387153, 1108.556291326407, 1433.7191886119642, 104.05213390155748, 295.6662609256694, 347.17070069516717, 397.6945384168557, 490.73418797838417, 660.8215640053864, 717.3686257126407]), ('abundance', array([9.30316607e+03, 2.02916088e+05, 1.86625881e+03, 2.15777257e+04,\n 1.41432741e+03, 4.10888489e+02, 1.34610081e+03, 9.84574532e+02,\n 6.62145583e+02, 1.53339292e+00, 3.28791814e+03, 3.04623979e+02,\n 5.12303399e+03, 5.62031103e+03, 1.23462504e+03, 3.15874841e+04,\n 9.33187026e+02, 1.61555185e+03, 1.02809063e+04, 3.22636087e+02,\n 1.21533172e+02])), ('precursor_mass', 773.9059512500003)])\nOrderedDict([('spectrum', [1113.5870510321417, 1441.76225534263, 1528.7942896366435, 114.08417324652687, 171.610718373549, 1675.8473929380093, 74.53407431548104, 232.60881156414598, 555.255278949137]), ('abundance', array([4.26830700e+05, 3.76939825e+03, 2.50909966e+04, 1.30413596e+02,\n 3.82164847e+03, 1.17375543e+03, 2.66313320e+03, 3.94240907e+02,\n 2.93668527e+03])), ('precursor_mass', 838.4272477500002)])\nOrderedDict([('spectrum', [114.09320313254062, 1212.6519476535605, 1657.8432564920638, 377.2161664332143, 606.836064498093, 364.1353048745773, 692.3154932067752, 1463.6929723922221, 476.21074490495295, 526.7341209743807]), ('abundance', array([10912.54843476, 1597.40236587, 177.50638501, 5196.45028402,\n 2613.13153103, 655.0176846 , 4724.09724402, 22128.44985953,\n 1222.17469937, 5177.12014491])), ('precursor_mass', 902.9485442500003)])\nOrderedDict([('spectrum', [753.4294479927726, 1657.8315378444827, 114.09175280452648, 284.18089250640253, 427.7417608623848, 893.9422361433719, 922.4547679519851, 1109.4867633531926, 375.16978081490055, 504.7223802482519, 555.2458876600167, 874.9200548554323]), ('abundance', array([6.12247534e+02, 2.55100395e+03, 4.07034824e+04, 1.29856436e+05,\n 1.07257499e+03, 1.39277841e+02, 1.14216938e+03, 1.03556935e+03,\n 5.86222994e+03, 6.04621979e+01, 4.29466896e+03, 4.96407712e+01])), ('precursor_mass', 931.4592762500002)])\nOrderedDict([('spectrum', [114.09253650465295, 227.17607297401568, 342.2020260996829, 1340.7159749624277, 1843.9012934794546, 171.60230145986458, 557.2981638213864, 893.9305831224056, 207.08479282427732, 552.1943351716004, 880.3644285888525, 1240.5305995685635, 1554.703022727969, 104.04265476481467, 168.5652417308545, 440.69147421313704, 570.2400988317033, 777.8551849978575]), ('abundance', array([16386.80807799, 1067.82340066, 898.57054251, 20243.58875867,\n 3282.53449358, 1326.37563974, 42949.7625235 , 5608.70383535,\n 4606.58735706, 3946.34200148, 2257.32687192, 381.90169643,\n 2922.8160236 , 1554.14147228, 224.26774038, 10550.34733875,\n 16799.71261504, 5150.94999293])), ('precursor_mass', 996.9795187500002)])\nOrderedDict([('spectrum', [298.21008688190926, 824.4676861024494, 1028.5232729747963, 36.529210025009114, 207.12268610758716, 412.7344921129018, 642.3533737672967, 402.24561217228717, 1132.5565713755689, 1429.7599248115428, 303.64758356032735, 460.7424112371426, 623.3235388959421, 679.8656238962906]), ('abundance', array([5.54420011e+02, 2.61061750e+04, 2.82511130e+03, 1.29953926e+04,\n 1.78145028e+04, 3.60168924e+03, 2.47296300e+01, 5.87455624e+03,\n 3.80471347e+03, 5.86690192e+02, 1.53543629e+04, 1.21364926e+04,\n 1.60410394e+03, 8.91457991e+04])), ('precursor_mass', 715.3846547500001)])\nOrderedDict([('spectrum', [413.2416165609844, 1283.69236754751, 1512.7998279051528, 36.52592038616441, 93.07023888259945, 207.12545659966835, 255.64937664041932, 412.73364179033643, 463.2625232290069, 592.8124899417976, 347.18477997520455, 606.3029824230154, 1021.5243178389815, 1233.6043938655102, 1530.8082782932152, 174.1003867791041, 447.2195418942987, 730.3924525069627, 765.9068184858731]), ('abundance', array([46679.18357896, 157.76975941, 655.96986843, 2676.80121964,\n 12952.6723031 , 3390.33356141, 24023.34918051, 561.55409589,\n 1493.38187592, 2053.90916415, 5071.82260534, 7465.85582432,\n 907.15142155, 426.43926382, 8711.3854784 , 95.5281764 ,\n 25932.27321679, 1668.49776394, 7949.22665523])), ('precursor_mass', 765.9084942500001)])\nOrderedDict([('spectrum', [1283.6962326872099, 1411.7492598939714, 1512.8001054347708, 36.52373578478728, 207.12151734835777, 642.3483183095142, 1205.6002404541491, 554.7832202978655, 660.820906498822, 717.3636377273654]), ('abundance', array([6630.55999126, 858.90347839, 1554.30868145, 251.85677852,\n 331.67457555, 851.64348987, 1465.50332036, 1248.81224647,\n 217.27379374, 866.89164265])), ('precursor_mass', 809.4245082500001)])\nOrderedDict([('spectrum', [72.04416192199449, 413.24029468912767, 510.29100892701365, 925.5162878379487, 1184.6288987793453, 592.8157878492517, 563.2670853474689, 1237.5969548710273, 1334.6520775083418, 74.53272749584244]), ('abundance', array([ 2667.15518583, 606.62717425, 255.43693539, 697.69275239,\n 99038.64949752, 56288.69311908, 2799.84724497, 2589.53370584,\n 3650.23743541, 1642.81501573])), ('precursor_mass', 873.9458047500001)])\nOrderedDict([('spectrum', [510.2921944090554, 1728.8737056326138, 800.4211316047448, 148.0628449878583, 364.1343486369205, 1691.805819357516, 74.53325672076275, 139.05462422547888, 424.70878155828524, 732.3503316812719]), ('abundance', array([2.36697572e+03, 1.07421604e+03, 1.24330861e+03, 7.16699062e+02,\n 6.19487340e+04, 5.22791270e+03, 4.07516106e+04, 2.23073341e+03,\n 2.90915739e+03, 5.21896321e+01])), ('precursor_mass', 938.4671012500002)])\nOrderedDict([('spectrum', [72.04268152214676, 185.12889921905779, 1028.5262057266318, 1184.6243318659047, 1512.801916734565, 1857.9164742752764, 36.53019646282199, 412.73714287068145, 514.7669535491129, 642.3490720258659, 706.3781577947937, 756.9029680068735, 864.9435558648648, 957.974369708095, 905.4304546413966, 1635.7439521298427, 1932.9481391665677, 103.04464161217037, 818.3749912398349, 966.978387276369]), ('abundance', array([6.56817384e+02, 5.56756640e+01, 1.07814142e+03, 1.02863746e+04,\n 1.99746565e+02, 5.38363231e+04, 2.18040005e+03, 4.12028550e+03,\n 1.10304023e+03, 8.24594574e+03, 1.13713231e+03, 1.92613962e+03,\n 3.94089362e+04, 6.42444487e+01, 7.45742223e+03, 1.05479795e+04,\n 2.13946868e+03, 1.46971923e+03, 1.68031094e+05, 6.93800685e+02])), ('precursor_mass', 966.9778332500001)])\nOrderedDict([('spectrum', [1184.6244736838626, 1283.691017200962, 1857.9183654311794, 93.06532679604081, 514.7663807051115, 800.4158807076184, 1023.4935387624358, 781.3024125233067, 1554.7032700526063, 1766.7841595303892, 233.08749531882395, 570.2448338225802, 826.3831239830048]), ('abundance', array([3.28228617e+03, 6.06405248e+03, 2.36300817e+03, 3.09440426e+04,\n 6.85347701e+02, 1.41029390e+03, 8.35269288e+00, 5.42185002e+02,\n 3.25414820e+03, 1.90925974e+03, 3.12042956e+03, 2.93503415e+02,\n 6.42475892e+02])), ('precursor_mass', 1032.49807575)])\nOrderedDict([('spectrum', [158.58013632742671, 210.0806894766059, 106.04582322270166, 280.0963521202448]), ('abundance', array([ 780.69327905, 2595.59746051, 3054.59179015, 405.09144329])), ('precursor_mass', 298.12324025000004)])\nOrderedDict([('spectrum', [102.05591086012889, 109.04451436479195, 317.6287258999484, 337.1174919284159, 82.0396594323182, 117.56031271951801, 326.6351058468798]), ('abundance', array([4895.59919097, 1954.76034 , 15.68310997, 1265.96208275,\n 4105.25753702, 210.56378129, 3971.49999006])), ('precursor_mass', 326.63397225000006)])\nOrderedDict([('spectrum', [102.050116449834, 634.2506394980107, 747.3392557786974, 109.04443232827808, 245.59796724412053, 189.1247764495018, 276.1554103122889, 66.55685816901118, 138.58132701649436, 174.102202997375]), ('abundance', array([5.57929594e+01, 8.97701486e+02, 2.82045692e+05, 3.17472201e+03,\n 1.41262058e+04, 1.97314584e+03, 1.17340431e+03, 7.44314939e+04,\n 8.21397735e+02, 1.79883950e+03])), ('precursor_mass', 383.17600425000006)])\nOrderedDict([('spectrum', [102.05646357727326, 490.18831046420706, 634.2437525957444, 747.3348817596698, 51.53052050995005, 438.2178627981668, 147.11157266345228, 260.19627491611647, 317.22169894088006, 159.11380020010927, 339.18431142914227]), ('abundance', array([ 278.32897214, 904.24479572, 11819.00139995, 5108.89405665,\n 624.48018471, 16456.14715941, 276.59915947, 6046.30839895,\n 4647.63771294, 710.63917745, 313.70785319])), ('precursor_mass', 447.22348575000007)])\nOrderedDict([('spectrum', [102.05634942924432, 316.14856317295954, 490.19780185266853, 577.2271671826389, 634.249401506295, 747.3343737090809, 158.57894438568573, 438.2175395757711, 148.0636665336376, 389.2365484110126, 921.4370956567553, 1022.4810908402725, 195.12415176611495, 223.63435967917678, 302.6737998538107, 461.2191001843282, 511.74627522854996]), ('abundance', array([ 1480.09803509, 2788.40571387, 6267.66874676, 13900.19133086,\n 482.10695215, 564.00132203, 5472.66905095, 4619.80751166,\n 359.14425773, 1695.43750736, 5013.12431161, 3841.10292036,\n 394.06828874, 5563.34591197, 1574.65538492, 7418.36636678,\n 2793.93771652])), ('precursor_mass', 511.74478225000007)])\nOrderedDict([('spectrum', [102.05286754142978, 316.15072003013125, 634.2529956216351, 1004.4708128488578, 289.1164147640877, 238.64016056312954, 267.15053619515794, 310.66511755551915, 346.1863198441036]), ('abundance', array([ 8689.72763936, 127.27717777, 2293.66450157, 17479.18629726,\n 927.06833377, 199.66026724, 38.12671159, 3109.00482723,\n 12614.60467808])), ('precursor_mass', 555.2607962500001)])\nOrderedDict([('spectrum', [634.2475299978169, 1091.5059807614164, 158.58189821704204, 502.74115714847824, 332.14654636492867, 1105.5175300562266, 1206.565434231349, 230.6237349126723]), ('abundance', array([ 273.37968952, 1071.75417369, 2197.23467602, 382.78226436,\n 1223.36755515, 377.30470232, 1225.46743403, 15924.90729049])), ('precursor_mass', 603.7871782500001)])\nOrderedDict([('spectrum', [314.1360204588865, 587.2490478896956, 100.05878578934016, 157.57033268599534, 258.60974710574743, 106.0487552286712, 177.0849422545473, 494.1916612474409, 692.2925720513687, 247.59639426524043, 346.65157994024474]), ('abundance', array([ 838.91937016, 289.77895886, 28451.50237155, 3122.46037175,\n 4627.28070859, 825.87903031, 2599.62193415, 69114.46910587,\n 3227.5868229 , 7893.1674362 , 2150.36264099])), ('precursor_mass', 346.64962225000005)])\nOrderedDict([('spectrum', [199.10849447057365, 314.14012719866645, 674.2781498194827, 731.3019590200286, 49.53346119646021, 157.56555576002566, 337.11549876159387, 436.18687969514065, 749.3132105623981, 82.03771502464745]), ('abundance', array([ 275.02170357, 3480.2739891 , 1106.70859042, 239.87679286,\n 1541.17999907, 280.8429949 , 3463.85826129, 1406.27130607,\n 504.24891315, 543.00510146])), ('precursor_mass', 375.16035425000007)])\nOrderedDict([('spectrum', [314.1319908601852, 587.2467067165259, 674.2771049853228, 366.1531927153757, 422.6984888758858, 132.101430290345, 549.2693675131636, 664.2969402037303]), ('abundance', array([1.12153280e+03, 2.22159308e+03, 8.79294290e+02, 2.10876083e+04,\n 4.36610446e+02, 2.56134221e+05, 4.33807387e+03, 2.17572044e+02])), ('precursor_mass', 431.7023862500001)])\nOrderedDict([('spectrum', [98.05723884478742, 314.1289949836415, 674.2832340069381, 844.3816311849599, 972.4807854774803, 157.56921462503675, 258.61081734458725, 294.1283038579701, 422.6960813929071, 475.2894121896395, 578.3030776612305, 74.05871090425815, 159.11542114926743, 202.6257176114554, 339.1866314333922, 396.70075710072655, 495.75182131435037]), ('abundance', array([ 1949.96186254, 539.48298506, 1234.01919525, 1067.41272688,\n 1084.22396483, 966.05755543, 269.09193096, 10649.54788548,\n 8270.02360787, 24706.72004551, 320.19235344, 8409.91497822,\n 4474.92548581, 487.67320539, 217.84911996, 10026.25243074,\n 2892.91130589])), ('precursor_mass', 495.7498677500001)])\nOrderedDict([('spectrum', [98.06147756061075, 199.10847656849455, 413.2042099883114, 587.2472771824873, 674.2821918942808, 731.3044242493884, 337.6423549713371, 366.1558205541136, 422.69697358997104, 486.7461155380726, 551.2626660635749, 148.06139381234658, 707.3436135589097, 921.4353573555582, 195.12494954668452, 267.1481279828135, 302.6671370436302, 403.71015988501426, 461.22043598053966, 560.2699786261105]), ('abundance', array([3.90752346e+04, 1.14286604e+05, 1.84661063e+05, 1.30420721e+03,\n 8.95656396e+03, 8.48388305e+03, 2.82073314e+02, 7.58053202e+03,\n 5.35040073e+02, 1.66972381e+03, 7.94274517e+02, 1.66141070e+03,\n 9.86153053e+01, 2.98266206e+02, 2.76911112e+02, 1.20414945e+03,\n 4.37922259e+02, 2.10258466e+03, 7.81068168e+03, 1.88172904e+03])), ('precursor_mass', 560.2711642500001)])\nOrderedDict([('spectrum', [98.0602240533249, 199.1049381692278, 157.5696945925051, 337.64555052820685, 486.7463566814413, 106.05047252332793, 476.2720349621569, 620.3262538026596, 691.3620410863097, 794.3729111236743, 267.14925340240416, 310.6569584669819, 447.2236111648121]), ('abundance', array([ 491.75665445, 146.31320164, 765.26082828, 8980.98758988,\n 51989.00182231, 2105.87565482, 2111.82233518, 5881.41262815,\n 726.50642381, 128.52266802, 295.97511981, 9477.70477648,\n 1064.14113129])), ('precursor_mass', 603.7871782500001)])\nOrderedDict([('spectrum', [731.301629976713, 258.60956294999085, 366.15499304007056, 717.3805440820596, 287.16591491339904, 315.67632773674865]), ('abundance', array([2645.80701291, 1660.67302701, 197.04665929, 57.16409434,\n 213.28667504, 324.81730148])), ('precursor_mass', 652.3135602500001)])\nOrderedDict([('spectrum', [413.20384497270686, 615.2818422151902, 50.54112365724393, 256.6384163744489, 387.1798142626564, 280.0962442523402, 494.1885327435931, 595.2452105252307, 692.2913905796653, 791.3634158290201, 89.0530631714177, 190.08602612346655, 247.59965608753683, 298.12463352884583, 396.1796067579999]), ('abundance', array([ 631.92647022, 179.22338401, 176.98241939, 139.10255386,\n 473.31940384, 217.58525037, 382.69590202, 80.11373994,\n 194.64365395, 485.11844178, 215.9350353 , 1885.30270597,\n 1012.28838797, 1218.97701358, 3263.64144395])), ('precursor_mass', 396.18382925000003)])\nOrderedDict([('spectrum', [298.1735995686237, 207.105090815606, 256.6388907951777, 308.1446312724451, 652.2604625193109, 38.524115810561206, 82.03906938497236, 117.5649858390852, 326.63427925642924]), ('abundance', array([2740.18385141, 6087.49414506, 4847.28538995, 356.26223347,\n 6678.93678381, 7628.46510296, 43.77557379, 4921.27482377,\n 1508.88046165])), ('precursor_mass', 424.69456125000005)])\nOrderedDict([('spectrum', [413.2003160876605, 686.3196983493144, 50.54020044769888, 99.06773896137068, 472.2305651858316, 189.1249582770377, 347.1921074905796, 664.2957970426986, 174.10070462599145, 383.1753564365524, 431.7011761019721]), ('abundance', array([13872.09884142, 38489.48000975, 800.14933279, 1627.95967353,\n 445.34429003, 697.21002357, 94.61926711, 156.92648395,\n 329.2351299 , 216.22361986, 917.96386818])), ('precursor_mass', 481.23659325000006)])\nOrderedDict([('spectrum', [100.08423879464993, 298.177314010952, 830.3721639635551, 943.4551446730292, 1071.5508648605144, 99.06806169261574, 472.2312690699503, 578.2962659397216, 893.4370967797164, 202.62861950898923, 339.18522172427237, 495.7539622589483, 545.2833359964101]), ('abundance', array([ 3027.96549725, 228.38379492, 2362.00621201, 1895.23936314,\n 4796.32682505, 763.35738313, 479.28331626, 15479.51033993,\n 4027.39049873, 248.16346605, 403.94501617, 368.43429129,\n 9869.53984359])), ('precursor_mass', 545.2840747500001)])\nOrderedDict([('spectrum', [298.17432596470695, 413.1974554367418, 830.3718729207843, 943.4578627806765, 1071.5498290698883, 308.14292166649443, 343.66384789061163, 415.6888672143295, 536.2784983539992, 604.3304614574208, 74.53405400369962, 267.1504747632764, 302.6691413368165, 354.17282568276096, 403.7078619595977, 461.2161493731637]), ('abundance', array([ 1342.33568752, 2355.84326639, 144.00769562, 21865.31987028,\n 18248.40683077, 55.50693329, 1119.6218259 , 1613.72105545,\n 37.00890981, 18452.02144037, 866.06667336, 892.97608172,\n 2088.70652506, 20100.50092664, 12844.62335764, 246.4120775 ])), ('precursor_mass', 609.8053712500001)])\nOrderedDict([('spectrum', [197.12808666521738, 413.2032352897461, 615.280743441096, 1071.5472151593242, 207.1067891359734, 308.146199746171, 387.1739162979302, 644.3163885950439, 235.0912040923942, 363.1887924003666, 476.26880883678393, 533.2932373288595, 620.3241800682003, 182.09701397416407, 238.63893132684103, 447.22082108099545, 504.73689167726945, 603.7809175432345]), ('abundance', array([3.85552116e+03, 1.78626096e+02, 2.07604497e+03, 8.91451843e+03,\n 2.40528613e+01, 2.65741539e+04, 1.50922270e+03, 4.78474643e+02,\n 6.84895018e+03, 6.36048253e+03, 1.41366759e+03, 8.07437257e+02,\n 9.00328239e+02, 1.07730768e+05, 8.39571678e+03, 3.27778687e+03,\n 7.57455772e+02, 1.37553884e+03])), ('precursor_mass', 653.3213852500002)])\nOrderedDict([('spectrum', [512.270043415009, 615.2813750836339, 830.3712063556025, 943.4550300907417, 207.1048867220659, 308.14530197601596, 387.17829806836755, 536.2815183630789, 600.8003456270525, 644.3153667773032, 692.8437891703085, 116.0720940647923, 717.3739408987803, 1105.519260102931, 1402.6862556306373, 102.05192970040609, 166.57423524148533, 394.7105812068277, 652.311689268088, 701.8473699449252]), ('abundance', array([7.66232517e+02, 8.33841303e+02, 1.99506300e+03, 2.90236302e+02,\n 2.02356328e+04, 2.54692759e+03, 5.54759080e+04, 2.19474922e+03,\n 8.05746781e+02, 5.13453110e+03, 4.29173421e+01, 2.29895102e+03,\n 1.21942017e+02, 3.06638721e+03, 3.84384637e+03, 1.06141858e+02,\n 2.61377070e+03, 7.03631817e+02, 1.35757569e+03, 4.78245309e+02])), ('precursor_mass', 701.8477672500002)])\nOrderedDict([('spectrum', [148.07512760421184, 920.4136077310031, 280.6334904603454, 381.6777975383953, 460.7108671970078, 938.425673178805]), ('abundance', array([ 1305.85927411, 978.29534052, 89.23867041, 167.28971628,\n 310.09884382, 39048.43429118])), ('precursor_mass', 469.71803624999995)])\nOrderedDict([('spectrum', [659.3376151774752, 172.60767889078343, 280.6418427666918, 163.06813674109225, 234.1096178044518, 38.521136897580554, 82.03931796494473, 424.6939759969358]), ('abundance', array([ 7794.43452388, 191.48716497, 471.37266743, 506.44529548,\n 66396.5900789 , 223.12366513, 3584.7231616 , 116523.61177034])), ('precursor_mass', 498.22876825)])\nOrderedDict([('spectrum', [445.2469468600041, 560.2712589084773, 659.3402565653142, 833.3869800184862, 977.4397361964592, 74.54156901418771, 124.0759168790261, 223.12479425347703, 330.17366147225727, 417.19772126528153, 489.22317377631106, 132.1018451839807, 450.2020922444364, 66.56095980044485, 174.0961715512601, 225.60438448455457, 383.1759175198324]), ('abundance', array([2.57553649e+03, 3.74497435e+03, 7.69559330e+03, 9.16115582e+02,\n 7.16931350e+02, 1.78947272e+01, 7.65718964e+02, 9.89755533e+03,\n 1.29851440e+03, 1.70690682e+03, 1.27834140e+03, 3.90537077e+03,\n 3.11075397e+02, 6.02317469e+01, 2.03184388e+02, 1.92446651e+04,\n 1.19513279e+02])), ('precursor_mass', 554.77080025)])\nOrderedDict([('spectrum', [247.14453247549974, 445.2451429820006, 833.3899991036348, 124.075828930437, 223.12574051349625, 489.22156554611706, 545.7663997495947, 609.8099661383566, 317.22064965317185, 893.4389975462356, 990.4947494861391, 1236.6235819468327, 447.2245656272423, 495.75086106226775, 618.8177356457965]), ('abundance', array([1.63223508e+03, 3.20237595e+03, 4.50557020e+04, 1.09297307e+03,\n 2.45782363e+03, 2.56233371e+03, 4.69815910e+03, 1.04736342e+03,\n 5.38128164e+03, 1.92558399e+03, 3.48559482e+03, 4.48727976e+03,\n 7.83529104e+02, 1.27399040e+00, 2.00755566e+05])), ('precursor_mass', 618.81828175)])\nOrderedDict([('spectrum', [247.13824843032816, 762.3477864886938, 920.4180493372849, 977.4458399288415, 1218.6185860356595, 172.60031070135145, 381.67940198695356, 674.3328203403363, 389.2447615781514, 533.2957934589549, 707.33851341656, 921.4342112432162, 1365.6742235911581, 461.22005121658646, 511.74529430568464]), ('abundance', array([4.53807368e+03, 5.05089661e+03, 5.88541029e+03, 1.25596232e+03,\n 3.48394906e+01, 1.50515694e+03, 3.24265359e+03, 1.12995755e+05,\n 3.57357188e+02, 3.84155939e+03, 4.44730768e+03, 2.68616375e+03,\n 2.60700210e+02, 9.11478876e+03, 1.57213703e+02])), ('precursor_mass', 683.33957825)])\nOrderedDict([('spectrum', [148.08581117540376, 560.2686249675374, 1434.6947120303198, 489.2262571363708, 893.4370014355286, 182.09548567407705, 238.63480834134398, 397.68953002424854, 447.2258542360428, 653.3222483547039]), ('abundance', array([ 527.98110535, 580.66341282, 249.78902128, 1831.5110919 ,\n 448.43565155, 641.50645157, 350.57919362, 467.7506433 ,\n 1922.23186851, 13983.89053441])), ('precursor_mass', 726.8555922500001)])\nOrderedDict([('spectrum', [247.1442725478064, 445.24664343647476, 560.2731719345132, 1218.619307180318, 124.0763549348386, 223.1249390877737, 460.7129895413744, 717.8510747677424, 766.3796457437543, 203.10016414871544, 58.538930839895485, 102.06054577962965, 166.57703319126463, 287.1672958773629, 652.3142679681364, 775.3846626506805]), ('abundance', array([ 1735.67708635, 2317.8764051 , 122309.89356973, 11378.67904091,\n 3481.56384892, 610.0208277 , 196.17792479, 1376.20529658,\n 138.6393062 , 14290.51337634, 568.2382952 , 3627.01671055,\n 1297.45992944, 14463.10961482, 702.84637362, 1480.94274459])), ('precursor_mass', 775.3819742500001)])\nOrderedDict([('spectrum', [262.12048453114363, 361.18529786063954, 458.24085470858694, 559.2877935094002, 131.5628370732309, 181.0965480736621, 229.6207014171563, 337.65999498400504, 438.70263772793226, 474.2243347951844, 517.7337202048548, 379.16550201689927, 494.18682206722616, 938.4258143269273, 1052.4712338794334, 53.53264408274911, 89.04671336062057, 298.126952782584, 469.71784215497274]), ('abundance', array([6.34329479e+03, 9.45339056e+02, 3.88994860e+04, 7.36266942e+03,\n 2.50327864e+04, 1.74744599e+04, 6.34374845e+03, 4.43418451e+02,\n 2.36896314e+04, 6.63428730e+01, 2.44350988e+03, 8.39894364e+03,\n 2.71127866e+03, 3.43238586e+01, 7.48213932e+02, 1.15372386e+04,\n 1.47802553e+03, 3.73057036e+03, 3.73639651e+04])), ('precursor_mass', 526.7394997499999)])\nOrderedDict([('spectrum', [559.2938494436028, 947.4280705552133, 1034.4605628818347, 280.14682035239457, 387.19562407207883, 517.739103691057, 848.381780144835, 995.4516526712243, 169.0616675076738, 375.16046396234526, 555.251578979932]), ('abundance', array([1.63787476e+04, 6.88959402e+00, 2.85986116e+03, 1.03136959e+04,\n 1.24436932e+03, 6.29837905e+02, 4.54125896e+02, 2.62090465e+02,\n 2.46296420e+03, 2.06502741e+03, 5.18093301e+04])), ('precursor_mass', 555.2502317499999)])\nOrderedDict([('spectrum', [262.11897090550406, 458.2417180269237, 674.3129857881719, 1034.4626579181243, 181.10084797355626, 337.66439630383695, 474.2183587444425, 132.10566706540573, 549.2689235928017, 664.2971922722468, 1108.531159777954, 1222.5828914124668, 95.06652571981186, 138.58202907212967, 554.7728634388226]), ('abundance', array([3.02724247e+03, 6.21953907e+02, 9.59022271e+04, 3.77138329e+03,\n 2.27085609e+01, 5.27148416e+03, 3.01416257e+02, 1.38911832e+04,\n 3.45941396e+03, 7.97150122e+02, 1.85631281e+04, 2.67966791e+02,\n 1.42424260e+04, 2.70291040e+01, 1.67530535e+04])), ('precursor_mass', 611.7922637499998)])\nOrderedDict([('spectrum', [262.11568362147733, 773.3778119636786, 947.4289103987769, 1034.460802619958, 58.02651626062315, 229.62094165891307, 387.194252305669, 517.7329616489372, 147.10581270993399, 578.2988666728585, 792.3965400222452, 1236.6279104024325, 1350.6711526199492, 130.59091471562246, 159.10367101274855, 202.6274941849318, 238.14992992165554, 545.2839396984708]), ('abundance', array([1.01229974e+03, 2.56814381e+02, 1.03660564e+04, 1.33082091e+03,\n 7.10258003e+02, 3.32156748e+02, 2.27481193e+03, 1.83017829e+02,\n 1.42386068e+03, 1.28246243e+03, 2.07716937e+03, 4.02828331e+03,\n 6.79272362e+02, 5.53350639e+04, 4.61944953e+05, 5.46141821e+02,\n 1.56655379e+04, 9.26286178e+02])), ('precursor_mass', 675.8397452499999)])\nOrderedDict([('spectrum', [115.04932132940341, 773.3840282071801, 1461.7026277864154, 58.03246956076067, 229.62482092024408, 387.198407642501, 438.6906970770655, 474.22105487435726, 517.7337033823604, 148.06012479475316, 921.4354894621852, 1218.6024012904636, 1479.7061087614366, 138.58125757298762, 195.12539283943957, 223.63053850909057, 267.15212181101043, 302.6680972288824, 403.70798966829045, 461.2159207668649, 683.3357946221981, 740.3621676089462]), ('abundance', array([3.33423293e+03, 4.56879508e+02, 5.05124242e+03, 2.10871809e+02,\n 3.62829801e+03, 1.92265480e+03, 2.25715582e+05, 1.06692316e+03,\n 5.01101912e+03, 2.51496691e+03, 2.49304423e+03, 4.01168904e+03,\n 5.75639624e+02, 2.24465736e+03, 1.39693639e+03, 3.64258189e+02,\n 3.30314493e+04, 2.76825699e+03, 2.12913402e+03, 3.61584707e+03,\n 4.72506494e+02, 1.68724490e+04])), ('precursor_mass', 740.3610417499998)])\nOrderedDict([('spectrum', [876.3934406536612, 1034.4593364839495, 1332.6611115234484, 58.02799828924481, 181.0958873376085, 387.1934982560433, 474.2251465547217, 546.2441614037874, 666.8351003971571, 731.355063325429, 774.8749260717511, 106.04995848922853, 363.18454681999833, 794.3673067210202, 118.05017807495871, 555.2652233476068, 726.8547596364203]), ('abundance', array([ 1637.97626665, 62.08604894, 1690.39905552, 4957.70359468,\n 338.45206735, 2171.722368 , 2236.37461288, 5844.33512577,\n 123.13623592, 4166.56001457, 1178.53271041, 649.4317243 ,\n 3891.20027253, 422.26373637, 38925.47755436, 1588.15870997,\n 3064.4496786 ])), ('precursor_mass', 783.8770557499998)])\nOrderedDict([('spectrum', [115.05088326553178, 947.4282409552231, 1091.4817681126344, 181.09534026462913, 280.1445425020062, 387.19553534997925, 438.69554119593073, 602.790867369217, 203.1044223028734, 460.2385123202866, 573.323174151395, 1206.567077043525, 1663.7982052654265, 102.05479389034944, 166.57237779465862, 287.1667636414055, 359.19214853421, 446.217095011073, 553.2592514471768, 603.7861347305615, 652.311255420668, 832.4048976538071]), ('abundance', array([ 1880.54178288, 49260.19294585, 1740.18240985, 21755.50636006,\n 1799.69833995, 11268.7696474 , 347.03263901, 358.25168509,\n 1638.81400913, 12954.01375794, 2064.01102184, 7063.3109059 ,\n 52564.07275827, 4118.20888342, 2513.65754304, 11318.82802269,\n 5098.04331313, 3024.6593037 , 370.42994886, 197.30922392,\n 1045.80856539, 5562.72535845])), ('precursor_mass', 832.4034377499999)])\nOrderedDict([('spectrum', [230.07680005572186, 476.21481666668376, 991.417072748157, 238.6124996858221, 444.70696708406507, 531.7322720223848, 106.04922391267046, 791.363710129589, 298.1253782782256]), ('abundance', array([ 4120.43859834, 2580.2082352 , 2417.0229307 , 17166.42300947,\n 4438.13184137, 93905.90478006, 30357.27636527, 2865.13220845,\n 493.32598749])), ('precursor_mass', 584.2529712500001)])\nOrderedDict([('spectrum', [991.4201603414429, 1206.5136113148153, 238.60789612891432, 337.6608296312262, 496.21343091564506, 337.11840460548257, 652.2622070093739, 749.3107295607326, 848.3819598150502, 1224.5197585123572, 218.59306600517496, 276.1108009766675, 498.2345168038406]), ('abundance', array([ 465.08532685, 787.68691672, 335.52404887, 352.45037126,\n 1057.93434068, 830.99849085, 1774.19566273, 2593.55750563,\n 1880.07448195, 1297.81087174, 2637.51754075, 90.03912136,\n 6645.19388648])), ('precursor_mass', 612.76370325)])\nOrderedDict([('spectrum', [573.2679323512583, 789.3393309082759, 132.10196034374746, 1337.603375331575, 138.5863726639289, 554.7752736880418]), ('abundance', array([4172.46480729, 2149.90300325, 2536.8065323 , 7735.28825802,\n 2430.04271391, 556.97307115])), ('precursor_mass', 669.30573525)])\nOrderedDict([('spectrum', [116.03422024127063, 674.3151044695496, 789.3379894245381, 1206.50796794422, 115.54338791162289, 238.61004269286457, 395.17732539513406, 444.70535917273884, 660.2998425720386, 317.2196232535131, 990.4915918159305, 1236.6327641161486, 1350.6700503251836, 339.1856488630582, 447.22403838364664, 545.2919974191019]), ('abundance', array([2.64143308e+03, 1.07631009e+03, 2.00939367e+03, 1.63619325e+04,\n 1.67138906e+03, 3.02688746e+03, 6.95857391e+03, 1.47701778e+04,\n 2.74272074e+03, 3.19002205e+05, 1.19276386e+02, 1.17886021e+02,\n 5.62514850e+03, 1.19721388e+03, 9.42642347e+03, 8.55935153e+03])), ('precursor_mass', 733.35321675)])\nOrderedDict([('spectrum', [230.07678819449654, 377.1471772142757, 476.2147489916675, 789.3377571987057, 991.4180947072906, 1149.4868540278696, 1319.5939857663973, 58.52171204156895, 115.53831611546445, 337.66080688125925, 603.7555832886796, 724.3463816320708, 148.06096694516606, 276.1563246724097, 707.3384209447556, 1022.479293384225, 1594.7411324825684, 195.12199816813083, 267.1520494986537, 511.7451023392584, 560.2714743980118, 609.8068934950904, 683.3391527722304, 740.3619261873524]), ('abundance', array([2.22796452e+04, 9.14994420e+03, 1.37991600e+04, 5.96042805e+04,\n 1.36710968e+03, 2.10608672e+03, 6.28277586e+02, 2.02846640e+03,\n 9.75253036e+02, 1.89455807e+04, 8.95867318e+02, 4.79606067e+03,\n 4.98362746e+04, 2.23379366e+04, 7.55224144e+03, 6.65043984e+03,\n 9.25388295e+03, 4.98300934e+02, 5.72652246e+03, 3.13943321e+02,\n 2.43981676e+03, 8.17476055e+03, 8.72804630e+02, 1.42808068e+01])), ('precursor_mass', 797.87451325)])\nOrderedDict([('spectrum', [476.21478640749694, 573.2670847968369, 789.338943030301, 888.4127913599816, 1319.593590513013, 724.3523395276457, 691.362626688582, 1305.637265413463, 1566.7463480479246, 118.05000151448132]), ('abundance', array([6807.59667942, 869.3528851 , 1254.25283469, 1280.83580083,\n 685.41267676, 386.11697583, 2260.98223796, 1338.0488416 ,\n 6175.21784544, 2480.1386316 ])), ('precursor_mass', 841.39052725)])\nOrderedDict([('spectrum', [377.14511091700365, 789.3394215039832, 991.4196727421813, 1062.455535384494, 1319.5935397582641, 1663.7605404166238, 58.52148554347112, 115.54213958397145, 395.17153066871145, 444.70842116451394, 496.212838369583, 660.2980206567337, 880.910125695584, 630.3488549749784, 717.3783191711143, 788.4143373931471, 990.4923011455588, 1549.7560612272155, 1778.8260874021614, 166.57376066744033, 701.8464853736957, 775.3851142974861, 889.917258824633]), ('abundance', array([ 1562.45870589, 7674.39892381, 37834.21302263, 607.48346571,\n 14957.1707841 , 595.70580333, 7394.93176791, 8581.33391661,\n 3197.40763929, 1299.5834294 , 32527.20278947, 186.48856096,\n 1351.14902168, 485.09901917, 2024.15022535, 639.24998676,\n 14763.0651273 , 81.08792443, 744.53810477, 40552.69089722,\n 20814.63111181, 7409.0232923 , 302.69133701])), ('precursor_mass', 889.91690925)])\nOrderedDict([('spectrum', [244.13036137241505, 253.12307510686588, 302.6554762650842, 351.18205393219677, 401.708269812279, 459.2204095211844, 560.2558842352187, 595.7825329762078, 379.16545977866264, 692.2931394518012, 938.4290143920731, 190.0877024283589, 469.7195789239908, 584.2511568329229]), ('abundance', array([1.02548611e+03, 3.93025182e+03, 1.08435139e+03, 1.21581987e+03,\n 2.15821786e+02, 6.40753428e+03, 8.15553560e+00, 1.31421108e+03,\n 8.75368771e+03, 4.31177074e+03, 1.22354848e+04, 2.12868981e+04,\n 7.71610583e+03, 2.42988284e+03])), ('precursor_mass', 648.30045275)])\nOrderedDict([('spectrum', [129.0988448591126, 358.17305087059765, 505.23876695941493, 802.4085501615151, 65.05532039318437, 253.12274436121078, 508.75993960522, 560.2625039258214, 595.7784311552736, 76.03518670952332, 337.12339728919335, 436.1881519365546, 652.2600620193192, 1109.4922705078075, 1224.5210465796429, 218.59567816526862, 276.1123858174536]), ('abundance', array([45627.29267073, 3000.04646868, 1728.52353412, 594.08120909,\n 1745.28204123, 3179.21514204, 171.05880193, 9975.48600686,\n 512.62014176, 1335.17000643, 239.67040493, 523.02172292,\n 13869.88137933, 1867.2060748 , 21745.72829482, 2036.57780661,\n 11686.02965173])), ('precursor_mass', 676.8111847499999)])\nOrderedDict([('spectrum', [917.436417829178, 1447.6954187633623, 302.65504483755774, 351.183407735138, 450.1986575914461, 765.3440455530312, 1222.576244393839, 138.58104631730802, 225.60206874135034, 275.14320368545833, 332.6504131960666, 383.1731442387893, 611.7916816085506]), ('abundance', array([ 273.13700566, 1773.98195692, 861.27611057, 3634.85798216,\n 5382.50698354, 207.9531411 , 23287.23183317, 781.28898801,\n 501.83104777, 6016.05691101, 1700.38652816, 183.84084188,\n 857.61451454])), ('precursor_mass', 733.3532167499999)])\nOrderedDict([('spectrum', [244.13183269410888, 505.23727990481177, 604.3100343844394, 701.3614067167651, 1016.504678585481, 1334.6074251447342, 1575.7834501128634, 122.5643938745069, 788.3910771795587, 147.11320165826658, 317.2159244262998, 677.3644476866755, 792.3900176666057, 990.4991257704015, 74.06002549981716, 289.656128010452, 447.2248288925882, 618.8138395703976, 797.3998612195941]), ('abundance', array([1.95250622e+04, 7.19631878e+02, 1.02471490e+04, 9.84308926e+02,\n 1.00137108e+03, 1.02950272e+03, 4.56275500e+04, 3.39620566e+04,\n 1.06516070e+03, 5.21745761e+03, 3.57556047e+02, 1.70965717e+05,\n 2.20747862e+02, 5.00598664e+03, 1.38562509e+06, 2.57322310e+02,\n 2.14985328e+03, 4.99267851e+04, 7.28627153e+03])), ('precursor_mass', 797.4006982499999)])\nOrderedDict([('spectrum', [244.12598014334617, 358.17026071494, 604.3110717179935, 1190.5508086694847, 1277.583122488388, 1447.6902608216687, 1704.8244461725262, 122.56998778391487, 253.11948483465233, 401.70609308436235, 508.7579108186229, 595.7797168231102, 788.39490084782, 148.0607587094459, 389.2408073539507, 446.2588213197752, 604.3331492423968, 707.3368004261486, 921.4358020540684, 138.5802106690825, 354.1731636022881, 403.70533013471123, 560.2706524428206]), ('abundance', array([3.11087000e+02, 1.01431236e+03, 2.50633095e+03, 2.69619677e+03,\n 3.33537886e+03, 1.84954940e+03, 7.51815209e+03, 1.39444549e+03,\n 2.29635028e+02, 5.60556195e+01, 9.19739113e+03, 3.25960383e+03,\n 8.86372661e+02, 4.21162765e+02, 5.73621068e+02, 5.34595786e+00,\n 1.62876578e+04, 9.38986447e+03, 3.73491418e+02, 4.64049951e+03,\n 1.46142623e+03, 1.56380436e+04, 1.08972239e+03])), ('precursor_mass', 861.92199475)])\nOrderedDict([('spectrum', [129.1038652359149, 244.1289368699479, 701.3615804181064, 802.4076932070469, 1190.5523222164713, 1277.5868327305163, 1447.6869604046549, 1704.8272424148702, 65.05706566248492, 302.6560868635759, 459.2201235266779, 560.2635352931385, 667.8070937339575, 724.3508893773479, 476.2700168459136, 794.3700733855219, 1305.6334679884176, 1452.701928840132, 1566.7432825184599, 238.6363027008751]), ('abundance', array([ 7524.60308013, 2315.29683587, 13933.24939458, 510.35732787,\n 710.40033877, 509.25038616, 4189.94944391, 2607.11630446,\n 127.75777174, 2482.06378392, 22462.05381903, 3440.05611141,\n 385.27294527, 2619.53269931, 24227.89988755, 963.33710499,\n 801.67228093, 3420.52964962, 1506.25095487, 780.01981662])), ('precursor_mass', 905.43800875)])\nOrderedDict([('spectrum', [1190.5509947942796, 1334.6017129019988, 1575.785237928692, 459.22082221561885, 896.4341243990065, 332.1460653724485, 1663.8008405241324, 603.7871190015524, 701.8470872723398, 832.4054762725314]), ('abundance', array([ 2032.91807022, 3759.18231239, 1151.20450385, 3574.67886192,\n 1136.4265333 , 11396.76639499, 35549.31104566, 398538.93038144,\n 5245.42533432, 962.1532296 ])), ('precursor_mass', 953.96439075)])\nOrderedDict([('spectrum', [130.55918656905143, 223.58590689613854, 561.2388066985789, 345.14980531949647]), ('abundance', array([ 3978.51674944, 13687.86725237, 285.14033879, 14068.04639285])), ('precursor_mass', 345.1497897500001)])\nOrderedDict([('spectrum', [389.149577133417, 446.1684125102581, 671.2822750974944, 708.2951098768814, 836.3643753028306, 196.09991695203516]), ('abundance', array([89166.42455217, 11225.15842052, 12618.40937531, 728.47647431,\n 350.30119961, 249.95962624])), ('precursor_mass', 418.68399675000006)])\nOrderedDict([('spectrum', [130.55654211151557, 287.61800554303835, 132.10058925967147, 949.4467940187576, 252.64468327868278, 281.15526192708853, 475.2282417305079]), ('abundance', array([29573.24585946, 6840.20384643, 3781.37021122, 5232.60783892,\n 72.14775102, 19015.85544645, 7781.66529436])), ('precursor_mass', 475.22602875000007)])\nOrderedDict([('spectrum', [574.2290650174987, 671.2817187424898, 818.3523469938791, 931.4355941365329, 1059.5297169635426, 130.5533842419341, 195.07564376610685, 336.1429009118399, 689.3984101972356, 818.4395053507495, 1077.5381201655707, 539.2731701945]), ('abundance', array([ 1152.75542775, 9755.34154957, 65.92004211, 971.39078571,\n 476.24391134, 5164.7803515 , 39317.37269738, 231.84818581,\n 19910.4199245 , 224.74477204, 536.39860384, 2410.60498129])), ('precursor_mass', 539.2735102500001)])\nOrderedDict([('spectrum', [260.10255681542264, 574.2254309783375, 130.5564910267641, 336.14489253195364, 494.28999175308826, 53.52870379418463, 247.65178864985742]), ('abundance', array([ 263.30158163, 16526.63714198, 193.81329438, 799.81914881,\n 10191.07762106, 3428.32938806, 274.973445 ])), ('precursor_mass', 582.7895242500001)])\nOrderedDict([('spectrum', [195.08259086576328, 409.6804458935426, 530.264209671745, 148.0591591680338, 848.4519354010973, 905.4719154281669, 1034.5124232326536, 1293.6141925856657, 424.7301951865135, 583.2782952219061]), ('abundance', array([1947.73921 , 1252.30993467, 582.26701527, 751.86725852,\n 208.21289505, 1061.2268586 , 1365.9393949 , 2474.65047629,\n 8453.2087446 , 2429.47417646])), ('precursor_mass', 647.3108207500001)])\nOrderedDict([('spectrum', [129.065561219504, 260.10581859124795, 574.2289041871497, 336.14225833912724, 466.22115886838657, 666.8179972910575, 680.3590569506001, 777.4032744689829, 905.472773049045, 38.52184047388283, 389.211028689903, 611.7923987584425, 675.8225640638278]), ('abundance', array([2.48556115e+04, 1.15704614e+03, 2.86855521e+03, 5.55609688e+03,\n 1.00428395e+03, 9.10402186e+02, 9.62917303e+01, 2.29800399e+03,\n 2.50788381e+03, 1.12914240e+00, 7.38813406e+03, 2.19248592e+02,\n 3.28870388e+03])), ('precursor_mass', 675.82155275)])\nOrderedDict([('spectrum', [675.2749662624387, 116.07035437513768, 301.15060755704985, 430.1947881329175, 790.3409240949983, 151.0791992788854, 215.5978146145427]), ('abundance', array([ 94.81913261, 234.12838506, 148.26536461, 1334.25635934,\n 1002.13598604, 1075.85914584, 340.55672256])), ('precursor_mass', 395.67362925000003)])\nOrderedDict([('spectrum', [102.05569420159664, 361.15913353855615, 919.3969300083394, 115.56003331736318, 386.6695001547912, 166.08719971441786, 448.21782892715936, 836.3616072537686, 937.4079246872171, 354.65668099000055, 418.68369555117414]), ('abundance', array([3.77577784e+02, 2.30271705e+03, 1.48250999e+03, 7.50063023e+03,\n 4.72459190e+02, 9.09639292e+01, 4.53507642e+03, 1.52315395e+04,\n 1.04960774e+04, 2.06764394e+05, 6.86710644e+02])), ('precursor_mass', 469.20783625)])\nOrderedDict([('spectrum', [51.53074601138156, 460.2015691501538, 132.10158201975844, 279.16998596403835, 376.22126496453916, 188.61559665615616]), ('abundance', array([ 1540.33874417, 2596.73750036, 839.44213696, 10561.45006512,\n 22583.8987417 , 2329.02366258])), ('precursor_mass', 525.74986825)])\nOrderedDict([('spectrum', [102.05545568149257, 919.3991227359003, 1160.5764157433873, 460.20104319231444, 147.11315688185053, 260.19443406911284, 632.3762326294215, 689.3969123118401, 818.4438687573887, 1077.5377150635304, 74.06142971234716, 204.13560155350618, 252.6478972840877, 345.2033259578947, 475.2439479416195]), ('abundance', array([1.76034479e+01, 5.65391029e+02, 8.09621697e+02, 2.95952366e+03,\n 1.39677173e+03, 6.87816591e+02, 4.59907454e+02, 3.53946382e+03,\n 5.84859701e+03, 1.95166482e+03, 2.67584075e+04, 3.61196857e+03,\n 8.71267098e+03, 3.27114019e+02, 4.80774248e+03])), ('precursor_mass', 589.79734975)])\nOrderedDict([('spectrum', [1247.6049874431426, 580.7948077538254, 106.04917579489431, 234.13778187749526, 591.3522192540405, 1265.6198010269145, 388.71788458750814, 582.7875296655881]), ('abundance', array([1232.36729882, 3867.67568136, 250.37901729, 213.04434901,\n 2508.75894247, 4797.63385518, 448.61338116, 506.04578909])), ('precursor_mass', 633.31336375)])\nOrderedDict([('spectrum', [230.11161586541687, 547.2177789031292, 274.1131008191861, 688.8295931615053, 476.2689378949281, 848.4511187158155, 118.04758069420288, 312.1735838259873]), ('abundance', array([ 431.41942381, 772.73346446, 1427.36581777, 9317.58810466,\n 13673.43689387, 19161.81423632, 2707.08930753, 8382.34477422])), ('precursor_mass', 697.83466025)])\nOrderedDict([('spectrum', [230.10871725072008, 338.14340936843337, 624.3072874422668, 680.3621591429346, 1222.5778472879022, 103.0385205467516, 611.789425891749]), ('abundance', array([ 537.128823 , 1554.00439645, 20260.1634842 , 10530.60927383,\n 2081.61528613, 4975.6651747 , 2937.65284506])), ('precursor_mass', 726.3453922499999)])\nOrderedDict([('spectrum', [281.1200381499183, 116.07447522539788, 244.128838381101, 430.1946180593827, 561.2352739044478, 790.3401007463776, 151.0784258511061, 215.59792418664023, 281.1198339356993, 345.1490134329149]), ('abundance', array([ 2624.63720077, 3421.96229348, 20789.0158315 , 746.05326679,\n 200804.26807452, 4459.61507082, 3020.23132565, 727.61957352,\n 985.75307054, 682.36489285])), ('precursor_mass', 431.1921862500001)])\nOrderedDict([('spectrum', [618.2550781755556, 746.3135454252226, 87.04842246480402, 151.08528929622193, 166.0860314764076, 708.3027503042129, 1008.4466846850644, 83.55050115507385, 196.10260386380654, 224.61451817635768, 418.6854100705717]), ('abundance', array([20169.3039895 , 2061.82477808, 7139.09902903, 438.53504231,\n 26012.57814065, 937.48560551, 267.99742992, 483.7711233 ,\n 2422.409456 , 2306.34920933, 126.96351963])), ('precursor_mass', 504.72639325000006)])\nOrderedDict([('spectrum', [301.1486311383734, 432.1900575079341, 746.3135414785875, 87.05143609523857, 216.6040812671023, 281.11597858520156, 309.6356189298308, 373.66052196154493, 552.2623666818163, 279.17590704721505, 376.2203194635481, 188.61510668742983, 252.64459777889084, 345.67692054812784, 411.19648895537233]), ('abundance', array([ 13213.371371 , 532.07577746, 482.79126388, 8419.96869246,\n 7201.45707979, 359.4481933 , 66623.78687856, 878.77721887,\n 25351.06854945, 13516.28534232, 3541.50994862, 660.87520857,\n 2283.07991012, 201792.6066747 , 611.97061338])), ('precursor_mass', 561.2684252500001)])\nOrderedDict([('spectrum', [1231.613598256166, 36.52582434769061, 87.04920530139282, 422.1860068687485, 495.720107504797, 504.3203925281551, 818.4402070104808, 949.4807738967635, 1077.537244211819, 1178.5847117650421, 1249.6240306076409, 74.06037526565304, 409.7237103753083]), ('abundance', array([5.79726400e+02, 4.93747405e+03, 1.61305279e+04, 3.53537624e+02,\n 5.52719015e+03, 4.74852269e+03, 6.03736126e+03, 1.01991798e+03,\n 4.59962872e+03, 1.60137169e+04, 3.55909476e+03, 8.69002890e+04,\n 2.90256384e+01])), ('precursor_mass', 625.3159067500001)])\nOrderedDict([('spectrum', [281.12407392761963, 719.4071303628779, 117.57563642579048, 247.65203034263837, 518.7569950758208, 633.3146008818347]), ('abundance', array([ 392.81232249, 23414.77624666, 286.37075006, 482.49147123,\n 147.55869259, 5322.4695937 ])), ('precursor_mass', 668.8319207500001)])\nOrderedDict([('spectrum', [561.2376052622528, 746.3132636510264, 843.3670576268864, 1103.5199198327698, 1231.6135745441677, 1318.6450750592312, 36.52578815750633, 422.18646673641007, 659.8267982985365, 363.1852610576445, 848.452182256149, 1034.5144708732896, 1293.613157758203, 312.17235099824217, 733.3548386407089]), ('abundance', array([2.73201669e+03, 2.05657927e+02, 1.35855419e+03, 2.24847849e+04,\n 5.40412555e+03, 1.29739088e+03, 5.62014947e+03, 1.20770075e+03,\n 2.31382046e+03, 3.78282106e+04, 1.33479410e+03, 7.21616122e+05,\n 1.49196120e+03, 3.31232172e+02, 4.21948757e+04])), ('precursor_mass', 733.3532172500001)])\nOrderedDict([('spectrum', [72.0431203100483, 173.09598704519212, 432.19045054227416, 618.2579039730414, 746.3126258495024, 1103.5179652689394, 1504.7097519863607, 36.52433536158765, 281.1205168688269, 309.63214977923764, 422.1889098371416, 752.8573356279129, 292.1146308279785, 1451.6826294558996, 38.52617700004105, 146.56512566448322, 210.61001381999853, 453.24069568871244, 675.8207786569177, 726.3455441019397]), ('abundance', array([6.78856200e+03, 4.26593250e+03, 4.85414806e+01, 4.58981858e+04,\n 5.84581477e+03, 3.88993375e+00, 2.88819018e+02, 1.56962354e+04,\n 1.40309584e+03, 3.60894898e+03, 3.20964795e+03, 2.17298964e+03,\n 1.78202217e+02, 1.72840232e+02, 6.30041640e+02, 7.04902173e+02,\n 2.57601075e+01, 2.52471566e+03, 2.39173110e+04, 7.07602230e+04])), ('precursor_mass', 761.86394925)])\nOrderedDict([('spectrum', [400.21757393418756, 423.19477255984566, 471.7250575190774, 430.1927899539641, 861.3757930757872, 122.56867982624156, 395.6722423045592, 480.72755224617947]), ('abundance', array([ 895.31199701, 7249.90132838, 3617.74102578, 3474.37521044,\n 2592.17189825, 439.727196 , 1919.90056638, 202.76549929])), ('precursor_mass', 480.72639325000006)])\nOrderedDict([('spectrum', [100.07608850032463, 272.16201322032015, 400.21668992015054, 660.299060766688, 845.3832011592214, 1089.5024665806295, 266.1335578913464, 545.2533048552259, 263.1397817784318, 708.3046606960896, 836.3574685238715, 937.4108295563116, 132.0718068773648]), ('abundance', array([4.06456769e+03, 7.63290362e+03, 1.85035076e+03, 5.77159080e+03,\n 9.75197524e+02, 1.53336482e+03, 1.54423725e+03, 2.18809280e+01,\n 8.92291987e+05, 4.60266014e+03, 2.49824837e+03, 8.93862154e+02,\n 1.55903091e+02])), ('precursor_mass', 554.26060025)])\nOrderedDict([('spectrum', [100.07386386681401, 1202.5875399828137, 86.05770339455756, 132.10402645418853, 376.22131193201744, 821.3872853321118, 1121.529420242487, 188.61457773268586]), ('abundance', array([ 912.82988835, 1166.78072511, 128.50105016, 657.53415319,\n 3962.34234254, 182.3660508 , 10441.67684317, 7567.06046843])), ('precursor_mass', 610.80263225)])\nOrderedDict([('spectrum', [400.2197667218726, 845.3823559561415, 942.4312745049149, 50.542333574624756, 86.06224448750669, 471.7234789402105, 204.1355481493692, 345.2057544719569, 475.2437194080638, 674.8482771398936]), ('abundance', array([1.22914513e+04, 1.82117560e+02, 2.67663478e+03, 1.30433496e+03,\n 7.25357823e+04, 6.11553117e+03, 5.88209123e+05, 1.79045030e+04,\n 1.10453481e+03, 1.08830331e+03])), ('precursor_mass', 674.85011375)])\nOrderedDict([('spectrum', [942.438609443363, 1089.5089010473012, 86.05674738870401, 591.3487335144691, 776.4306325852267, 905.4724828246391, 1336.654619492065, 117.57600204473238, 247.6532131727159, 296.1829446381131]), ('abundance', array([8.08253580e+02, 1.13053860e+04, 1.66537707e+02, 2.09938223e+03,\n 1.95505768e+02, 2.40936998e+03, 1.80531713e+02, 3.98179513e+05,\n 1.15782463e+04, 5.85361852e+02])), ('precursor_mass', 718.36612775)])\nOrderedDict([('spectrum', [1330.6708498941987, 601.7980504656142, 905.4727267710509, 424.72680673583704, 583.2820831028037]), ('abundance', array([ 584.79479718, 1537.65705574, 201.8856247 , 4056.89396387,\n 6316.26538638])), ('precursor_mass', 782.88742425)])\nOrderedDict([('spectrum', [100.07821531813575, 171.11375346995328, 400.220075570127, 531.2649348248717, 1417.7141317030032, 1546.7565788432128, 1603.7758628452887, 136.58818708215477, 200.6144502095615, 266.1319327029913, 330.658580164182, 359.1626124260431, 545.2551883329829, 773.8806546822806, 76.03804780037417, 292.1124457532245, 533.2893702473513, 905.4731859523828, 1350.6350613860764, 1451.6808723635227, 1522.7215992539668, 1621.7862091544703, 146.56178252888205, 267.14680039997745, 675.8218917629368, 761.8653170858436, 811.3933372579754]), ('abundance', array([ 1133.90030622, 4702.98779893, 3338.93890136, 35414.95139704,\n 7983.95687069, 35737.30482537, 105824.01970697, 692.46043536,\n 400.54848525, 5976.32458395, 86618.89813877, 3274.87238555,\n 129.07778857, 12661.83629465, 7617.52369757, 2759.215658 ,\n 2958.71070495, 234.13861685, 1402.08546631, 2569.67360917,\n 234.9736378 , 357.22823112, 444.59386002, 10067.18769673,\n 1739.38340969, 11122.62328693, 275.92896194])), ('precursor_mass', 811.3981562499999)])\nOrderedDict([('spectrum', [114.09172792804492, 385.2427668616196, 513.3038828169153, 57.54869022364121, 107.08642212603293, 142.59952413113564, 479.73861455020227, 430.19496113420905, 790.3410285907888, 58.53953228340083, 122.5648001577924, 151.0795998437938, 345.14872191327254, 395.6733417899982]), ('abundance', array([ 295.06948982, 44.60996987, 664.50521779, 479.08481231,\n 3631.5364701 , 2249.35439304, 780.66107722, 10571.43733331,\n 839.93376892, 699.22963421, 12912.54978106, 3923.94742072,\n 2312.48417694, 1713.51430341])), ('precursor_mass', 537.2684252500001)])\nOrderedDict([('spectrum', [284.1946102278734, 385.24491970394945, 773.3872579032335, 830.4098244702501, 1055.5186480507057, 387.1995654832563, 415.70717760933013, 601.7960710645004, 166.08741292945993, 708.3030575904404, 937.4086928815395, 1008.4437719253895, 224.61337191919813, 354.6517807760746, 504.73183817120395, 554.25897458055, 610.8030285486858]), ('abundance', array([73993.93738017, 2720.46215105, 5505.17476436, 1367.0698158 ,\n 3508.54319261, 3196.66623155, 77.14962089, 7446.28418961,\n 18724.88609205, 1448.44957862, 1300.58619472, 2375.24846729,\n 9070.98654034, 6766.05254305, 520.36528196, 18031.96151362,\n 1735.04378744])), ('precursor_mass', 610.8026322500001)])\nOrderedDict([('spectrum', [114.09421816350553, 773.3847159930564, 387.2008831493412, 528.2629904075911, 690.3455225374136, 281.161266707088, 561.2649425215247, 610.8001438172197]), ('abundance', array([6198.02338613, 907.08439935, 7140.80356846, 2226.52981697,\n 568.24885179, 182.71461689, 571.69566091, 3995.55608234])), ('precursor_mass', 667.34466425)])\nOrderedDict([('spectrum', [114.09107582164604, 284.19925024672546, 385.24565415702824, 644.3467793236612, 830.4095487941106, 958.4671329518674, 1202.5922009587741, 1443.7654938995706, 57.551165151660086, 142.60089478931857, 528.2622883689935, 722.3859900684748, 260.1968356552784, 407.2658634785875, 504.3174203248104, 689.3973026488331, 818.4409758011302, 1077.5394420695368, 1249.621785993384, 130.5929251363233, 204.13689006155482, 252.66108207773777, 475.2433427928613, 539.2741500180008, 625.3173538423105, 674.8506260100722]), ('abundance', array([ 1305.67299879, 6256.69880078, 131.07196965, 1476.55160455,\n 2500.33582622, 135.54554256, 4420.81874247, 1571.13055041,\n 684.1061192 , 205.07374602, 459.66277952, 13517.34408435,\n 873.14333462, 3169.11898126, 12361.7629775 , 2446.35097212,\n 706.06088292, 1131.01198111, 1882.74128719, 4898.20209068,\n 2365.6861306 , 209.5860154 , 247.65219477, 94633.58096102,\n 1348.94697753, 5913.33892466])), ('precursor_mass', 731.39214575)])\nOrderedDict([('spectrum', [513.3039100640929, 644.3433028458896, 1055.5236860115276, 57.54859233485326, 107.08777278886527, 193.12625425117906, 415.70641374173465, 106.05034825127777, 1265.618473074824, 1336.666705364617, 53.53070316927839, 296.184999264831, 582.7930524617742]), ('abundance', array([3.43401250e+04, 3.51490852e+03, 2.51617410e+04, 6.04556530e+03,\n 2.10518174e+03, 3.01241590e+03, 8.72228595e+03, 4.10067000e+03,\n 2.85642376e+01, 1.21181534e+02, 4.26694495e+03, 1.07403763e+04,\n 1.89168996e+04])), ('precursor_mass', 774.9081597500001)])\nOrderedDict([('spectrum', [213.16215346485143, 284.1980522549916, 644.3490348815553, 1055.5165425896794, 1202.5880701181813, 1659.8420261913564, 107.08939343788063, 658.340728718849, 722.3864975690669, 830.4224903572814, 363.18834132599613, 905.4718327537174, 1034.5137297818094, 1165.5552981511876, 1564.7659539484412, 1677.8510632044351, 453.2372192877123, 697.8300843850423]), ('abundance', array([1.24751611e+02, 2.61764679e+03, 3.79359408e+04, 8.39487567e+02,\n 1.15805396e+03, 1.35297224e+04, 4.29507677e+03, 1.45022588e+03,\n 2.90262743e+02, 4.62707703e+02, 3.69946854e+05, 2.33323992e+03,\n 6.39484659e+02, 3.14397438e+03, 5.93199615e+03, 5.53438045e+03,\n 4.79001929e+03, 4.44116859e+02])), ('precursor_mass', 839.42945625)])\nOrderedDict([('spectrum', [773.3845603636667, 830.4090043760402, 958.4639078984017, 1315.6707758575546, 107.0824882529192, 142.60377011739882, 322.6765444230111, 387.1996203091325, 415.7101979993768, 479.73664766745463, 858.9307964676982, 680.3633374875441, 777.4106105437234, 962.4941775923495, 1222.5778633965458, 1350.6366033361826, 1621.786628314171, 1734.872820447285, 38.52292831466029, 340.6776230939245, 453.24453799019136, 675.8204147243443, 726.349190080231, 761.8642068584893]), ('abundance', array([3.86663925e+04, 1.54386439e+03, 3.57805640e+03, 6.19156645e+02,\n 8.60473466e+04, 4.51871302e+03, 3.45557708e+02, 1.05761963e+03,\n 9.09916274e+02, 1.43429034e+04, 2.40398573e+02, 6.95419998e+02,\n 6.57512003e+03, 4.84550218e+03, 1.08820729e+04, 3.15387138e+04,\n 2.17605399e+05, 5.56049260e+03, 3.56400054e+03, 1.01373128e+02,\n 1.03498816e+03, 7.45647359e+00, 1.46317144e+02, 1.21137843e+03])), ('precursor_mass', 867.94018825)])\nOrderedDict([('spectrum', [72.04445430397874, 185.1279088147804, 355.2331492044759, 456.2840238308903, 844.4245842024145, 93.06768682257885, 228.64584154900444, 358.19240640947925, 422.7129350229234, 430.1941614466858, 1073.529981752631, 215.5943045131434, 281.1177142994624, 345.15175775998995, 431.1923416032863]), ('abundance', array([10134.64654969, 21848.1853157 , 20370.36188715, 1437.79944066,\n 120.53926728, 1845.80389609, 2323.83269935, 3350.6107668 ,\n 2277.90225966, 191.8153076 , 392.46919455, 5658.86478067,\n 874.75132069, 900.58870694, 2321.40163093])), ('precursor_mass', 572.78698225)])\nOrderedDict([('spectrum', [284.19722376442195, 456.28503068988783, 844.4212967700453, 1029.5057159371727, 178.12029737902566, 422.7154744461353, 563.7766882139227, 836.3608485286038, 1291.6355446154469, 354.65513792195327]), ('abundance', array([1.13103269e+03, 1.02259823e+02, 2.53789290e+03, 1.72023765e+03,\n 1.25118463e+05, 6.56118735e+03, 8.21284026e+02, 1.05082074e+04,\n 1.36084445e+04, 5.25259799e+03])), ('precursor_mass', 646.3211892500001)])\nOrderedDict([('spectrum', [72.04300958313983, 901.4455810589061, 292.6759515688846, 1404.7187521667427]), ('abundance', array([ 590.05636344, 4968.08029097, 5465.4205135 , 459.84725521])), ('precursor_mass', 702.86322125)])\nOrderedDict([('spectrum', [456.2844436357696, 584.3387536540077, 715.3811654169436, 844.4243972422486, 901.4473105836705, 36.52856056473028, 142.6024958714717, 228.63558394868036, 147.1115263776609, 632.3777527064121, 74.05959011027474, 345.20742449605564]), ('abundance', array([2.71790976e+03, 1.24223178e+03, 1.35514762e+03, 6.69378868e+02,\n 2.18927777e+03, 1.08719144e+03, 1.37361470e+05, 4.28906974e+01,\n 1.88151404e+04, 1.69793605e+03, 2.22361140e+02, 1.34929973e+04])), ('precursor_mass', 766.91070275)])\nOrderedDict([('spectrum', [72.04348180046989, 584.3364903480432, 1273.6264510988156, 1386.7106116322989, 93.06539764905108, 142.60166655249617, 178.11762674084073, 228.6427264806876, 292.67338471706154, 358.1932361533631, 422.7155516091461, 637.3153631244529, 801.4219128706164, 591.3510762604071, 719.4090441833828, 776.4290469171382, 1036.516259005295, 1548.8089259033707, 1619.8490915954, 810.4271047112555]), ('abundance', array([ 2816.99306938, 3932.04178877, 2169.51771805, 992.73398643,\n 195.68255216, 1363.74374377, 25153.05804302, 1577.31172273,\n 664.15027234, 1212.45660706, 3080.61259822, 988.9580816 ,\n 6241.99996325, 2116.8127916 , 1344.47670313, 209.07902049,\n 31572.73815275, 51.63445423, 1225.66068149, 1076.8578312 ])), ('precursor_mass', 810.4267167500001)])\nOrderedDict([('spectrum', [185.12614965615342, 284.1935758214185, 715.3830593484873, 901.4450828774085, 1126.556874801225, 1386.7082631357657, 1514.80484298068, 142.60167992296437, 358.1938871316507, 422.7151309690975, 235.09292693636675, 476.26879638924925, 1034.5119236754977, 1165.5556404697434, 1394.6624721655735, 424.72536069451957, 453.2401513301056, 517.7641641633583, 647.3101482197053, 874.9507578360638]), ('abundance', array([1.60933540e+04, 3.15091348e+02, 1.06266724e+04, 1.31239402e+05,\n 5.05828938e+04, 1.79661248e+02, 2.15248851e+03, 1.20370175e+04,\n 1.89728435e+03, 1.43243456e+03, 2.08878585e+04, 3.01524956e+05,\n 1.86242503e+03, 1.36366983e+03, 1.69787978e+02, 1.01036199e+03,\n 5.10948221e+03, 2.55253874e+03, 1.77222981e+03, 2.76784070e-01])), ('precursor_mass', 874.9480132500001)])\nOrderedDict([('spectrum', [715.3801001331489, 844.4209534222174, 1126.5592204012603, 36.52452270182998, 142.60329812022695, 178.1190668302314, 292.67450314762567, 515.253122112526, 693.8560901482845, 801.4222478086461, 865.9421400664506, 76.03846964451344, 533.2924748099106, 680.3613510237902, 962.4918678962251, 1734.8729365292072, 210.6095126441966, 340.6878181952577, 389.20931534984425, 611.7946139022715]), ('abundance', array([ 1322.24316167, 424.34080185, 2546.30653971, 4940.44964093,\n 261.94043721, 1774.1486904 , 68.72526456, 2251.72834336,\n 6495.13792997, 5128.57725517, 2279.83173458, 2897.24311675,\n 122.47329082, 12565.57046553, 3944.9038386 , 5866.42052143,\n 10761.09205479, 500.09774959, 106.67818744, 4029.71591021])), ('precursor_mass', 903.4587452500001)])\nOrderedDict([('spectrum', [228.14295590793188, 871.4803720780119, 1000.5253222482535, 306.69187518125204, 370.7256290900596, 561.2353943348683, 689.2918541516252, 1144.565018538914, 281.11757465674145, 431.19524913112457, 480.72533268959694, 572.7896981002511]), ('abundance', array([ 212.44704171, 54758.88740731, 16850.39500683, 83890.65809686,\n 18468.98187591, 1435.02069751, 11452.55611152, 2182.88472911,\n 151.27068915, 560.18039718, 1056.37833047, 1078.22165254])), ('precursor_mass', 650.83753775)])\nOrderedDict([('spectrum', [157.10871317403954, 740.4428726064082, 871.4817868235181, 1429.7232637665436, 79.05541218901473, 114.57707704859077, 171.1172066493442, 306.696897975769, 500.76509781485396, 529.2747254654906, 708.2973483979365, 1008.4436478254685, 1107.5120956956564, 1220.6000953134173, 1291.6327923487356, 83.54340686145179, 132.07401723160933, 224.61549456622376, 289.1346530305266, 354.653795712583, 554.260959423999, 610.8018825644947, 646.3187741004091]), ('abundance', array([ 2551.05086859, 19583.33465212, 2407.6230014 , 474.31944697,\n 106.77958583, 1764.44332064, 1321.44872128, 3883.94509528,\n 1095.4085439 , 1365.35252852, 78756.00516643, 1751.86724566,\n 2992.35885431, 1223.61546169, 485.70426886, 5419.14854894,\n 1437.18892052, 1371.21321605, 373.56828762, 239.60437615,\n 1094.44885444, 103.1538324 , 3566.42442444])), ('precursor_mass', 724.3717447500001)])\nOrderedDict([('spectrum', [228.1475661086765, 220.65473198823264, 500.7669547048181, 593.3044127991506, 66.55432713841705, 188.61495674897418, 252.64447394597514, 561.2677139695858, 667.3438795266629]), ('abundance', array([4.52918982e+03, 5.67254870e+03, 1.30221136e+01, 3.99633190e+04,\n 6.43895455e+03, 7.17503453e+02, 3.66438147e+03, 1.68808020e+04,\n 1.26581236e+04])), ('precursor_mass', 780.91377675)])\nOrderedDict([('spectrum', [157.1089643823447, 228.14477384737594, 341.2305180781929, 612.3820175716403, 1000.5246932669767, 1282.6573486630232, 114.57243877531364, 171.11835422975122, 220.6526109880566, 256.171053119868, 306.6955719411912, 370.7211955544487, 436.2436450243093, 593.3056071568025, 835.9578946297788, 260.20106584576956, 1077.5370931638795, 589.7995087377303, 674.8490367070603, 844.9607690314153]), ('abundance', array([ 2786.2700418 , 58516.24155375, 7566.48076738, 184.53519277,\n 1299.93465233, 116.55519061, 2903.45930314, 557.70206012,\n 562.6883733 , 3601.75029661, 3484.12529257, 712.61907748,\n 937.07747822, 1034.7467685 , 1612.73339079, 500.00284369,\n 276.52090379, 3831.78283069, 1877.31910038, 1747.2269753 ])), ('precursor_mass', 844.96125825)])\nOrderedDict([('spectrum', [157.10852012836432, 341.22934766307003, 1000.5288556815201, 1185.6044970157523, 1429.7275451961514, 1670.903892817321, 79.06254344365931, 114.57483567623485, 256.1716894905276, 500.7667633513806, 593.3051727832099, 591.3498100540475, 905.4724636955231, 1036.5128660502073, 1775.9493820422347, 53.53073300490174, 360.2052012119697, 774.9080531575362]), ('abundance', array([9.13344020e+02, 2.23155071e+04, 5.38605410e+03, 2.72091237e+02,\n 1.63741999e+04, 2.56809831e+02, 7.05838087e+05, 1.17178147e+04,\n 7.14085479e+02, 8.13854984e+03, 6.77683639e+03, 3.65193804e+03,\n 3.59399308e+03, 2.80780811e+03, 2.33878828e+03, 3.59997729e+02,\n 3.49853386e+03, 5.82087629e+02])), ('precursor_mass', 888.47727225)])\nOrderedDict([('spectrum', [440.2975437034097, 612.3827860355342, 740.4416175694273, 1057.54547955142, 1429.7222690805381, 79.05843220706892, 114.57871148427681, 306.69708455119684, 436.2459426634667, 363.18791289216387, 1034.5153660631877, 1465.696643285379, 1564.7664171714941, 182.09687526998133, 453.2348841076874, 839.4280755267698, 953.0015870782634]), ('abundance', array([1.35538986e+02, 7.94221280e+02, 1.18533876e+04, 7.64134417e+03,\n 7.22961938e+02, 1.25184349e+03, 5.43351912e+02, 8.68939386e+00,\n 8.92318213e+03, 3.40812243e+02, 3.12790885e+02, 5.72191719e+04,\n 1.34097069e+03, 2.75737017e+02, 6.05735162e+03, 1.14154900e+03,\n 1.62861746e+03])), ('precursor_mass', 952.9985687500001)])\nOrderedDict([('spectrum', [440.2975815640483, 740.4399822106361, 1057.5454616372388, 1282.658214804748, 1886.9783661714587, 306.6951171672164, 593.3058854114761, 943.9936787526399, 962.4957503362544, 1805.9112138283965, 146.56121124458141, 675.8223644228746, 761.8627536106634]), ('abundance', array([ 2021.15134619, 16496.717404 , 9813.10409301, 97.43998945,\n 2776.63462408, 9069.87913401, 572.1307375 , 492.08513592,\n 2297.37357967, 25186.35584476, 183.98980012, 5573.76745158,\n 3146.10424828])), ('precursor_mass', 981.5093007500001)])\nOrderedDict([('spectrum', [171.1113788700285, 447.22466509089406, 50.54180375600497, 86.05468798171643, 224.11381931968293, 76.04228145072724, 223.10705008155145, 499.2200577453691, 38.524787431545086, 250.11389378138617]), ('abundance', array([9.56358253e+03, 2.54828768e+02, 1.12260319e+04, 1.58291934e+04,\n 3.13877543e+04, 6.16331518e+03, 4.31207095e+04, 1.54527803e+03,\n 1.77877814e+02, 2.92510721e+01])), ('precursor_mass', 335.16576525000005)])\nOrderedDict([('spectrum', [171.11672484901538, 594.2943065716647, 86.05934830807809, 189.12613656418696, 683.3377744297541, 168.59829738871963]), ('abundance', array([3830.57946756, 2726.97326778, 389.07343052, 8739.22229265,\n 1508.87756144, 1125.6011969 ])), ('precursor_mass', 391.70779725000006)])\nOrderedDict([('spectrum', [100.07923304540925, 300.1564499640792, 867.4057716402381, 50.54155087961438, 224.11718746273672, 122.03039488059505, 235.11108457461623, 439.20185405904664, 885.4141539436908, 220.10661771394956]), ('abundance', array([ 1104.43092897, 82852.72356984, 149716.20153882, 949.15091384,\n 1526.04883293, 1164.09264447, 949.65740601, 505.24247176,\n 4940.27054202, 6149.25820542])), ('precursor_mass', 443.21238975000006)])\nOrderedDict([('spectrum', [171.1028925764542, 966.4786277319209, 50.540721704843925, 224.11496808136357, 434.2040815913815, 483.74283164093146, 334.18700099091245, 391.2002908862996, 885.4181311711823, 167.5929299063739, 269.6389125273729, 343.17035553957226, 492.7453119058225]), ('abundance', array([ 3418.73215202, 384.4054376 , 222.17015371, 12255.20203617,\n 2997.46259345, 1120.5313265 , 68.5567065 , 2454.95222551,\n 1107.87486594, 2268.74934287, 855.60657139, 624.78433117,\n 14716.54760687])), ('precursor_mass', 492.74659675000004)])\nOrderedDict([('spectrum', [100.0752336248396, 171.11216913648676, 300.15555546893046, 1079.5583395839021, 86.05682580867416, 540.2867235210912, 231.16826066398048, 998.4992950671144, 66.55432270745916, 116.08789149782172, 167.59325634669204, 224.13468719678093, 252.6452311038554, 464.2348921061518]), ('abundance', array([ 535.23737208, 5122.19487658, 10285.26477213, 815.05692195,\n 2101.96425757, 9804.85481265, 3944.53073181, 1971.07975864,\n 4728.40257348, 8710.88810159, 438.34357827, 3107.69396216,\n 2577.96559948, 45861.29080897])), ('precursor_mass', 549.28862875)])\nOrderedDict([('spectrum', [100.07422579745511, 300.1557409339696, 447.2268318128835, 594.2936056186694, 651.3133840761072, 966.4741946700672, 1079.5620613648443, 86.05996666731984, 590.805572475211, 233.14317500696205, 435.22519679225985, 548.3064979205027, 899.4700098023326, 1099.550043672522, 1198.6187145143763, 60.5361628481096, 218.11647285670813, 376.70554649675626, 550.2767116535513, 599.8118949308943]), ('abundance', array([ 2013.7772074 , 2135.14437652, 388.02705915, 572.59729905,\n 117345.93507785, 373.42695009, 1208.36530768, 4887.43665586,\n 9358.73522017, 695.74230959, 8618.2702829 , 247.74090385,\n 22590.86313614, 11159.88713681, 225.99982805, 350.30499306,\n 6099.38063742, 591.39016954, 183.64735035, 4603.31238996])), ('precursor_mass', 599.81246825)])\nOrderedDict([('spectrum', [594.2950081240552, 764.3986493445426, 867.4069157500179, 224.11782176092143, 434.20612294354385, 590.8053682711563, 867.4324617937891, 1313.6450496295527, 67.52520290513773, 174.5904028478815, 360.6832061972202, 572.273556266685]), ('abundance', array([ 433.06851038, 1913.13222664, 14303.16624531, 5245.5592745 ,\n 2748.07113478, 108141.16745877, 3966.5831224 , 785.47820385,\n 1832.08868681, 5469.34693495, 8004.95693753, 1650.22755993])), ('precursor_mass', 657.3259397500001)])\nOrderedDict([('spectrum', [575.2857098641325, 114.57361628599863, 370.17477377887934, 499.21980532561093, 669.3232880471168, 38.522633162247836, 112.05727479785497, 185.59235726634145, 335.1691308062451]), ('abundance', array([ 9078.40323865, 11709.21144446, 837.22310341, 1739.92136384,\n 454.98272249, 4384.44754861, 682.13583554, 7817.45235674,\n 297049.45876305])), ('precursor_mass', 399.19505425)])\nOrderedDict([('spectrum', [722.3510904163306, 65.03424965464114, 150.08897176414055, 214.6105868899882, 288.1464443230037, 361.6830151976867, 390.1896411708408, 132.09653482401828, 483.2590524728205, 910.4663109199471, 306.6539380977268, 391.70489055784606]), ('abundance', array([5.33623868e+03, 6.09305678e+02, 1.14650834e+03, 2.01807937e+03,\n 5.62224446e+03, 2.43215675e+03, 2.53250719e+04, 7.41901057e+02,\n 1.78303739e+03, 6.43244810e+02, 2.79492570e+03, 9.86901553e+00])), ('precursor_mass', 455.73708625)])\nOrderedDict([('spectrum', [299.172345018443, 361.68061491175723, 498.2410767965549, 122.02756013895836, 439.20125596665144, 885.4163366886837, 146.56930519518926, 293.6387679601791]), ('abundance', array([ 1571.13435415, 1406.25655408, 9377.72507789, 11815.34376296,\n 2978.43404919, 1098.38916105, 9306.15782192, 1869.93280689])), ('precursor_mass', 507.24167875)])\nOrderedDict([('spectrum', [129.0667280671103, 228.13288316851038, 575.2835391092505, 1094.5345409107902, 390.1902653132028, 446.7218720631153, 547.7714602832348, 221.0985061506804, 538.2653738133977, 443.2114627174614, 492.7525964098806]), ('abundance', array([1.76292807e+01, 8.37300114e+05, 7.65336384e+01, 3.54483686e+03,\n 3.54544006e+02, 9.37784602e+03, 2.16672130e+04, 7.67314109e+03,\n 3.54038591e+02, 1.89985577e+03, 8.40659412e+01])), ('precursor_mass', 556.77588575)])\nOrderedDict([('spectrum', [575.2861913780916, 150.08904652740875, 214.60948787139858, 604.3103582553734, 504.2850029772513, 998.5008449900251, 499.75343829408826]), ('abundance', array([ 933.11218453, 2627.97563016, 23982.53130418, 17551.38276366,\n 125121.95949247, 1306.62543083, 1246.8620144 ])), ('precursor_mass', 613.31791775)])\nOrderedDict([('spectrum', [228.13024907712088, 779.3728440928325, 892.4647949481658, 995.4651942791068, 1207.616654705911, 65.03974443223255, 654.8394005779305, 233.14565158798007, 332.21504765125576, 60.53313004104389, 450.2288119529764]), ('abundance', array([ 12857.58736136, 778.15554541, 159.109291 , 7836.70619781,\n 1147.17327918, 2172.3281544 , 26427.80296777, 101974.27962995,\n 6782.15646507, 2032.42300018, 8356.83312823])), ('precursor_mass', 663.84175725)])\nOrderedDict([('spectrum', [428.2125058791204, 722.3478724658462, 1094.535712408228, 446.7318160439572, 604.312096016203, 654.8373966596541, 134.05257004141612, 348.1762200690429, 1014.4949116816987, 67.52743209797747, 118.05031839518924, 224.12186731782336, 360.68254554497463, 507.7506411952299, 607.7918870571157]), ('abundance', array([2.31331251e+03, 4.90206765e+02, 1.78725060e+03, 3.68359478e+03,\n 2.91047136e+04, 8.16587636e+02, 5.71542382e+02, 1.00377779e+05,\n 5.53391071e+02, 3.37656884e+02, 2.16864501e+02, 3.48959939e+03,\n 1.83254093e+03, 8.21199705e+01, 1.13484078e+03])), ('precursor_mass', 721.35522875)])\nOrderedDict([('spectrum', [116.03908945150125, 244.09090318787597, 343.16121232372495, 837.3756906372489, 345.6596933027943, 419.19423141903167, 76.04137788630531, 499.219185958957, 797.382547522296, 38.52269918316573]), ('abundance', array([1.22232070e+05, 1.40675721e+04, 3.69648311e+03, 1.35552193e+04,\n 5.40913730e+01, 2.55100850e+02, 2.53935326e+03, 8.40401279e+02,\n 2.93792044e+03, 2.51166356e+02])), ('precursor_mass', 456.70852575000004)])\nOrderedDict([('spectrum', [543.2438099632027, 894.3987220920832, 1007.479403790875, 58.52139828142753, 272.1210604967827, 419.186931929531, 504.24464738894943, 189.12316201627607, 910.4646014775277, 66.55441344740494, 391.7090262488612, 513.2536534161809]), ('abundance', array([ 542.57134527, 517.58062129, 1619.94681848, 2588.92257354,\n 326.99378858, 2051.17597463, 16976.95468858, 3608.21796114,\n 2320.37099809, 1902.2437918 , 180.82232013, 20.92023923])), ('precursor_mass', 513.25055775)])\nOrderedDict([('spectrum', [543.2419838198854, 1007.4803050323783, 207.59561169775574, 272.1231775270658, 715.3165157108685, 1128.5032021681182, 61.51772161408459, 358.160575325043, 507.24399847778545]), ('abundance', array([ 59.62177749, 2883.93982205, 39701.43306811, 2637.27502199,\n 1384.1374716 , 109.50139659, 584.98227968, 1471.13947793,\n 5735.76334676])), ('precursor_mass', 564.7551502499999)])\nOrderedDict([('spectrum', [343.1625920060198, 414.19837973466053, 1110.4878542788292, 58.52456862866935, 122.54852363491041, 447.7033560782068, 605.283352972061, 118.09085917447976, 814.3805680470723, 984.4843550885184, 59.5456404244543, 111.05098138697865, 167.59254363674816, 443.2130750789321, 492.7487541768462, 614.289534693085]), ('abundance', array([ 10793.35371311, 754.75722553, 425.02997222, 334.09890506,\n 13065.02901243, 4121.54071038, 1271.94231363, 517.53470072,\n 27542.349129 , 10341.97447573, 1732.9721517 , 110522.79638035,\n 745.09237087, 691.03722156, 31845.82572046, 19891.10110506])), ('precursor_mass', 614.28935725)])\nOrderedDict([('spectrum', [116.0342477241909, 894.4109681514537, 1110.490278049357, 172.0839694873047, 605.2883808042743, 447.2650807799519, 998.5010634757564, 1097.5697199048382, 167.59251447459707, 399.7142177544688]), ('abundance', array([ 912.28733009, 10525.56883284, 362.92816885, 5917.49748134,\n 559.40505989, 3799.12880274, 10612.6429055 , 6276.67735631,\n 19342.14722472, 7416.33052749])), ('precursor_mass', 670.8313892499999)])\nOrderedDict([('spectrum', [116.037475901855, 690.3028344219002, 837.3781122880523, 1322.6426978970183, 122.55272200000975, 435.2278649031936, 1326.673900328879, 218.1123382365329]), ('abundance', array([ 5104.71323045, 3585.52370311, 142.20727892, 4677.8040874 ,\n 2616.20526309, 10719.89717951, 3673.73593768, 1635.18678883])), ('precursor_mass', 721.3552287499999)])\nOrderedDict([('spectrum', [116.03305661199569, 837.3773853439553, 1209.5600296732887, 1322.6452847686276, 122.54989567525088, 172.08603852938163, 419.19299908152436, 447.7025592889276, 504.24702940761046, 769.8619898741846, 134.04017704845316, 235.0930181539913, 447.24325414474237, 1014.497664520429, 1214.5733702287266, 360.6822405622411, 434.22014714466854, 572.2762501828098, 778.8699346273173]), ('abundance', array([1.61116277e+03, 1.76890914e+03, 1.23254644e+03, 1.49373224e+04,\n 1.86138770e+03, 1.93385180e+02, 6.07395896e+02, 3.09534138e+01,\n 8.74991580e+02, 8.65101198e+02, 4.85729584e+02, 1.13058264e+02,\n 5.05439036e+02, 6.46875999e+04, 1.08455077e+04, 4.18365092e+03,\n 4.14677428e+02, 5.47370407e+02, 9.93231761e+02])), ('precursor_mass', 778.86870025)])\nOrderedDict([('spectrum', [100.07527991869051, 215.10301227314812, 442.2269270784041, 513.2671495653393, 936.4570042885977, 172.08352235538723, 76.03926388845981, 223.10818996869833, 370.17682210696245, 570.257576899755, 669.3280116653684, 797.3823436763021, 1011.4790597685047, 112.05376185612792, 250.11249240850367, 335.1653177811805, 399.1933546219806, 506.2422867893847]), ('abundance', array([4.41869776e+02, 1.00788929e+05, 3.13014859e+04, 2.50342857e+03,\n 9.98351492e+03, 1.53018770e+03, 3.24574477e+02, 3.81400228e+03,\n 2.34643013e+04, 3.06597187e+03, 2.02867915e+03, 1.06511464e+03,\n 9.35335451e+02, 1.76951829e+02, 4.61461551e+02, 1.13911326e+03,\n 8.63650664e+01, 2.72412421e+03])), ('precursor_mass', 506.24273275)])\nOrderedDict([('spectrum', [215.1079968764549, 513.2630940961903, 221.62275663944, 257.1351487780674, 395.1876362238571, 132.1028237785517, 612.301621872743, 782.4092770527894, 66.554391137213, 95.06648973194964, 242.1365330621013, 306.65974112001953, 455.73898648513665, 513.2497378123027]), ('abundance', array([2260.41762264, 133.17563196, 119.98375445, 916.82103478,\n 703.70456078, 375.19814163, 9.05955424, 298.09200204,\n 1416.06339131, 1901.84928641, 2801.12648389, 3604.16153481,\n 1664.16034296, 298.41510106])), ('precursor_mass', 562.78476475)])\nOrderedDict([('spectrum', [993.4642837312085, 1106.552891214238, 122.02272614002288, 235.1091098863568, 292.1318046533369, 586.2684846897539, 885.4194887349822, 1128.50196466821, 146.5716083666961, 220.1023659601185, 293.6392187818367]), ('abundance', array([ 404.66789689, 2990.6855302 , 2575.23253856, 6773.36448445,\n 555.48359882, 466.55685542, 2042.47371289, 28586.07726031,\n 7737.10808323, 2594.47862451, 1335.47009978])), ('precursor_mass', 614.2893572500001)])\nOrderedDict([('spectrum', [100.07513924870693, 513.2663572879208, 789.3762518880358, 221.61617581444276, 257.1341284884165, 395.1935399180957, 334.177391665948, 814.3771314101361, 1227.5733291887664, 59.546811027279716, 111.05679827932072, 269.6354168040932, 492.74858629256727, 614.2904918281711]), ('abundance', array([ 1764.22642953, 4502.25303442, 35180.13547103, 6947.8667497 ,\n 1336.6747011 , 464.9677301 , 685.01754429, 100.56886444,\n 319.43784674, 1245.11830276, 1492.62947242, 1496.06530543,\n 1345.82500736, 96.7360484 ])), ('precursor_mass', 663.8235642500001)])\nOrderedDict([('spectrum', [993.4670180552556, 1106.5483435938786, 1209.5609088005258, 108.05253985862917, 221.61610940586317, 257.13804926949103, 605.2769922800427, 927.4715275575167, 998.4996855924649, 1340.6488462757898, 66.5567135716464, 224.13621974176223]), ('abundance', array([ 271.08014138, 5447.53479576, 842.28845301, 918.54603961,\n 3988.45564218, 5153.30350305, 18.25687803, 246.22322036,\n 1737.53689299, 2070.8477927 , 9051.65897395, 12213.48452937])), ('precursor_mass', 720.3655962500001)])\nOrderedDict([('spectrum', [343.1561282878529, 642.3096724688538, 993.4709184960795, 1522.7595727432865, 221.6151641028542, 257.1335724354928, 395.1877847203785, 497.23647540048336, 553.7800986437452, 761.8832836041096, 605.3322241812698, 1028.508783605562, 1326.677480470649, 1540.7701212115946, 60.53449306765884, 166.61169640672904, 274.65901807042115, 303.17137583388325, 550.2791505807928, 599.8128542900827, 663.8410223126937]), ('abundance', array([ 518.39086722, 273.28907217, 7675.25659612, 1506.73594954,\n 39137.12234523, 1715.48919588, 4899.46849489, 1038.94188289,\n 625.28435565, 7596.28902797, 21875.04933621, 4565.39144835,\n 1114.26377908, 12303.06021507, 7867.50575378, 816.8817063 ,\n 3343.14071412, 3650.27496494, 6426.33466213, 2828.6696421 ,\n 381.06522165])), ('precursor_mass', 770.8894357500001)])\nOrderedDict([('spectrum', [100.07480616012518, 442.23663197306666, 513.2673847691017, 642.3145747580694, 1209.559381268213, 1308.631687760584, 1421.7110022732265, 50.54181722954165, 395.19160438980833, 605.283767005266, 711.3601743018717, 348.178259032912, 720.355346476531, 1014.4953059381343, 1143.539038582841, 1313.6449349689974, 1556.7309213820376, 1655.7949242973016, 174.59143110308494, 275.6290219012777, 360.6834659220366, 434.2167662176879, 507.7494275665636, 572.2738983868019, 657.3269020000471, 828.4007255626674]), ('abundance', array([ 1859.16793741, 2193.47871951, 1308.15948218, 4572.00509069,\n 767.06946176, 924.19122121, 3140.3126252 , 1645.83742671,\n 3134.80044616, 139830.83157025, 1328.60851636, 3788.5831611 ,\n 638.37982957, 69392.26152782, 907.4567995 , 10619.5670284 ,\n 6560.43320175, 766.98726881, 1486.70084161, 1959.20031561,\n 909.20790981, 826.02826694, 1952.56856846, 324.64972472,\n 1119.55830859, 1375.06216648])), ('precursor_mass', 828.4029072500001)])\nOrderedDict([('spectrum', [214.12330432416587, 457.2032974218261, 556.2724572250203, 1107.5089965028305, 58.02634410005488, 229.1043936526826, 76.03612041564091, 223.10742626296906, 570.2596516187069, 912.409217840494, 1011.4751924231276, 456.7084854870272, 506.24461493330955, 563.2641448815812]), ('abundance', array([ 3195.66867088, 2412.57266804, 838.71819229, 249.67535459,\n 20206.81493891, 4676.92690701, 83.99631191, 1312.91197973,\n 1953.17964752, 539.04951891, 42.80026432, 1581.84041601,\n 607.67963169, 4117.62688883])), ('precursor_mass', 563.2641962499999)])\nOrderedDict([('spectrum', [214.11848318891293, 627.3146144724845, 165.07736649417313, 132.10655419180728, 336.19174766896646, 683.3414666090081, 66.5527651360641, 95.06613122825286, 455.73621145825365]), ('abundance', array([ 673.83677367, 206.36867333, 684.41252171, 2422.23109866,\n 17747.09055353, 526.44925149, 1627.85438669, 5848.16488775,\n 1254.11823041])), ('precursor_mass', 619.8062282499999)])\nOrderedDict([('spectrum', [115.04952211508082, 329.1480643131938, 627.2972986337331, 1050.4888099604518, 1107.5106690651126, 1323.6052212272616, 554.2586143782553, 235.1092994581311, 439.2011720469994, 586.2679999447361, 1013.478272980195, 1227.566463203588, 118.05887873448346, 146.57449328495915, 220.10428082591235, 443.2124470942201, 564.7565692064117, 671.3105053844237]), ('abundance', array([ 3398.41362713, 324.37389066, 922.48023016, 85.35682618,\n 1107.81305129, 7042.53579386, 21602.60288548, 1615.60717884,\n 2761.30620973, 2486.79842665, 182.97075545, 18097.52206626,\n 3125.70770936, 1295.13665703, 1807.58667028, 16406.21422564,\n 690.16260966, 13479.2240514 ])), ('precursor_mass', 671.3108207499998)])\nOrderedDict([('spectrum', [1422.6744545556146, 452.216047348132, 662.3050094330093, 118.08420653558508, 391.2015045953462, 984.486004149532, 59.54669074036271, 196.10426665412643, 269.6361909641418, 663.8233922422373]), ('abundance', array([ 1062.95602106, 697.92660707, 227.5185921 , 251.65159556,\n 62869.32059944, 107473.05995921, 9746.74439729, 936.34959369,\n 149.92356834, 3612.28050252])), ('precursor_mass', 720.8450277499999)])\nOrderedDict([('spectrum', [329.14551637930833, 556.2753080892826, 756.3510991812086, 903.4213201495753, 1107.5090078307699, 1220.594468858997, 1323.6053209408594, 1422.6760957889428, 1535.7555701300494, 107.5624889899518, 165.0747398795018, 229.10803154634195, 378.68124912332627, 452.2127067013135, 525.7467747242925, 554.2584104713301, 768.3811080417007, 231.16933323599267, 504.28581503647735, 998.4985038037936, 1225.6279073708422, 1553.7660363282323, 66.55499141303473, 116.08859267293533, 252.6445072100766, 326.1785681768881, 777.3865102087647]), ('abundance', array([6.21661767e+03, 8.99658108e+01, 3.31285113e+02, 7.28434665e+03,\n 8.94486462e+02, 2.10379970e+03, 9.62616452e+02, 2.46522242e+02,\n 1.03713331e+03, 3.83211467e+02, 1.78037117e+02, 1.44662566e+03,\n 6.55257621e+02, 6.22454259e+02, 4.94845276e+02, 5.41238763e+02,\n 1.79168564e+03, 1.15674209e+04, 6.96782717e+03, 1.72938753e+04,\n 3.35712974e+02, 4.74405537e+04, 9.39109857e+03, 4.14669133e+01,\n 7.82371978e+02, 3.97439264e+02, 1.15753739e+03])), ('precursor_mass', 777.3870597499998)])\nOrderedDict([('spectrum', [627.31019677625, 525.7484326209477, 610.8018225485564, 662.3043394329025, 332.2142656699297, 435.2223543316904, 548.3118122391602, 166.60999861034995, 274.6607476291167, 303.1688075316204, 599.8131652930198, 721.3555742340742]), ('abundance', array([16355.99463371, 1456.93916025, 20882.69740765, 629.02941971,\n 1782.35493207, 351.98122064, 2461.88297062, 1389.33093291,\n 7069.05164675, 80.85663904, 8143.86042777, 13022.86431311])), ('precursor_mass', 827.9108992499998)])\nOrderedDict([('spectrum', [115.05169431814356, 1050.4914504935948, 1323.602282354949, 1422.6714392625, 107.55977164577389, 314.1587427446905, 452.21390573349265, 610.8059263631756, 134.05132945314494, 235.09079430088119, 67.52514644766644, 275.6308475451217, 572.27325697322, 607.7940893731426, 721.3546756476668, 885.423060209866]), ('abundance', array([ 4454.29070276, 727.98950238, 6849.27585559, 2258.27119221,\n 8363.47670455, 279.27346425, 31115.12845826, 15529.56991193,\n 4900.15433135, 84.04720957, 3538.61673381, 1020.28046674,\n 5384.33412012, 3119.85336875, 497.80579657, 2638.04754714])), ('precursor_mass', 885.4243707499999)])\nOrderedDict([('spectrum', [130.05003657566155, 458.1870746321796, 586.2449667126073, 1179.5308526437977, 172.08797429725996, 343.16290747028023, 378.6817007325404, 516.7338356329532, 223.11014059709072, 370.1778434035163, 1125.5217051974532, 112.05701521613994, 185.59226353458996, 335.16449519666617]), ('abundance', array([ 514.65265928, 24195.37466288, 19702.40718616, 38.69951943,\n 2971.70731269, 1456.10993201, 2467.02742824, 464.76496102,\n 788.30001819, 107.53479562, 1328.67588532, 121.27610648,\n 94.3009415 , 7001.05712425])), ('precursor_mass', 627.78549275)])\nOrderedDict([('spectrum', [1032.4686336136403, 1179.5364544805457, 618.7698917719192, 336.1904587485984, 1124.562409076786, 306.6545299331366, 619.8054725428364]), ('abundance', array([1.84750827e+02, 4.89674996e+03, 1.92747281e+05, 1.47217079e+03,\n 3.20828960e+02, 2.07989655e+03, 1.22766407e+03])), ('precursor_mass', 684.32752475)])\nOrderedDict([('spectrum', [1179.5303414171747, 715.3113473403974, 786.349167459782, 293.6395826166042, 393.68452350560915, 671.3113265383384]), ('abundance', array([ 1262.48905211, 4474.68935096, 100.06198659, 6090.07279238,\n 3320.20965362, 18854.24059243])), ('precursor_mass', 735.8321172499999)])\nOrderedDict([('spectrum', [1236.5525387897726, 1551.715155341344, 172.08434941916698, 229.59769112484486, 776.3595473198021, 118.08627354063631, 221.09543404070791, 685.3382678922999, 167.59398105938712, 196.10332664771497, 269.6384075392035, 720.8460444222355, 785.3609328193824]), ('abundance', array([ 1855.73858251, 18672.59152559, 1834.86462003, 1929.96535038,\n 129.5780052 , 1429.18247455, 124770.56253043, 575.73406342,\n 289.97719386, 567.38934617, 271.58836802, 1364.99684921,\n 574.25774251])), ('precursor_mass', 785.3663242499999)])\nOrderedDict([('spectrum', [586.2471977321709, 1032.4630727289684, 1664.8024063129453, 675.3237747755644, 726.8304464147435, 132.1038344815811, 231.1684250475973, 1225.6291401073297, 1439.7220815540718, 499.7599379551618]), ('abundance', array([ 877.93361151, 3602.44628525, 244.11131701, 737.70585476,\n 1399.55510496, 1955.239167 , 3858.32929942, 532.24717106,\n 2805.73542792, 1853.16458382])), ('precursor_mass', 841.9083562499999)])\nOrderedDict([('spectrum', [343.1611804200574, 685.3156776769574, 885.3943901132267, 1032.461574609416, 1349.6379517254106, 1452.647947927675, 1551.7143353099375, 65.53291018474795, 122.55047688119917, 229.59585846877758, 618.7786387139773, 233.1496023217676, 605.3338859420124, 752.3999786644658, 1028.5118567444088, 1099.5516054538132, 1540.769771281508, 1654.8152701456893, 599.8115955656604, 663.8409112363493, 721.3552687744152, 770.8905330552981]), ('abundance', array([ 5966.23322843, 4296.54638422, 282.39569226, 2288.84697523,\n 19450.02233069, 513.93137481, 38863.69858514, 26410.27673697,\n 1596.25201166, 79837.16336255, 477.95050924, 4382.67779657,\n 2863.32867386, 5264.19258 , 183.09746457, 2712.53353302,\n 989.19652262, 313.38764851, 304.24848467, 1400.95673595,\n 3458.70040821, 5346.89037842])), ('precursor_mass', 892.4321957499999)])\nOrderedDict([('spectrum', [586.2459167162477, 1179.5328489800681, 1236.5551072353778, 1765.844054009929, 590.268530607846, 618.7830909911213, 675.3271475399524, 447.2440764973178, 720.3593715432712, 1556.7426215214134, 1769.8390851906952, 275.62995793624316, 332.1731291938059, 434.21490378380923, 572.2781283578754, 607.7929707266763]), ('abundance', array([ 3272.82263143, 116.42498805, 2835.8332313 , 7044.16800928,\n 1371.40591965, 11599.85356167, 65.64636865, 1756.75713614,\n 2948.90428496, 235.46908938, 1321.32258114, 30.81860921,\n 23896.79321564, 4475.54035457, 57.65021461, 245.22612494])), ('precursor_mass', 949.9456672499999)])\nOrderedDict([('spectrum', [605.2552967599563, 733.314371769512, 832.3858518401739, 903.4195241628992, 303.1305026159608, 416.7032657736899, 452.21350841970934, 663.8053640475584, 912.4107456933077, 1125.5199922296406, 250.1095814516706, 285.63009209481135, 335.1655080506208, 399.1926386010368, 701.3205515575262]), ('abundance', array([ 216.99142896, 241.26510912, 1197.94087525, 15435.9894277 ,\n 1209.07426609, 584.95599023, 634.48887173, 1086.24770466,\n 7567.38829564, 23038.73569 , 4302.3654292 , 2989.08848798,\n 15237.47514283, 3797.41634541, 3008.4557304 ])), ('precursor_mass', 701.31969975)])\nOrderedDict([('spectrum', [903.4249516789148, 1179.5315351903964, 1383.621289167224, 139.06243540388732, 483.25536810577563, 612.3040494586007, 683.3390559596771, 1367.6473163188414, 168.59969071766568, 342.17413150596667, 619.8058989347661]), ('abundance', array([9.12643557e+03, 2.14542636e+04, 4.67119114e+04, 2.70791087e+04,\n 3.55904470e+03, 1.28912758e+04, 4.67199684e+02, 2.12123949e+03,\n 3.92630056e+01, 5.30602210e+02, 9.72093568e+01])), ('precursor_mass', 757.86173175)])\nOrderedDict([('spectrum', [391.15532909487234, 605.2555033186323, 903.4161835992271, 1383.6201692434092, 1496.7064393171024, 139.06691842306438, 196.08423863050615, 245.61807162590728, 452.21717241094547, 663.8011183535964, 692.3138294088818, 800.3633229054652, 235.10860238740568, 1470.6578243367076, 61.51599692382097, 293.644095225673, 358.15925076947553, 393.6788690142063, 564.7546368903373, 614.286708495681]), ('abundance', array([ 4416.85612503, 330.06180379, 3143.42653559, 3782.91229103,\n 7266.47569193, 1145.7741959 , 973.17695717, 1926.03355215,\n 7844.44140392, 1420.79418819, 10686.08393764, 536.64399085,\n 1679.16851015, 8758.31066785, 2263.6063111 , 533.4466433 ,\n 2311.72451681, 3519.80510444, 50.77116932, 3566.05521954])), ('precursor_mass', 809.36632425)])\nOrderedDict([('spectrum', [832.3828537598424, 903.419965884108, 367.1611975127807, 516.7323915677911, 692.3134460871547, 748.8534822098122, 849.8960031894795, 118.08863227688323, 221.0971688066483, 334.1787551007555, 538.2687431587201, 984.4869779792705, 1112.54469447023, 1326.6410788978656, 59.550800412047664, 269.63805174172415, 407.69381660666045, 443.2147169525381, 492.74716516669014, 785.3703791083769]), ('abundance', array([ 802.08593024, 5120.62914607, 2833.7411139 , 1291.47043257,\n 2543.15034529, 587.87107293, 2604.2356449 , 7294.34250483,\n 3022.8598486 , 1280.50650749, 7899.46591226, 1652.79432158,\n 4870.80313948, 836.70588315, 347.19426582, 1016.15335156,\n 1500.95409749, 944.52012896, 1417.44435315, 1333.42358458])), ('precursor_mass', 858.9005312500001)])\nOrderedDict([('spectrum', [733.3147047189507, 832.3812648708288, 903.4200857963993, 1326.5981447988634, 1383.6211550967696, 1496.7067293591808, 303.12981652291245, 516.7356733379738, 590.266659212125, 663.8017514841645, 748.8572519890124, 231.16844132401582, 651.3541951736879, 798.4242427235105, 927.4627936770012, 1097.567437296369, 1225.628456593098, 326.1795355117294, 399.7132038239422, 464.2375552186417, 549.2882781049188, 720.3656224885701]), ('abundance', array([ 1266.60093259, 9181.28993841, 11302.05430205, 239.00599636,\n 2191.03243517, 10895.25839484, 409.98564617, 25453.85816388,\n 6859.42509469, 13285.54300283, 184.20222714, 30007.73255456,\n 600.03699426, 821.61804176, 4719.56737225, 3761.70797017,\n 5535.87081095, 1334.81899314, 281.39814752, 1407.78875477,\n 535.65547492, 3033.57709238])), ('precursor_mass', 915.44256325)])\nOrderedDict([('spectrum', [277.1170315626802, 832.3858885004065, 1032.4645047471072, 1326.5988985256104, 1383.6229216907689, 956.9654074184092, 435.2316099696098, 1326.6768126604295, 1783.858148806733, 60.537490888084974, 117.07845762011368, 218.1163520707205, 274.6578362442886, 599.8136401779686, 770.8857645737146, 892.4315098851876, 965.9660899355796]), ('abundance', array([ 1993.19739586, 165.17302055, 711.48274606, 102.12819391,\n 602.83372253, 131.62134015, 1321.41926383, 1153.25472477,\n 428.35014848, 938.43866458, 45272.62805762, 3352.05877012,\n 1813.63546575, 7302.64696998, 1542.88246766, 96.11892209,\n 495.74813401])), ('precursor_mass', 965.96640275)])\nOrderedDict([('spectrum', [277.1187028559604, 391.16164781543335, 605.2568320039278, 832.3817885361443, 903.4222790933214, 1032.4628061613432, 1179.5316791318985, 1326.6083573296407, 1496.707000606876, 1599.7134267783313, 1912.9150044900177, 2027.9432511085272, 74.54061359381939, 196.0879473799489, 245.61804084762682, 303.1309005336606, 367.1607511380561, 416.6954371366191, 452.21030741511174, 516.7347340877526, 800.3615881732399, 348.17313853520204, 867.4272191558, 1014.4946874480431, 1441.7028714812557, 1898.8842299521796, 2045.9516163891933, 67.52652565729574, 224.125782344231, 360.6824295461946, 434.2178303331589, 657.3257845283139, 949.9441126142711, 1023.4776669034549]), ('abundance', array([9.05671243e+02, 1.10899564e+03, 2.05365687e+04, 2.82577330e+03,\n 1.42199464e+03, 2.87506312e+01, 6.77256734e+02, 5.04177172e-01,\n 1.23499759e+03, 2.66517222e+02, 4.04182707e+02, 3.58127434e+02,\n 6.45193291e+03, 2.32211064e+03, 1.16693915e+03, 3.22439735e+02,\n 6.77764488e+03, 5.65069838e+02, 4.17416020e+02, 1.51223059e+04,\n 6.79925603e+02, 1.87294929e+03, 1.53969200e+03, 2.31613566e+03,\n 2.71705226e+03, 1.42242811e+05, 3.27825856e+04, 2.34356643e+03,\n 5.35392192e+02, 1.86894468e+02, 6.46303493e+02, 6.19231549e+03,\n 5.04864934e+03, 9.07297363e+02])), ('precursor_mass', 1023.4798742500001)])\nOrderedDict([('spectrum', [279.0966114372326, 426.1654786157253, 513.1988681542357, 82.53878911461238, 140.05108870896802, 276.13423725121413, 363.1673392669573, 182.086416418123, 255.62186467845808]), ('abundance', array([12986.99106857, 510.05720677, 322.23727174, 2574.44644516,\n 4320.23424852, 505.35841737, 1315.13619764, 3066.58184621,\n 11581.34587966])), ('precursor_mass', 394.66612475)])\nOrderedDict([('spectrum', [279.096287945132, 770.3167366349862, 134.04710146642145, 625.2605821469299, 313.1351419993408]), ('abundance', array([ 463.4102534 , 2354.34222555, 7765.91552165, 5665.24339362,\n 8859.6979267 ])), ('precursor_mass', 452.17959625)])\nOrderedDict([('spectrum', [279.09728155053233, 584.2355639820016, 885.3476478177713, 1013.3992223034526, 213.59099365410486, 292.62086747020913, 385.66021352120094, 260.1144636282694, 434.68108154983287]), ('abundance', array([12847.91954088, 8433.48891037, 2037.35051713, 1165.86199673,\n 4211.43119391, 2490.23194378, 2350.9135428 , 3970.22788488,\n 1012.44606254])), ('precursor_mass', 516.20888525)])\nOrderedDict([('spectrum', [513.1959148874934, 584.2360440255046, 770.3161302436667, 1013.4013558034497, 213.5879775036112, 292.6242453743085, 556.7392502942465, 705.3191375417191, 1130.4788914221567, 59.54744186321882, 123.57614848707252, 274.1310304947728, 484.2118138219627]), ('abundance', array([ 4651.61642918, 2467.23573129, 2846.68614265, 12575.58857617,\n 1232.48568545, 140.71291493, 3423.25017203, 803.54177348,\n 4386.75478531, 1938.38933757, 881.28586595, 709.64905226,\n 389.00084594])), ('precursor_mass', 565.74309225)])\nOrderedDict([('spectrum', [584.2354189937089, 213.59033043726413, 385.6571934213705, 507.19731883478977, 556.7347249641105, 448.20309774522343, 792.3510693368877, 1054.44938276937, 53.52960292207774, 103.0604518355312, 396.678672133812, 609.2612279676279]), ('abundance', array([5041.79402172, 151.39077419, 4428.85950565, 7955.15976351,\n 5767.75249008, 4601.47157491, 79.39045842, 3450.19930769,\n 5223.04045068, 130.14023655, 4507.40318074, 509.89502976])), ('precursor_mass', 609.2591062500001)])\nOrderedDict([('spectrum', [279.0969045768324, 513.1977227004726, 584.2313393570424, 1013.3991552022213, 140.05031134697998, 257.1037904551944, 292.6221515651265, 385.66068866972716, 507.2046654380141, 166.08489700509804, 480.2434476239198, 939.4220294907453, 1086.49095191923, 127.06223280397441, 240.62564597040716, 298.14612127754225, 543.7487729043169, 601.2634757016066]), ('abundance', array([ 1460.61486913, 11134.89390846, 2059.27669422, 2444.61544395,\n 10294.64623964, 62454.70118224, 3940.14823322, 519.27074295,\n 1543.90951809, 5024.25944992, 408.70548027, 3972.5413488 ,\n 6866.53765946, 5151.28320927, 15652.21409729, 5105.33626161,\n 3167.7874426 , 83.82420628])), ('precursor_mass', 682.7933132500001)])\nOrderedDict([('spectrum', [164.07238662765118, 885.3376783332097, 292.6209309147348, 507.20523649827857, 747.3215801597188, 928.4196652935492, 999.4543280923957, 250.13155978619324, 500.2319844442199, 543.7483707198962, 617.2829979938293, 674.7952172152003]), ('abundance', array([1.10534788e+04, 1.07924664e+03, 1.86311419e+03, 3.20684869e+02,\n 6.10517201e+03, 9.12743119e+03, 7.01090309e+01, 3.47113318e+03,\n 1.10307974e+05, 7.76742234e+03, 1.68379977e+03, 1.31130406e+04])), ('precursor_mass', 756.3275202500001)])\nOrderedDict([('spectrum', [407.1916951371941, 712.3312897078682, 204.09817587320433, 276.13591458367245]), ('abundance', array([5290.01410028, 3553.33838905, 8807.17287525, 4236.4043027 ])), ('precursor_mass', 458.71360625)])\nOrderedDict([('spectrum', [129.10219410710556, 292.17463420014377, 898.4074488583714, 1013.4331509636903, 65.05450616301492, 204.09507106300043, 321.1494839366908, 507.22372483478495, 134.044541190243, 625.2592807212086, 903.35317919784, 67.52475926043087]), ('abundance', array([24582.09916299, 511.88102668, 1978.127926 , 357.21427684,\n 153.98217442, 5260.75077648, 7024.50890497, 3157.34475317,\n 257.22051067, 983.24085761, 69538.75772311, 9151.39616668])), ('precursor_mass', 516.22707775)])\nOrderedDict([('spectrum', [292.16797839543307, 65.05083624583114, 146.58749616931692, 507.2216967985636, 147.0795923498986, 262.1029596465541, 606.2518917320224, 753.3181840662578, 131.55219103004168, 260.1137431628897, 516.2055506307926]), ('abundance', array([ 1422.88231643, 771.23576939, 635.83388421, 1493.94099203,\n 154.19713149, 2202.60724839, 422.6695056 , 181.51966244,\n 526.60818843, 25011.76400644, 1424.16952543])), ('precursor_mass', 580.25636675)])\nOrderedDict([('spectrum', [129.10207010622858, 146.58697410354634, 321.1433005902699, 246.14424546153646, 547.2508216517742, 705.3193012436916, 1130.4723104364864, 181.08654151494127, 274.13115731223917, 353.16486083218734]), ('abundance', array([ 7302.58507011, 2763.82100733, 371.93148056, 9057.92104199,\n 2482.42526855, 857.04166668, 1898.14367453, 2372.64049832,\n 6047.91119797, 19023.75874764])), ('precursor_mass', 629.79057375)])\nOrderedDict([('spectrum', [129.10249443976008, 712.3302929532389, 1327.5956243316548, 146.58423060432145, 277.631252363793, 705.320907431432, 792.3510029426191, 1054.4508533913213, 1217.5117792262981, 1345.6047162768316, 53.52727254568049, 317.6473669559024, 396.68012886791377, 470.2127867440229, 527.7277625310251, 673.3062584990212]), ('abundance', array([ 457.2692478 , 93.09588137, 1508.07335388, 18797.70495628,\n 1587.66586578, 2171.71549449, 4796.41912608, 1843.04688498,\n 2603.35889886, 767.68006072, 3404.24646572, 6124.78082468,\n 3709.7189586 , 1829.16492362, 24.90570106, 4323.10683636])), ('precursor_mass', 673.3065877500001)])\nOrderedDict([('spectrum', [641.2937216230581, 277.6366847510858, 507.2242176952711, 664.2908879396911, 253.11384864525274, 939.4178707774219, 1086.4877446122255, 1492.6753411372988, 83.55080482739211, 127.05969721593895, 176.59448182211932, 240.62460910698445, 391.1796463251244, 543.748052619972, 601.2646002516491, 746.8393524799641]), ('abundance', array([ 339.95841853, 238.11875476, 1858.37340416, 528.94874909,\n 983.74072943, 52.92053091, 14486.87859858, 3476.23571444,\n 2263.15338288, 932.58877731, 801.10113954, 441.96295113,\n 45827.4501105 , 9111.64165214, 7327.49570683, 3171.65547064])), ('precursor_mass', 746.8407947500001)])\nOrderedDict([('spectrum', [407.1908707631521, 712.3293411522028, 146.58462059392764, 664.3010160381376, 811.3698693513156, 313.15317008162344, 499.2553802989654, 627.3054977115644, 200.59524744896154, 371.6737557686502, 500.23256085931104, 820.3824628655955]), ('abundance', array([17762.21728676, 4637.2845279 , 1020.76513098, 255.14559 ,\n 8424.20877768, 17867.72391652, 686.79926027, 1819.13243683,\n 3825.24420749, 273.56395742, 859.33645351, 777.27247888])), ('precursor_mass', 820.3750017500001)])\nOrderedDict([('spectrum', [563.2932612693576, 1054.5116256819338, 399.1976020806179, 276.13826224912054, 788.3247206081501, 394.6655535586933]), ('abundance', array([ 243.78957955, 6055.46898506, 8900.70072683, 432.76176543,\n 3740.28948036, 1834.59108494])), ('precursor_mass', 536.76416175)])\nOrderedDict([('spectrum', [224.63686625829493, 434.71919021333787, 478.19804147169503, 740.2873832513056, 903.3516432902081, 1031.4508444352518, 196.08367657970356, 452.1826764635906]), ('abundance', array([2907.47425957, 1351.923938 , 4636.7262663 , 161.48001254,\n 2564.30327186, 690.78914872, 2689.60520627, 1377.88695596])), ('precursor_mass', 594.27763325)])\nOrderedDict([('spectrum', [797.3945084835386, 1169.5343768524112, 224.63700933775533, 282.15118548822977, 355.69110365435034, 434.71810016574113, 585.2731890282495, 147.07469200534092, 448.180794231094, 1031.4095431530675, 74.04041499224174, 303.6285020479824, 377.1619696666346]), ('abundance', array([9.31086509e+02, 5.81881243e+02, 1.49818013e+02, 2.28813346e+01,\n 8.98397018e+03, 3.31642733e+03, 9.66822190e+02, 8.41637211e+02,\n 1.09629305e+03, 3.12016443e+03, 6.99953439e+02, 1.35062593e+03,\n 2.41503599e+04])), ('precursor_mass', 658.30692225)])\nOrderedDict([('spectrum', [710.3609381180131, 1054.5104249664682, 79.05977258550264, 282.150289407917, 355.68210341435207, 1130.4780112803498, 1414.6743617652032, 353.16137164419274, 484.21131250123585, 565.7424896324303]), ('abundance', array([2.71286029e+04, 2.50043984e+03, 1.59463953e+02, 1.02921551e+05,\n 1.12421072e+05, 1.67069792e+03, 3.47268824e+03, 8.85814219e+02,\n 8.62119284e+01, 1.80777890e+03])), ('precursor_mass', 707.84112925)])\nOrderedDict([('spectrum', [157.11022478037162, 563.2910500607106, 710.3576926732183, 868.4294872610316, 1396.6594294005902, 143.10507207039515, 399.19903102716086, 434.7193294106867, 205.11755045301265, 448.20490327497316, 705.3212110916902, 1345.6057454516706, 1501.7071152276098, 53.53220655221468, 103.0625446480726, 353.1681490316601, 396.67969781131904, 470.2118501193715, 527.7270404555381, 751.3575228844917]), ('abundance', array([1.50355434e+03, 3.90518279e+03, 9.94019855e+02, 3.11095065e+04,\n 1.65516755e+05, 3.62254325e+02, 1.84297047e+03, 1.82369572e+03,\n 1.55651774e+04, 4.26236113e+02, 1.92817551e+04, 9.78627307e+04,\n 2.04678555e+03, 2.53448023e+02, 6.24471593e+01, 1.85499598e+03,\n 6.15107509e+02, 3.03694833e+02, 2.51502462e+04, 2.17308212e+02])), ('precursor_mass', 751.35714325)])\nOrderedDict([('spectrum', [157.11041485532402, 563.2990331806219, 710.3634674814332, 868.4320611982266, 1054.5171131960406, 1297.5972571675502, 1396.6658228398105, 1630.7654885323295, 224.63538227970975, 282.150583491671, 355.68474498812157, 434.7153051158565, 585.2723418170832, 815.8854868982228, 166.08510921645387, 253.11892340422537, 480.2451011136992, 781.3512889783894, 1086.491074410996, 1492.6751673563078, 83.54639635752213, 470.2191689084665, 682.7938466544666, 824.8922409388412]), ('abundance', array([ 7927.20227437, 178.4317955 , 1392.40816505, 20754.30487487,\n 4081.28132022, 1164.9754202 , 19224.26160023, 106.33624028,\n 229.02311058, 1997.94347441, 803.9964195 , 563.04962364,\n 282.97126095, 50.40316169, 353.45401731, 448.66682084,\n 26846.97640838, 2246.46468863, 137.391952 , 7410.30960312,\n 721.25148557, 2851.9507227 , 28611.00333637, 1386.83602577])), ('precursor_mass', 824.8913502500001)])\nOrderedDict([('spectrum', [797.394353903041, 434.71931524866454, 649.2998560216532, 742.3587383819024, 889.4184956334295, 313.15409304864005, 499.2520219542395, 627.3127258403123, 999.4566227645863, 1348.5814382480721, 1511.6467104260107, 83.5463825630837]), ('abundance', array([ 1609.85403472, 1789.245462 , 217.38807313, 14298.19444521,\n 1207.23749632, 95.5261551 , 63461.29853129, 342.35050522,\n 346.77329004, 2240.49864013, 2537.61145575, 1846.07859086])), ('precursor_mass', 898.4255572500001)])\nOrderedDict([('spectrum', [58.03165350128731, 767.3836590178712, 29.518577578705685, 363.1636673441278, 916.420070109662]), ('abundance', array([3390.92972437, 1986.74612104, 9263.57308919, 1841.47229923,\n 9.72773938])), ('precursor_mass', 565.2748937499999)])\nOrderedDict([('spectrum', [58.03452377731854, 505.2904992400154, 854.4133725168647, 925.4522105891111, 1226.5571620068713, 253.1503505977497, 134.04339193615183, 391.16091155038686, 478.1949566561985, 625.2655065205798, 903.354190821495, 67.52526126111653, 160.56563596458443, 239.5993310679825, 622.79408274159]), ('abundance', array([ 1134.46764447, 18756.03503388, 1834.53218741, 570.46036721,\n 996.08564525, 7401.53760447, 1620.45885979, 1449.62841442,\n 2697.51087101, 3606.64216749, 6088.07319434, 6987.26629865,\n 100.26202878, 217.60192567, 3702.49208724])), ('precursor_mass', 622.78836525)])\nOrderedDict([('spectrum', [1354.6178174529023, 448.1812525647714, 519.2186483880272, 753.3181253538272, 868.3517210019929, 1372.6266244987887, 516.2085065070709, 580.2555043576532]), ('abundance', array([ 1990.80360623, 10728.25760453, 39039.73458176, 1570.90094255,\n 205.48654465, 819.69415767, 9846.76829814, 1132.76110137])), ('precursor_mass', 686.8176542499999)])\nOrderedDict([('spectrum', [505.2922433614179, 620.3159141790263, 1453.6805361804045, 107.57078442117951, 384.1950835100363, 427.71313757964714, 246.14635132776132, 705.3185703295654, 274.13234743999936, 565.7422235111264, 629.7893508946104, 736.3466677948828]), ('abundance', array([ 294.44529077, 1830.02233294, 725.72229807, 18959.49110974,\n 2903.97293242, 373.55452012, 7674.53214227, 806.4036874 ,\n 3735.65847132, 207.20539941, 952.52757526, 86861.56584663])), ('precursor_mass', 736.35186125)])\nOrderedDict([('spectrum', [854.4151705583976, 1111.5340196111504, 29.517738827209598, 705.3241596796913, 792.3523396185044, 1054.4475432195197, 103.06452151791913, 396.68039332626444, 779.868113186454]), ('abundance', array([11486.52268994, 821.35546612, 5575.22125863, 877.14936625,\n 52.17150834, 2362.77991317, 376.67063631, 1502.80090288,\n 1432.81819209])), ('precursor_mass', 779.86787525)])\nOrderedDict([('spectrum', [854.4135923655263, 925.453171422141, 253.14712235445347, 310.66166412606754, 463.2311723046818, 556.2766835336315, 677.811918505646, 770.8602033181459, 253.1164214063693, 352.188536919147, 480.2462907133241, 781.3503781446343, 1648.7759207191295, 1705.7972608452674, 176.59899479648826, 470.2143355347807, 543.747462778796, 682.7912219763322, 746.8370022153371]), ('abundance', array([3.73092606e+03, 4.31471682e+03, 4.87618666e+02, 2.21234483e+04,\n 2.50396875e+02, 8.43972117e+02, 2.57409863e+03, 3.27502414e+04,\n 2.46829763e+04, 2.70719870e+03, 2.92285168e+02, 1.96619000e+03,\n 1.64726936e+03, 9.51722458e+00, 2.47000269e+02, 3.29872466e+04,\n 5.39457131e+02, 2.72777101e+03, 2.40318007e+02])), ('precursor_mass', 853.40208225)])\nOrderedDict([('spectrum', [214.13352272456007, 342.22230953712034, 505.2876095658858, 620.3218157497519, 1453.685629944753, 29.52066569055408, 253.1477779950351, 384.19941106972794, 463.22549068270285, 313.15235254912477, 742.3398594157377, 999.4567703771576, 83.5438430748039, 543.755307953237]), ('abundance', array([1.04825392e+04, 2.23136469e+03, 7.74032185e+02, 1.08932721e+03,\n 4.59281409e+03, 3.10331352e+03, 2.23734074e+03, 3.19748960e+02,\n 1.83087320e+00, 2.53945018e+01, 1.34022930e+03, 1.32573255e+04,\n 8.36474455e+01, 2.16037677e+03])), ('precursor_mass', 926.9362892500001)])\nOrderedDict([('spectrum', [505.28823671980496, 1088.5157367619695, 111.05179055205832, 189.1001819461843, 334.68093725674527, 637.8012824413937, 205.09733259998166, 276.132988341904, 625.2617287078612, 916.4186599184583, 1072.520946809437, 182.0863101512294, 313.13433355280733, 394.6668062265708, 536.7655572263586, 565.2756661212226]), ('abundance', array([1.05240357e+03, 4.81396327e+02, 8.05295924e+04, 1.41066824e+03,\n 2.51138782e+02, 4.90014423e+02, 6.51115449e+02, 2.46455321e+03,\n 2.70066010e+03, 4.80844742e+02, 8.70146259e+01, 6.87237236e+02,\n 6.56200016e+01, 8.75863469e+03, 1.34605104e+02, 2.09894682e+03])), ('precursor_mass', 646.8065537499999)])\nOrderedDict([('spectrum', [377.19240090294795, 505.29440997491287, 783.3788186017609, 1088.5145003469431, 253.14954788435477, 637.7982122208097, 1031.4479524225753, 160.5654049501222, 313.13711842090817, 370.6439987341019, 594.2802465260492, 704.3195810117904]), ('abundance', array([ 2004.03680002, 235.62323804, 2662.15413644, 719.62460614,\n 2952.943782 , 3519.43519539, 502.41374114, 648.89557856,\n 545.92475604, 47308.78776606, 69.76776529, 1622.6364144 ])), ('precursor_mass', 704.32002525)])\nOrderedDict([('spectrum', [1017.4799831045025, 1274.5961713050835, 392.1907855368878, 465.7265617310779, 759.3436594826342, 262.09939341568844, 519.2184427087401, 868.3471789039054, 74.04164220359709, 224.59475970062306, 580.2559347698254, 686.817212434368]), ('abundance', array([1894.93422409, 3090.18806534, 6449.54656224, 21.90842261,\n 916.81190736, 340.05320361, 793.45262733, 4684.22220736,\n 406.72212237, 4706.2688342 , 86.16675305, 5166.01744533])), ('precursor_mass', 768.34931425)])\nOrderedDict([('spectrum', [164.07014048693992, 1017.4832530882896, 1616.7517108318523, 465.7243889593972, 544.7631236662041, 759.3435843513583, 246.14725053498438, 1471.7039725283937, 59.54667229310219, 123.57647125702655, 181.08662244775152, 629.7857323631854, 736.3504957004202, 817.8868980335504]), ('abundance', array([ 1005.93366834, 11452.89835085, 10837.80625401, 205.08709076,\n 854.76930935, 7087.16010455, 22335.86729304, 495.66139044,\n 3642.21128671, 566.97325612, 2274.90137954, 4222.58766607,\n 1231.71684081, 700.31354348])), ('precursor_mass', 817.8835212500001)])\nOrderedDict([('spectrum', [164.07163972325796, 930.4467174110829, 1088.5110020276197, 1274.5940800011026, 1616.749388699156, 82.54158209039387, 253.14949097664424, 334.67815405976984, 392.1907826041915, 465.72759262602875, 509.2352027704655, 695.313596473414, 852.393007074223, 333.182098594299, 448.20237402314416, 634.2834701588924, 792.3519188107357, 939.4192448522227, 1054.4448767549966, 1721.7938456912789, 53.528575801388065, 224.6082199853332, 396.6865134962697, 527.7270012896944, 609.2587350637008, 673.3086772172654, 751.3567657143359]), ('abundance', array([1.12704007e+03, 8.02646890e+02, 2.27584617e+04, 2.46043438e+02,\n 5.46701332e+04, 1.32983650e+01, 3.88308514e+03, 3.89960856e+03,\n 1.45379503e+03, 3.99140024e+02, 3.07367541e+03, 8.69416237e+02,\n 9.91888171e+03, 7.92518010e+03, 2.32498331e+03, 3.64220308e+03,\n 1.13460916e+02, 3.68524581e+03, 9.99692022e+03, 3.01285629e+03,\n 2.54688865e+03, 1.12722170e+02, 3.42067650e+03, 1.12892149e+03,\n 1.79799695e+03, 4.37470808e+03, 3.02696257e+02])), ('precursor_mass', 861.3995352500001)])\nOrderedDict([('spectrum', [377.1932827579582, 1389.6248607428554, 1616.7486885008286, 82.53621522232908, 189.09990445808435, 637.8035111985652, 759.3382462724453, 480.24669369725166, 781.3486324640309, 1086.4902639121071, 1492.6765562814514, 1868.8600906157446, 391.180170910165, 426.70324300835205]), ('abundance', array([2.95480993e+03, 1.20784554e+03, 1.16774380e+02, 5.64919633e+02,\n 4.06494622e+03, 1.08662283e+03, 7.10884775e+02, 5.86988050e+06,\n 1.21654212e+03, 1.42956105e+04, 4.83839092e+03, 2.24201161e+02,\n 1.96485322e+02, 4.68572529e+02])), ('precursor_mass', 934.9337422500001)])\nOrderedDict([('spectrum', [221.0952832530545, 1703.7827810776355, 465.72917258487234, 637.8057527126981, 808.8746196835696, 1233.5570096462075, 1511.6379748275583, 2015.9301343572151, 314.160835199857, 500.2324119792176]), ('abundance', array([ 743.84523263, 1604.64463469, 419.27037399, 199.08311066,\n 382.28848315, 3136.3705361 , 421.50103391, 2027.11370053,\n 416.74393106, 2154.33659517])), ('precursor_mass', 1008.4679492500002)])\nOrderedDict([('spectrum', [490.2755549267413, 781.4377101200872, 896.4621919167793, 1043.529480892309, 1387.6762406952917, 167.5907364010752, 1405.695640400874, 103.06548578405189, 565.2736091784448]), ('abundance', array([ 3425.78876839, 1245.16339837, 9257.157334 , 1442.17400754,\n 4035.67947867, 62405.24936193, 12020.1868021 , 533.54197458,\n 6715.02776391])), ('precursor_mass', 703.34858575)])\nOrderedDict([('spectrum', [448.7327045696697, 601.3020864216891, 1244.5671431990343, 452.1773411072844, 622.7937088208733]), ('abundance', array([1.26892203e+04, 7.94926042e+02, 5.67705887e+00, 3.20929921e+02,\n 3.49361450e+03])), ('precursor_mass', 760.86205725)])\nOrderedDict([('spectrum', [277.1555876661203, 490.2774360335782, 618.3690403305429, 896.4633899101802, 1201.6028154979992, 167.5974048717396, 448.17990285226927, 519.2170765298644, 1159.5074365662178, 131.5558696447574, 658.3066809958757, 824.8927007086124]), ('abundance', array([ 6017.73156851, 797.76285085, 2474.93446451, 4488.02780144,\n 8171.92316914, 552.70337681, 4690.35235609, 65693.35675624,\n 1057.71197324, 4364.90044269, 2848.00753911, 1757.88581705])), ('precursor_mass', 824.8913462500001)])\nOrderedDict([('spectrum', [334.1762219355762, 781.4349203674068, 1043.531825577086, 1502.7067581837705, 57.55469022769958, 391.2185105694851, 448.7360262998673, 601.3036759462232, 118.08456481999613, 547.2505093182688, 967.4142700394715, 123.57691840217049, 309.6483639826635, 426.69960289337513, 736.3588671243192, 874.4233978086156]), ('abundance', array([ 3565.76994721, 165.07822528, 4247.66493883, 10008.71389065,\n 745.22265794, 12075.0308538 , 5061.90426285, 691.31424491,\n 650.8717041 , 2416.02035583, 688.46133463, 1358.68346905,\n 4014.68112626, 13971.73031405, 632.41260611, 3864.11918431])), ('precursor_mass', 874.4255532500001)])\nOrderedDict([('spectrum', [114.08980517837512, 490.2708614405569, 618.3708147322214, 1387.6792933512322, 1630.7663381186492, 1729.833703440613, 205.11747823560913, 1217.5068165149946, 1558.725702344203, 1721.787946057565, 779.8742133808639]), ('abundance', array([ 3863.21549151, 254.07112422, 14478.60139377, 3312.45994766,\n 34042.83721842, 1425.52570676, 788.96706802, 77628.11404524,\n 2843.02517083, 94.3302347 , 11851.18979093])), ('precursor_mass', 917.9415672500002)])\nOrderedDict([('spectrum', [618.3734604047854, 896.4593862634007, 1043.533425594858, 1502.708050150771, 57.54908819043124, 245.6452009411739, 601.3003865382318, 865.4215023620569, 908.936863735637, 1705.7953165988645, 543.7479483294381, 824.8926515898524]), ('abundance', array([1.54462956e+03, 1.06390150e+05, 2.27091856e+04, 1.54235959e+03,\n 1.36166690e+03, 3.42843823e+01, 3.33006729e+03, 4.86612657e+03,\n 6.76465758e+03, 3.32999704e+04, 1.01164073e+03, 2.95614706e+03])), ('precursor_mass', 991.4757742500002)])\nOrderedDict([('spectrum', [1130.5628753192157, 1387.6794045938063, 1630.7634320530121, 1729.8307097562474, 1963.9299587935664, 139.07717416195123, 167.593072870408, 309.691618906608, 522.2652085082493, 751.8556996324209, 815.8904407012014, 908.9366544617126, 982.4648811972176, 1056.0008589035328, 313.1540633215026, 627.3132521604621, 928.4208245764559, 1233.5593281588028, 1852.8642725106254, 2015.9338609538734, 2129.0116100423124, 250.1317057590831, 464.7138933685459, 617.2816642211901, 756.3286774617708, 898.4264625424265, 1008.4650423572791]), ('abundance', array([ 1415.87930434, 3134.63741547, 1128.17472203, 5185.46086239,\n 1973.59026761, 2404.80038119, 2367.02177289, 451.82514219,\n 289.992863 , 2887.76796034, 42.71620886, 1091.41885279,\n 599.62885363, 385.70093924, 13388.12836123, 3011.09180172,\n 2416.84344359, 1864.9733543 , 13894.0770411 , 166.59960574,\n 5891.47204128, 2909.82143098, 4842.76034035, 488.18977402,\n 171.69500037, 389.13739704, 1685.19065999])), ('precursor_mass', 1065.00998125)])\nOrderedDict([('spectrum', [148.07272775566994, 261.166628504159, 424.22185005429156, 212.61430862972625, 383.22340850504173, 625.2625293817106, 103.0513398531974, 182.08565353174802, 394.6667893136968, 646.8072628515694, 703.3533821732765, 776.8835493593389]), ('abundance', array([1.94442705e+03, 2.41110615e+05, 6.73137947e+02, 3.48883983e+02,\n 1.18418167e+03, 3.88535259e+02, 1.36456134e+04, 1.56029694e+03,\n 4.47814136e+02, 1.00634003e+05, 2.97289823e+03, 7.53511235e+01])), ('precursor_mass', 776.88279275)])\nOrderedDict([('spectrum', [1043.531873756995, 131.08189437699642, 639.3188409716577, 825.3942571429073, 313.13572938095564, 516.2263966649689, 622.7919124889906, 704.3204404076273]), ('abundance', array([14316.99169207, 12234.41122508, 307.30634858, 6701.98576592,\n 1738.87014811, 1684.75015783, 709.79908095, 12256.08082715])), ('precursor_mass', 834.3962642500001)])\nOrderedDict([('spectrum', [424.2239263278658, 1043.5302348343066, 1277.6337296352538, 1348.6663107583913, 131.08377117204267, 212.61614833244855, 241.126482753674, 595.8016905674893, 825.3905563135322, 147.07561240148002, 262.1012778993338, 448.18387779189817, 753.3207399831804, 868.3453477532394, 1315.612480230207, 1535.6901230669885, 1795.843769757683, 74.04242875398347, 131.55978468177827, 303.6256633917176, 516.2083187270628, 658.304905855625, 898.4239318690924]), ('abundance', array([ 123.48347522, 942.15547346, 5996.36468374, 724.91369122,\n 29581.10683629, 980.0262567 , 46389.6536388 , 321.52442256,\n 2115.97723625, 924.68475304, 448.12210391, 2026.59011755,\n 3087.53983897, 1782.65175221, 4797.74803339, 719.55145912,\n 23887.88400964, 3759.44996904, 2604.57848812, 7192.67387243,\n 2637.18337572, 2739.63232773, 8533.30806691])), ('precursor_mass', 898.42555325)])\nOrderedDict([('spectrum', [148.07881154815036, 1043.5303556279707, 1348.6677266811141, 1876.9014226084191, 319.1747318186947, 464.75505908650655, 522.2664562246032, 674.8419267743441, 825.3883662659936, 889.4203135499815, 938.9555252254365, 1258.5739657704455, 1894.9111248193276, 274.12580937790005, 565.7397498290651, 736.3489827000451, 874.4236578146284, 947.9624453318241]), ('abundance', array([8.05706290e+01, 3.25671372e+02, 6.96450881e+02, 1.12007036e+03,\n 1.50937148e+04, 9.02786801e+03, 4.39900657e+02, 5.97597048e+02,\n 1.86339897e+05, 4.34750959e+03, 6.10379288e+03, 3.69116414e+03,\n 1.35427371e+03, 1.05572283e+04, 2.54360474e+03, 9.67189007e+04,\n 1.16134501e+03, 7.82418690e+02])), ('precursor_mass', 947.95976025)])\nOrderedDict([('spectrum', [148.08276053778664, 765.4408038365935, 1277.6313145549993, 1534.7475954781955, 1777.8340003936098, 1876.9036070537124, 1963.9346370892347, 74.541659560481, 131.08349005430807, 241.12438755087396, 464.7504699376464, 595.8002002163679, 639.3203171255013, 674.8380614119504, 767.881533138896, 825.3906489450927, 205.11839282716426, 333.1762100926136, 448.2028910558419, 1054.4512810212414, 1501.7101767586325, 1721.7932275073056, 1981.9454828067944, 103.06253378935958, 167.09257754480652, 317.6466933057482, 353.1632768874538, 396.6827603147636, 527.7272872380488, 609.2590651313111, 673.3034480728254, 917.9419010057593]), ('abundance', array([1.85028331e+04, 7.68500824e+02, 1.77883312e+03, 4.01371031e+03,\n 8.84125302e+02, 2.19503864e+03, 9.45587114e+03, 1.99916733e+03,\n 1.85623906e+03, 8.75025367e+01, 9.48156446e+03, 1.51154531e+02,\n 1.73680804e+03, 1.47377188e+04, 5.30367806e+03, 1.23205240e+04,\n 8.57953499e+00, 4.16362023e+02, 1.04471415e+04, 8.27153442e+03,\n 4.23953189e+03, 3.50845428e+04, 1.68971695e+04, 2.06742986e+03,\n 2.01430037e+01, 1.54531004e+03, 4.27613769e+05, 1.27781423e+04,\n 1.07506169e+03, 6.13049878e+02, 5.97423030e+03, 6.34825411e+03])), ('precursor_mass', 991.4757742500001)])\nOrderedDict([('spectrum', [148.07157012014778, 424.2242522598984, 928.5041651047748, 1190.6028292455562, 1277.6341259338942, 1649.775898256719, 1963.93485770616, 2111.0053344750336, 319.17588621111463, 383.2227737242432, 464.75551779620946, 674.8357230498821, 767.8763785975784, 889.4142361536632, 1056.003543551667, 480.2455471187982, 781.3517923446128, 939.420392619222, 1086.4923158090166, 1648.7809149376797, 2129.01503500135, 127.06130529147755, 176.59625820511525, 298.13812443204944, 426.6981941845719, 470.21205380931104, 543.7508081899017, 682.7905605028793, 824.8921867428234, 934.933873842488, 991.4739138829437, 1065.0082587547554]), ('abundance', array([6.69419355e+02, 4.46782827e+03, 8.30814526e+01, 2.57975078e+03,\n 1.19687493e+05, 1.83561457e+03, 3.90614078e+03, 1.59620055e+04,\n 2.33201033e+03, 1.44904412e+03, 6.86256833e+03, 2.01315953e+03,\n 4.39178413e+02, 1.70292728e+04, 9.74072062e+02, 1.12178395e+03,\n 2.78529244e+04, 1.88125040e+03, 1.88503154e+04, 4.38151858e+03,\n 7.92173458e+03, 2.51897106e+03, 2.80188350e+03, 1.38531476e+03,\n 3.34319855e+02, 6.14160318e+04, 4.42856121e+03, 3.49677493e+02,\n 1.96096542e+03, 7.25270214e+03, 5.84195651e+03, 9.24786837e+02])), ('precursor_mass', 1065.00998125)])\nOrderedDict([('spectrum', [261.1595870021889, 481.2472171131063, 637.3453083092165, 928.5038530191717, 1043.5312940011315, 1534.7450411787963, 1777.834069614848, 2258.069095493573, 212.61328286184175, 383.2270612494351, 639.3176134515653, 767.8768157659597, 825.3920431431796, 889.4209680431373, 938.9575164614328, 982.4703929173584, 742.3405087966224, 928.4223242448525, 999.4556988554021, 1086.4913015954357, 1511.646955076816, 1639.7433408311397, 83.54795719976156, 157.09257132947303, 200.59862534503165, 314.16033592976584, 371.6701860416618, 674.7968498513969, 820.3757627066549, 898.4252017101244, 926.9350872150246, 1138.5426477542085]), ('abundance', array([2.54033688e+03, 1.96646847e+04, 6.12256956e+02, 1.18124570e+03,\n 2.65658739e+03, 5.99552667e+03, 1.57379484e+04, 1.70950610e+04,\n 4.94397594e+04, 2.83547210e+02, 3.89742023e+01, 6.93806965e+03,\n 1.84260749e+03, 3.72390195e+03, 1.21932603e+04, 2.89557268e+03,\n 4.78736393e+02, 2.96151124e+04, 3.77264361e+03, 5.42486643e+03,\n 6.12162197e+03, 5.50275032e+02, 2.91715161e+03, 5.06424406e+03,\n 1.54092923e+02, 4.30006189e+02, 1.01065231e+04, 2.97542778e+03,\n 4.06281983e+02, 1.83167772e+03, 4.31298444e+03, 2.00282056e+03])), ('precursor_mass', 1138.54418825)])\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbb2f0a5eb7fa8d072ad03570f3ddcd832e5a602
| 8,086 |
ipynb
|
Jupyter Notebook
|
ch_01/ch_01_solution.ipynb
|
BilkisKhan/Assignments_Panda
|
df534e18f7b4addc4bb1b4a3175ea00acdb5878d
|
[
"MIT"
] | null | null | null |
ch_01/ch_01_solution.ipynb
|
BilkisKhan/Assignments_Panda
|
df534e18f7b4addc4bb1b4a3175ea00acdb5878d
|
[
"MIT"
] | null | null | null |
ch_01/ch_01_solution.ipynb
|
BilkisKhan/Assignments_Panda
|
df534e18f7b4addc4bb1b4a3175ea00acdb5878d
|
[
"MIT"
] | null | null | null | 20.114428 | 90 | 0.473535 |
[
[
[
"from statistics import mean, stdev\nfrom statistics import stdev\nfrom statistics import variance\nfrom collections import Counter\nfrom statistics import mode\nfrom statistics import mean\nfrom statistics import median\nfrom statistics import mean, stdev\nimport numpy as np\nimport math\nimport random\n\nrandom.seed(0)\nsalaries = [round(random.random()*1000000, -3) for _ in range(100)]\n",
"_____no_output_____"
],
[
"#####\n# 5(a) mean\nsum(salaries) / len(salaries) == mean(salaries)\n",
"_____no_output_____"
],
[
"# 5(b) Median \n\n\ndef getmedian(val):\n val.sort()\n midnumber = (len(val) + 1) / 2 - 1\n if len(val) % 2:\n return x[int(midnumber)]\n else:\n return (val[math.floor(midnumber)] + val[math.ceil(midnumber)]) / 2\n\n\nprint(getmedian(salaries) == median(salaries))",
"True\n"
],
[
"# 5(c) Mode\n\n\nc = Counter(salaries)\nmodeVal = c.most_common(1)[0][0]\nprint(modeVal)\nprint(modeVal == mode(salaries))",
"477000.0\nTrue\n"
],
[
"# 5(d) Varience\nprint(variance(salaries))\n\nmeanDat = sum(salaries) / len(salaries)\nvar = sum(pow(x-meanDat, 2) for x in salaries)/(len(salaries) - 1)\nprint(var == variance(salaries))",
"70664054444.44444\nTrue\n"
],
[
"# 5(e) Standard deviation\nmeanVal = sum(salaries) / len(salaries)\nvar = sum(pow(x-meanVal, 2) for x in salaries)/(len(salaries) - 1)\nstd = math.sqrt(var)\nprint(std)\n(std == stdev(salaries))",
"265827.11382484\n"
],
[
"# 6(a) Range\nsalrange = max(salaries) - min(salaries)\nprint(salrange)",
"995000.0\n"
],
[
"# 6(b) coefficient of variation\n\nprint(stdev(salaries) / mean(salaries))",
"0.45386998894439035\n"
],
[
"\n# 6(c) interquartile\n\ndef percentile(val, percentage):\n val.sort()\n length = len(val) \n index_number = (length + 1) * percentage\n index_number= index_number- 1\n \n if len(val) % 2:\n return val[int(index_number)]\n else:\n return (val[math.floor(index_number)] + val[math.ceil(index_number)]) / 2\n \nQ3 = percentile(salaries, 0.75)\nQ1 = percentile(salaries, 0.25) \n\nIQR = Q3 - Q1\nIQR\n",
"_____no_output_____"
],
[
"# 6(d) quartile coefficent of dispersion\n\nIQR / (Q1 + Q3)",
"_____no_output_____"
],
[
"\n# 7(a) scale the data \n#𝑧𝑖=𝑥𝑖−min(𝑥)/max(𝑥)−min(𝑥)\n\nminSal = min(salaries)\nmaxSal = max(salaries)\nsalRange = maxSal - minSal\nscaled = [(v - minSal) / salRange for v in salaries]\n",
"_____no_output_____"
],
[
"# 7(b) standardizing\n\nmeanVal\nstdDv = stdev(salaries)\nstnd = [(v - meanVal) / stdDv for v in salaries]",
"_____no_output_____"
],
[
"# 8(a) covariance between standardized and normalized \nimport numpy as np\nnp.cov(scaled, stnd)",
"_____no_output_____"
],
[
"# 8(b) Pearson correlation coefficient\nnp.corrcoef(np.cov(scaled, stnd))",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb2f9394fc96ffbd5d4ee20f4b0611a917c0f62
| 148,214 |
ipynb
|
Jupyter Notebook
|
JANUSPHASETHREEPOINTTWO.ipynb
|
lordfiftyfive/Special-Projects
|
ffdf333c4f194ed3f6f3eaec3aecf35ca4118cf6
|
[
"BSD-2-Clause"
] | null | null | null |
JANUSPHASETHREEPOINTTWO.ipynb
|
lordfiftyfive/Special-Projects
|
ffdf333c4f194ed3f6f3eaec3aecf35ca4118cf6
|
[
"BSD-2-Clause"
] | null | null | null |
JANUSPHASETHREEPOINTTWO.ipynb
|
lordfiftyfive/Special-Projects
|
ffdf333c4f194ed3f6f3eaec3aecf35ca4118cf6
|
[
"BSD-2-Clause"
] | null | null | null | 68.968823 | 47,314 | 0.655957 |
[
[
[
"<a href=\"https://colab.research.google.com/github/lordfiftyfive/Special-Projects/blob/master/JANUSPHASETHREEPOINTTWO.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
]
],
[
[
" #!pip install --upgrade tf-nightly tfp-nightly\n#!pip uninstall tensorflow\n!pip install tensorflow==2.0.0-beta1\n#!pip install tensorflow==2.0.0rc0\n#!pip install tensorflow-probability\n#!pip install gaussian_processes\n!pip install quandl\n#!pip install rpy2\n!pip install bootstrapped\n!pip install hurst\n!pip install stldecompose\n!pip install GPyOpt\n!pip install parameter-sherpa\n\n#!pip install tensorflow-probability==0.8.0\n#!pip install gpflow==1.5.1\n#!pip install gpflow==2.0.0rc1",
"Requirement already satisfied: tensorflow==2.0.0a0 in /usr/local/lib/python3.6/dist-packages (2.0.0a0)\nRequirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.1.0)\nRequirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.0.8)\nRequirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (0.8.1)\nRequirement already satisfied: google-pasta>=0.1.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (0.2.0)\nRequirement already satisfied: numpy<2.0,>=1.14.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.18.2)\nRequirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.27.2)\nRequirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (0.34.2)\nRequirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.1.0)\nRequirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (3.10.0)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.12.0)\nRequirement already satisfied: tf-estimator-nightly<1.14.0.dev2019030116,>=1.14.0.dev2019030115 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.14.0.dev2019030115)\nRequirement already satisfied: gast>=0.2.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (0.3.3)\nRequirement already satisfied: tb-nightly<1.14.0a20190302,>=1.14.0a20190301 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (1.14.0a20190301)\nRequirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==2.0.0a0) (0.9.0)\nRequirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.6->tensorflow==2.0.0a0) (2.10.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tensorflow==2.0.0a0) (46.0.0)\nRequirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.14.0a20190302,>=1.14.0a20190301->tensorflow==2.0.0a0) (3.2.1)\nRequirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<1.14.0a20190302,>=1.14.0a20190301->tensorflow==2.0.0a0) (1.0.0)\nCollecting tensorflow-probability==0.7.0rc0\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/50/a5/c4dac165347b939a59406b33510f0ecc37cef296f078d6517b8643b0bb13/tensorflow_probability-0.7.0rc0-py2.py3-none-any.whl (981kB)\n\u001b[K |████████████████████████████████| 983kB 12.3MB/s \n\u001b[?25hRequirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0rc0) (1.18.2)\nRequirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0rc0) (1.12.0)\nRequirement already satisfied: cloudpickle>=0.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0rc0) (1.1.1)\nRequirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from tensorflow-probability==0.7.0rc0) (4.4.2)\n\u001b[31mERROR: tensorflow-gan 2.0.0 has requirement tensorflow-probability>=0.7, but you'll have tensorflow-probability 0.7.0rc0 which is incompatible.\u001b[0m\n\u001b[31mERROR: tensor2tensor 1.14.1 has requirement tensorflow-probability==0.7.0, but you'll have tensorflow-probability 0.7.0rc0 which is incompatible.\u001b[0m\nInstalling collected packages: tensorflow-probability\n Found existing installation: tensorflow-probability 0.8.0rc0\n Uninstalling tensorflow-probability-0.8.0rc0:\n Successfully uninstalled tensorflow-probability-0.8.0rc0\nSuccessfully installed tensorflow-probability-0.7.0rc0\nRequirement already satisfied: quandl in /usr/local/lib/python3.6/dist-packages (3.5.0)\nRequirement already satisfied: more-itertools in /usr/local/lib/python3.6/dist-packages (from quandl) (8.2.0)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from quandl) (1.12.0)\nRequirement already satisfied: numpy>=1.8 in /usr/local/lib/python3.6/dist-packages (from quandl) (1.18.2)\nRequirement already satisfied: requests>=2.7.0 in /usr/local/lib/python3.6/dist-packages (from quandl) (2.21.0)\nRequirement already satisfied: inflection>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from quandl) (0.3.1)\nRequirement already satisfied: python-dateutil in /usr/local/lib/python3.6/dist-packages (from quandl) (2.8.1)\nRequirement already satisfied: pandas>=0.14 in /usr/local/lib/python3.6/dist-packages (from quandl) (0.25.3)\nRequirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.7.0->quandl) (2.8)\nRequirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.7.0->quandl) (1.24.3)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.7.0->quandl) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.7.0->quandl) (2019.11.28)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.14->quandl) (2018.9)\nRequirement already satisfied: bootstrapped in /usr/local/lib/python3.6/dist-packages (0.0.2)\nRequirement already satisfied: numpy>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from bootstrapped) (1.18.2)\nRequirement already satisfied: pandas>=0.18.1 in /usr/local/lib/python3.6/dist-packages (from bootstrapped) (0.25.3)\nRequirement already satisfied: matplotlib>=1.5.3 in /usr/local/lib/python3.6/dist-packages (from bootstrapped) (3.2.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.18.1->bootstrapped) (2018.9)\nRequirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.18.1->bootstrapped) (2.8.1)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.5.3->bootstrapped) (0.10.0)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.5.3->bootstrapped) (1.1.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib>=1.5.3->bootstrapped) (2.4.6)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.6.1->pandas>=0.18.1->bootstrapped) (1.12.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from kiwisolver>=1.0.1->matplotlib>=1.5.3->bootstrapped) (46.0.0)\nRequirement already satisfied: hurst in /usr/local/lib/python3.6/dist-packages (0.0.5)\nRequirement already satisfied: pandas>=0.18 in /usr/local/lib/python3.6/dist-packages (from hurst) (0.25.3)\nRequirement already satisfied: numpy>=1.10 in /usr/local/lib/python3.6/dist-packages (from hurst) (1.18.2)\nRequirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.18->hurst) (2.8.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.18->hurst) (2018.9)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.6.1->pandas>=0.18->hurst) (1.12.0)\nRequirement already satisfied: stldecompose in /usr/local/lib/python3.6/dist-packages (0.0.5)\nRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from stldecompose) (1.18.2)\nRequirement already satisfied: statsmodels in /usr/local/lib/python3.6/dist-packages (from stldecompose) (0.10.2)\nRequirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from stldecompose) (0.25.3)\nRequirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from stldecompose) (1.4.1)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from stldecompose) (3.2.1)\nRequirement already satisfied: patsy>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from statsmodels->stldecompose) (0.5.1)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->stldecompose) (2018.9)\nRequirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->stldecompose) (2.8.1)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->stldecompose) (1.1.0)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->stldecompose) (0.10.0)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->stldecompose) (2.4.6)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from patsy>=0.4.0->statsmodels->stldecompose) (1.12.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from kiwisolver>=1.0.1->matplotlib->stldecompose) (46.0.0)\nRequirement already satisfied: GPyOpt in /usr/local/lib/python3.6/dist-packages (1.2.6)\nRequirement already satisfied: GPy>=1.8 in /usr/local/lib/python3.6/dist-packages (from GPyOpt) (1.9.9)\nRequirement already satisfied: numpy>=1.7 in /usr/local/lib/python3.6/dist-packages (from GPyOpt) (1.18.2)\nRequirement already satisfied: scipy>=0.16 in /usr/local/lib/python3.6/dist-packages (from GPyOpt) (1.4.1)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from GPy>=1.8->GPyOpt) (1.12.0)\nRequirement already satisfied: paramz>=0.9.0 in /usr/local/lib/python3.6/dist-packages (from GPy>=1.8->GPyOpt) (0.9.5)\nRequirement already satisfied: decorator>=4.0.10 in /usr/local/lib/python3.6/dist-packages (from paramz>=0.9.0->GPy>=1.8->GPyOpt) (4.4.2)\nRequirement already satisfied: parameter-sherpa in /usr/local/lib/python3.6/dist-packages (1.0.6)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (3.2.1)\nRequirement already satisfied: GPyOpt>=1.2.5 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (1.2.6)\nRequirement already satisfied: numpy>=1.8.2 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (1.18.2)\nRequirement already satisfied: enum34 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (1.1.10)\nRequirement already satisfied: pandas>=0.20.3 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (0.25.3)\nRequirement already satisfied: flask>=0.12.2 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (1.1.1)\nRequirement already satisfied: scikit-learn>=0.19.1 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (0.22.2.post1)\nRequirement already satisfied: pymongo>=3.5.1 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (3.10.1)\nRequirement already satisfied: scipy>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from parameter-sherpa) (1.4.1)\nRequirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->parameter-sherpa) (2.4.6)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->parameter-sherpa) (0.10.0)\nRequirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->parameter-sherpa) (2.8.1)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->parameter-sherpa) (1.1.0)\nRequirement already satisfied: GPy>=1.8 in /usr/local/lib/python3.6/dist-packages (from GPyOpt>=1.2.5->parameter-sherpa) (1.9.9)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.20.3->parameter-sherpa) (2018.9)\nRequirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from flask>=0.12.2->parameter-sherpa) (7.1.1)\nRequirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from flask>=0.12.2->parameter-sherpa) (1.1.0)\nRequirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from flask>=0.12.2->parameter-sherpa) (2.11.1)\nRequirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from flask>=0.12.2->parameter-sherpa) (1.0.0)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.19.1->parameter-sherpa) (0.14.1)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from cycler>=0.10->matplotlib->parameter-sherpa) (1.12.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from kiwisolver>=1.0.1->matplotlib->parameter-sherpa) (46.0.0)\nRequirement already satisfied: paramz>=0.9.0 in /usr/local/lib/python3.6/dist-packages (from GPy>=1.8->GPyOpt>=1.2.5->parameter-sherpa) (0.9.5)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->flask>=0.12.2->parameter-sherpa) (1.1.1)\nRequirement already satisfied: decorator>=4.0.10 in /usr/local/lib/python3.6/dist-packages (from paramz>=0.9.0->GPy>=1.8->GPyOpt>=1.2.5->parameter-sherpa) (4.4.2)\n"
],
[
"#!git clone git://github.com/statsmodels/statsmodels.git\n#!pip install git+https://github.com/statsmodels/statsmodels\n#install-gpflow-20-beta-version.",
"_____no_output_____"
]
],
[
[
"possible additional data\n\nhttps://usafacts.org/metrics/33937?regions=US&year=2016\n\nhttps://usafacts.org/metrics/55121?regions=US&year=2018",
"_____no_output_____"
]
],
[
[
"\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport quandl\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nimport rpy2\n#from rpy2.robjects.packages import importr\nfrom sklearn.decomposition import PCA, KernelPCA\n#from keras.layers import Input, Dense, Activation, Flatten, BatchNormalization\n#from tensorflow_probability import sts\nimport pandas as pd\nimport bootstrapped.bootstrap as bs\nimport bootstrapped.stats_functions as bs_stats\nfrom scipy.stats import ttest_ind, ttest_ind_from_stats,chisquare, mstats\nimport seaborn as sns\nimport statsmodels.api\n#from statsmodels.tsa.seasonal import STL\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom hurst import compute_Hc, random_walk\nimport scipy.integrate as integrate\nfrom stldecompose import decompose\nimport sherpa\n#import gpflow\n",
"_____no_output_____"
]
],
[
[
"SEE THIS LINK FOR JANUS PHASE THREE\n\nhttps://github.com/GPflow/GPflow/issues/1007",
"_____no_output_____"
]
],
[
[
"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\"\"\"\nImporting libraries\n\"\"\"\n#import os\n#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\"\"\"\nimport keras\nfrom keras.layers import Input, Dense, Activation, Flatten, BatchNormalization, RNN, LSTM\nimport numpy as np\n#from numpy import array\nfrom keras.models import load_model, Model, model_from_json, Sequential\nfrom keras.callbacks import EarlyStopping\nimport pandas as pd\n#import datetime\n#import requests\n#import sys\n#from time import time, sleep\n#import time as systime\nimport quandl\n#import math\n#import collections, itertools\nimport tensorflow as tf\n#from sklearn import preprocessing\n#from sklearn.preprocessing import Imputer, StandardScaler, Normalizer\nfrom sklearn.preprocessing import MinMaxScaler\nfrom scipy.stats import mstats\nimport matplotlib.pyplot as plt\nfrom scipy.stats import ttest_ind, ttest_ind_from_stats,chisquare\nfrom sklearn.decomposition import PCA\n\"\"\"\n\"\"\"\n@misc{,\n title={EconomicGrowthPredictor},\n author={Subarno},\n year={2018},\n \n}\n\n\"\"\"\n\n# in supervised clustering samples are in rows and features are in columns\n\n\"\"\"\nunsupervised learning can be used to find hidden patterns data \n\"\"\"\n\n\n\"\"\"\nGetting data\n\"\"\"\nquandl.ApiConfig.api_key = 'DNMZo2iRzVENxpxqHBKF'\n\n#te.getCalendarData(country=['united states', 'china'], category=['imports','exports'],\n #initDate='2017-06-07', endDate='2017-12-31',\n #output_type='df')\ndatafour = quandl.get(\"YALE/SPCOMP\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", transform=\"rdiff\", collapse=\"quarterly\", start_date=\"1959-09-30\", end_date=\"2018-12-31\")# earliest date is 1960-06-30 #quandl.get(\"YALE/CPIQ\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", collapse=\"quarterly\", start_date=\"1970-12-31\", end_date=\"2016-03-31\")#quandl.get(\"UNAE/GDPCD_USA\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", end_date=\"2016-12-31\")# quandl.get(\"UNAE/GDPCD_USA\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", end_date=\"2016-12-31\")\nData_to_predict = quandl.get(\"FRBP/GDPPLUS_042619\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", collapse=\"quarterly\")#quandl.get(\"FRBP/GDPPLUS_042619\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", transform=\"rdiff\")#quandl.get(\"FRBP/GDPPLUS\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", collapse=\"quarterly\", start_date=\"1960-06-30\")\ndatafive = quandl.get(\"FRED/PCETRIM1M158SFRBDAL\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", collapse=\"quarterly\", start_date=\"1977-02-01\",end_date=\"2016-03-31\")#quandl.get(\"FRED/VALEXPUSM052N\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", transform=\"rdiff\", collapse=\"quarterly\", start_date=\"1960-09-30\")#quandl.get(\"WWDI/USA_NE_GDI_TOTL_CD\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", start_date=\"1970-12-31\")\nData_To_predict = Data_to_predict.values\nDESPAIR = quandl.get(\"USMISERY/INDEX\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", transform=\"rdiff\", collapse=\"quarterly\", start_date=\"1959-09-30\", end_date=\"2018-12-31\") \nDebt_data_change_of_change = quandl.get(\"FRED/NCBDSLQ027S\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", transform=\"rdiff\",collapse=\"quarterly\",start_date=\"1959-06-30\",end_date=\"2018-12-31\")\n \nDataSix = quandl.get(\"FRED/ROWFDIQ027S\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", transform=\"rdiff\", collapse=\"quarterly\", start_date=\"1959-06-30\",end_date=\"2018-12-31\")\nprint(DataSix)\n#Data_To_Predict = np.matrix(Data_To_predict) \nprint(\"datasix\")\n#print(Data_To_Predict)\n#print(\"input\")\n#print(Datafour)\n#early_stop = EarlyStopping(monitor='loss',patience=5, verbose=1)\ndata_to_predict = Data_To_predict#[-47::]#np.reshape(Data_TO_predict, (9,6)\n\n\"\"\"\n#Ask if my model is making good predictions or whether the predicitons are due to the loss of information from the nornmalization procedure of the outputs\n\n#create a plot of the data before this ß\n#split_date= pd.Timestamp('01-01-2011')\n#train = df.loc(:split_date,[''])\n#test = df.loc(split_date:, [''])\n\n\"\"\"\n#data preprocessing\n\ntrainingtarget = data_to_predict#normalizer.transform(data_to_predict)\n#mstats.winsorize()\nScalar = MinMaxScaler(feature_range=(0,1))\n\t\n#trainingtarget = Scalar.fit_transform(trainingtarget)\n \n \n#datafour = preprocessing.scale(datafour)\n#trainingtarget = preprocessing.scale(trainingtarget)\ndatasix = pd.DataFrame(DataSix)\ndatafour = pd.DataFrame(datafour)\ndatasix = datasix.drop(datasix.index[0])\nprint(\"data six\")\nprint(datasix)\n#\n #class statsmodels.tsa.seasonal.STL(endog, period=None, seasonal=7, trend=None, low_pass=None, seasonal_deg=0, trend_deg=0, low_pass_deg=0, robust=False, seasonal_jump=1, trend_jump=1, low_pass_jump=1)¶\ndatafour = pd.concat([datafour, Debt_data_change_of_change,DESPAIR], axis=1)\n#datafour = datafour.fillna(0)\ndata_to_predict = pd.DataFrame(data_to_predict)\n#z = pd.concat([datafour,data_to_predict])\n#print(z.ndim)\n#z = Scalar.fit(z)\n#z = np.array(z)\n#z = np.vsplit(z,7)\n \n#datafour = z[0]\n \n#trainingtarget = z[1]\n \n#z = pd.concat(datafour,trainingtarget)\n#z = Scalar.fit_transform(z)\n#print(z.shape())\n#print(z)\nprint(datafour)\nprint(trainingtarget)\npca = PCA()\na = decompose(trainingtarget)#seasonal_decompose(trainingtarget,model='additive',freq=1)\na.plot()\nprint(trainingtarget)\nplt.plot(trainingtarget)\n#trainingtarget = a.trend\ndatafour = Scalar.fit_transform(datafour)\ndatafour = pca.fit_transform(datafour)\n#datafour = normalizer.fit(datafour)\ntrainingtarget = Scalar.fit_transform(trainingtarget)\ny = trainingtarget\nX = datafour\n#trainingtarget = pd.DataFrame(trainingtarget)\n#trainingtarget = pd.DataFrame(trainingtarget)\n#time_index = pd.date_range(start=1959.6, end=2018.8, periods=237)#np.linspace(1959.6,2018.8,237)#np.linspace(0, 10, N, endpoint=True)\n#trainingtarget = trainingtarget.set_index(time_index)\n\n\n\n#trainingtarget = statsmodels.tsa.seasonal.STL(trainingtarget,period=None)\n#Reminder: look into possibility that the DATES column is being included into datafour\n\n#inputOne = len(dataThree)\n#print(inputOne)\n#print(dataThree)\n#x_train = Scalar.fit_transform(datafour[:220:])\n#y_train = Scalar.fit_transform(trainingtarget[:220:])\n#x_train = pca.fit(x_train)\n#x_test = Scalar.transform(datafour[220::]) \n\nprint(\"shape of x\")\nprint(X.shape)\n\ny = trainingtarget#[:, None]\n#Xshape = np.arange(dataThree).reshape(86, 1)\n#xshape.flat(86)\n#ConsolidatedInput = pd.merge(dataThree,dataTwo,dataOne)\n#b = dataThree.flatten('K')\n\t\n#xShape = X[:,None]#datafour.shape[1]\n#print(xShape)\n#X=np.reshape(X.shape[1],X.shape[0]) \n#datafour = tf.cast(datafour, tf.float32)\n#trainingtarget = tf.cast(trainingtarget, tf.float32) \n#Deep learning algorithm\n\t\n\n\n\"\"\"\ninputs = tf.keras.Input(shape=(1,13))\nfirst = tf.keras.layers.LSTM(10,activation='relu',kernel_initializer='ones', use_bias=False)(inputs)\n\nu = tf.keras.layers.Dense(250,activation='relu',kernel_initializer='ones',use_bias=False)(first)\nb = tf.keras.layers.BatchNormalization()(u)\nu = tf.keras.layers.Dense(500, activation='relu',kernel_initializer='ones',use_bias=False)(b)\nu = tf.keras.layers.Dense(10, activation='relu')(u)\noutputs = tf.keras.layers.Dense(1, activation='sigmoid')(u)\nModel = tf.keras.Model(inputs=inputs, outputs=outputs)\n\n#Adadelta\nModel.compile(optimizer='Adagrad',\n loss='MSLE',\n metrics=['accuracy'])\n\t\nModel.fit(X,Y,epochs=8, verbose=1,validation_split=0.2)#, callbacks=[early_stop])\n\nPrediction = Model.predict(X[189::])\nprint(Prediction)\nprint(Prediction.shape)\nu = 219\nModel.summary()\n\"\"\"\n#a = model.evaluate(trainingtarget[180::], Prediction, verbose=0)\n#.save_weights('weights-init.h5')\n#trainingtarget = trainingtarget#[:-15:]\n#trainingtarget = normalizer.transform(trainingtarget)\n#blue is prediction orange is actual\n\n#Note to self: check to see that it is actually comparing predictions to TEST DATA\n \n\n#Graphing\n\n\n",
" Value\nDate \n1959-12-31 -2.436508\n1960-03-31 -1.574586\n1960-06-30 -0.298077\n1960-09-30 0.246575\n1960-12-31 -0.483516\n... ...\n2017-12-31 -0.310452\n2018-03-31 0.278582\n2018-06-30 -0.951335\n2018-09-30 43.060628\n2018-12-31 -0.316263\n\n[237 rows x 1 columns]\ndatasix\ndata six\n Value\nDate \n1960-03-31 -1.574586\n1960-06-30 -0.298077\n1960-09-30 0.246575\n1960-12-31 -0.483516\n1961-03-31 1.021277\n... ...\n2017-12-31 -0.310452\n2018-03-31 0.278582\n2018-06-30 -0.951335\n2018-09-30 43.060628\n2018-12-31 -0.316263\n\n[236 rows x 1 columns]\n S&P Composite Dividend ... Inflation Rate Misery Index\n1959-12-31 0.035232 0.011050 ... 0.253623 0.021802\n1960-03-31 -0.068405 0.060109 ... 0.000000 0.014225\n1960-06-30 0.040712 0.005155 ... -0.005780 -0.001403\n1960-09-30 -0.042787 0.000000 ... -0.406977 -0.084270\n1960-12-31 0.036307 0.000000 ... 0.333333 0.220859\n... ... ... ... ... ...\n2017-12-31 0.068797 0.015777 ... -0.053812 -0.034215\n2018-03-31 0.014424 0.021868 ... 0.118483 0.040258\n2018-06-30 0.019084 0.019800 ... 0.216102 0.063467\n2018-09-30 0.053425 0.026476 ... -0.205575 -0.129549\n2018-12-31 -0.115178 0.026939 ... -0.162281 -0.028428\n\n[237 rows x 13 columns]\n[[ 5.79203 ]\n [ 1.34229 ]\n [-0.328963 ]\n [-0.391626 ]\n [ 1.90183 ]\n [ 5.79442 ]\n [ 6.4968 ]\n [ 7.8818 ]\n [ 5.05793 ]\n [ 4.51151 ]\n [ 3.86883 ]\n [ 4.55533 ]\n [ 4.04211 ]\n [ 5.59246 ]\n [ 4.79488 ]\n [ 4.57696 ]\n [ 5.70386 ]\n [ 5.77085 ]\n [ 5.12072 ]\n [ 5.27936 ]\n [ 7.19789 ]\n [ 5.98077 ]\n [ 6.13003 ]\n [ 7.81088 ]\n [ 6.82991 ]\n [ 3.65192 ]\n [ 3.00844 ]\n [ 3.23455 ]\n [ 2.32443 ]\n [ 2.77207 ]\n [ 3.89892 ]\n [ 4.65521 ]\n [ 5.44585 ]\n [ 5.30513 ]\n [ 4.80952 ]\n [ 3.57479 ]\n [ 3.19119 ]\n [ 2.53623 ]\n [ 1.74349 ]\n [-0.266546 ]\n [-1.43488 ]\n [ 0.372749 ]\n [ 1.55772 ]\n [ 0.157684 ]\n [ 4.89411 ]\n [ 3.27026 ]\n [ 3.43351 ]\n [ 5.2628 ]\n [ 5.73162 ]\n [ 5.09541 ]\n [ 6.70557 ]\n [ 8.86805 ]\n [ 6.14461 ]\n [ 2.39464 ]\n [ 2.063 ]\n [ 2.15205 ]\n [-1.45832 ]\n [-1.92259 ]\n [-2.14581 ]\n [-3.89255 ]\n [-2.30409 ]\n [ 3.09246 ]\n [ 6.39202 ]\n [ 5.15312 ]\n [ 6.19155 ]\n [ 3.23315 ]\n [ 3.03576 ]\n [ 2.45687 ]\n [ 4.82759 ]\n [ 7.6408 ]\n [ 5.97181 ]\n [ 3.49203 ]\n [ 4.79085 ]\n [ 8.17563 ]\n [ 4.10268 ]\n [ 3.26017 ]\n [ 2.49731 ]\n [-0.340506 ]\n [ 0.337329 ]\n [ 0.871606 ]\n [-1.30615 ]\n [-3.098 ]\n [ 3.06715 ]\n [ 6.80654 ]\n [ 2.58093 ]\n [ 1.64311 ]\n [ 2.64545 ]\n [-2.49919 ]\n [-1.73221 ]\n [ 0.242102 ]\n [-0.664651 ]\n [ 0.0786178]\n [ 4.1591 ]\n [ 6.04926 ]\n [ 6.15629 ]\n [ 8.4147 ]\n [ 9.23808 ]\n [ 6.32872 ]\n [ 4.50995 ]\n [ 4.24965 ]\n [ 3.5434 ]\n [ 3.41461 ]\n [ 3.95261 ]\n [ 2.81839 ]\n [ 3.20738 ]\n [ 1.97781 ]\n [ 2.42752 ]\n [ 3.23469 ]\n [ 4.25261 ]\n [ 5.62971 ]\n [ 5.77631 ]\n [ 4.88257 ]\n [ 4.855 ]\n [ 4.27421 ]\n [ 4.08692 ]\n [ 4.51391 ]\n [ 2.49301 ]\n [ 0.418549 ]\n [ 1.26007 ]\n [ 1.35855 ]\n [ 2.72697 ]\n [ 1.76043 ]\n [-0.322732 ]\n [-1.07429 ]\n [-0.0692295]\n [ 0.974605 ]\n [ 1.31889 ]\n [ 2.3353 ]\n [ 5.22727 ]\n [ 3.47557 ]\n [ 2.03133 ]\n [ 2.58641 ]\n [ 0.45102 ]\n [ 3.46622 ]\n [ 2.49934 ]\n [ 5.73686 ]\n [ 3.52112 ]\n [ 4.95061 ]\n [ 4.09487 ]\n [ 3.88778 ]\n [ 2.26596 ]\n [ 2.76656 ]\n [ 4.07994 ]\n [ 3.2402 ]\n [ 4.5535 ]\n [ 4.96334 ]\n [ 4.08749 ]\n [ 4.5329 ]\n [ 4.81146 ]\n [ 5.0082 ]\n [ 5.64033 ]\n [ 5.21966 ]\n [ 4.48614 ]\n [ 5.33569 ]\n [ 5.26808 ]\n [ 4.02887 ]\n [ 4.56124 ]\n [ 3.35166 ]\n [ 4.18453 ]\n [ 5.44795 ]\n [ 7.02761 ]\n [ 2.74501 ]\n [ 2.74998 ]\n [ 0.407766 ]\n [ 3.19998 ]\n [-0.100841 ]\n [-0.927735 ]\n [-0.599602 ]\n [ 3.09227 ]\n [ 2.86451 ]\n [ 1.20552 ]\n [ 2.36795 ]\n [ 1.63761 ]\n [ 3.44626 ]\n [ 3.63754 ]\n [ 3.09285 ]\n [ 3.56996 ]\n [ 4.52768 ]\n [ 4.25835 ]\n [ 2.87328 ]\n [ 3.53497 ]\n [ 3.45902 ]\n [ 3.39299 ]\n [ 5.61161 ]\n [ 5.20711 ]\n [ 1.78291 ]\n [ 1.92163 ]\n [ 1.19981 ]\n [ 0.412618 ]\n [ 0.569938 ]\n [-1.73 ]\n [-0.898518 ]\n [ 0.0769245]\n [-1.2496 ]\n [-2.8226 ]\n [-6.14489 ]\n [-4.68704 ]\n [ 0.7185 ]\n [ 2.08095 ]\n [ 3.86987 ]\n [ 2.86261 ]\n [ 4.13249 ]\n [ 4.80083 ]\n [ 1.55757 ]\n [ 1.17476 ]\n [ 2.29793 ]\n [ 2.44344 ]\n [ 3.59489 ]\n [ 5.94664 ]\n [ 1.95291 ]\n [-0.455773 ]\n [ 2.70585 ]\n [ 1.01155 ]\n [ 2.12825 ]\n [ 1.12048 ]\n [ 2.2386 ]\n [ 3.53684 ]\n [ 4.44024 ]\n [ 4.08105 ]\n [ 3.17901 ]\n [ 2.71998 ]\n [ 1.42263 ]\n [ 1.02912 ]\n [ 0.716699 ]\n [ 1.21727 ]\n [ 0.0507613]\n [ 1.69025 ]\n [ 2.33425 ]\n [ 3.1253 ]\n [ 2.64049 ]\n [ 1.67384 ]\n [ 1.8482 ]\n [ 3.24842 ]\n [ 1.80685 ]\n [ 3.43576 ]\n [ 2.30958 ]\n [ 2.82159 ]]\n[[ 5.79203 ]\n [ 1.34229 ]\n [-0.328963 ]\n [-0.391626 ]\n [ 1.90183 ]\n [ 5.79442 ]\n [ 6.4968 ]\n [ 7.8818 ]\n [ 5.05793 ]\n [ 4.51151 ]\n [ 3.86883 ]\n [ 4.55533 ]\n [ 4.04211 ]\n [ 5.59246 ]\n [ 4.79488 ]\n [ 4.57696 ]\n [ 5.70386 ]\n [ 5.77085 ]\n [ 5.12072 ]\n [ 5.27936 ]\n [ 7.19789 ]\n [ 5.98077 ]\n [ 6.13003 ]\n [ 7.81088 ]\n [ 6.82991 ]\n [ 3.65192 ]\n [ 3.00844 ]\n [ 3.23455 ]\n [ 2.32443 ]\n [ 2.77207 ]\n [ 3.89892 ]\n [ 4.65521 ]\n [ 5.44585 ]\n [ 5.30513 ]\n [ 4.80952 ]\n [ 3.57479 ]\n [ 3.19119 ]\n [ 2.53623 ]\n [ 1.74349 ]\n [-0.266546 ]\n [-1.43488 ]\n [ 0.372749 ]\n [ 1.55772 ]\n [ 0.157684 ]\n [ 4.89411 ]\n [ 3.27026 ]\n [ 3.43351 ]\n [ 5.2628 ]\n [ 5.73162 ]\n [ 5.09541 ]\n [ 6.70557 ]\n [ 8.86805 ]\n [ 6.14461 ]\n [ 2.39464 ]\n [ 2.063 ]\n [ 2.15205 ]\n [-1.45832 ]\n [-1.92259 ]\n [-2.14581 ]\n [-3.89255 ]\n [-2.30409 ]\n [ 3.09246 ]\n [ 6.39202 ]\n [ 5.15312 ]\n [ 6.19155 ]\n [ 3.23315 ]\n [ 3.03576 ]\n [ 2.45687 ]\n [ 4.82759 ]\n [ 7.6408 ]\n [ 5.97181 ]\n [ 3.49203 ]\n [ 4.79085 ]\n [ 8.17563 ]\n [ 4.10268 ]\n [ 3.26017 ]\n [ 2.49731 ]\n [-0.340506 ]\n [ 0.337329 ]\n [ 0.871606 ]\n [-1.30615 ]\n [-3.098 ]\n [ 3.06715 ]\n [ 6.80654 ]\n [ 2.58093 ]\n [ 1.64311 ]\n [ 2.64545 ]\n [-2.49919 ]\n [-1.73221 ]\n [ 0.242102 ]\n [-0.664651 ]\n [ 0.0786178]\n [ 4.1591 ]\n [ 6.04926 ]\n [ 6.15629 ]\n [ 8.4147 ]\n [ 9.23808 ]\n [ 6.32872 ]\n [ 4.50995 ]\n [ 4.24965 ]\n [ 3.5434 ]\n [ 3.41461 ]\n [ 3.95261 ]\n [ 2.81839 ]\n [ 3.20738 ]\n [ 1.97781 ]\n [ 2.42752 ]\n [ 3.23469 ]\n [ 4.25261 ]\n [ 5.62971 ]\n [ 5.77631 ]\n [ 4.88257 ]\n [ 4.855 ]\n [ 4.27421 ]\n [ 4.08692 ]\n [ 4.51391 ]\n [ 2.49301 ]\n [ 0.418549 ]\n [ 1.26007 ]\n [ 1.35855 ]\n [ 2.72697 ]\n [ 1.76043 ]\n [-0.322732 ]\n [-1.07429 ]\n [-0.0692295]\n [ 0.974605 ]\n [ 1.31889 ]\n [ 2.3353 ]\n [ 5.22727 ]\n [ 3.47557 ]\n [ 2.03133 ]\n [ 2.58641 ]\n [ 0.45102 ]\n [ 3.46622 ]\n [ 2.49934 ]\n [ 5.73686 ]\n [ 3.52112 ]\n [ 4.95061 ]\n [ 4.09487 ]\n [ 3.88778 ]\n [ 2.26596 ]\n [ 2.76656 ]\n [ 4.07994 ]\n [ 3.2402 ]\n [ 4.5535 ]\n [ 4.96334 ]\n [ 4.08749 ]\n [ 4.5329 ]\n [ 4.81146 ]\n [ 5.0082 ]\n [ 5.64033 ]\n [ 5.21966 ]\n [ 4.48614 ]\n [ 5.33569 ]\n [ 5.26808 ]\n [ 4.02887 ]\n [ 4.56124 ]\n [ 3.35166 ]\n [ 4.18453 ]\n [ 5.44795 ]\n [ 7.02761 ]\n [ 2.74501 ]\n [ 2.74998 ]\n [ 0.407766 ]\n [ 3.19998 ]\n [-0.100841 ]\n [-0.927735 ]\n [-0.599602 ]\n [ 3.09227 ]\n [ 2.86451 ]\n [ 1.20552 ]\n [ 2.36795 ]\n [ 1.63761 ]\n [ 3.44626 ]\n [ 3.63754 ]\n [ 3.09285 ]\n [ 3.56996 ]\n [ 4.52768 ]\n [ 4.25835 ]\n [ 2.87328 ]\n [ 3.53497 ]\n [ 3.45902 ]\n [ 3.39299 ]\n [ 5.61161 ]\n [ 5.20711 ]\n [ 1.78291 ]\n [ 1.92163 ]\n [ 1.19981 ]\n [ 0.412618 ]\n [ 0.569938 ]\n [-1.73 ]\n [-0.898518 ]\n [ 0.0769245]\n [-1.2496 ]\n [-2.8226 ]\n [-6.14489 ]\n [-4.68704 ]\n [ 0.7185 ]\n [ 2.08095 ]\n [ 3.86987 ]\n [ 2.86261 ]\n [ 4.13249 ]\n [ 4.80083 ]\n [ 1.55757 ]\n [ 1.17476 ]\n [ 2.29793 ]\n [ 2.44344 ]\n [ 3.59489 ]\n [ 5.94664 ]\n [ 1.95291 ]\n [-0.455773 ]\n [ 2.70585 ]\n [ 1.01155 ]\n [ 2.12825 ]\n [ 1.12048 ]\n [ 2.2386 ]\n [ 3.53684 ]\n [ 4.44024 ]\n [ 4.08105 ]\n [ 3.17901 ]\n [ 2.71998 ]\n [ 1.42263 ]\n [ 1.02912 ]\n [ 0.716699 ]\n [ 1.21727 ]\n [ 0.0507613]\n [ 1.69025 ]\n [ 2.33425 ]\n [ 3.1253 ]\n [ 2.64049 ]\n [ 1.67384 ]\n [ 1.8482 ]\n [ 3.24842 ]\n [ 1.80685 ]\n [ 3.43576 ]\n [ 2.30958 ]\n [ 2.82159 ]]\nshape of x\n(237, 13)\n"
]
],
[
[
"Hypotheses which underly this algorithm\n\n\n1. The data exhibits long term dependence. This is in part due to the fact that we believe components of the S&p 500 input variable exhibits long term dependence. Note: this hypothesis has been confirmed.\n\n2. IF hypothesis 1 is true the final posterior distribution does NOT follow a Standard normal distribution\n\n3. THe input variables DO NOT follow a Independent standard normal distribution but are correlated to one another\n\nwhat we need is a kernel which takes into account the fact that the data is time series (in other words we need a autocovariance function) and we need that auto covariance function to have long term dependence built in",
"_____no_output_____"
]
],
[
[
"#Hearst Exponent\nH, c, data = compute_Hc(y, kind='change', simplified=True)\nprint(a.trend)\nprint(np.abs(H))\n",
"_____no_output_____"
],
[
"#labels = quandl.get(\"FRBP/GDPPLUS_042619\", authtoken=\"DNMZo2iRzVENxpxqHBKF\", collapse=\"quarterly\")#quandl.get(\"FRBP/GDPPLUS_042619\", authtoken=\"DNMZo2iRzVENxpxqHBKF\")\n#labels=Scalar.fit_transform(labels)\n#b = decompose(labels)\n\nX = datafour[:,None]\nx = X\n#y = b\n#Y = a.trend\n#y = Y\n\nnum_inducing_points = 45\n#custom time series kernel integrate.quad(lambda x: special.jv(2.5,x), -π, π)e^(ih*lambda)*f(lambda)d(lambda)\n#default RBF kernel k(x, y) = amplitude**2 * exp(-||x - y||**2 / (2 * length_scale**2))\n\"\"\"\n def kernel(self):\n return 1/2*np.absolute(t)**(2H)+np.absolute(s)**(2H) - (np.absolute(t)-np.absolute(s))**2H \n t = x\n s = y\n Calculating the average value, Xm, of the X1..Xn series\n Calculating the standard series deviation, S\n Normalization of the series by deducting the average value, Zr (where r=1..n), from each value\n Creating a cumulative time series Y1=Z1+Zr, where r=2..n\n Calculating the magnitude of the cumulative time series R=max(Y1..Yn)-min(Y1..Yn)\n Dividing the magnitude of the cumulative time series by the standard deviation (S).\n\n\n\"\"\"\n\n#Time series gaussian kernel with long term dependence: E[BSubSccript(H)(H)BsubscriptH(s)] = 1/2|t|^2H-|t-s|&2H where H is the hearst exponent If we assume there is a long term dependence that means 1 > H > 1/2 \n\nx = x.astype(np.float32)#tf.dtypes.cast(x, tf.int32) #\n#x = tf.cast(x, tf.float32)\n#x = tensor_util.convert_nonref_to_tensor(x, dtype=x.dtype)\n\nclass RBFKernelFn(tf.keras.layers.Layer):\n def __init__(self, **kwargs):\n super(RBFKernelFn, self).__init__(**kwargs)\n dtype = kwargs.get('dtype', None)\n\n self._amplitude = self.add_variable(\n initializer=tf.constant_initializer(0),\n dtype=dtype,\n name='amplitude')\n \n self._length_scale = self.add_variable(\n initializer=tf.constant_initializer(0),\n dtype=dtype,\n name='length_scale')\n \n def call(self, x):\n # Never called -- this is just a layer so it can hold variables\n # in a way Keras understands.\n #print(dtype)\n return x\n\n @property\n def kernel(self):\n\n \n return tfp.positive_semidefinite_kernels.ExponentiatedQuadratic(\n amplitude=tf.nn.softplus(0.1 * self._amplitude),\n length_scale=tf.nn.softplus(5. * self._length_scale)\n )\n \n #x1 = x[0]\n #x2 = x[1]\n\n #return tf.convert_to_tensor(1/2*(np.absolute(x1))**(2*H)+(np.absolute(x2))**(2*H) - (np.absolute(x1)-np.absolute(x2))**2*H)#tf.as_dtype(1/2*(np.absolute(x))**(2*H)+(np.absolute(y))**(2*H) - (np.absolute(x)-np.absolute(y))**2*H) ",
"_____no_output_____"
],
[
"#this is in reality a fractional brownian motion kernel\n\"\"\"\nclass Brownian(gpflow.kernels.Kernel):\n def __init__(self):\n super().__init__(active_dims=[0])\n #self.variance = gpflow.Param(1.0, transform=gpflow.transforms.positive)\n\n #@gpflow.params_as_tensors\n def K(self, X, X2=None):\n if X2 is None:\n X2 = X\n return 1/2*(np.absolute(X))**(2*H)+(np.absolute(X2))**(2*H) - (np.absolute(X))-(np.absolute(X2))**(2*H)\n def K_diag(self, X, presliced=None):\n return tp.astype(self.variance * tf.reshape(X, (-1,)),tf.int64 ) \n\"\"\"",
"_____no_output_____"
]
],
[
[
"#custom gaussian time series kernel logic\n## #the autocovariance function is ysubscript(f)(h) = integral pi, -p^ih*lambda*f(lambda)*d(lambda) is the function if P^nSubscript(f) is the distribution of X1, ... Xn for a stationary mean-zero gaussian time series (Xsubscript(t):t strange symbol which looks like E Z)\n\n---\nThis is the final thing I have to implement for phase 3 to be complete. Unfortunately I will need to wait until gpflow is updated before I can make that final update\n",
"_____no_output_____"
]
],
[
[
"\n#bijector=tfb.BatchNorm()\n#kernel = tfk.\n #tf.keras.layers.BatchNormalization(),\n #tf.keras.layers.Dense(250, activation='sigmoid',kernel_initializer='ones', use_bias=False),\n#datafour = x\n#trainingtarget = y\n#x = datafour\n#y = trainingtarget\nx_tst = x[189::]\nx_range = 237\nnum_distributions_over_Functions = 1\n\n#kernel = Brownian #tfp.positive_semidefinite_kernels.ExponentiatedQuadratic#MaternOneHalf()\n\n\nmodel = tf.keras.Sequential([\n tf.keras.Input(shape=(1,13), dtype=x.dtype),\n tf.keras.layers.LSTM(25,kernel_initializer='ones', dtype = x.dtype, use_bias=False),\n #tf.keras.layers.InputLayer(input_shape=(10),dtype=x.dtype),#put a 1 before the 9 later\n tf.keras.layers.Dense(50,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(75,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(100,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(125,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(150,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(175,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(200,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(225,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(250,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(225,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(200,kernel_initializer='ones',use_bias=False),\n #goal is to eventually replace the first dense layer with an LSTM layer \n #tf.keras.layers.LSTM\n #tf.keras.layers.TimeDistributed(Dense(vocabulary)))\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(150,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(125,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(100,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(75,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(50,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(25, kernel_initializer='ones',use_bias=False,),\n tfp.layers.VariationalGaussianProcess(\n num_inducing_points=num_inducing_points,\n kernel_provider=RBFKernelFn(dtype=x.dtype),\n inducing_index_points_initializer=tf.constant_initializer(\n np.linspace(0,x_range, num=1125,#num_inducing_points,\n dtype=x.dtype)[..., np.newaxis]),\n unconstrained_observation_noise_variance_initializer=(\n tf.constant_initializer(np.log(np.expm1(1.)).astype(x.dtype))),\n event_shape=[num_distributions_over_Functions],jitter=1e-06\n\n )\n #in unconstrained thing replace astype with tf.dtype thing.\n])\n\n\n\n#AttributeError: 'numpy.dtype' object has no attribute 'as_numpy_dtype' when trying to implement custom kernel\n\n#TypeError: linspace() missing 1 required positional argument: 'stop' This is the error to be resolved before I can add the inducing_indexpoints_initializer",
"_____no_output_____"
],
[
"import sherpa.algorithms.bayesian_optimization as bayesian_optimization\nparameters = [sherpa.Continuous('lrinit', [0.01, 0.011], 'log')]\n #sherpa.Continuous('lrdecay', [1e-2, 1e-7], 'log')]\nalg = bayesian_optimization.GPyOpt(max_num_trials=50)#sherpa.algorithms.GPyOpt('GP', num_initial_data_points='infer',initial_data_points=[0.1,0.11,0.12], acquisition_type='MPI',verbosity=True) \nstudy = sherpa.Study(parameters=parameters,\n algorithm=alg,\n lower_is_better=False)\n\nbatch_size =19\nloss = lambda y, rv_y: rv_y.variational_loss(\n y, kl_weight=np.array(batch_size, x.dtype) / x.shape[0])\nnum_iterations = 5\nepochs = 20\nfor trial in study:\n\n \n\n lr = trial.parameters['lrinit']\n model = tf.keras.Sequential([\n tf.keras.Input(shape=(1,13), dtype=x.dtype),\n tf.keras.layers.LSTM(25,kernel_initializer='ones', dtype = x.dtype, use_bias=False),\n #tf.keras.layers.InputLayer(input_shape=(10),dtype=x.dtype),#put a 1 before the 9 later\n tf.keras.layers.Dense(50,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(75,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(100,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(125,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(150,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(175,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(200,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(225,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(250,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(225,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(200,kernel_initializer='ones',use_bias=False),\n #goal is to eventually replace the first dense layer with an LSTM layer \n #tf.keras.layers.LSTM\n #tf.keras.layers.TimeDistributed(Dense(vocabulary)))\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(150,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(125,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(100,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(75,kernel_initializer='ones', use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(50,kernel_initializer='ones',use_bias=False),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(25, kernel_initializer='ones',use_bias=False,),\n tfp.layers.VariationalGaussianProcess(\n num_inducing_points=num_inducing_points,\n kernel_provider=RBFKernelFn(dtype=x.dtype),\n inducing_index_points_initializer=tf.constant_initializer(\n np.linspace(0,x_range, num=1125,#num_inducing_points,\n dtype=x.dtype)[..., np.newaxis]),\n unconstrained_observation_noise_variance_initializer=(\n tf.constant_initializer(np.log(np.expm1(1.)).astype(x.dtype))),\n event_shape=[num_distributions_over_Functions],jitter=1e-06\n\n )\n #in unconstrained thing replace astype with tf.dtype thing.\n ])\n\n optimizer = tf.optimizers.Adam(learning_rate=lr)\n model.compile(optimizer=optimizer, loss=loss)\n for i in range(epochs):\n\n model.fit(x, y,epochs=epochs, verbose=True,validation_split=0.2)\n loss= model.evaluate(x[189::],y[189::])\n study.add_observation(trial=trial,iteration=i,objective=loss,context={'loss':loss})\n #training_error = model.fit(epochs=1)\n\n \n study.finalize(trial=trial)\n#",
"_____no_output_____"
],
[
"# Do inference.\n#Note: look into BATCHES and make sure they are fed in in order second potential problem to explore: It is possible I already looked into this possibility in phase 1 but make sure that it isnt using input data from the same day to create its predictions\nbatch_size =19\n#use a different loss other than the variational gaussian loss\n\nloss = lambda y, rv_y: rv_y.variational_loss(\n y, kl_weight=np.array(batch_size, x.dtype) / x.shape[0])\n\nmodel.compile(optimizer=tf.optimizers.Adam(learning_rate=0.011), loss=loss)#tf.optimizers.Adam(learning_rate=0.01)\nmodel.fit(x, y,epochs=290, verbose=True,validation_split=0.2)\n#model.predict(x)\n#adjust it to 240 epochs if using pca first\n#prediction = model.predict(x_tst)\n# Make predictions. \n#yhats = [model(x_tst) for _ in range(100)]\n#\n",
"_____no_output_____"
]
],
[
[
"what this algorithm is a joint distribution describing the relationship between the input variables and economic growth. this joint distribution is actually a distribution over functions between input and output.\n We then use these to determine a predictive distribution and make point predictions Although this can be used to make a overall predictive distribution in reality this is far more useful for making a distribution over every point in the function. In other words a contnuous set of changing liklihoods for our point predictions. ",
"_____no_output_____"
]
],
[
[
"yhat = model(x_tst)#Note that this is a distribution not a tensor\nnum_samples = 6 #note: num_samples refers to how many generated future evolutions of economic growth you want it to generate over the specified period of time\nModels = []\n#probability = \naverage = []\n\"\"\"\nnote: the below code works for turning from a tensorflow distribution back to a tensor\na = tf.compat.v1.convert_to_tensor(\n yhat,\n dtype=None,\n name=None,\n preferred_dtype=None,\n dtype_hint=None\n)\n\"\"\"\n#plt.plot(a)\n#plt.plot(yhats)#Note: yhat is supposedly a distribution and not a tensor explore the possibility that it is outputting probabilities and not tensors\nfor i in range(num_samples):\n #plt.plot(yhat)\n sample_ = yhat.sample().numpy()\n #Model = sample\n #sample_[..., 0].T,\n #print(model.summary)\n mean = yhat.mean().numpy()\n #print(mean)\n #variance = yhat.variance().numpy()\n #std = yhat.stddev().numpy()\n #print(yhat.sample().numpy)\n \n print(len(r[0]))\n plt.plot(sample_[..., 0].T,\n 'r',\n linewidth=0.2,\n label='ensemble means' if i == 0 else None);\n \n\"\"\"\n(variational_loss,\nvariational_distributions) = tfp.sts.build_factored_variational_loss(\nmodel=model, observed_time_series=observed_time_series,\ninit_batch_shape=[10])\n\n\n\"\"\"\n#a = yhat.sample_[..., 0].T\n\nprint(\"Predictions\")\n#print(predictions)\n#plt.plot(predictions)\n\n#forecast_dist = tfp.sts.forecast(model, observed_time_series,parameter_samples=sample_,num_steps_forecast=5)\nprint(sample_)\n\nr = []\n\n#r = pd.DataFrame(r)\n\nfor i in range(num_samples):\n sample_ = yhat.sample().numpy()\n #sns.kdeplot(sample_[..., 0].T)\n e = sample_[..., 0].T\n print(\"asdf\")\n #print(len(e))\n r.append(e)\n print(len(r[0]))\nrfinal = (r[0]+r[1]+r[2]+r[3]+r[4]+r[5])/6\nplt.plot(rfinal)\nu1 = r[0]\nu2 = r[1]\nu3 = r[2]\nu4 = r[3]\nu5 = r[4]\nu6 = r[5]\nufinal = ((u1 - rfinal) + (u2-rfinal) + (u4-rfinal) + (u5 - rfinal) + (u6-rfinal))/6\nfrom shapely.geometry import LineString\n\n#note: use shapely to fine intersection points\n#first_line = LineString(np.column_stack((x, f)))\n#second_line = LineString(np.column_stack((x, g)))\n#intersection = first_line.intersection(second_line)\n\n#this is for plotting the intersection points\n#plt.plot(*LineString(intersection).xy, 'o')\n\n#this is for getting the x and y of the intersection \n#x, y = LineString(intersection).xy\n\nprint(ufinal)\nprint(len(ufinal))#note ufinal len is 48\n\n\nplt.plot(y[189::]) \nprint(\"average\")\n#st_dev = average.mean()#stddev()\n#average = mean#.mean()#.numpy()\n\n#plt.plot(sample_[20::])\nprint(\"samples\")\n#print(sample_.T[20::])\nprint(sample_)\nprint(sample_.shape)\n#plt.plot(average[20::])\n#print(len(average))#Note that supposedly the average error rate for the Fed's current forcasting model called gdpNow is 0.56%\n#print(std)\nerror = rfinal/y[189::] #if this was a standard normal distribution than 95% would be 0.252 and 0.968\nprint(\"error\")\nprint(error)\nprint(\"average error\")\nprint(np.sum(error)/len(error))\n#c = np.corrcoef(rfinal, y[:-189:])[0, 1]\n#print(c)",
"_____no_output_____"
],
[
"from scipy import signal\n#average error rate is about 10%\nr = []\n\n#r = pd.DataFrame(r)\n\nfor i in range(num_samples):\n sample_ = yhat.sample().numpy()\n sns.kdeplot(sample_[..., 0].T)\n e = sample_[..., 0].T\n r.append(e)\n\n #Model = sample\n #sample_[..., 0].T,\n #print(model.summary)\n #print(yhat.log_prob(y[189::]))\n mean = yhat.mean().numpy()\n #print(mean)\n #variance = yhat.variance().numpy()\n #std = yhat.stddev().numpy()\n #print(yhat.sample().numpy)\n #you have to figure out what the x and y axis are before you present\n #it appears from this plot of economic growth has a very low hurst exponent\nprint(r[0])\nprint(r[1])\nrfinal = (r[0]+r[1]+r[2]+r[3]+r[4]+r[5])/6\n\nOne = r[0]\ntwo = r[1]\nThree = r[2]\nfour = r[3]\nfive = r[4]\n\npone = signal.fftconvolve(r[0],r[1],'same')\nptwo = signal.fftconvolve(r[2],r[3],'same')\npthree = signal.fftconvolve(r[4],r[5],'same')\n\npfinal = signal.fftconvolve(pone,ptwo)\npfinal = signal.fftconvolve(pfinal,pthree, 'same')\n\n\n\n #yhat.prob()\n #print(mean)\n ",
"_____no_output_____"
],
[
"sns.kdeplot(rfinal)",
"_____no_output_____"
],
[
"tfp.stats.stddev(\n yhat,\n sample_axis=0,\n keepdims=False,\n name=None\n)#yhat\n#observed_time_series = x_tst\n#co2_by_month_training_data = co2_by_month[:-num_forecast_steps] this has to be the format in which \n#between 0.16 and 0.18",
"_____no_output_____"
],
[
"\ny = np.squeeze(y) \nsns.kdeplot(y[189::])",
"_____no_output_____"
],
[
"model.summary()",
"_____no_output_____"
],
[
"#confidence and credible intervals\n!pip install bayesint\nfrom bayesint import rel_risk\nfor i in range(num_samples):\n #print(\"Credible interval\")\n #print(rel_risk(sample_[..., 0].T))\n print(bs.bootstrap(sample_[..., 0].T, stat_func=bs_stats.mean))\nprint(y[189::])\n#print(\"probability\")\n#print(yhat.log_prob([0,0.34]))",
"_____no_output_____"
],
[
"from sklearn.ensemble import AdaBoostRegressor\n\nregr = AdaBoostRegressor(random_state=0, n_estimators=100)\nx = np.squeeze(x)\nregr.fit(x[189::], y[189::])\nplt.plot(y[189::])\n#plt.plt(48)\nplt.plot(regr.predict(x[:48:]))",
"_____no_output_____"
],
[
"print(__doc__)\n\n# Author: Vincent Dubourg <[email protected]>\n# Jake Vanderplas <[email protected]>\n# Jan Hendrik Metzen <[email protected]>s\n# License: BSD 3 clause\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, ConstantKernel as C\n\nnp.random.seed(1)\n\n\ndef f(x):\n \"\"\"The function to predict.\"\"\"\n return x * np.sin(x)\n\n# ----------------------------------------------------------------------\n# First the noiseless case\nX = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T\n\n# Observations\ny = f(X).ravel()\n\n# Mesh the input space for evaluations of the real function, the prediction and\n# its MSE\nx = np.atleast_2d(np.linspace(0, 10, 1000)).T\n\n# Instantiate a Gaussian Process model\nkernel = C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2))\ngp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9)\n\n# Fit to data using Maximum Likelihood Estimation of the parameters\ngp.fit(X, y)\n\n# Make the prediction on the meshed x-axis (ask for MSE as well)\ny_pred, sigma = gp.predict(x, return_std=True)\n\n# Plot the function, the prediction and the 95% confidence interval based on\n# the MSE\nplt.figure()\nplt.plot(x, f(x), 'r:', label=r'$f(x) = x\\,\\sin(x)$')\nplt.plot(X, y, 'r.', markersize=10, label='Observations')\nplt.plot(x, y_pred, 'b-', label='Prediction')\nplt.fill(np.concatenate([x, x[::-1]]),\n np.concatenate([y_pred - 1.9600 * sigma,\n (y_pred + 1.9600 * sigma)[::-1]]),\n alpha=.5, fc='b', ec='None', label='95% confidence interval')\nplt.xlabel('$x$')\nplt.ylabel('$f(x)$')\nplt.ylim(-10, 20)\nplt.legend(loc='upper left')\n\n# ----------------------------------------------------------------------\n# now the noisy case\nX = np.linspace(0.1, 9.9, 20)\nX = np.atleast_2d(X).T\n\n# Observations and noise\ny = f(X).ravel()\ndy = 0.5 + 1.0 * np.random.random(y.shape)\nnoise = np.random.normal(0, dy)\ny += noise\n\n# Instantiate a Gaussian Process model\ngp = GaussianProcessRegressor(kernel=kernel, alpha=dy ** 2,\n n_restarts_optimizer=10)\n\n# Fit to data using Maximum Likelihood Estimation of the parameters\ngp.fit(X, y)\n\n# Make the prediction on the meshed x-axis (ask for MSE as well)\ny_pred, sigma = gp.predict(x, return_std=True)\n\n# Plot the function, the prediction and the 95% confidence interval based on\n# the MSE\nplt.figure()\nplt.plot(x, f(x), 'r:', label=r'$f(x) = x\\,\\sin(x)$')\nplt.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label='Observations')\nplt.plot(x, y_pred, 'b-', label='Prediction')\n\nplt.fill(np.concatenate([x, x[::-1]]),\n np.concatenate([y_pred - 1.9600 * sigma,\n (y_pred + 1.9600 * sigma)[::-1]]),\n alpha=.5, fc='b', ec='None', label='95% confidence interval')\n\nplt.xlabel('$x$')\nplt.ylabel('$f(x)$')\nplt.ylim(-10, 20)\nplt.legend(loc='upper left')\n\nplt.show()",
"_____no_output_____"
],
[
"sns.kdeplot(regr.predict(x[:48:]))",
"_____no_output_____"
],
[
"def my_kernel(X, X2,H):\n \"\"\"\n We create a custom kernel:\n\n (2 0)\n k(X, Y) = X ( ) Y.T\n (0 1)\n \"\"\"\n H = 0.85\n return 1/2*(np.absolute(X))**(2*H)+(np.absolute(X2))**(2*H) - (np.absolute(X))-(np.absolute(X2))**(2*H)\n",
"_____no_output_____"
],
[
"from sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.datasets import load_iris\nimport numpy as np\n#y = y.ravel()\n\nr, g = load_iris(return_X_y=True)\nprint(r)\nprint(g)\n\n#x = pd.DataFrame(x)\n#y = pd.DataFrame(y)\nX = np.squeeze(X)\n\ngpc = GaussianProcessRegressor(kernel=my_kernel,random_state=0).fit(X, trainingtarget.ravel())\na = gpc.predict_proba(x[:2,:])\nprint(\"gpc\")\nprint(a)\n#gpc = GaussianProcessClassifier().fit(x,y)\na = gpc.predict(x[220::])\nb = gpc.log_marginal_likelihood()\n#b = gpc.predict(x[220::])\n#score = gpr.score(x,y)\n#is the great score because training and test arent seperated?\n\n#print(b)\n#print(gpc.score(x[220::],y[220::]))\n#print(score)\nprint(-1*gpc.log_marginal_likelihood())\nprint(a)\nplt.plot(a)\nplt.plot(y[220::]) \n#model.fit(x, y,epochs=50, verbose=True,validation_split=0.2)",
"_____no_output_____"
],
[
"#List of stuff left to do\n\n#1. average out all the various evolutions and see if you can create an additional composite line for economic growth. Bonus: see if you can do a weighted average so that for example stuff outside of the 95% confidence interval at that point is given less weight\n#2. Allow it to predict the future and allow it to give an 95% confidence interval for that one prediction. Also make sure that the various possible evolutions of economic growth and the composite are part of that\n#3.figure out a way to convert the first Dense layer to an LSTM layer\n#4. This is the easiest make it have 2 stages with an exponential decay for the second stage learning rate so the learning rate never becomes negative\nmodelOne = []\nmodelTwo = []\nmodelThree = []\nmodelFour = []\nmodelFive = []\nmodelSix = []\n\nprint(len(sample_))\n #suspected current loss function\n\"\"\"\nvgp.variational_loss(\n observations=y_train_batch,\n observation_index_points=x_train_batch,\n kl_weight=float(batch_size) / float(num_training_points_))\n\"\"\"",
"_____no_output_____"
],
[
"#gpc.predict_proba(X[:2,:])\nplt.plot(x_tst)",
"_____no_output_____"
],
[
"#second stage of Janus Prediction engine\ntime_series = np.linspace(1960.25,2016.25,224)\nobserved_time_series = tfp.sts.MaskedTimeSeries(\n time_series=time_series, is_missing=None\n )\n\"\"\"\nlocal_level_model = LocalLevelStateSpaceModel(\n num_timesteps=50,\n level_scale=0.5,\n initial_state_prior=tfd.MultivariateNormalDiag(scale_diag=[1.]))\n\"\"\"\n\nndims = 2\nstep_std = 1.0\nnoise_std = 5.0\n\n\npredictions = tfp.sts.forecast(observed_time_series,parameter_samples=sample_,observed_time_series=observed_time_series,num_steps_forecast=5)\nprint(predictions)\nplt.plot(predictions)\n\"\"\"\n\n#potential alternate loss function\n#lambda y, rv_y: -rv_y.log_prob(y)\n\"\"\"\nlambda y, rv_y: -rv_y.kl_divergence(\n y,\n rv_y,\n name='loss'\n)\n\"\"\"\n\nloss = lambda y, rv_y: tfp.distributions.kl_divergence(\n y,\n kl,\n allow_nan_stats=True,\n name=None\n)\n\n#los = los*-1\n\none_step_predictive_dist = tfp.sts.one_step_predictive(\n model, observed_time_series, parameter_samples=sample_)\n\"\"\"",
"_____no_output_____"
],
[
"model = make_state_space_model(\n num_timesteps,\n param_vals=None,\n initial_state_prior=None,\n initial_step=0\n)\n\n\ntfp.sts.build_factored_variational_loss(\n model,\n observed_time_series,\n init_batch_shape=(),\n seed=None,\n name=None\n)\n\"\"\"\nmodel = tf.keras.Sequential([\n \n tf.keras.Input(shape=(1,13), dtype=x.dtype),\n tf.keras.layers.LSTM(8,kernel_initializer='ones', use_bias=False),\n #tf.keras.layers.InputLayer(input_shape=(10),dtype=x.dtype),#put a 1 before the 9 later\n #tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(400,kernel_initializer='ones', use_bias=False),#check what the shape is it should be 237,9,1 and put LSTM HERE later\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(800,kernel_initializer='ones',use_bias=False),\n\n #goal is to eventually replace the first dense layer with an LSTM layer \n #tf.keras.layers.LSTM\n #tf.keras.layers.TimeDistributed(Dense(vocabulary)))\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(10, kernel_initializer='ones',use_bias=False,),\n tfp.layers.DenseFlipout(512, activation=tf.nn.relu),\n #tfp.layers.DenseFlipout(1),\n])\n#kalaman filter\n\nmodel = LinearGaussianStateSpaceModel(\n num_timesteps=100,\n transition_matrix=tfl.LinearOperatorIdentity(ndims),\n transition_noise=tfd.MultivariateNormalDiag(\n scale_diag=step_std**2 * tf.ones([ndims])),\n observation_matrix=tfl.LinearOperatorIdentity(ndims),\n observation_noise=tfd.MultivariateNormalDiag(\n scale_diag=noise_std**2 * tf.ones([ndims])),\n initial_state_prior=tfd.MultivariateNormalDiag(\n scale_diag=tf.ones([ndims])))\n)\n\n\"\"\"\n\n#First sucessful build using tf 2.0 with functional API\n\nnum_inducing_points = 45\ninputs = tf.keras.Input(shape=(1,10))\nfirst = tf.keras.layers.LSTM(8,kernel_initializer='ones', use_bias=False)(inputs)\nfirst = tf.keras.layers.Dense(8,kernel_initializer='ones', use_bias=False)(first)\nu = tf.keras.layers.BatchNormalization()(first)\nu = tf.keras.layers.Dense(800,kernel_initializer='ones',use_bias=False)(u)\noutputs = tf.keras.layers.Dense(10, activation='sigmoid')(u)\nmodel = tf.keras.Model(inputs=inputs, outputs=outputs)\n\n\n",
"_____no_output_____"
]
],
[
[
"",
"_____no_output_____"
],
[
"",
"_____no_output_____"
],
[
"\n\n\nnotes on presentation\n\nasks what diversity and inclusion are\n\ndifferent priorities or miscommunication may be affected by background\n\n\ndiversity; who is on the team\n\nculture plays a role in every attitude \n\ndo i care about your unique perspective\n\ndo i understand differences\n\ndiversity is more then just race and ethnicity and age gender race national origin\n\nnow asking what does it mean to be in a more i diverse community\n\nShowing pictures of diversity initiatives from companies\n\nnow asking how to develop cultural competency",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cbb300a4328008e3b6050afab13202b5b41b478e
| 547,001 |
ipynb
|
Jupyter Notebook
|
notebooks/hamiltorch_log_prob_examples.ipynb
|
hyunjimoon/hamiltorch
|
4c5a11d0f23701517a19d1f3aeffb0839b4e41bb
|
[
"BSD-2-Clause"
] | null | null | null |
notebooks/hamiltorch_log_prob_examples.ipynb
|
hyunjimoon/hamiltorch
|
4c5a11d0f23701517a19d1f3aeffb0839b4e41bb
|
[
"BSD-2-Clause"
] | null | null | null |
notebooks/hamiltorch_log_prob_examples.ipynb
|
hyunjimoon/hamiltorch
|
4c5a11d0f23701517a19d1f3aeffb0839b4e41bb
|
[
"BSD-2-Clause"
] | null | null | null | 547,001 | 547,001 | 0.735447 |
[
[
[
"### Tutorial in hamiltorch for log probabilities\n\n* For the corresponding blog post please see: https://adamcobb.github.io/journal/hamiltorch.html\n* Bayesian neural networks are left to a different notebook ",
"_____no_output_____"
]
],
[
[
"#notes for setting by Hyunji\n\n#install\n# - git clone the following repo in google drive/Colab Notebook folder\n# - go to browser google drive/Colab Notebook and open this notebook with colab (right click)\n# - \n# !pip3 install git+https://github.com/hyunjimoon/hamiltorch\n\n# to edit the python files\nfrom google.colab import drive\ndrive.mount('/content/drive', force_remount=True)\n\n# add hamiltorch for edit purpose (RUN THIS CELL ARTER .py EDIT!)\nimport sys\nsys.path.append('/content/drive/MyDrive/Colab Notebooks/hamiltorch')\nimport hamiltorch\n#/content/drive/MyDrive/Colab Notebooks/hamiltorch import hamiltorch",
"Mounted at /content/drive\n"
],
[
"import torch\n#import hamiltorch \nimport matplotlib.pyplot as plt\n%matplotlib inline",
"_____no_output_____"
],
[
"hamiltorch.set_random_seed(123)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"_____no_output_____"
],
[
"print(hamiltorch.__version__)",
"0.4.0.dev1\n"
]
],
[
[
"## Sampling a multivariate Gaussian",
"_____no_output_____"
],
[
"In `hamiltorch`, we have designed the samplers to receive a function handle `log_prob_func`, which the sampler will use to evaluate the log probability of each sample. A `log_prob_func` must take a 1-d vector of length equal to the number of parameters that are being sampled. For the example of our multivariate Gaussian distribution, we can define our `log_prob_func` as follows:",
"_____no_output_____"
]
],
[
[
"def log_prob(omega):\n mean = torch.tensor([0.,0.,0.])\n stddev = torch.tensor([.5,1.,2.]) \n return torch.distributions.MultivariateNormal(mean, torch.diag(stddev**2)).log_prob(omega).sum()",
"_____no_output_____"
],
[
"N = 400\nstep_size = .3\nL = 5",
"_____no_output_____"
]
],
[
[
"### Sample using standard HMC\n* Initialise the parameters e.g. `params_init = torch.zeros(3)` and pass them into the `hamiltorch.sample()` function as `params_init=params_init`.\n* Set the number of samples `num_samples=N` corresponding to the number of momentum resampling steps/the number of trajectories to sample.\n* Set the step size and trajectory length via `step_size=step_size, num_steps_per_sample=L`.",
"_____no_output_____"
]
],
[
[
"# HMC\nhamiltorch.set_random_seed(123)\nparams_init = torch.zeros(3)\nparams_hmc = hamiltorch.sample(log_prob_func=log_prob, params_init=params_init, num_samples=N,\n step_size=step_size, num_steps_per_sample=L)",
"Sampling (Sampler.HMC; Integrator.IMPLICIT)\nTime spent | Time remain.| Progress | Samples | Samples/sec\n\nAcceptance Rate 0.99\n"
]
],
[
[
"### Sample using the No-U-Turn Sampler (NUTS)\n* As in Hoffman and Gelman 2011.\n* This is set using the additional parameter `sampler=hamiltorch.Sampler.HMC_NUTS`.\n* The step size is adapted with the objective of a desired acceptance rate `desired_accept_rate=0.8`.\n* The step size is fixed after the burn stage `burn=burn` and we define `N_nuts = burn + N`\n",
"_____no_output_____"
]
],
[
[
"# HMC NUTS\nhamiltorch.set_random_seed(123)\nparams_init = torch.zeros(3) + 5\nburn=500\nN_nuts = burn + N\nparams_hmc_nuts = hamiltorch.sample(log_prob_func=log_prob, params_init=params_init,\n num_samples=N_nuts,step_size=step_size,num_steps_per_sample=L,\n sampler=hamiltorch.Sampler.HMC_NUTS, burn=burn,\n desired_accept_rate=0.8)",
"Sampling (Sampler.HMC; Integrator.IMPLICIT)\nTime spent | Time remain.| Progress | Samples | Samples/sec\nFinal Adapted Step Size: 0.7333879470825195\n\nAcceptance Rate 0.78\n"
]
],
[
[
"### Sample using implicit Riemannian manifold Hamiltonian Monte Carlo (RMHMC)\n\n* As in Girolami and Calderhead 2011.\n* Switch the sampler via setting `sampler=hamiltorch.Sampler.RMHMC` and the integrator via `integrator=hamiltorch.Integrator.IMPLICIT`.\n* Limit the number of fixed point iterations in the generalised leapforg via `fixed_point_max_iterations=1000` and set the convergence threshold for 'breaking out' of the while loop via `fixed_point_threshold=1e-05`.\n",
"_____no_output_____"
]
],
[
[
"# Implicit RMHMC\nhamiltorch.set_random_seed(123)\nparams_init = torch.zeros(3)\nparams_irmhmc = hamiltorch.sample(log_prob_func=log_prob, params_init=params_init, num_samples=N,\n step_size=step_size,num_steps_per_sample=L, sampler=hamiltorch.Sampler.RMHMC,\n integrator=hamiltorch.Integrator.IMPLICIT, fixed_point_max_iterations=1000,\n fixed_point_threshold=1e-05)",
"Sampling (Sampler.RMHMC; Integrator.IMPLICIT)\nTime spent | Time remain.| Progress | Samples | Samples/sec\n\nAcceptance Rate 0.99\n"
]
],
[
[
"### Sample using explicit Riemannian manifold Hamiltonian Monte Carlo (RMHMC)\n\n* As in Cobb et. al. 2019\n* Switch the integrator to explicit via `integrator=hamiltorch.Integrator.EXPLICIT`. Note that the sampler is still set to RMHMC.\n* Introduce and set the binding term via `explicit_binding_const=omega`. This can be subsequently optimised for the highest acceptance rate.\n\n",
"_____no_output_____"
]
],
[
[
"# Explicit RMHMC\nhamiltorch.set_random_seed(123)\nparams_init = torch.zeros(3)\nomega = 100.\nparams_ermhmc = hamiltorch.sample(log_prob_func=log_prob, params_init=params_init, num_samples=N,\n step_size=step_size,num_steps_per_sample=L, sampler=hamiltorch.Sampler.RMHMC,\n integrator=hamiltorch.Integrator.EXPLICIT, explicit_binding_const=omega)",
"Sampling (Sampler.RMHMC; Integrator.EXPLICIT)\nTime spent | Time remain.| Progress | Samples | Samples/sec\n\nAcceptance Rate 0.99\n"
],
[
"# Hyperelliptical RMHMC\nhamiltorch.set_random_seed(123)\nparams_init = torch.zeros(3)\nomega = 100.\nparams_hermhmc = hamiltorch.sample(log_prob_func=log_prob, params_init=params_init, num_samples=N,\n step_size=step_size, num_steps_per_sample=L, sampler=hamiltorch.Sampler.RMHMC,\n integrator=hamiltorch.Integrator.EXPLICIT, explicit_binding_const=omega, metric = hamiltorch.Metric.HYPERELLIP)",
"\u001b[1;30;43m스트리밍 출력 내용이 길어서 마지막 5000줄이 삭제되었습니다.\u001b[0m\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1369, -2.9985], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1369, -2.9985], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1369, -2.9985], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1369, -2.9985], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1369, -2.9985], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1369, -2.9985], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1369, -2.9985], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1382, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1382, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1382, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1382, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0713, 1.1395, -2.9946], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0713, 1.1395, -2.9946], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0713, 1.1395, -2.9946], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0713, 1.1395, -2.9946], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0720, 1.1409, -2.9926], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0720, 1.1409, -2.9926], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0720, 1.1409, -2.9926], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0720, 1.1409, -2.9926], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0727, 1.1422, -2.9906], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0727, 1.1422, -2.9906], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0727, 1.1422, -2.9906], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0727, 1.1422, -2.9906], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0734, 1.1436, -2.9886], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0734, 1.1436, -2.9886], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0734, 1.1436, -2.9886], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0734, 1.1436, -2.9886], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1449, -2.9865], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1449, -2.9865], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1449, -2.9865], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1449, -2.9865], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1463, -2.9845], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1463, -2.9845], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1463, -2.9845], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1463, -2.9845], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0756, 1.1476, -2.9824], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0756, 1.1476, -2.9824], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0756, 1.1476, -2.9824], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0756, 1.1476, -2.9824], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1490, -2.9803], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1490, -2.9803], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1490, -2.9803], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1490, -2.9803], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1504, -2.9782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1504, -2.9782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1504, -2.9782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1504, -2.9782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1504, -2.9782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1504, -2.9782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1504, -2.9782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0777, 1.1508, -2.9795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0777, 1.1508, -2.9795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0776, 1.1508, -2.9795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0776, 1.1508, -2.9795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0782, 1.1511, -2.9808], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0782, 1.1511, -2.9808], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0782, 1.1511, -2.9808], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0782, 1.1511, -2.9808], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1515, -2.9821], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1515, -2.9821], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1515, -2.9821], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1515, -2.9821], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0795, 1.1518, -2.9834], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0795, 1.1518, -2.9834], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0795, 1.1518, -2.9834], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0795, 1.1518, -2.9834], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1522, -2.9847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1522, -2.9847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1522, -2.9847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1522, -2.9847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0807, 1.1525, -2.9860], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0807, 1.1525, -2.9860], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0807, 1.1525, -2.9860], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0807, 1.1525, -2.9860], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0813, 1.1529, -2.9873], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0813, 1.1529, -2.9873], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0813, 1.1529, -2.9873], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0813, 1.1529, -2.9873], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0819, 1.1532, -2.9885], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0819, 1.1532, -2.9885], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0819, 1.1532, -2.9885], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0819, 1.1532, -2.9885], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1535, -2.9898], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1535, -2.9898], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1535, -2.9898], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1535, -2.9898], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1539, -2.9910], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1539, -2.9910], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1539, -2.9910], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1539, -2.9910], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1539, -2.9910], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1539, -2.9910], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1539, -2.9910], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0830, 1.1535, -2.9929], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0830, 1.1535, -2.9929], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0830, 1.1535, -2.9929], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0830, 1.1535, -2.9929], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0829, 1.1531, -2.9947], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0829, 1.1531, -2.9947], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0829, 1.1531, -2.9947], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0829, 1.1531, -2.9947], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0828, 1.1527, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0828, 1.1527, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0828, 1.1527, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0828, 1.1527, -2.9966], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1524, -2.9984], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1524, -2.9984], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1524, -2.9984], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1524, -2.9984], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1520, -3.0002], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1520, -3.0002], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1520, -3.0002], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0827, 1.1520, -3.0002], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0826, 1.1516, -3.0020], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0826, 1.1516, -3.0020], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0826, 1.1516, -3.0020], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0826, 1.1516, -3.0020], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1513, -3.0037], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1513, -3.0037], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1513, -3.0037], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1513, -3.0037], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0824, 1.1509, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0824, 1.1509, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0824, 1.1509, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0824, 1.1509, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0823, 1.1505, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0823, 1.1505, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0823, 1.1505, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0823, 1.1505, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0822, 1.1502, -3.0090], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0822, 1.1502, -3.0090], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0822, 1.1502, -3.0090], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0822, 1.1502, -3.0090], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0822, 1.1502, -3.0090], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0822, 1.1502, -3.0090], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0822, 1.1502, -3.0090], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0817, 1.1493, -3.0088], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0817, 1.1493, -3.0088], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0817, 1.1493, -3.0088], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0817, 1.1493, -3.0088], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0811, 1.1485, -3.0085], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0811, 1.1485, -3.0085], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0811, 1.1485, -3.0085], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0811, 1.1485, -3.0085], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1476, -3.0083], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1476, -3.0083], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1476, -3.0083], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1476, -3.0083], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1468, -3.0081], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1468, -3.0081], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1468, -3.0081], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1468, -3.0081], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1459, -3.0078], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1459, -3.0078], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1459, -3.0078], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1459, -3.0078], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1450, -3.0076], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1450, -3.0076], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1450, -3.0076], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1450, -3.0076], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0783, 1.1442, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0783, 1.1442, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0783, 1.1442, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0783, 1.1442, -3.0073], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0777, 1.1433, -3.0070], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0777, 1.1433, -3.0070], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0777, 1.1433, -3.0070], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0777, 1.1433, -3.0070], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1424, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1424, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1424, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1424, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1416, -3.0065], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1416, -3.0065], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1416, -3.0065], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1416, -3.0065], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1416, -3.0065], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1416, -3.0065], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1416, -3.0065], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0757, 1.1417, -3.0063], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0757, 1.1417, -3.0063], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0757, 1.1417, -3.0063], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0757, 1.1417, -3.0063], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1418, -3.0061], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1418, -3.0061], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1418, -3.0061], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1418, -3.0061], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1420, -3.0059], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1420, -3.0059], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1420, -3.0059], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1420, -3.0059], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1421, -3.0057], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1421, -3.0057], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1421, -3.0057], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1421, -3.0057], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1423, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1423, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1423, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1423, -3.0055], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0716, 1.1424, -3.0053], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0716, 1.1424, -3.0053], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0716, 1.1424, -3.0053], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0716, 1.1424, -3.0053], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0708, 1.1425, -3.0051], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0708, 1.1425, -3.0051], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0708, 1.1425, -3.0051], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0708, 1.1425, -3.0051], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1427, -3.0049], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1427, -3.0049], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1427, -3.0049], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1427, -3.0049], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0691, 1.1428, -3.0046], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0691, 1.1428, -3.0046], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0691, 1.1428, -3.0046], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0691, 1.1428, -3.0046], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0683, 1.1429, -3.0044], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0683, 1.1429, -3.0044], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0683, 1.1429, -3.0044], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0683, 1.1429, -3.0044], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0683, 1.1429, -3.0044], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0683, 1.1429, -3.0044], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0683, 1.1429, -3.0044], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0684, 1.1423, -3.0056], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0684, 1.1423, -3.0056], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0684, 1.1424, -3.0056], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0684, 1.1424, -3.0056], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1418, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1418, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1418, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1418, -3.0068], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1412, -3.0079], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1412, -3.0079], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1412, -3.0079], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1412, -3.0079], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0689, 1.1406, -3.0091], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0689, 1.1406, -3.0091], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0689, 1.1406, -3.0091], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0689, 1.1406, -3.0091], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0690, 1.1400, -3.0102], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0690, 1.1400, -3.0102], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0690, 1.1400, -3.0102], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0690, 1.1400, -3.0102], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1394, -3.0114], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1394, -3.0114], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1394, -3.0114], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1394, -3.0114], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0694, 1.1388, -3.0125], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0694, 1.1388, -3.0125], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0694, 1.1388, -3.0125], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0694, 1.1388, -3.0125], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0695, 1.1383, -3.0136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0695, 1.1383, -3.0136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0695, 1.1383, -3.0136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0695, 1.1383, -3.0136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0697, 1.1377, -3.0148], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0697, 1.1377, -3.0148], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0697, 1.1377, -3.0148], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0697, 1.1377, -3.0148], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0698, 1.1371, -3.0159], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0698, 1.1371, -3.0159], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0698, 1.1371, -3.0159], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0698, 1.1371, -3.0159], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0698, 1.1371, -3.0159], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0698, 1.1371, -3.0159], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0698, 1.1371, -3.0159], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1386, -3.0181], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1386, -3.0181], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1386, -3.0181], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0692, 1.1386, -3.0181], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1401, -3.0202], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1401, -3.0202], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1401, -3.0202], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0686, 1.1401, -3.0202], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0679, 1.1416, -3.0224], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0679, 1.1416, -3.0224], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0679, 1.1416, -3.0224], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0679, 1.1416, -3.0224], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0673, 1.1431, -3.0245], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0673, 1.1431, -3.0245], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0673, 1.1431, -3.0245], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0673, 1.1431, -3.0245], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1446, -3.0266], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1446, -3.0266], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1446, -3.0266], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1446, -3.0266], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1460, -3.0286], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1460, -3.0286], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1460, -3.0286], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1460, -3.0286], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0655, 1.1475, -3.0307], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0655, 1.1475, -3.0307], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0655, 1.1475, -3.0307], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0655, 1.1475, -3.0307], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0648, 1.1489, -3.0327], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0648, 1.1489, -3.0327], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0648, 1.1489, -3.0327], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0648, 1.1489, -3.0327], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1503, -3.0347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1503, -3.0347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1503, -3.0347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1503, -3.0347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0637, 1.1517, -3.0367], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0637, 1.1517, -3.0367], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0637, 1.1517, -3.0367], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0637, 1.1517, -3.0367], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0637, 1.1517, -3.0367], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0637, 1.1517, -3.0367], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0637, 1.1517, -3.0367], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0640, 1.1512, -3.0374], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0640, 1.1512, -3.0374], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0640, 1.1512, -3.0374], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0640, 1.1512, -3.0374], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1508, -3.0381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1508, -3.0381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1508, -3.0381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0643, 1.1508, -3.0381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0647, 1.1503, -3.0388], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0647, 1.1503, -3.0388], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0647, 1.1503, -3.0388], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0647, 1.1503, -3.0388], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0650, 1.1498, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0650, 1.1498, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0650, 1.1498, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0650, 1.1498, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0654, 1.1493, -3.0402], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0654, 1.1493, -3.0402], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0654, 1.1493, -3.0402], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0654, 1.1493, -3.0402], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0657, 1.1488, -3.0409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0657, 1.1488, -3.0409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0657, 1.1488, -3.0409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0657, 1.1488, -3.0409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1483, -3.0415], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1483, -3.0415], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1483, -3.0415], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1483, -3.0415], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1479, -3.0422], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1479, -3.0422], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1479, -3.0422], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1479, -3.0422], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1474, -3.0429], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1474, -3.0429], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1474, -3.0429], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1474, -3.0429], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0671, 1.1469, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0671, 1.1469, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0671, 1.1469, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0671, 1.1469, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0671, 1.1469, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0671, 1.1469, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0671, 1.1469, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1450, -3.0442], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1450, -3.0442], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1451, -3.0442], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1451, -3.0442], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0669, 1.1432, -3.0448], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0669, 1.1432, -3.0448], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0669, 1.1432, -3.0448], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0669, 1.1432, -3.0448], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1413, -3.0455], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1413, -3.0455], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1413, -3.0455], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0668, 1.1413, -3.0455], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1395, -3.0461], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1395, -3.0461], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1395, -3.0461], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1395, -3.0461], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0666, 1.1376, -3.0467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0666, 1.1376, -3.0467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0666, 1.1376, -3.0467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0666, 1.1376, -3.0467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1357, -3.0474], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1357, -3.0474], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1357, -3.0474], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1357, -3.0474], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1338, -3.0480], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1338, -3.0480], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1338, -3.0480], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0664, 1.1338, -3.0480], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0663, 1.1320, -3.0486], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0663, 1.1320, -3.0486], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0663, 1.1320, -3.0486], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0663, 1.1320, -3.0486], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1301, -3.0492], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1301, -3.0492], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1301, -3.0492], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1301, -3.0492], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0660, 1.1282, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0660, 1.1282, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0660, 1.1282, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0660, 1.1282, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0660, 1.1282, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0660, 1.1282, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0660, 1.1282, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1291, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1291, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1291, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1291, -3.0499], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1300, -3.0500], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1300, -3.0500], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1300, -3.0500], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1300, -3.0500], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1309, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1309, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1309, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1309, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1318, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1318, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1318, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1318, -3.0501], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1327, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1327, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1327, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0661, 1.1327, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1336, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1336, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1336, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1336, -3.0502], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1345, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1345, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1345, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1345, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1354, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1354, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1354, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1354, -3.0503], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1363, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1363, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1363, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1363, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1371, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1371, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1371, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1371, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1371, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1371, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0662, 1.1371, -3.0504], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1378, -3.0515], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1378, -3.0515], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1378, -3.0515], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0665, 1.1378, -3.0515], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1384, -3.0526], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1384, -3.0526], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1384, -3.0526], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0667, 1.1384, -3.0526], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1390, -3.0537], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1390, -3.0537], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1390, -3.0537], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0670, 1.1390, -3.0537], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0672, 1.1396, -3.0547], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0672, 1.1396, -3.0547], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0672, 1.1396, -3.0547], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0672, 1.1396, -3.0547], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0675, 1.1402, -3.0558], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0675, 1.1402, -3.0558], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0675, 1.1402, -3.0558], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0675, 1.1402, -3.0558], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0677, 1.1409, -3.0568], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0677, 1.1409, -3.0568], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0677, 1.1409, -3.0568], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0677, 1.1409, -3.0568], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0680, 1.1415, -3.0579], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0680, 1.1415, -3.0579], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0680, 1.1415, -3.0579], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0680, 1.1415, -3.0579], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0682, 1.1421, -3.0589], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0682, 1.1421, -3.0589], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0682, 1.1421, -3.0589], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0682, 1.1421, -3.0589], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0685, 1.1427, -3.0599], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0685, 1.1427, -3.0599], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0685, 1.1427, -3.0599], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0685, 1.1427, -3.0599], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1433, -3.0610], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1433, -3.0610], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1433, -3.0610], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1433, -3.0610], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1433, -3.0610], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1433, -3.0610], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0687, 1.1433, -3.0610], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0694, 1.1421, -3.0636], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0694, 1.1421, -3.0636], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0693, 1.1421, -3.0636], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0693, 1.1421, -3.0636], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1409, -3.0662], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1409, -3.0662], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1409, -3.0662], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0699, 1.1409, -3.0662], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1398, -3.0688], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1398, -3.0688], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1398, -3.0688], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0706, 1.1398, -3.0688], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0712, 1.1386, -3.0714], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0712, 1.1386, -3.0714], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0712, 1.1386, -3.0714], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0712, 1.1386, -3.0714], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0718, 1.1374, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0718, 1.1374, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0718, 1.1374, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0718, 1.1374, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1363, -3.0764], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1363, -3.0764], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1363, -3.0764], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0724, 1.1363, -3.0764], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1352, -3.0789], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1352, -3.0789], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1352, -3.0789], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1352, -3.0789], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1340, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1340, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1340, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1340, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1329, -3.0838], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1329, -3.0838], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1329, -3.0838], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1329, -3.0838], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1318, -3.0863], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1318, -3.0863], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1318, -3.0863], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1318, -3.0863], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1318, -3.0863], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1318, -3.0863], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0748, 1.1318, -3.0863], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0755, 1.1320, -3.0849], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0755, 1.1320, -3.0849], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0754, 1.1320, -3.0849], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0754, 1.1320, -3.0849], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1322, -3.0836], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1322, -3.0836], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1322, -3.0836], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1322, -3.0836], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1324, -3.0822], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1324, -3.0822], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1324, -3.0822], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1324, -3.0822], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1326, -3.0809], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1326, -3.0809], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1326, -3.0809], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1326, -3.0809], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0781, 1.1328, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0781, 1.1328, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0781, 1.1328, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0781, 1.1328, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1330, -3.0781], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1330, -3.0781], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1330, -3.0781], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0788, 1.1330, -3.0781], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1332, -3.0767], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1332, -3.0767], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1332, -3.0767], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1332, -3.0767], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1335, -3.0753], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1335, -3.0753], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1335, -3.0753], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1335, -3.0753], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1337, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1337, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1337, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1337, -3.0739], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0815, 1.1339, -3.0725], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0815, 1.1339, -3.0725], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0815, 1.1339, -3.0725], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0815, 1.1339, -3.0725], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0815, 1.1339, -3.0725], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0815, 1.1339, -3.0725], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0815, 1.1339, -3.0725], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1339, -3.0735], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1339, -3.0735], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1339, -3.0735], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0808, 1.1339, -3.0735], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1340, -3.0745], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1340, -3.0745], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1340, -3.0745], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0801, 1.1340, -3.0745], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1341, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1341, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1341, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0794, 1.1341, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1341, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1341, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1341, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1341, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0780, 1.1342, -3.0775], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0780, 1.1342, -3.0775], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0780, 1.1342, -3.0775], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0780, 1.1342, -3.0775], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1343, -3.0785], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1343, -3.0785], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1343, -3.0785], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1343, -3.0785], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1343, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1343, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1343, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1343, -3.0795], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1344, -3.0804], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1344, -3.0804], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1344, -3.0804], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1344, -3.0804], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1345, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1345, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1345, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1345, -3.0814], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1345, -3.0823], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1345, -3.0823], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1345, -3.0823], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1345, -3.0823], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1345, -3.0823], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1345, -3.0823], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1345, -3.0823], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0744, 1.1354, -3.0815], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0744, 1.1354, -3.0815], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0744, 1.1353, -3.0815], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0744, 1.1353, -3.0815], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0743, 1.1362, -3.0807], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0743, 1.1362, -3.0807], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0743, 1.1362, -3.0807], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0743, 1.1362, -3.0807], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1370, -3.0799], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1370, -3.0799], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1370, -3.0799], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0741, 1.1370, -3.0799], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0740, 1.1378, -3.0790], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0740, 1.1378, -3.0790], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0740, 1.1378, -3.0790], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0740, 1.1378, -3.0790], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1387, -3.0782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1387, -3.0782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1387, -3.0782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1387, -3.0782], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0737, 1.1395, -3.0774], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0737, 1.1395, -3.0774], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0737, 1.1395, -3.0774], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0737, 1.1395, -3.0774], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1404, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1404, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1404, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1404, -3.0765], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0735, 1.1412, -3.0757], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0735, 1.1412, -3.0757], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0735, 1.1412, -3.0757], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0735, 1.1412, -3.0757], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1420, -3.0748], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1420, -3.0748], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1420, -3.0748], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0733, 1.1420, -3.0748], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1426, -3.0704], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1426, -3.0704], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1426, -3.0704], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1426, -3.0704], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1423, -3.0668], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1423, -3.0668], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1423, -3.0668], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1423, -3.0668], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1421, -3.0630], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1421, -3.0630], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1421, -3.0630], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1421, -3.0630], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1418, -3.0593], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1418, -3.0593], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1418, -3.0593], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1418, -3.0593], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1415, -3.0554], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1415, -3.0554], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1415, -3.0554], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1415, -3.0554], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1412, -3.0516], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1412, -3.0516], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1412, -3.0516], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1412, -3.0516], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1409, -3.0476], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1409, -3.0476], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1409, -3.0476], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0731, 1.1409, -3.0476], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1406, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1406, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1406, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1406, -3.0436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1403, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1403, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1403, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1403, -3.0395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1400, -3.0354], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1400, -3.0354], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0730, 1.1400, -3.0354], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], grad_fn=<CloneBackward>)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], grad_fn=<CloneBackward>)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0732, 1.1429, -3.0740], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1441, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0736, 1.1441, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0735, 1.1441, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0735, 1.1441, -3.0755], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1453, -3.0771], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1453, -3.0771], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1453, -3.0771], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0739, 1.1453, -3.0771], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1465, -3.0786], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1465, -3.0786], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1465, -3.0786], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0742, 1.1465, -3.0786], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1477, -3.0802], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1477, -3.0802], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1477, -3.0802], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0745, 1.1477, -3.0802], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1489, -3.0817], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1489, -3.0817], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1489, -3.0817], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0749, 1.1489, -3.0817], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1501, -3.0832], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1501, -3.0832], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1501, -3.0832], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0752, 1.1501, -3.0832], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0755, 1.1513, -3.0847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0755, 1.1513, -3.0847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0755, 1.1513, -3.0847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0755, 1.1513, -3.0847], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1525, -3.0862], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1525, -3.0862], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1525, -3.0862], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0759, 1.1525, -3.0862], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1536, -3.0877], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1536, -3.0877], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1536, -3.0877], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1536, -3.0877], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1548, -3.0891], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1548, -3.0891], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1548, -3.0891], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1548, -3.0891], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1548, -3.0891], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1548, -3.0891], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1548, -3.0891], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1544, -3.0923], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1544, -3.0923], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1544, -3.0923], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1544, -3.0923], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1541, -3.0955], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1541, -3.0955], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1541, -3.0955], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1541, -3.0955], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1538, -3.0986], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1538, -3.0986], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1538, -3.0986], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1538, -3.0986], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1534, -3.1017], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1534, -3.1017], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1534, -3.1017], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1534, -3.1017], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1531, -3.1047], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1531, -3.1047], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1531, -3.1047], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1531, -3.1047], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1528, -3.1077], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1528, -3.1077], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1528, -3.1077], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1528, -3.1077], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1525, -3.1107], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1525, -3.1107], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1525, -3.1107], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1525, -3.1107], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1522, -3.1136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1522, -3.1136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1522, -3.1136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1522, -3.1136], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1519, -3.1165], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1519, -3.1165], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1519, -3.1165], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1519, -3.1165], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1515, -3.1194], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1515, -3.1194], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1515, -3.1194], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1515, -3.1194], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1515, -3.1194], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1515, -3.1194], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1515, -3.1194], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1519, -3.1203], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1519, -3.1203], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1519, -3.1203], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1519, -3.1203], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1523, -3.1213], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1523, -3.1213], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1523, -3.1213], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0768, 1.1523, -3.1213], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1527, -3.1222], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1527, -3.1222], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1527, -3.1222], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1527, -3.1222], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1530, -3.1231], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1530, -3.1231], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1530, -3.1231], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1530, -3.1231], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1534, -3.1240], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1534, -3.1240], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1534, -3.1240], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0765, 1.1534, -3.1240], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1537, -3.1249], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1537, -3.1249], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1537, -3.1249], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1537, -3.1249], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1541, -3.1258], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1541, -3.1258], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1541, -3.1258], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1541, -3.1258], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1545, -3.1267], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1545, -3.1267], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1545, -3.1267], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0762, 1.1545, -3.1267], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1548, -3.1275], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1548, -3.1275], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1548, -3.1275], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1548, -3.1275], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0760, 1.1552, -3.1284], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0760, 1.1552, -3.1284], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0760, 1.1552, -3.1284], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0760, 1.1552, -3.1284], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0760, 1.1552, -3.1284], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0760, 1.1552, -3.1284], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0760, 1.1552, -3.1284], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1561, -3.1290], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1561, -3.1290], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1561, -3.1290], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0761, 1.1561, -3.1290], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1570, -3.1297], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1570, -3.1297], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1570, -3.1297], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0763, 1.1570, -3.1297], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1578, -3.1303], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1578, -3.1303], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1578, -3.1303], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0764, 1.1578, -3.1303], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1587, -3.1309], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1587, -3.1309], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1587, -3.1309], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0766, 1.1587, -3.1309], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1596, -3.1316], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1596, -3.1316], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1596, -3.1316], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0767, 1.1596, -3.1316], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1605, -3.1322], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1605, -3.1322], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1605, -3.1322], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0769, 1.1605, -3.1322], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1614, -3.1328], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1614, -3.1328], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1614, -3.1328], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0770, 1.1614, -3.1328], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1622, -3.1334], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1622, -3.1334], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1622, -3.1334], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0771, 1.1622, -3.1334], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1631, -3.1340], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1631, -3.1340], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1631, -3.1340], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0773, 1.1631, -3.1340], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1640, -3.1346], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1640, -3.1346], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1640, -3.1346], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1640, -3.1346], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1640, -3.1346], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1640, -3.1346], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0774, 1.1640, -3.1346], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0781, 1.1647, -3.1354], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0781, 1.1647, -3.1354], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0780, 1.1647, -3.1354], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0780, 1.1647, -3.1354], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1654, -3.1361], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1654, -3.1361], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1654, -3.1361], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0787, 1.1654, -3.1361], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0793, 1.1661, -3.1369], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0793, 1.1661, -3.1369], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0793, 1.1661, -3.1369], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0793, 1.1661, -3.1369], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1669, -3.1377], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1669, -3.1377], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1669, -3.1377], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0800, 1.1669, -3.1377], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1676, -3.1384], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1676, -3.1384], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1676, -3.1384], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0806, 1.1676, -3.1384], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0812, 1.1683, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0812, 1.1683, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0812, 1.1683, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0812, 1.1683, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0819, 1.1690, -3.1399], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0819, 1.1690, -3.1399], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0818, 1.1690, -3.1399], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0818, 1.1690, -3.1399], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1697, -3.1406], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1697, -3.1406], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1697, -3.1406], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0825, 1.1697, -3.1406], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1705, -3.1414], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1705, -3.1414], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1705, -3.1414], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0831, 1.1705, -3.1414], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0837, 1.1712, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0837, 1.1712, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0837, 1.1712, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0837, 1.1712, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0837, 1.1712, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0837, 1.1712, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0837, 1.1712, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0839, 1.1705, -3.1413], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0839, 1.1705, -3.1413], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0839, 1.1706, -3.1413], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0839, 1.1706, -3.1413], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0840, 1.1699, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0840, 1.1699, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0840, 1.1699, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0840, 1.1699, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0842, 1.1693, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0842, 1.1693, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0842, 1.1693, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0842, 1.1693, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0843, 1.1687, -3.1389], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0843, 1.1687, -3.1389], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0843, 1.1687, -3.1389], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0843, 1.1687, -3.1389], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0845, 1.1681, -3.1381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0845, 1.1681, -3.1381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0845, 1.1681, -3.1381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0845, 1.1681, -3.1381], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0846, 1.1674, -3.1372], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0846, 1.1674, -3.1372], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0846, 1.1674, -3.1372], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0846, 1.1674, -3.1372], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0848, 1.1668, -3.1364], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0848, 1.1668, -3.1364], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0848, 1.1668, -3.1364], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0848, 1.1668, -3.1364], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0849, 1.1662, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0849, 1.1662, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0849, 1.1662, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0849, 1.1662, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0851, 1.1655, -3.1347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0851, 1.1655, -3.1347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0851, 1.1655, -3.1347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0851, 1.1655, -3.1347], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0852, 1.1649, -3.1339], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0852, 1.1649, -3.1339], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0852, 1.1649, -3.1339], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0852, 1.1649, -3.1339], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0852, 1.1649, -3.1339], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0852, 1.1649, -3.1339], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0852, 1.1649, -3.1339], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0855, 1.1652, -3.1353], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0855, 1.1652, -3.1353], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0855, 1.1652, -3.1352], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0855, 1.1652, -3.1352], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0858, 1.1654, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0858, 1.1654, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0858, 1.1654, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0858, 1.1654, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0860, 1.1657, -3.1379], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0860, 1.1657, -3.1379], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0860, 1.1657, -3.1379], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0860, 1.1657, -3.1379], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0863, 1.1660, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0863, 1.1660, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0863, 1.1660, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0863, 1.1660, -3.1392], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0866, 1.1663, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0866, 1.1663, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0866, 1.1663, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0866, 1.1663, -3.1405], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0869, 1.1666, -3.1418], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0869, 1.1666, -3.1418], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0869, 1.1666, -3.1418], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0869, 1.1666, -3.1418], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0871, 1.1668, -3.1431], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0871, 1.1668, -3.1431], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0871, 1.1668, -3.1431], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0871, 1.1668, -3.1431], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0874, 1.1671, -3.1444], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0874, 1.1671, -3.1444], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0874, 1.1671, -3.1444], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0874, 1.1671, -3.1444], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0877, 1.1674, -3.1457], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0877, 1.1674, -3.1457], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0877, 1.1674, -3.1457], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0877, 1.1674, -3.1457], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0879, 1.1676, -3.1470], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0879, 1.1676, -3.1470], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0879, 1.1676, -3.1470], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0879, 1.1676, -3.1470], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0879, 1.1676, -3.1470], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0879, 1.1676, -3.1470], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0879, 1.1676, -3.1470], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0883, 1.1674, -3.1468], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0883, 1.1674, -3.1468], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0882, 1.1674, -3.1468], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0882, 1.1674, -3.1468], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0885, 1.1672, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0885, 1.1672, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0885, 1.1672, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0885, 1.1672, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0888, 1.1670, -3.1466], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0888, 1.1670, -3.1466], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0888, 1.1670, -3.1466], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0888, 1.1670, -3.1466], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0892, 1.1668, -3.1464], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0892, 1.1668, -3.1464], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0892, 1.1668, -3.1464], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0892, 1.1668, -3.1464], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0895, 1.1666, -3.1463], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0895, 1.1666, -3.1463], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0895, 1.1666, -3.1463], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0895, 1.1666, -3.1463], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1664, -3.1462], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1664, -3.1462], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1664, -3.1462], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1664, -3.1462], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0901, 1.1662, -3.1460], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0901, 1.1662, -3.1460], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0901, 1.1662, -3.1460], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0901, 1.1662, -3.1460], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1660, -3.1459], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1660, -3.1459], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1660, -3.1459], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1660, -3.1459], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0907, 1.1657, -3.1458], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0907, 1.1657, -3.1458], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0907, 1.1657, -3.1458], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0907, 1.1657, -3.1458], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0908, 1.1663, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0908, 1.1663, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0908, 1.1663, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0908, 1.1663, -3.1421], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0906, 1.1672, -3.1386], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0906, 1.1672, -3.1386], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0906, 1.1672, -3.1386], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0906, 1.1672, -3.1386], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1680, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1680, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1680, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0904, 1.1680, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0902, 1.1689, -3.1313], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0902, 1.1689, -3.1313], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0902, 1.1689, -3.1313], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0902, 1.1689, -3.1313], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0900, 1.1698, -3.1276], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0900, 1.1698, -3.1276], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0900, 1.1698, -3.1276], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0900, 1.1698, -3.1276], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1706, -3.1239], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1706, -3.1239], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1706, -3.1239], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0898, 1.1706, -3.1239], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0896, 1.1715, -3.1200], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0896, 1.1715, -3.1200], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0896, 1.1715, -3.1200], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0896, 1.1715, -3.1200], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0893, 1.1724, -3.1162], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0893, 1.1724, -3.1162], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0893, 1.1724, -3.1162], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0893, 1.1724, -3.1162], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0891, 1.1733, -3.1123], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0891, 1.1733, -3.1123], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0891, 1.1733, -3.1123], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0891, 1.1733, -3.1123], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0889, 1.1743, -3.1083], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0889, 1.1743, -3.1083], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0889, 1.1743, -3.1083], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], grad_fn=<CloneBackward>)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], grad_fn=<CloneBackward>)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0910, 1.1655, -3.1456], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0916, 1.1660, -3.1469], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0916, 1.1660, -3.1469], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0916, 1.1660, -3.1469], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0916, 1.1660, -3.1469], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0922, 1.1665, -3.1481], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0922, 1.1665, -3.1481], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0922, 1.1665, -3.1481], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0922, 1.1665, -3.1481], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1669, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1669, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1669, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1669, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1674, -3.1505], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1674, -3.1505], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1674, -3.1505], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1674, -3.1505], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0939, 1.1678, -3.1517], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0939, 1.1678, -3.1517], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0939, 1.1678, -3.1517], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0939, 1.1678, -3.1517], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0945, 1.1683, -3.1529], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0945, 1.1683, -3.1529], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0945, 1.1683, -3.1529], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0945, 1.1683, -3.1529], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0951, 1.1688, -3.1541], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0951, 1.1688, -3.1541], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0951, 1.1688, -3.1541], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0951, 1.1688, -3.1541], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0956, 1.1692, -3.1552], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0956, 1.1692, -3.1552], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0956, 1.1692, -3.1552], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0956, 1.1692, -3.1552], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1697, -3.1564], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1697, -3.1564], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1697, -3.1564], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1697, -3.1564], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1701, -3.1576], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1701, -3.1576], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1701, -3.1576], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1701, -3.1576], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1701, -3.1576], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1701, -3.1576], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1701, -3.1576], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0963, 1.1697, -3.1562], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0963, 1.1697, -3.1562], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0964, 1.1697, -3.1562], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0964, 1.1697, -3.1562], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0959, 1.1692, -3.1549], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0959, 1.1692, -3.1549], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0959, 1.1692, -3.1549], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0959, 1.1692, -3.1549], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1687, -3.1535], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1687, -3.1535], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1687, -3.1535], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1687, -3.1535], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0950, 1.1683, -3.1521], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0950, 1.1683, -3.1521], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0950, 1.1683, -3.1521], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0950, 1.1683, -3.1521], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0946, 1.1678, -3.1507], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0946, 1.1678, -3.1507], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0946, 1.1678, -3.1507], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0946, 1.1678, -3.1507], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0941, 1.1673, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0941, 1.1673, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0941, 1.1673, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0941, 1.1673, -3.1493], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0937, 1.1668, -3.1479], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0937, 1.1668, -3.1479], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0937, 1.1668, -3.1479], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0937, 1.1668, -3.1479], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0932, 1.1663, -3.1465], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0932, 1.1663, -3.1465], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0932, 1.1663, -3.1465], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0932, 1.1663, -3.1465], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1659, -3.1451], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1659, -3.1451], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1659, -3.1451], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0927, 1.1659, -3.1451], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0923, 1.1654, -3.1436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0923, 1.1654, -3.1436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0923, 1.1654, -3.1436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0923, 1.1654, -3.1436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0923, 1.1654, -3.1436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0923, 1.1654, -3.1436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0923, 1.1654, -3.1436], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0928, 1.1648, -3.1427], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0928, 1.1648, -3.1427], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0928, 1.1648, -3.1427], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0928, 1.1648, -3.1427], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1642, -3.1417], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1642, -3.1417], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1642, -3.1417], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0933, 1.1642, -3.1417], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0938, 1.1636, -3.1407], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0938, 1.1636, -3.1407], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0938, 1.1636, -3.1407], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0938, 1.1636, -3.1407], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0944, 1.1630, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0944, 1.1630, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0944, 1.1630, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0944, 1.1630, -3.1397], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0949, 1.1624, -3.1387], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0949, 1.1624, -3.1387], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0949, 1.1624, -3.1387], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0949, 1.1624, -3.1387], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1618, -3.1376], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1618, -3.1376], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1618, -3.1376], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0955, 1.1618, -3.1376], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0960, 1.1612, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0960, 1.1612, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0960, 1.1612, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0960, 1.1612, -3.1366], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1606, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1606, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1606, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1606, -3.1356], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1600, -3.1345], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1600, -3.1345], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1600, -3.1345], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1600, -3.1345], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0977, 1.1594, -3.1335], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0977, 1.1594, -3.1335], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0977, 1.1594, -3.1335], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0977, 1.1594, -3.1335], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0977, 1.1594, -3.1335], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0977, 1.1594, -3.1335], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0977, 1.1594, -3.1335], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0975, 1.1589, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0975, 1.1589, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0975, 1.1589, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0975, 1.1589, -3.1350], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0973, 1.1585, -3.1365], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0973, 1.1585, -3.1365], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0973, 1.1585, -3.1365], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0973, 1.1585, -3.1365], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1580, -3.1380], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1580, -3.1380], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1580, -3.1380], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0971, 1.1580, -3.1380], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0970, 1.1575, -3.1395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0970, 1.1575, -3.1395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0970, 1.1575, -3.1395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0970, 1.1575, -3.1395], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1571, -3.1409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1571, -3.1409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1571, -3.1409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0968, 1.1571, -3.1409], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1566, -3.1424], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1566, -3.1424], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1566, -3.1424], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0966, 1.1566, -3.1424], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0964, 1.1561, -3.1438], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0964, 1.1561, -3.1438], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0964, 1.1561, -3.1438], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0964, 1.1561, -3.1438], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1557, -3.1453], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1557, -3.1453], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1557, -3.1453], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0962, 1.1557, -3.1453], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0961, 1.1552, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0961, 1.1552, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0961, 1.1552, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0961, 1.1552, -3.1467], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0959, 1.1548, -3.1481], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0959, 1.1548, -3.1481], requires_grad=True)\nhess: tensor([[-4.0000, 0.0000, 0.0000],\n [ 0.0000, -1.0000, 0.0000],\n [ 0.0000, 0.0000, -0.2500]], grad_fn=<CopySlices>)\nparams: tensor([ 0.0959, 1.1548, -3.1481], requires_grad=True)\n\nAcceptance Rate 0.92\n"
]
],
[
[
"### Convert samples to numpy arrays to plot using matplotlib",
"_____no_output_____"
]
],
[
[
"coords_hmc = torch.cat(params_hmc).reshape(len(params_hmc),-1).numpy()\ncoords_nuts = torch.cat(params_hmc_nuts).reshape(len(params_hmc_nuts),-1).numpy()\ncoords_i_rmhmc = torch.cat(params_irmhmc).reshape(len(params_irmhmc),-1).numpy()\ncoords_e_rmhmc = torch.cat(params_ermhmc).reshape(len(params_ermhmc),-1).numpy()\ncoords_h_e_rmhmc = torch.cat(params_hermhmc).reshape(len(params_hermhmc),-1).numpy()",
"_____no_output_____"
],
[
"xlim = [-5,5]\nylim = [-5,5]\nfs=16\nmean = torch.tensor([0.,0.,0.])\nstddev = torch.tensor([.5,1.,2.])\n\nfig, axs = plt.subplots(3, 1, figsize=(15,15))\n\naxs[0].scatter(coords_hmc[:,0], coords_hmc[:,1],s=5,alpha=0.3,label='HMC')\naxs[0].scatter(coords_nuts[:,0], coords_nuts[:,1],s=5,alpha=0.3,label='NUTS')\naxs[0].scatter(coords_i_rmhmc[:,0], coords_i_rmhmc[:,1],s=5,alpha=0.3,label='Implicit RMHMC')\naxs[0].scatter(coords_e_rmhmc[:,0], coords_e_rmhmc[:,1],s=5,alpha=0.3,label='Explicit RMHMC')\naxs[0].scatter(coords_h_e_rmhmc[:,0], coords_h_e_rmhmc[:,1],s=5,alpha=0.3,label='Hyper Explicit RMHMC')\naxs[0].scatter(mean[0],mean[1],marker = '*',color='C3',s=100,label='True Mean')\naxs[0].legend(fontsize=fs)\naxs[0].grid()\naxs[0].set_xlim(xlim)\naxs[0].set_ylim(ylim)\n\naxs[1].scatter(coords_hmc[:,0], coords_hmc[:,2],s=5,alpha=0.3,label='HMC')\naxs[1].scatter(coords_nuts[:,0], coords_nuts[:,2],s=5,alpha=0.3,label='NUTS')\naxs[1].scatter(coords_i_rmhmc[:,0], coords_i_rmhmc[:,2],s=5,alpha=0.3,label='Implicit RMHMC')\naxs[1].scatter(coords_e_rmhmc[:,0], coords_e_rmhmc[:,2],s=5,alpha=0.3,label='Explicit RMHMC')\naxs[1].scatter(coords_h_e_rmhmc[:,0], coords_h_e_rmhmc[:,2],s=5,alpha=0.3,label='Hyper Explicit RMHMC')\naxs[1].scatter(mean[0],mean[2],marker = '*',color='C3',s=100,label='True Mean')\naxs[1].legend(fontsize=fs)\naxs[1].grid()\naxs[1].set_xlim(xlim)\naxs[1].set_ylim(ylim)\n\naxs[2].scatter(coords_hmc[:,1], coords_hmc[:,2],s=5,alpha=0.3,label='HMC')\naxs[2].scatter(coords_nuts[:,1], coords_nuts[:,2],s=5,alpha=0.3,label='NUTS')\naxs[2].scatter(coords_i_rmhmc[:,1], coords_i_rmhmc[:,2],s=5,alpha=0.3,label='Implicit RMHMC')\naxs[2].scatter(coords_e_rmhmc[:,1], coords_e_rmhmc[:,2],s=5,alpha=0.3,label='Explicit RMHMC')\naxs[2].scatter(coords_h_e_rmhmc[:,1], coords_h_e_rmhmc[:,2],s=5,alpha=0.3,label='Hyper Explicit RMHMC')\naxs[2].scatter(mean[1],mean[2],marker = '*',color='C3',s=100,label='True Mean')\naxs[2].legend(fontsize=fs)\naxs[2].grid()\naxs[2].set_xlim(xlim)\naxs[2].set_ylim(ylim)\n\nplt.tight_layout()\n\n# plt.savefig('../../Gaussian_plots.png',bbox_inches='tight')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### KL divergence:\n* Calculated the KL divergence as a measure of how well we have approximated the target distribution (the Gaussian).",
"_____no_output_____"
]
],
[
[
"p = torch.distributions.MultivariateNormal(mean, stddev.diag()**2)\nq_hmc = torch.distributions.MultivariateNormal(torch.FloatTensor(coords_hmc.mean(0)),torch.diag(torch.FloatTensor(coords_hmc.var(0))))\nq_nuts = torch.distributions.MultivariateNormal(torch.FloatTensor(coords_nuts.mean(0)),torch.diag(torch.FloatTensor(coords_nuts.var(0))))\nq_i_rmhmc = torch.distributions.MultivariateNormal(torch.FloatTensor(coords_i_rmhmc.mean(0)),torch.diag(torch.FloatTensor(coords_i_rmhmc.var(0))))\nq_e_rmhmc = torch.distributions.MultivariateNormal(torch.FloatTensor(coords_e_rmhmc.mean(0)),torch.diag(torch.FloatTensor(coords_e_rmhmc.var(0))))\nq_h_e_rmhmc = torch.distributions.MultivariateNormal(torch.FloatTensor(coords_h_e_rmhmc.mean(0)),torch.diag(torch.FloatTensor(coords_e_rmhmc.var(0))))\n\nprint('HMC kl: ',torch.distributions.kl.kl_divergence(p, q_hmc))\nprint('NUTS kl: ',torch.distributions.kl.kl_divergence(p, q_nuts))\nprint('Implicit RMHMC kl: ',torch.distributions.kl.kl_divergence(p, q_i_rmhmc))\nprint('Explicit RMHMC kl: ',torch.distributions.kl.kl_divergence(p, q_e_rmhmc))\nprint('HyperEllip Explicit RMHMC kl: ',torch.distributions.kl.kl_divergence(p, q_h_e_rmhmc))",
"HMC kl: tensor(2.2522)\nNUTS kl: tensor(0.0082)\nImplicit RMHMC kl: tensor(0.0122)\nExplicit RMHMC kl: tensor(0.0124)\nHyperEllip Explicit RMHMC kl: tensor(1.2894)\n"
]
],
[
[
"Experiment until here (02.28)",
"_____no_output_____"
],
[
"# Sampling from a more complicated distribution: funnel distribution\n\n* We now define the funnel distribution as in Neal et al. 2003:\n$$\\prod_i\\mathcal{N}(\\mathbf{x}_i\\vert 0, \\exp\\{-v\\})\\mathcal{N}(v\\vert 0, 9). $$\n* This is our new `log_prob_func`.",
"_____no_output_____"
]
],
[
[
"D = 10\n\ndef funnel_ll(w, dim=D):\n v_dist = torch.distributions.Normal(0,3)\n ll = v_dist.log_prob(w[0])\n x_dist = torch.distributions.Normal(0,torch.exp(-w[0])**0.5)\n ll += x_dist.log_prob(w[1:]).sum()\n return ll",
"_____no_output_____"
]
],
[
[
"### Sample using standard HMC\n* As we did above for the multivariate Gaussian.",
"_____no_output_____"
]
],
[
[
"# HMC\nhamiltorch.set_random_seed(123)\nparams_init = torch.ones(D + 1)\nparams_init[0] = 0.\nstep_size = 0.2 \nnum_samples = 1000 # For results in plot num_samples = 10000\nL = 25\n\nparams_hmc = hamiltorch.sample(log_prob_func=funnel_ll, params_init=params_init, num_samples=num_samples,\n step_size=step_size, num_steps_per_sample=L)",
"_____no_output_____"
]
],
[
[
"### Sample using the No-U-Turn Sampler (NUTS)\n* Again, as we did above.\n* Note that this log probability is badly defined in certain parts of the parameter space. Therefore you will see invalid log probabilities printed out as the model samples. (Especially in the burn in stage.)\n* Do not worry about print statements of `Invalid log_prob`!\n",
"_____no_output_____"
]
],
[
[
"# HMC NUTS\nhamiltorch.set_random_seed(123)\nparams_init = torch.ones(D + 1)\nparams_init[0] = 0.\nstep_size = 0.01 \nnum_samples = 1200 # For results in plot num_samples = 12000\nL = 25\nburn = 200 # For results in plot burn = 2000\n\nparams_hmc_nuts = hamiltorch.sample(log_prob_func=funnel_ll, params_init=params_init, num_samples=num_samples,\n step_size=step_size, num_steps_per_sample=L,desired_accept_rate=0.75,sampler=hamiltorch.Sampler.HMC_NUTS,burn=burn)\n\n",
"_____no_output_____"
]
],
[
[
"### Sample using implicit Riemannian manifold Hamiltonian Monte Carlo (RMHMC)\n* We change sampler flag and integrator flag as before.\n* For the funnel distribution our metric tensor is no longer guaranteed to be positive semi-definite (PSD) if we use the Hessian as above. Therefore we introduce a new flag and set is as `metric=hamiltorch.Metric.SOFTABS`. This forces our metric to be PSD as in Betancourt 2013.\n* As is common in practice, we must often add jitter along the diagonal of the metric tensor to ensure we can invert it (it also allows us to differentiate through it using `torch.symeig`). We do this via `jitter=jitter`.",
"_____no_output_____"
]
],
[
[
"# Implicit RMHMC with SOFTABS\nhamiltorch.set_random_seed(123)\nparams_init = torch.ones(D + 1)\nparams_init[0] = 0. \nstep_size = 0.14 \nnum_samples = 10 # For results in plot num_samples = 1000, but this takes a while! Setting to 100 is also reasonable.\nL = 25\nthreshold = 1e-3\nsoftabs_const=10**6\nfixed_point_max_iterations=1000\njitter= 0.001\n\nparams_i_rmhmc = hamiltorch.sample(log_prob_func=funnel_ll, params_init=params_init, num_samples=num_samples,\n sampler=hamiltorch.Sampler.RMHMC, integrator=hamiltorch.Integrator.IMPLICIT,\n metric=hamiltorch.Metric.SOFTABS, fixed_point_threshold=threshold, jitter=jitter,\n num_steps_per_sample=L, step_size=step_size, softabs_const=softabs_const,\n fixed_point_max_iterations=fixed_point_max_iterations)\n\n",
"_____no_output_____"
]
],
[
[
"### Sample using explicit Riemannian manifold Hamiltonian Monte Carlo (RMHMC)\n\n* We use our faster integrator with the SOFTABS metric to get a similar result to the implicit integrator.",
"_____no_output_____"
]
],
[
[
"# Explicit RMHMC with SOFTABS\nhamiltorch.set_random_seed(123)\nparams_init = torch.ones(D + 1)\nparams_init[0] = 0.\nstep_size = 0.14 \nnum_samples = 100 # For results in plot num_samples = 1000\nL = 25\nomega=10\nsoftabs_const=10**6\njitter=0.001\n\nparams_e_rmhmc = hamiltorch.sample(log_prob_func=funnel_ll, params_init=params_init, num_samples=num_samples,\n sampler=hamiltorch.Sampler.RMHMC, integrator=hamiltorch.Integrator.EXPLICIT,\n metric=hamiltorch.Metric.SOFTABS, jitter=jitter,\n num_steps_per_sample=L, step_size=step_size, explicit_binding_const=omega, \n softabs_const=softabs_const)",
"_____no_output_____"
],
[
"# Explicit RMHMC with HYPERELLIP\nhamiltorch.set_random_seed(123)\nparams_init = torch.ones(D + 1)\nparams_init[0] = 0.\nstep_size = 0.14 \nnum_samples = 100 # For results in plot num_samples = 1000\nL = 25\nomega=10\nsoftabs_const=10**6\njitter=0.001\n\nparams_e_rmhmc = hamiltorch.sample(log_prob_func=funnel_ll, params_init=params_init, num_samples=num_samples,\n sampler=hamiltorch.Sampler.RMHMC, integrator=hamiltorch.Integrator.EXPLICIT,\n metric=hamiltorch.Metric.HYPERELLIP, jitter=jitter,\n num_steps_per_sample=L, step_size=step_size, explicit_binding_const=omega, \n ) #softabs_const=softabs_const",
"_____no_output_____"
]
],
[
[
"### Convert to numpy arrays for plotting",
"_____no_output_____"
]
],
[
[
"coords_hmc = torch.cat(params_hmc).reshape(len(params_hmc),-1).numpy()\ncoords_hmc_nuts = torch.cat(params_hmc_nuts).reshape(len(params_hmc_nuts),-1).numpy()\ncoords_i_rmhmc = torch.cat(params_i_rmhmc).reshape(len(params_i_rmhmc),-1).numpy()\ncoords_e_rmhmc = torch.cat(params_e_rmhmc).reshape(len(params_e_rmhmc),-1).numpy()",
"_____no_output_____"
],
[
"# One that I made earlier!\nparams_i_rmhmc = torch.load('../../data/funnel/params_i_rmhmc_10D_funnel_1000.npy')\nparams_e_rmhmc = torch.load('../../data/funnel/params_e_rmhmc_10D_funnel_1000.npy')\nparams_hmc = torch.load('../../data/funnel/params_hmc_10D_funnel_10000.npy')\nparams_hmc_nuts = torch.load('../../data/funnel/params_hmc_nuts_10D_funnel_10000.npy')\n\ncoords_hmc = torch.cat(params_hmc).reshape(len(params_hmc),-1).numpy()\ncoords_hmc_nuts = torch.cat(params_hmc_nuts).reshape(len(params_hmc_nuts),-1).numpy()\ncoords_i_rmhmc = torch.cat(params_i_rmhmc).reshape(len(params_i_rmhmc),-1).numpy()\ncoords_e_rmhmc = torch.cat(params_e_rmhmc).reshape(len(params_e_rmhmc),-1).numpy()",
"_____no_output_____"
],
[
"xlim = [-4,4]\nylim = [0,7]#[-2,9]\ntext_x = -1.5\ntext_y = 8\nfont_size_text = 20\nfs=17\nvxx = torch.linspace(xlim[0],xlim[1],300)\np = torch.distributions.Normal(0,3)\nv_pdf = torch.exp(p.log_prob(vxx))\n\nfig, axs = plt.subplots(1, 4, figsize=(20,5), sharey=True)\naxs[0].scatter(coords_hmc[:,1], coords_hmc[:,0],s=5,alpha=0.3,rasterized=True, color='C0', label='HMC')\nl = axs[0].legend(loc=0,fontsize=fs)\nl.legendHandles[0]._sizes = [100]\naxs[0].grid()\naxs[0].set_xlim(xlim)\naxs[0].set_ylim(ylim)\naxs[0].tick_params(axis='both', labelsize=fs)\naxs[0].set_xlabel(r'$x_1$',fontsize=font_size_text)\naxs[0].set_ylabel(r'$v$',fontsize=font_size_text,rotation=0,labelpad=30)\naxs[1].scatter(coords_hmc_nuts[:,1], coords_hmc_nuts[:,0],s=5,alpha=0.3,label='NUTS',rasterized=True,color='C5')\n\nl = axs[1].legend(loc=0,fontsize=fs)\nl.legendHandles[0]._sizes = [100]\naxs[1].grid()\naxs[1].set_xlim(xlim)\naxs[1].set_ylim(ylim)\naxs[1].tick_params(axis='both', labelsize=fs)\naxs[1].set_xlabel(r'$x_1$',fontsize=font_size_text)\n\naxs[2].scatter(coords_i_rmhmc[:,1], coords_i_rmhmc[:,0],s=5,alpha=0.3,rasterized=True, color='C1',label='Implicit\\nRMHMC')\nl = axs[2].legend(loc=0,fontsize=fs)\nl.legendHandles[0]._sizes = [100]\naxs[2].grid()\naxs[2].set_xlim(xlim)\naxs[2].set_ylim(ylim)\naxs[2].tick_params(axis='both', labelsize=fs)\naxs[2].set_xlabel(r'$x_1$',fontsize=font_size_text)\n\naxs[3].scatter(coords_e_rmhmc[:,1], coords_e_rmhmc[:,0],s=5,alpha=0.3,rasterized=True, color='C2', label='Explicit\\nRMHMC')\nl = axs[3].legend(loc=0,fontsize=fs)\nl.legendHandles[0]._sizes = [100]\naxs[3].grid()\naxs[3].set_xlim(xlim)\naxs[3].set_ylim(ylim)\naxs[3].tick_params(axis='both', labelsize=fs)\naxs[3].set_xlabel(r'$x_1$',fontsize=font_size_text)\n\nplt.tight_layout()\n\n# plt.savefig('../../data/funnel/funnel_hist_plots_scatter.pdf',bbox_inches='tight')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Marginal distribution $p(v)$\n\nWe can also plot the marginal distributions of $v$ by representing them in histograms. We plot the known Gaussian distribution in each figure for comparison. The KL divergence is also included to measure how close the empirical distribution is from the true one.",
"_____no_output_____"
]
],
[
[
"p = torch.distributions.Normal(0,3)\nq_hmc = torch.distributions.Normal(coords_hmc[:,0].mean(),coords_hmc[:,0].std())\nq_hmc_nuts = torch.distributions.Normal(coords_hmc_nuts[:,0].mean(),coords_hmc_nuts[:,0].std())\nq_i_rmhmc = torch.distributions.Normal(coords_i_rmhmc[:,0].mean(),coords_i_rmhmc[:,0].std())\nq_e_rmhmc = torch.distributions.Normal(coords_e_rmhmc[:,0].mean(),coords_e_rmhmc[:,0].std())\n\nkl_hmc = torch.distributions.kl.kl_divergence(p, q_hmc)\nkl_hmc_nuts = torch.distributions.kl.kl_divergence(p, q_hmc_nuts)\nkl_i_rmhmc = torch.distributions.kl.kl_divergence(p, q_i_rmhmc)\nkl_e_rmhmc = torch.distributions.kl.kl_divergence(p, q_e_rmhmc)\n\nprint('HMC kl: ',kl_hmc)\nprint('NUTS HMC kl: ',kl_hmc_nuts)\nprint('Implicit RMHMC kl: ',kl_i_rmhmc)\nprint('Explicit RMHMC kl: ',kl_e_rmhmc)",
"_____no_output_____"
],
[
"xlim = [-9,9]\nylim = [0,.25]\ntext_x = -4.5\ntext_y = .233\nfont_size_text = 20\nfs=17\nvxx = torch.linspace(xlim[0],xlim[1],300)\np = torch.distributions.Normal(0,3)\nv_pdf = torch.exp(p.log_prob(vxx))\n\nfig, axs = plt.subplots(1, 4, figsize=(20,5),sharey=True)\naxs[0].hist(coords_hmc[:,0], color='C0', bins=20,density=True, alpha=0.5, label='HMC',range=xlim)\naxs[0].plot(vxx.numpy(), v_pdf.numpy(),'C3',label='$p(v)$')\naxs[0].legend(loc=0,fontsize=fs)\naxs[0].grid()\naxs[0].set_xlim(xlim)\naxs[0].text(text_x, text_y, \"$\\mathrm{D_{KL}} = $\" + '{:.3f}'.format(kl_hmc), size=font_size_text, rotation=0.,\n ha=\"center\", va=\"center\",\n bbox=dict(boxstyle=\"round\",\n ec=\"k\", # Outer colour\n fc='w',\n )\n )\naxs[0].set_ylim(ylim)\naxs[0].tick_params(axis='both', labelsize=fs)\naxs[0].set_xlabel(r'$v$',fontsize=font_size_text)\naxs[0].set_ylabel(r'$p(v)$',fontsize=font_size_text,rotation=0,labelpad=30)\n\naxs[1].hist(coords_hmc_nuts[:,0], color='C5',bins=20,density=True, alpha=0.5,label='NUTS',range=xlim)\naxs[1].plot(vxx.numpy(), v_pdf.numpy(),'C3', label='$p(v)$')\naxs[1].legend(loc=0,fontsize=fs)\naxs[1].grid()\naxs[1].set_xlim(xlim)\naxs[1].text(text_x, text_y, \"$\\mathrm{D_{KL}} = $\" + '{:.3f}'.format(kl_hmc_nuts), size=font_size_text, rotation=0.,\n ha=\"center\", va=\"center\",\n bbox=dict(boxstyle=\"round\",\n ec=\"k\", # Outer colour\n fc='w',\n )\n )\naxs[1].set_ylim(ylim)\naxs[1].tick_params(axis='both', labelsize=fs)\naxs[1].set_xlabel(r'$v$',fontsize=font_size_text)\n\naxs[2].hist(coords_i_rmhmc[:,0], color='C1',bins=20,density=True, alpha=0.5,label='Implicit\\nRMHMC')\naxs[2].plot(vxx.numpy(), v_pdf.numpy(),'C3', label='$p(v)$')\naxs[2].legend(loc=1,fontsize=fs)\naxs[2].grid()\naxs[2].set_xlim(xlim)\naxs[2].text(text_x, text_y, \"$\\mathrm{D_{KL}} = $\" + '{:.3f}'.format(kl_i_rmhmc), size=font_size_text, rotation=0.,\n ha=\"center\", va=\"center\",\n bbox=dict(boxstyle=\"round\",\n ec=\"k\", # Outer colour\n fc='w',\n )\n )\naxs[2].set_ylim(ylim)\naxs[2].tick_params(axis='both', labelsize=fs)\naxs[2].set_xlabel(r'$v$',fontsize=font_size_text)\n\naxs[3].hist(coords_e_rmhmc[:,0], color='C2',bins=20,density=True, alpha=0.5, label='Explicit\\nRMHMC')\naxs[3].plot(vxx.numpy(), v_pdf.numpy(),'C3',label='$p(v)$')\naxs[3].legend(loc=0,fontsize=fs)\naxs[3].grid()\naxs[3].set_xlim(xlim)\naxs[3].text(text_x, text_y, \"$\\mathrm{D_{KL}} = $\" + '{:.3f}'.format(kl_e_rmhmc), size=font_size_text, rotation=0.,\n ha=\"center\", va=\"center\",\n bbox=dict(boxstyle=\"round\",\n ec=\"k\", # Outer colour\n fc='w',\n )\n )\naxs[3].set_ylim(ylim)\naxs[3].tick_params(axis='both', labelsize=fs)\naxs[3].set_xlabel(r'$v$',fontsize=font_size_text)\n\nplt.tight_layout()\n\n# plt.savefig('../../data/funnel/funnel_hist_plots_nuts.pdf',bbox_inches='tight')\nplt.show()",
"_____no_output_____"
]
],
[
[
"### DEBUG MODE\n* For `hamiltorch.sample()` we can pass `debug=True`. This is useful for checking how many iterations RMHMC takes to converge and also to look at the values of the Hamiltonian.\n* Also, for NUTS, debug mode returns an EXTRA output corresponding to the adapted step size.",
"_____no_output_____"
]
],
[
[
"# HMC NUTS\nhamiltorch.set_random_seed(123)\nparams_init = torch.ones(D + 1)\nparams_init[0] = 0.\nstep_size = 0.01 \nnum_samples = 6 #In paper: 12000\nL = 25\nburn = 3 #2000\n\n############\ndebug = True\n############\n\nparams_hmc_nuts, adapted_step_size = hamiltorch.sample(log_prob_func=funnel_ll, params_init=params_init,\n num_samples=num_samples, step_size=step_size, \n num_steps_per_sample=L,desired_accept_rate=0.75,\n sampler=hamiltorch.Sampler.HMC_NUTS,burn=burn, debug=debug)\n",
"_____no_output_____"
]
],
[
[
"* DEBUG Mode for implicit RMHMC.",
"_____no_output_____"
]
],
[
[
"# Implicit RMHMC with SOFTABS\nhamiltorch.set_random_seed(123)\nparams_init = torch.ones(D + 1)\nparams_init[0] = 0. \nstep_size = 0.14 \nnum_samples = 2\nL = 25\nthreshold = 1e-3\nsoftabs_const=10**6\nfixed_point_max_iterations=1000\njitter= 0.001\n\n############\ndebug = True\n############\n\nparams_i_rmhmc = hamiltorch.sample(log_prob_func=funnel_ll, params_init=params_init, num_samples=num_samples,\n sampler=hamiltorch.Sampler.RMHMC, integrator=hamiltorch.Integrator.IMPLICIT,\n metric=hamiltorch.Metric.SOFTABS, fixed_point_threshold=threshold, jitter=jitter,\n num_steps_per_sample=L, step_size=step_size, softabs_const=softabs_const,\n fixed_point_max_iterations=fixed_point_max_iterations,debug=debug)",
"_____no_output_____"
]
],
[
[
"The print statements below show how many iterations each implicit Euler integrator took before breaking out the loop:\n\n```Converged (params), iterations: 3, params_diff: 0.00030622229678556323\n Converged (momentum), iterations: 2, momenta_diff: 0.0001082777525880374```\n\nTherefore here, the `params` fixed-point step took 3 iterations and the `momentum` took 2.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbb30b54a4f3564365d05266d04f7445193b335b
| 686,968 |
ipynb
|
Jupyter Notebook
|
learning-virtual-values.ipynb
|
pjordan/learned-position-auctions
|
9920342072ee66b64d07e070caeedfcea8985188
|
[
"Apache-2.0"
] | null | null | null |
learning-virtual-values.ipynb
|
pjordan/learned-position-auctions
|
9920342072ee66b64d07e070caeedfcea8985188
|
[
"Apache-2.0"
] | null | null | null |
learning-virtual-values.ipynb
|
pjordan/learned-position-auctions
|
9920342072ee66b64d07e070caeedfcea8985188
|
[
"Apache-2.0"
] | null | null | null | 1,246.76588 | 83,636 | 0.957378 |
[
[
[
"# Learning Virtual Values\n\nIn this tutorial, we will extend the ideas from the [previous tutorial](learning-position-auctions.ipynb). We will consider position auctions, like those found in paid search marketplaces, but focus on virtual value transformations rather than payment and allocation networks.\n\n## Motivating example\n\nConsider a two-bidder, two-slot position auction where the values for the two bidders are correlated. There is a signal $c\\sim U[0,1]$, which we intepret as a _conversion rate_. The value of the item for bidder 1 is a random variable $v_1 = x_1 c$ where $x_1 \\sim U[0,1]$, similarly for bidder 2.\n\nThe first slot has a click-through-rate (quality) of 1. The second slot has a click-through-rate of 0.5. A bidder may purchase one slot only, so we can consider this a special case of a multi-item, unit-demand scenario.\n\n## Architectures and supporting functions\n\nIn this tutorial, we will make use of Monotonic networks.\n\n### Preliminaries\n\nWe will make heavy use of numpy, pandas, and pytorch.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndevice = torch.device(\"cuda:1\") if torch.cuda.is_available() else torch.device('cpu')",
"_____no_output_____"
]
],
[
[
"We will also make use of matplotlib and seaborn for visualization:",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Common components\n\nWe add common `dmch` components:",
"_____no_output_____"
]
],
[
[
"import dmch\nfrom dmch import Mechanism\nfrom dmch import SequentialMechanism\nfrom dmch import build_spa, create_spa_mechanism\n",
"_____no_output_____"
]
],
[
[
"Now we define the auction scenario:",
"_____no_output_____"
]
],
[
[
"# Number of bidders\nbidders = 2\n\n# Pr(click|position)\nslot_weights = [1, 0.5]\n\n# Number of slots\nslots = len(slot_weights)\n",
"_____no_output_____"
]
],
[
[
"## GSP\n\nFor comparison, we define the GSP mechanism by using sequantial second-price auctions (SPA):",
"_____no_output_____"
]
],
[
[
"def create_gsp_mechanism():\n mbuilder = dmch.build_spa(bidders, context_features=1)\n return mbuilder.build_sequential(slots,weights=slot_weights)",
"_____no_output_____"
]
],
[
[
"## MyersonNet\n\nThe allocation network is defined as follows:",
"_____no_output_____"
]
],
[
[
"def create_myerson_net(context_features=0, hidden_features=100, linear_functions=1, groups=1):\n mbuilder = dmch.build_spa(bidders, context_features=context_features)\n \n mbuilder.set_virtual_function(\n hidden_features=hidden_features,\n linear_functions=linear_functions,\n groups=groups)\n \n return mbuilder.build_sequential(slots,weights=slot_weights)",
"_____no_output_____"
]
],
[
[
"## Auction for the motivating example\n\n",
"_____no_output_____"
],
[
"The networks will train on data that is sampled from the value distribution, which is loaded into a `DataLoader`.",
"_____no_output_____"
]
],
[
[
"import torch.utils.data as data_utils\n\nepochs = 500\nsample_size = 2**15\nbatch_size = 2**12\n\nindepedent_components = torch.rand(sample_size, bidders)\ncommon_components = torch.rand(sample_size, 1)\ninputs = indepedent_components * common_components\ninputs_with_common = torch.cat([indepedent_components * common_components, common_components], dim=1)\n\ninputs_loader=data_utils.DataLoader(\n data_utils.TensorDataset(inputs),\n batch_size=batch_size)\n\ninputs_with_common_loader=data_utils.DataLoader(\n data_utils.TensorDataset(inputs_with_common),\n batch_size=batch_size)",
"_____no_output_____"
]
],
[
[
"Before training the networks, let's establish a GSP baseline.",
"_____no_output_____"
]
],
[
[
"gsp = create_gsp_mechanism()\ngsp_report = pd.DataFrame(\n dmch.evaluate(\n gsp,\n inputs_loader,\n bidders,\n epochs=epochs,\n device=device,\n misreport_lr=1e-1,\n misreport_epochs=100))",
"_____no_output_____"
]
],
[
[
"We now create a simple MyersonNet instance.",
"_____no_output_____"
]
],
[
[
"myerson_net = create_myerson_net().to(device)",
"_____no_output_____"
]
],
[
[
"We loop over the data for a number of epochs and record traces of the networks learning.",
"_____no_output_____"
]
],
[
[
"myerson_net_report = pd.DataFrame(dmch.train(\n myerson_net, # the mechanism\n inputs_loader, # the bid inputs\n bidders, # the number of bidders\n epochs=epochs, # the total number of loops over the data\n device=device, # the device\n rho=1e2, # the rho parameter for the augmented Lagrangian method\n mechanism_lr=1e-3, # the learning rate for the mechanism networks\n consider_dsic=False,\n consider_ir=False))",
"100%|██████████| 500/500 [01:59<00:00, 3.94it/s]\n"
]
],
[
[
"We can also test supplying MyersonNet with the common signal:",
"_____no_output_____"
]
],
[
[
"myerson_net_with_common = create_myerson_net(context_features=1).to(device)\n\nmyerson_net_with_common_report = pd.DataFrame(dmch.train(\n myerson_net_with_common, # the mechanism\n inputs_with_common_loader, # the bid inputs\n bidders, # the number of bidders\n epochs=epochs, # the total number of loops over the data\n device=device, # the device\n rho=1e2, # the rho parameter for the augmented Lagrangian method\n mechanism_lr=1e-3, # the learning rate for the mechanism networks\n consider_dsic=False,\n consider_ir=False))",
"100%|██████████| 500/500 [02:25<00:00, 3.41it/s]\n"
]
],
[
[
"Let's review the revenue of the network: _MyersonNet_ exceeds _GSP_ revenue and _MyersonNet with common_. Adding the common signal as context allows MyersonNet to condition on that context, which reduces a problem of finding an optimal reserve for two IID bidders from U[0,common].",
"_____no_output_____"
]
],
[
[
"fig, ax = plt.subplots(figsize=(8,6));\nax.axhline(y=gsp_report.mean()[['revenue']].values, color='g', label='GSP');\nax.plot(myerson_net_report.groupby('epoch')[['revenue']].mean(), label='MyersonNet');\nax.plot(myerson_net_with_common_report.groupby('epoch')[['revenue']].mean(), label='MyersonNet with common');\nax.legend();",
"_____no_output_____"
],
[
"def plot_mechanism(mechanism, common=1):\n X, Y = np.meshgrid(\n np.arange(0.0, common, 0.01),\n np.arange(0.0, common, 0.01))\n \n n = X.shape[0]*X.shape[1]\n \n inputs = torch.cat(\n (torch.from_numpy(np.reshape(X, (n,1))),\n torch.from_numpy(np.reshape(Y, (n,1)))),\n dim=1).float().to(device)\n \n inputs = torch.cat((inputs,torch.zeros(n,1).float().to(device)),dim=1)\n inputs[:,2] = common\n \n allocation, payment = mechanism(inputs)\n \n allocation_levels = np.arange(0, 1.5, 0.01)\n bid_levels = np.arange(0, 1.0, 0.01)\n fig, axes = plt.subplots(nrows=2, ncols=bidders+1, figsize=(20,10));\n \n def plot_contour(tensor,axis_index,bidder_title,main_title,levels):\n for bidder in range(bidders):\n CS = axes[axis_index,bidder].tricontourf(\n inputs[:,0].cpu().numpy(),\n inputs[:,1].cpu().numpy(),\n tensor[:,bidder].detach().cpu().numpy(),\n levels=levels,\n cmap=\"RdBu_r\",\n extend='both');\n fig.colorbar(CS, ax=axes[axis_index,bidder]);\n axes[axis_index,bidder].set_title(bidder_title+str(bidder));\n CS = axes[axis_index,bidders].tricontourf(\n inputs[:,0].cpu().numpy(),\n inputs[:,1].cpu().numpy(),\n tensor.sum(dim=1).detach().cpu().numpy(),\n levels=levels,\n cmap=\"RdBu_r\",\n extend='both');\n fig.colorbar(CS, ax=axes[axis_index,bidders]);\n axes[axis_index,bidders].set_title(main_title);\n plot_contour(allocation,0,'Allocation to bidder ','Allocation to all bidders',allocation_levels)\n plot_contour(payment,1,'Payment from bidder ','Payment from all bidders',allocation_levels)",
"_____no_output_____"
],
[
"plot_mechanism(gsp,common=1)\nplot_mechanism(myerson_net,common=1)\nplot_mechanism(myerson_net_with_common,common=1)",
"_____no_output_____"
],
[
"plot_mechanism(gsp,common=0.66)\nplot_mechanism(myerson_net,common=0.66)\nplot_mechanism(myerson_net_with_common,common=0.66)",
"_____no_output_____"
],
[
"plot_mechanism(gsp,common=0.33)\nplot_mechanism(myerson_net,common=0.33)\nplot_mechanism(myerson_net_with_common,common=0.33)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbb31be7a3e7918d20bc72d8d8f76f2aa8b9ed16
| 7,498 |
ipynb
|
Jupyter Notebook
|
01.Python-Basics/12. Tuples, Dictionary, Sets/09.Functions-in-sets.ipynb
|
PramitSahoo/Python-with-Data-Structures-and-Algorithms
|
f0004e2f5f981da2ae9c2b81c36659b1b7d92cc8
|
[
"Apache-2.0"
] | null | null | null |
01.Python-Basics/12. Tuples, Dictionary, Sets/09.Functions-in-sets.ipynb
|
PramitSahoo/Python-with-Data-Structures-and-Algorithms
|
f0004e2f5f981da2ae9c2b81c36659b1b7d92cc8
|
[
"Apache-2.0"
] | null | null | null |
01.Python-Basics/12. Tuples, Dictionary, Sets/09.Functions-in-sets.ipynb
|
PramitSahoo/Python-with-Data-Structures-and-Algorithms
|
f0004e2f5f981da2ae9c2b81c36659b1b7d92cc8
|
[
"Apache-2.0"
] | null | null | null | 17.316397 | 336 | 0.44972 |
[
[
[
"a = {1,2,3,4}\nb = {3,4,5,6}",
"_____no_output_____"
],
[
"# intersection\na.intersection(b)",
"_____no_output_____"
],
[
"a.union(b)",
"_____no_output_____"
],
[
"a.difference(b)",
"_____no_output_____"
],
[
"b.difference(a)",
"_____no_output_____"
],
[
"a.symmetric_difference(b) # union - intersection",
"_____no_output_____"
],
[
"a.intersection_update(b)",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"a.difference_update(b)",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"a.symmetric_difference_update(b)",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"a.union_update(b)",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"b",
"_____no_output_____"
],
[
"c = {3,4}",
"_____no_output_____"
],
[
"a.issubset(c)",
"_____no_output_____"
],
[
"c.issubset(a)",
"_____no_output_____"
],
[
"a.issuperset(c)",
"_____no_output_____"
],
[
"a.isdisjoint(b)",
"_____no_output_____"
],
[
"d = {7,8}",
"_____no_output_____"
],
[
"a.isdisjoint(d)",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb320b48b9c68f8ae85dccd2aaaabb183d1a8d7
| 4,458 |
ipynb
|
Jupyter Notebook
|
divisive_5x5_surround_net/analysis.ipynb
|
ecker-lab/burg2021_learning_divisive_normalization
|
9996c910db03f8101fab25328f2dd1f2dcc020b3
|
[
"MIT"
] | 2 |
2021-11-05T02:37:19.000Z
|
2022-02-07T13:58:40.000Z
|
divisive_5x5_surround_net/analysis.ipynb
|
ecker-lab/burg2021_learning_divisive_normalization
|
9996c910db03f8101fab25328f2dd1f2dcc020b3
|
[
"MIT"
] | null | null | null |
divisive_5x5_surround_net/analysis.ipynb
|
ecker-lab/burg2021_learning_divisive_normalization
|
9996c910db03f8101fab25328f2dd1f2dcc020b3
|
[
"MIT"
] | 1 |
2021-06-09T09:47:19.000Z
|
2021-06-09T09:47:19.000Z
| 28.76129 | 117 | 0.54262 |
[
[
[
"import logging\n\nimport pandas as pd\nimport seaborn as sns\nfrom scipy import stats\n\nimport divisivenormalization.utils as helpers\nfrom divisivenormalization.data import Dataset, MonkeySubDataset\n\nhelpers.config_ipython()\n\nlogging.basicConfig(level=logging.INFO)\n\nsns.set()\nsns.set_style(\"ticks\")\n# adjust sns paper context rc parameters\nfont_size = 8\nrc_dict = {\n \"font.size\": font_size,\n \"axes.titlesize\": font_size,\n \"axes.labelsize\": font_size,\n \"xtick.labelsize\": font_size,\n \"ytick.labelsize\": font_size,\n \"legend.fontsize\": font_size,\n \"figure.figsize\": (helpers.cm2inch(8), helpers.cm2inch(8)),\n \"figure.dpi\": 300,\n \"pdf.fonttype\": 42,\n \"savefig.transparent\": True,\n \"savefig.bbox_inches\": \"tight\",\n}\nsns.set_context(\"paper\", rc=rc_dict)\n\n\nclass args:\n num_best = 10\n fname_best_csv = \"df_best.csv\"\n weights_path = \"weights\"\n train_logs_path = \"train_logs\"\n stim_full_size = 140 # full size of stimulus w/o subsampling and cropping\n stim_subsample = 2\n crop = 10\n\n",
"_____no_output_____"
]
],
[
[
" ### Load data",
"_____no_output_____"
]
],
[
[
"results_df = pd.read_csv(\"results.csv\")\n# Save a simplified version of the csv file, sorted by validation set performance\ndf_plain = helpers.simplify_df(results_df)\ndf_plain.to_csv(\"results_plain.csv\")\n\ndata_dict = Dataset.get_clean_data()\ndata = MonkeySubDataset(data_dict, seed=1000, train_frac=0.8, subsample=args.stim_subsample, crop=args.crop)\n\n",
"_____no_output_____"
]
],
[
[
" ### Get and save FEV performance on test set\n Use the 10 best models for analysis. As this operation requires model loading, we do it only if it\n was not done before.",
"_____no_output_____"
]
],
[
[
"try:\n df_best = pd.read_csv(args.fname_best_csv)\n logging.info(\"loaded data from \" + args.fname_best_csv)\n\nexcept FileNotFoundError:\n df_best = df_plain[0 : args.num_best].copy()\n\n fev_lst = []\n for i in range(args.num_best):\n run_no = df_best.iloc[i][\"run_no\"]\n logging.info(\"load run no \" + str(run_no))\n model = helpers.load_dn_model(run_no, results_df, data, args.train_logs_path)\n\n fev = model.evaluate_fev_testset()\n fev_lst.append(fev)\n\n feve = model.evaluate_fev_testset_per_neuron()\n helpers.pkl_dump(feve, run_no, \"feve.pkl\", args.weights_path)\n\n with model.session.as_default():\n u = model.u.eval()\n helpers.pkl_dump(u, run_no, \"u.pkl\", args.weights_path)\n\n df_best[\"fev\"] = fev_lst\n df_best.to_csv(args.fname_best_csv)\n\n",
"_____no_output_____"
],
[
"fev = df_best.fev.values * 100\nprint(\"Mean FEV\", fev.mean())\nprint(\"SEM\", stats.sem(fev, ddof=1))\nprint(\"max FEV\", fev.max())\nprint(\"FEV of model with max correlation on validation set\", fev[0])\n",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbb346569a3e9ad77e2e7669e58f31061539730e
| 1,976 |
ipynb
|
Jupyter Notebook
|
module1-python-modules-packages-and-environments/Untitled.ipynb
|
aklefebvere/DS-Unit-3-Sprint-1-Software-Engineering
|
91ba746ff05bec7d81586f4c3727d3f35d276a5b
|
[
"MIT"
] | null | null | null |
module1-python-modules-packages-and-environments/Untitled.ipynb
|
aklefebvere/DS-Unit-3-Sprint-1-Software-Engineering
|
91ba746ff05bec7d81586f4c3727d3f35d276a5b
|
[
"MIT"
] | null | null | null |
module1-python-modules-packages-and-environments/Untitled.ipynb
|
aklefebvere/DS-Unit-3-Sprint-1-Software-Engineering
|
91ba746ff05bec7d81586f4c3727d3f35d276a5b
|
[
"MIT"
] | null | null | null | 29.939394 | 363 | 0.582996 |
[
[
[
"pip install -i https://test.pypi.org/simple/ themecampmanager",
"Looking in indexes: https://test.pypi.org/simple/\nRequirement already satisfied: themecampmanager in /home/adriann/anaconda3/envs/lambda/lib/python3.7/site-packages (0.1.2)\nNote: you may need to restart the kernel to use updated packages.\n"
],
[
"from themecampmanager.mods import return_hash",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code"
]
] |
cbb349e08ef9f0b4bf9a6b6ef3f2493ba15942f8
| 1,358 |
ipynb
|
Jupyter Notebook
|
01.Python-Basics/05. Patterns 2/5.Isosceles-Pattern.ipynb
|
PramitSahoo/Python-with-Data-Structures-and-Algorithms
|
f0004e2f5f981da2ae9c2b81c36659b1b7d92cc8
|
[
"Apache-2.0"
] | null | null | null |
01.Python-Basics/05. Patterns 2/5.Isosceles-Pattern.ipynb
|
PramitSahoo/Python-with-Data-Structures-and-Algorithms
|
f0004e2f5f981da2ae9c2b81c36659b1b7d92cc8
|
[
"Apache-2.0"
] | null | null | null |
01.Python-Basics/05. Patterns 2/5.Isosceles-Pattern.ipynb
|
PramitSahoo/Python-with-Data-Structures-and-Algorithms
|
f0004e2f5f981da2ae9c2b81c36659b1b7d92cc8
|
[
"Apache-2.0"
] | null | null | null | 18.861111 | 40 | 0.407953 |
[
[
[
"n = int(input())\ni = 1\nwhile(i <= n ):\n spaces = 1\n while(spaces <= n - i + 1):\n print(\" \", end='')\n spaces += 1\n colsNo = 1\n while(colsNo <= i):\n print(colsNo,end='')\n colsNo += 1\n p = i - 1\n while(p >= 1):\n print(p,end='')\n p -= 1\n print()\n i += 1",
"4\n 1\n 121\n 12321\n 1234321\n"
]
]
] |
[
"code"
] |
[
[
"code"
]
] |
cbb34cbbed8d808e1f731c4c800ac81db8cee52f
| 41,838 |
ipynb
|
Jupyter Notebook
|
talktorials/10_binding_site_similarity/T10_off-targets.ipynb
|
richardjgowers/TeachOpenCADD
|
b50506394a2a1309319bbaa19e2263de52aec2e1
|
[
"CC-BY-4.0"
] | null | null | null |
talktorials/10_binding_site_similarity/T10_off-targets.ipynb
|
richardjgowers/TeachOpenCADD
|
b50506394a2a1309319bbaa19e2263de52aec2e1
|
[
"CC-BY-4.0"
] | null | null | null |
talktorials/10_binding_site_similarity/T10_off-targets.ipynb
|
richardjgowers/TeachOpenCADD
|
b50506394a2a1309319bbaa19e2263de52aec2e1
|
[
"CC-BY-4.0"
] | null | null | null | 35.576531 | 556 | 0.619485 |
[
[
[
"# Talktorial 10\n\n# Binding site similarity and off-target prediction\n\n#### Developed in the CADD seminars 2017 and 2018, AG Volkamer, Charité/FU Berlin \n\nAngelika Szengel, Marvis Sydow and Dominique Sydow",
"_____no_output_____"
],
[
"**Note**: Please run this notebook cell by cell. Running all cells in one is possible also, however, a few PyMol images might not turn out as intended.",
"_____no_output_____"
],
[
"## Aim of this talktorial\n\nIn this talktorial, we use the structural similarity of whole proteins and binding sites to predict off-targets, i.e. proteins that are not intended targets of a drug, which may lead to unwanted side effects or enable desired alternate applications of a drug (drug repositioning).\nWe discuss the main steps for binding site comparison and implement a basic method, i.e. the geometrical variation between structures (the root mean square deviation of two structures).\n\n## Learning goals\n\n### Theory\n\n* Off-target proteins\n* Computational off-target prediction: binding site comparison\n* Pairwise RMSD as simple measure for similarity\n* Imatinib, a tyrosine kinase inhibitor\n\n### Practical\n\n* Load and visualize the ligand of interest (Imatinib/STI)\n* Get all protein-STI complexes from the PDB\n * Query the PDB\n * Filter the PDB data set\n * Save the filtered PDB IDs\n* Visualize the PDB structures\n* Align the PDB structures (whole protein)\n* Get pairwise RMSD (whole protein)\n* Align the PDB structures (binding site)\n* Get pairwise RMSD (binding site)\n\n\n## References\n\nBinding site comparison: \n\n* Binding site comparison reviews: \n([<i>Curr. Comput. Aided Drug Des. </i> (2008), <b>4</b>, 209-20](https://www.eurekaselect.com/67606/article/how-measure-similarity-between-protein-ligand-binding-sites)) \nand \n([<i>J. Med. Chem. </i> (2016), <b>9</b>, 4121-51](https://pubs.acs.org/doi/10.1021/acs.jmedchem.6b00078))\n* Documentation on PyMol `align` command \n([PyMolWiki: `align`](https://pymolwiki.org/index.php/Align))\n* Wikipedia article on root mean square deviation (RMSD) \n([Wikipedia: RMSD](https://en.wikipedia.org/wiki/Root-mean-square_deviation_of_atomic_positions)) and structural superposition ([Wikipedia: structural superposition](https://en.wikipedia.org/wiki/Structural_alignment))\n* Structural superposition ([Book chapter: Algorithms, Applications, and Challenges of Protein Structure Alignment in *Advances in Protein Chemistry and Structural Biology* (2014), **94**, 121-75](https://www.sciencedirect.com/science/article/pii/B9780128001684000056?via%3Dihub))\n\nImatinib: \n\n* Review on Imatinib \n([<i>Nat. Rev. Clin. Oncol.</i> (2016), <b>13</b>, 431-46](https://www.nature.com/articles/nrclinonc.2016.41))\n* Promiscuity of imatinib \n([<i>J. Biol.</i> (2009), <b>8</b>, 10.1186/jbiol134](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2689438/))\n* ChEMBL information on Imatinib \n([ChEMBL: Imatinib](https://www.ebi.ac.uk/chembl/compound/inspect/CHEMBL941))\n* PDB information on Imatinib \n([PDB: STI](https://www3.rcsb.org/ligand/STI))\n* Side effects of Imatinib\n([Drugs.com: Imatinib](https://www.drugs.com/cdi/imatinib.html))\n* Side effects of Imatinib\n ([<i>BMC Struct. Biol.</i> (2009), <b>9</b>, 10.1186/1472-6807-9-7](https://bmcstructbiol.biomedcentral.com/articles/10.1186/1472-6807-9-7))",
"_____no_output_____"
],
[
"## Theory\n\n### Off-target proteins\n\nAn off-target can be any protein which interacts with a drug or (one of) its metabolite(s) without being the designated target protein. \nThe molecular reaction caused by the off-target can lead to unwanted side effects, ranging from a rather harmless to extremely harmful impact. \nOff-targets mainly occur because on- and off-targets share similar structural motifs with each other in their binding site and therefore can bind similar ligands. \n\n### Computational off-target prediction: binding site comparison\n\nComputation-aided prediction of potential off-targets is aimed at minimizing the risk of developing potentially dangerous substances for medical treatment.\nThere are several algorithmic approaches to assess binding site similarity but they always consist of three main steps:\n\n1. **Binding site encoding**: binding sites are encoded using different descriptor techniques and stored in a target database.\n2. **Binding site comparison**: a query binding site is compared with the target database, using different similarity measures.\n3. **Target ranking**: targets are ranked based on a suitable scoring approach.\n\nFor detailed information on different similarity measures and existing tools, we refer to two excellent reviews on binding site comparison ([<i>Curr. Comput. Aided Drug Des. </i> (2008), <b>4</b>, 209-20](https://www.eurekaselect.com/67606/article/how-measure-similarity-between-protein-ligand-binding-sites) and [<i>J. Med. Chem. </i> (2016), <b>9</b>, 4121-51](https://pubs.acs.org/doi/10.1021/acs.jmedchem.6b00078)).\n\n<img src=\"images/binding_site_comparison_steps.png\" align=\"above\" alt=\"Image cannot be shown\" width=\"700\">\n<div align=\"center\"> Figure 1: Main steps of binding site comparison methods (figure by Dominique Sydow).</div>\n\n### Pairwise RMSD as simple measure for similarity\n\nA simple and straightforward method for scoring the similarity is to use the calculated root mean square deviation (RMSD), which is the square root of the mean of the square of the distances between the atoms of two aligned structures ([Wikipedia: RMSD](https://en.wikipedia.org/wiki/Root-mean-square_deviation_of_atomic_positions)). \n\n\nIn order to find the respective atoms that are compared between two structures, they need to be aligned first based on sequence-based or sequence-independent alignment algorithms ([Book chapter: Algorithms, Applications, and Challenges of Protein Structure Alignment in *Advances in Protein Chemistry and Structural Biology* (2014), **94**, 121-75](https://www.sciencedirect.com/science/article/pii/B9780128001684000056?via%3Dihub)).\n\n\n\n\n### Imatinib, a tyrosine kinase inhibitor\n\nKinases transfer a phosphate group from ATP to proteins, and thereby regulate various cellular processes such as signal transduction, metabolism, and protein regulation.\nIf these kinases are constitutively active (due to genomic mutations), they can distort regulation processes and cause cancer.\nAn example for cancer treatment is Imatinib ([<i>Nat. Rev. Clin. Oncol.</i> (2016), <b>13</b>, 431-46](https://www.nature.com/articles/nrclinonc.2016.41)), a small molecule tyrosine kinase inhibitor used to treat cancer, more specifically chronic myeloid leukaemia (CML) and gastrointestinal stromal tumour (GIST). \n\nImatinib was shown to be not entirely specific and to target tyrosine kinases other than its main target. This was used for drug repositioning, i.e. Imatinib was approved for alternate cancer types, ([<i>J. Biol.</i> (2009), <b>8</b>, 10.1186/jbiol134](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2689438/)), however can also show unwanted side effects such as signs of an allergic reaction, infection, bleeding, or headache ([Drugs.com: Imatinib](https://www.drugs.com/cdi/imatinib.html)).",
"_____no_output_____"
],
[
"## Practical\n\nIn the following, we will fetch and filter PDB structures that bind Imatinib. We will investigate the structure similarity of Imatinib-binding proteins (those with a solved protein structure). \nThe similarity measure used is a pairwise RMSD calculation (as a simple similarity measure), in order to show that this simple method can be used as an initial test for potential off-targets.",
"_____no_output_____"
]
],
[
[
"import os\nimport pprint\nimport pickle\nimport glob\nimport time\n\nfrom rdkit import Chem\nfrom rdkit.Chem.Draw import IPythonConsole\nfrom rdkit.Chem import Draw, AllChem\n#from rdkit.Chem import PyMol\nIPythonConsole.ipython_useSVG=True\n\nimport nglview as nv\n\nimport pandas as pd\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom pypdb import *\nfrom biopandas.pdb import PandasPdb",
"_____no_output_____"
]
],
[
[
"### Load and visualize the ligand of interest (Imatinib/STI)\n\nThe SMILES format for Imatinib (common abbreviation: STI) can be retrieved from e.g. the ChEMBL database \n([ChEMBL: Imatinib](https://www.ebi.ac.uk/chembl/compound/inspect/CHEMBL941)) \nor the PDB database by its common abbreviation STI \n([PDB: STI](https://www3.rcsb.org/ligand/STI)). \nWe simply copy the string from the \"Isomeric SMILES\" entry of the Chemical Component Summary table, and load the ligand here by hand.",
"_____no_output_____"
]
],
[
[
"sti = Chem.MolFromSmiles('CN1CCN(Cc2ccc(cc2)C(=O)Nc2ccc(C)c(Nc3nccc(n3)-c3cccnc3)c2)CC1')\nDraw.MolToImage(sti)",
"_____no_output_____"
]
],
[
[
"In order to inspect the 3D structure of STI, we use the open source tool PyMol (see introduction in talktorial T8). \nBefore we can view STI in PyMol, we need to compute its 3D coordinates.\n\nFirst, we add hydrogen atoms to the molecule, which are not always explicitly denoted in the SMILES format.\nSecond, we use the distance geometry to obtain initial coordinates for the molecule and optimize the structure of the molecule using the force field UFF (Universal Force Field).",
"_____no_output_____"
]
],
[
[
"sti_mol = Chem.AddHs(sti)\nsti_mol",
"_____no_output_____"
],
[
"AllChem.EmbedMolecule(sti_mol)\nAllChem.UFFOptimizeMolecule(sti_mol)\nsti_mol",
"_____no_output_____"
]
],
[
[
"Now, we are ready to roll in nglview! \n",
"_____no_output_____"
]
],
[
[
"nv.show_rdkit(sti_mol)",
"_____no_output_____"
]
],
[
[
"### Get all protein-STI complexes from the PDB\n\nWe can look up Imatinib/STI in open databases like the PDB and search for proteins which are reported targets. In the PDB, Imatinib is usually abbreviated by STI. We will search for both terms and merge the results in the following.\n\n#### Query the PDB\n\nFirst, we retrieve all proteins from the PDB that bind the ligand of interest (STI).",
"_____no_output_____"
]
],
[
[
"search_dict = make_query('STI') # Query PDB for proteins bound to the ligand STI\nfound_pbd_ids = do_search(search_dict)\n\nprint(found_pbd_ids)\nprint(\"\\nNumber of structures connected with STI in the PDB: \" + str(len(found_pbd_ids)))",
"_____no_output_____"
]
],
[
[
"Note that the query results can differ depending on the term used for the query ligand (here: Imatinib). ",
"_____no_output_____"
]
],
[
[
"search_dict2 = make_query('Imatinib') # Query PDB for proteins bound to the ligand Imatinib\nfound_pbd_ids2 = do_search(search_dict2)\n\nprint(found_pbd_ids2)\nprint(\"\\nNumber of structures connected with Imatinib in the PDB: \" + str(len(found_pbd_ids2)))",
"_____no_output_____"
]
],
[
[
"We merge both query results and keep only unique entries.",
"_____no_output_____"
]
],
[
[
"pdb_ids = list(set(found_pbd_ids + found_pbd_ids))\nprint(\"Number of structures connected with STI/Imatinib in the PDB: \" + str(len(pdb_ids)))",
"_____no_output_____"
]
],
[
[
"#### Filter the PDB data set\n\nWe retrieve meta information on the PDB structures using the `pypdb` function `get_entity_info`, in order to filter the data set based on the following criteria:\n\n1. Filter by experimental method (`xray`).\n2. Filter by resolution (equal or lower than 3 Å).\n3. Retain only PDB structures with a single chain (for simplicity).\n4. Retain only Imatinib-bound structures (e.g. some PDB structures are returned that are associated with Imatinib but not bound to it).\n5. Retain only PDB IDs deposited before 2019 (data set resource at the time of the talktorial publication).\n\nFor more info on how to query the PDB see **talktorial 8**.",
"_____no_output_____"
]
],
[
[
"# Get meta information from the PDB\nentity_info = []\nfor i in pdb_ids:\n entity_info.append(get_entity_info(i))\nentity_info[0]",
"_____no_output_____"
],
[
"# Transform list to DataFrame\nentity_info_pd = pd.DataFrame(entity_info)\na = [int(i.split(\" \")[5]) for i in entity_info_pd[\"release_date\"].tolist()]\nentity_info_pd.head()",
"_____no_output_____"
],
[
"# 1. Filter by experimental method\nentity_info_pd = entity_info_pd[entity_info_pd[\"Method\"] == {'@name': 'xray'}]\n\n# 2. Filter by resolution\nentity_info_pd = entity_info_pd[entity_info_pd[\"resolution\"].astype(float) <= 3.0]\n\n# 3. Retain only structures with a single chain (for simplicity)\nentity_info_pd = entity_info_pd[[type(i) == dict for i in entity_info_pd[\"Entity\"]]]\nentity_info_pd = entity_info_pd[[type(i[\"Chain\"]) == dict for i in entity_info_pd[\"Entity\"]]]\n\npdb_ids = entity_info_pd[\"structureId\"].tolist()\n\nprint(\"Number of structures after filtering: \" + str(len(pdb_ids)))",
"_____no_output_____"
]
],
[
[
"In the following, we will use a package called `BioPandas`, which provides useful functions to load molecular structures of biological macromolecules (from PDB and MOL2 files) in pandas DataFrames. We will use the `PandasPdb` object to facilitate our work with PDB files.",
"_____no_output_____"
]
],
[
[
"# 4. Retain only Imatinib-bound structures\n\ndef check_if_ligand_present(pdb_id, ligand_name):\n ppdb = PandasPdb().fetch_pdb(pdb_id) # Fetch PDB (atom info, coordinates)\n return sum(ppdb.df[\"HETATM\"][\"residue_name\"] == ligand_name) > 0 # Check for existence of STI entries\n\nentity_info_pd = entity_info_pd[[check_if_ligand_present(pdb_id, \"STI\") for pdb_id in pdb_ids]] # Apply function\n\npdb_ids = entity_info_pd[\"structureId\"].tolist()\n\nprint(\"Number of structures after filtering: \" + str(len(pdb_ids)))",
"_____no_output_____"
],
[
"# 5. Retain only PDB IDs deposited before 2019\n\nentity_info_pd = entity_info_pd[[int(i.split()[5]) < 2019 for i in entity_info_pd[\"release_date\"].tolist()]]\n\npdb_ids = entity_info_pd[\"structureId\"].tolist()\n\nprint(\"Number of structures after filtering: \" + str(len(pdb_ids)))",
"_____no_output_____"
],
[
"# 6. After manual visual inspection remove 3GVU (contains 2x STI: not feasable for automatic workflow below)\npdb_ids.remove(\"3GVU\")",
"_____no_output_____"
],
[
"pdb_ids\n#random.shuffle(pdb_ids) # In case you would like to change the order of IDs",
"_____no_output_____"
]
],
[
[
"#### Save the filtered PDB IDs\n\nWe save the PDB IDs of the filtered data set for further analysis (we will use PyMol python scripts later on that will process PDB IDs according to this file).",
"_____no_output_____"
]
],
[
[
"pickle.dump(pdb_ids, open(\"../data/T10/pdb_ids.p\", \"wb\"))",
"_____no_output_____"
]
],
[
[
"### Visualize the PDB structures\n\nFirst, we load all structures to PyMol for visual inspection of the 3D structure of the protein data set. \n\nBesides the visualization here in this Jupyter notebook in form of fixed images of a PyMol frame, it is advised to also view and interact with the structures in 3D directly within the PyMol application, which should be opened and manipulated in parallel to this talktorial. ",
"_____no_output_____"
]
],
[
[
"pdb_ids",
"_____no_output_____"
],
[
"w = nv.NGLWidget()\nfor pdb_id in pdb_ids:\n w.add_pdbid(pdb_id)\nw",
"_____no_output_____"
]
],
[
[
"Though this image is beautifully colorful and curly, it is not informative yet. We align the structures to each other in the next step.",
"_____no_output_____"
],
[
"### Align the PDB structures (whole protein)\n\nPyMol offers different alignment methods suitable for different levels of sequence and structural similarity:\n\n* The [`super`](https://pymolwiki.org/index.php/Super) command is preferred for proteins with *decent structural similarity* (sequence-independent).\n* The [`align`](https://pymolwiki.org/index.php/Align) command is preferred for proteins with *decent sequence similarity* (sequence-dependent). \n* The [`cealign`](https://pymolwiki.org/index.php/Cealign) command is very robust for proteins with *little to no sequence similarity* (twilight zone).\n\nIn this talktorial, we choose the `align` command to superimpose the structures (based on sequence) by minimizing their RMSD. \n\nNote: This approach biases the analysis towards structures with similar sequences (the `align` command perform better for protein pairs with decent sequence similarity). For some comparisons with lower sequence similarity the `super` or `cealign` command could be a better choice. For an automated workflow (where we do not know the sequence or structural similarity of protein pairs) a solution could be to calculate the RMSD based on all three measures and retain the best for further analysis.\n\nFirst, we show the alignment of all structures to the first structure in the list `pdb_ids`.",
"_____no_output_____"
]
],
[
[
"from biotite import sequence\nfrom biotite.sequence import align\nfrom MDAnalysis.analysis import align as mda_align",
"_____no_output_____"
],
[
"def get_sequence(protein):\n # protein - mda.AtomGroup\n # return string representation of protein\n seq = protein.residues.sequence()\n return str(seq.seq)\n\n\ndef align_sequences(s1, s2):\n # s1, s2 - string of sequence\n # returns biotite.Alignment (first/best)\n alignments = align.align_optimal(sequence.ProteinSequence(s1),\n sequence.ProteinSequence(s2),\n align.SubstitutionMatrix.std_protein_matrix(),\n gap_penalty=(-10, -1), terminal_penalty=True,\n )\n return alignments[0]\n\n\ndef get_aligned(ref, mobile):\n # ref, mobile - mda.AtomGroup\n # returns filtered versions of ref & mobile that are now sequence aligned\n s1, s2 = get_sequence(ref), get_sequence(mobile)\n a = align_sequences(s1, s2)\n # indices of residue alignment\n trace = a.trace\n # grab only rows where sequences are aligned\n trace = trace[~(trace == -1).any(axis=1)]\n \n aref = ref.residues[trace[:, 0]]\n amob = mobile.residues[trace[:, 1]]\n \n return aref.atoms, amob.atoms\n\n\ndef align_protein(ref, mobile):\n # sequence align then shift mobile to align to ref\n aref, amob = get_aligned(ref, mobile)\n\n \n mda_align.alignto(amob, aref, strict=False, select='name CA')\n \n return aref, amob",
"_____no_output_____"
],
[
"# download pdbids (again) into MDAnalysis\nstructures = [mda.fetch_mmtf(pdb_id) for pdb_id in pdb_ids[1:]]\n# strip solvent etc\nproteins = [s.select_atoms('protein') for s in structures]",
"_____no_output_____"
],
[
"# choose first protein as reference\nref = proteins[0]\n# align all but first protein to first protein\nfor mobile in proteins[1:]:\n align_protein(ref, mobile)",
"_____no_output_____"
],
[
"view = nv.NGLWidget()\n\nfor protein in proteins:\n view.add_component(protein)\nview",
"_____no_output_____"
]
],
[
[
"One of the proteins, i.e. 3FW1, is poorly aligned in comparison to the other proteins. We hide this protein, in order to visually show the well aligned proteins.",
"_____no_output_____"
]
],
[
[
"view = nv.NGLWidget()\n\nfor protein in proteins[1:]:\n view.add_component(protein)\nview",
"_____no_output_____"
]
],
[
[
"The structural alignment for many e.g. helices is high, whereas lower or poor for others.",
"_____no_output_____"
]
],
[
[
"from MDAnalysis.analysis import rms\n\ndef calc_rmsd(A, B):\n # sequence alignment\n A, B = get_aligned(A, B)\n \n # select backbone\n A = A.select_atoms('name CA')\n B = B.select_atoms('name CA')\n \n A, B = mda_align.get_matching_atoms(A, B)\n \n return rms.rmsd(A.positions, B.positions, superposition=False)",
"_____no_output_____"
],
[
"rmsd_matrix = np.zeros((6, 6))\n\nfor i, A in enumerate(proteins):\n for j, B in enumerate(proteins):\n rmsd_matrix[i, j] = calc_rmsd(A, B)",
"_____no_output_____"
],
[
"rmsd_matrix",
"_____no_output_____"
]
],
[
[
"### Get pairwise RMSD (whole protein)\n\nSince we could not find a function to return the RMSD values from PyMol in this Jupyter notebook (which *is* possible within PyMol and within a PyMol python script), we call here a PyMol python script: the superposition and final RMSD refinement is performed for all protein pairs. The resulting RMSD values are saved for further analysis.\n\nFirst, we take a look at the python script for PyMol, which we will use for this task.",
"_____no_output_____"
]
],
[
[
"f = open(\"./pymol_scripts/pymol_align_proteins.py\")\nfile_content = f.readlines()\nfor i in file_content:\n print(i, end=\"\")",
"_____no_output_____"
],
[
"os.popen(\"python ./pymol_scripts/pymol_align_proteins.py\")",
"_____no_output_____"
]
],
[
[
"This PyMol python script saves all pairwise RMSD results to a file, which we load now to the Jupyter notebook.",
"_____no_output_____"
]
],
[
[
"align_df_proteins = pickle.load(open(\"../data/T10/align_df_proteins.p\", \"rb\"))",
"_____no_output_____"
]
],
[
[
"`align_df_proteins` is a DataFrame and contains for each pairwise comparison the return values of the `align` command in PyMol, i.e. a tuple with 7 items:\n\n1. RMSD after refinement\n2. Number of aligned atoms after refinement\n3. Number of refinement cycles\n4. RMSD before refinement\n5. Number of aligned atoms before refinement\n6. Raw alignment score\n7. Number of residues aligned\n\nWe familiarize ourselves with this data structure for an example protein pair:",
"_____no_output_____"
]
],
[
[
"print(\"Structures in the data set:\")\ncols = align_df_proteins.columns\nrows = align_df_proteins.index\nprint(cols)\nprint(rows)\n\nexample_col = cols[0]\nexample_row = rows[2]\nprint(\"\\nExample align return values for the {}-{} pair: \".format(example_col, example_row))\nprint(align_df_proteins.loc[example_col, example_row])\n\nprint(\"\\nRMSD value (in Angström) after refinement for the {}-{} pair: \".format(example_col, example_row))\nprint(align_df_proteins.loc[example_col, example_row][0])",
"_____no_output_____"
]
],
[
[
"Now, we extract the RMSD after refinement (or any other position of the `align` return value) for all pairs in form of a pandas DataFrame for further analysis. \n\nTherefore, we define a function that takes as input the `align` function return values for all pairs `pymol_align_results` and the position of the return value of interest `position`.",
"_____no_output_____"
]
],
[
[
"def extract_align_info(align_df, position):\n if position in [0, 3, 5]:\n return align_df.applymap(lambda x: np.float(x[position]))\n if position in [1, 2, 4, 6]:\n return align_df.applymap(lambda x: np.int(x[position]))\n else:\n print(\"Position not available.\")",
"_____no_output_____"
]
],
[
[
"For example, we can check the number of aligned residues per protein pair (last position of the `align` return value).",
"_____no_output_____"
]
],
[
[
"extract_align_info(align_df_proteins, 6)",
"_____no_output_____"
]
],
[
[
"Here, we can see that for most protein pairs a large proportion of their residues could be aligned (EGFR sequence lengths range here from about 270 to 350). However, 3FW1 shows only low sequence alignment.",
"_____no_output_____"
],
[
"FYI: You can check the sequence alignment of all pairs here: `../data/T10/alignment/`. An example is shown below:",
"_____no_output_____"
]
],
[
[
"example_alignment_path = glob.glob(\"../data/T10/alignment/*\")[3]\nf = open(example_alignment_path)\nfile_content = f.readlines()\nfor i in file_content:\n print(i, end=\"\")",
"_____no_output_____"
]
],
[
[
"In the next step, we generate a DataFrame for the RMSD values after refinement (first position of the `align` return value).",
"_____no_output_____"
]
],
[
[
"rmsd = extract_align_info(align_df_proteins, 0)\nrmsd",
"_____no_output_____"
]
],
[
[
"We visualize the results of this RMSD refinement as heatmap.",
"_____no_output_____"
]
],
[
[
"sns.heatmap(rmsd, linewidths=1, annot=True, cbar_kws={\"label\": \"RMSD ($\\AA$)\"}, cmap=\"Blues\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"We cluster the heatmap in order to see protein similarity based on the RMSD refinement.",
"_____no_output_____"
]
],
[
[
"def plot_clustermap(rmsd, title):\n g = sns.clustermap(rmsd, linewidths=1, annot=True, cbar_kws={\"label\": \"RMSD ($\\AA$)\"}, cmap=\"Blues\")\n plt.setp(g.ax_heatmap.get_xticklabels(), rotation=0)\n plt.setp(g.ax_heatmap.get_yticklabels(), rotation=0)\n sns.set(font_scale=1.5)\n \n # Save plot - use bbox_inches to include text boxes:\n # https://stackoverflow.com/questions/44642082/text-or-legend-cut-from-matplotlib-figure-on-savefig?rq=1\n plt.savefig(\"../data/T10/bsc_{}.png\".format(title), dpi=300, bbox_inches=\"tight\", transparent=True)\n\n plt.show()",
"_____no_output_____"
],
[
"plot_clustermap(rmsd, \"protein\")",
"_____no_output_____"
]
],
[
[
"The RMSD comparison shows that one protein differs from the other proteins, i.e. 3FW1 (as already discussed based on the visual 3D inspection of the alignment and on the number of aligned residues).\n\nProteins are classified by the chemical reactions they catalyze with so called EC (Enzyme Commission) numbers, which we will use here to check the enzymatic groups the proteins belong to.",
"_____no_output_____"
]
],
[
[
"# Get EC numbers for PDB IDs from PDB\npdb_all_info = [get_all_info(pdb_id) for pdb_id in pdb_ids]\nec_numbers = [i[\"polymer\"][\"enzClass\"][\"@ec\"] for i in pdb_all_info]\ntarget_set = {\"pdb_id\": pdb_ids,\n \"ec_number\": ec_numbers}\ntarget_set = pd.DataFrame(target_set)\ntarget_set",
"_____no_output_____"
]
],
[
[
"We can see that 3FW1, the human quinone reductase 2 (NQO2), belongs to EC class 1, i.e. oxidoreductases, whereas the other proteins belong to class 2.7, i.e. phosphorus transferases, which contain the tyrosine kinases (EC 2.7.10.2), the designated targets for Imatinib. 3FW1 is a reported off-target \"with potential implications for drug design and treatment of chronic myelogenous leukemia in patients\" ([<i>BMC Struct. Biol.</i> (2009), <b>9</b>, 10.1186/1472-6807-9-7](https://bmcstructbiol.biomedcentral.com/articles/10.1186/1472-6807-9-7)).\n\n",
"_____no_output_____"
],
[
"### Align PDB structures (binding sites)",
"_____no_output_____"
],
[
"So far we have used the whole protein structure for the alignment and RMSD refinement. However, the ligand binds only at the protein binding site and therefore the similarity of binding sites rather than of whole protein structures is a more putative basis for off-target prediction. \n\nWe define a binding site of a protein by selecting all residues that are within 10 Å of any ligand atom. These binding site residues are used for alignment and only their Cɑ atoms (protein backbone) are used for the RMSD refinement. Here, we show the alignment of all structures to the first structure in the list `pdb_ids`.",
"_____no_output_____"
]
],
[
[
"# Reinitialize PyMol\nobjPMV.server.do(\"reinitialize\")\n\n# Load proteins files\nfor pdb_id in pdb_ids:\n cmd = \"fetch \" + pdb_id\n objPMV.server.do(cmd)\n\n# Show proteins as cartoon (may be necessary depending on your pymol version)\n#objPMV.server.do('cmd.show(\"cartoon\",\"all\")')\n\n# Hide objects\nobjPMV.server.do(\"hide polar_contacts\")\n\n# Set background to white\nobjPMV.server.do(\"bg_color white\")\n# Remove water and ions\nobjPMV.server.do(\"remove solvent\")\n\n# Align binding sites\nimmobile_pdb_id = pdb_ids[0]\nfor mobile_pdb_id in pdb_ids[1:]:\n # Select atoms within a certain radius of any atom of STI and extend selection to full residues\n objPMV.server.do(\"select mobile_bs, byres \" + mobile_pdb_id + \" within 10 of (\" + mobile_pdb_id + \" and resn STI)\")\n objPMV.server.do(\"select immobile_bs, byres \" + immobile_pdb_id + \" within 10 of (\" + immobile_pdb_id + \" and resn STI)\")\n # Perform alignment\n objPMV.server.do(\"align mobile_bs, immobile_bs\")\n\n# Center and zoom \nobjPMV.server.do(\"center all\")\nobjPMV.server.do(\"zoom all\")\nobjPMV.server.do(\"ray 400,400\")\n\n# Display PyMol frame in Jupyter notebook\nobjPMV.GetPNG(h=500)",
"_____no_output_____"
]
],
[
[
"### Get pairwise RMDS (binding sites)",
"_____no_output_____"
],
[
"As shown before for the alignment and RMSD refinement of the whole protein structure, we here run a PyMol python script that calculates the alignment and RMSD for all protein binding site pairs as describe above.\n\nThe PyMol commands used are explained within the PyMol python script.",
"_____no_output_____"
]
],
[
[
"f = open(\"./pymol_scripts/pymol_align_bindingsites.py\")\nfile_content = f.readlines()\nfor i in file_content:\n print(i, end=\"\")",
"_____no_output_____"
]
],
[
[
"We run the PyMol python script via the terminal (ligand-protein radius as input for binding site atom definition).",
"_____no_output_____"
]
],
[
[
"# Perform binding site comparison using the align function in PyMol\nos.popen(\"python ./pymol_scripts/pymol_align_bindingsites.py 10\")",
"_____no_output_____"
]
],
[
[
"We load the `align` DataFrame for binding site comparisons.",
"_____no_output_____"
]
],
[
[
"align_df_bindingsites = pickle.load(open(\"../data/T10/align_df_bindingsites.p\", \"rb\"))",
"_____no_output_____"
]
],
[
[
"We extract the RMSD values from that DataFrame.",
"_____no_output_____"
]
],
[
[
"rmsd_bs = extract_align_info(align_df_bindingsites, 0)",
"_____no_output_____"
],
[
"extract_align_info(align_df_bindingsites, 6)",
"_____no_output_____"
]
],
[
[
"We show the clustered heatmap for the RMSD results.",
"_____no_output_____"
]
],
[
[
"# Show the pairwise RMSD values as clustered heatmap\nplot_clustermap(rmsd_bs, \"bs\")",
"_____no_output_____"
]
],
[
[
"RMSD values of aligned binding sites shows a dissimilarity of 3FW1 (EC number 1.10.5.1) within the dataset (EC number 2.7) - visual inspection in PyMol shows that STI is binding to the surface of the protein. The pairs 1XBB-4CVS and 1XBB-3HEC also show dissimilarities, whereas the rest of the dataset shows low RMSD values.\n\nRMSD values as calculated here are dependend on the residue selection (binding site definition) and the quality of the a priori sequence alignment.",
"_____no_output_____"
]
],
[
[
"# Clean up directory (remove PDB downloads and PyMol alignment files)\nos.popen(\"rm ./*.cif\")\nos.popen(\"rm ../data/T10/alignment/*.aln\")",
"_____no_output_____"
]
],
[
[
"## Discussion\n\nIn this talktorial, we have used sequence alignment and subsequent RMSD refinement of whole protein structures and binding sites to assess the similarity and dissimilarity of a set of Imatinib-binding proteins. \nHowever, off-target prediction for Imatinib requires to compare the binding site of an intended target of Imatinib (a tyrosine kinase) with a large database of resolved structures (PDB). \nSince this results in the comparison of sequences also with low similarity, more sophisticated methods should be invoked\nthat use a sequence-independent alignment algorithm and that include the physico-chemical properties of the binding site in order to enable a more sophisticated search.\n\n## Quiz\n\n1. Explain the terms on- and off-targets of a drug.\n2. Explain why binding site similarity can be used to find off-targets to a query target.\n3. Discuss how useful the RMSD value of (i) whole proteins and (ii) protein binding sites is for off-target prediction.\n4. Think of alternate approaches for binding site information (how to encode a binding site for binding site comparison?).",
"_____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"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbb3518c328fae36c8853dbc33037725d42eb6ea
| 283,911 |
ipynb
|
Jupyter Notebook
|
TSSP_ARIMA_model.ipynb
|
thxi/tssp_tutorials_2020_21
|
7617110266846c7d2312e6568bb6c52f38c32ef9
|
[
"CC0-1.0"
] | 3 |
2021-02-09T19:21:36.000Z
|
2021-02-11T06:00:25.000Z
|
TSSP_ARIMA_model.ipynb
|
thxi/tssp_tutorials_2020_21
|
7617110266846c7d2312e6568bb6c52f38c32ef9
|
[
"CC0-1.0"
] | 2 |
2021-02-04T09:21:16.000Z
|
2021-03-03T18:24:30.000Z
|
TSSP_ARIMA_model.ipynb
|
thxi/tssp_tutorials_2020_21
|
7617110266846c7d2312e6568bb6c52f38c32ef9
|
[
"CC0-1.0"
] | 25 |
2021-02-03T15:50:35.000Z
|
2021-12-03T22:00:03.000Z
| 274.045367 | 92,328 | 0.897665 |
[
[
[
"# Vladislav Abramov and Sergei Garshin DSBA182",
"_____no_output_____"
],
[
"## The Task\n### Что ждем от туториала?\n\n1. Оценить конкретную модель заданного класса. Не только сделать .fit, но и выписать полученное уравнение!\n2. Автоматически подобрать модель (встроенный подбор)\n3. Построить графики прогнозов, интервальные прогнозы где есть.\n4. Сравнить несколько (две-три) модели данного класса с помощью скользящего окна.\n5. Творчество, любые дополнения, мемасики :)\n\n### Класс выбираем: ETS, ARIMA, BATS + TBATS, PROPHET, случайный лес + создание признаков, GARCH, своё предложить\n\n### Цель: когда через год будут люди спрашивать \"как в питоне оценить ets/arima?\" ответ должен быть \"читайте туториалы от нашего курса!\"",
"_____no_output_____"
],
[
"---\n---\n---\n# Real Data Analysis with ARIMA models\n\nLet's begin with collecting stock data",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport yfinance as yf\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom pmdarima.arima import auto_arima, ARIMA, ADFTest\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nfrom tqdm import tqdm\nfrom sklearn.metrics import r2_score\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef should_diff(data):\n adf_test = ADFTest(alpha = 0.05)\n return adf_test.should_diff(data)\n\ndef get_stock_data(ticker, start, end):\n tickerData = yf.Ticker(ticker)\n tickerDf = tickerData.history(period='1d', start = start, end = end)\n return tickerDf\n\ndef train_test_devision(n, data):\n train = data[:-n]\n test = data[-n:]\n return train, test\n\ndef differentiate_data(dataset, interval=1):\n diff = list()\n for i in range(interval, len(dataset)):\n value = dataset[i] - dataset[i - interval]\n diff.append(value)\n return diff\n\ndef autocorrelation_plot(data):\n data = np.array(data)**2\n plot_acf(data)\n plt.show()\n \ndef p_autocorrelation_plot(data):\n data = np.array(data)**2\n plot_pacf(data)\n plt.show()",
"_____no_output_____"
],
[
"data = get_stock_data('AAPL', '2015-1-1', '2021-2-1')\ndata.head(10)",
"_____no_output_____"
]
],
[
[
"---\nHere we may observe the graph of stock price for Apple Inc. on the perios 1st Jan 2015 till 1st Feb 2021",
"_____no_output_____"
]
],
[
[
"plt.plot(data['Close'])\nplt.title('Close Stock Prices')",
"_____no_output_____"
]
],
[
[
"---\nLooking at the graph it is obvious that data is not stationary and has a strong trend. However, lets make sure that data is not stationary by Autocorrelation plot and Augmented Dickey-Fuller test.",
"_____no_output_____"
]
],
[
[
"print('Should differentiate? :', should_diff(data['Close']))\nprint()\nprint('ACF of undifferentiated data')\nautocorrelation_plot(data['Close'])",
"Should differentiate? : (0.99, True)\n\nACF of undifferentiated data\n"
]
],
[
[
"---\nAs we can see, we were right, the data is not stationary!",
"_____no_output_____"
],
[
"## Stationarity check & convertion data to stationary\nFor now, lets differentiate our initial stock data to build a stationary graph of deltas",
"_____no_output_____"
]
],
[
[
"X = pd.DataFrame()\nX['Diff_Close'] = differentiate_data(data['Close'])\nplt.plot(X['Diff_Close'])\nplt.title('Stationary stock data plot')",
"_____no_output_____"
]
],
[
[
"As we may notice we have vanished trend and made the data much more stationary than it was before, for the next step, lets check the stationary feature by Autocorrelation, Partial Autocorrelation plot and Augmented Dickey-Fuller test again.",
"_____no_output_____"
]
],
[
[
"print('Should differentiate? :', should_diff(X['Diff_Close']))\nprint()\nprint('ACF of differentiated data')\nautocorrelation_plot(X['Diff_Close'])",
"Should differentiate? : (0.01, False)\n\nACF of differentiated data\n"
],
[
"print('PACF of differentiated data')\np_autocorrelation_plot(X['Diff_Close'])",
"PACF of differentiated data\n"
]
],
[
[
"Wow! The data has become stationary! We may go further!",
"_____no_output_____"
],
[
"---\n\n## Train / Test devision\n\nOn this step we have devide our data into two parts, train and test. Our model will use the training set to make predictions and compare them with testing set.",
"_____no_output_____"
]
],
[
[
"n = 50\ntrain, test = train_test_devision(n, data['Close'])\n\nfig, ax = plt.subplots()\nax.plot(train, label = 'Train Set')\nax.plot(test, label = 'Test Set')\nfig.set_figheight(6)\nfig.set_figwidth(10)\nax.legend()",
"_____no_output_____"
]
],
[
[
"---\n# Manual Model\nIn this part we have decided to train ARIMA(3,1,2) model, where p = 3 AR parts, d = 1 as we need 1 differentiation and q = 2 MA parts",
"_____no_output_____"
]
],
[
[
"X = data['Close'].values\nsize = len(train.values)\ntrain, test = train.values, test.values\nhistory = [x for x in train]\npredictions, CI = [],[]\n\nfor t in tqdm(range(len(test))):\n model = ARIMA((3,1,2))\n model.fit(history)\n y_hat, conf_int = model.predict(n_periods = 1, return_conf_int = True, alpha=0.05)\n predictions.append(y_hat)\n CI.append(conf_int)\n \n obs = test[t]\n history.append(obs)\n# print('predicted=%f, expected=%f' % (yhat, obs))\n",
"100%|██████████| 50/50 [01:34<00:00, 1.90s/it]\n"
],
[
"\nrmse = sqrt(mean_squared_error(test, predictions))\nr_squared = r2_score(test, predictions)\nprint('Test RMSE: %.3f' % rmse)\nprint('Test R^2: %.3f' % r_squared)\nfig, ax = plt.subplots(figsize=(15,8))\nax.plot(test, label = 'Test Set')\nax.plot(predictions, label = 'Prediction Set')\nax.set_title('ARIMA (3,1,2)')\nax.set_xlabel('Price')\nax.set_ylabel('Day')\nax.legend()",
"Test RMSE: 2.686\nTest R^2: 0.861\n"
],
[
"model.summary()",
"_____no_output_____"
]
],
[
[
"## The ARIMA equation we got\n$\\Delta y_t = -0.0090 \\Delta y_{t-1} -0.1220 \\Delta y_{t-2} -0.0377 \\Delta y_{t-3} -0.1042 \\varepsilon_{t-1} -0.1690 y_{t-2}\\varepsilon_{t-2}$ \n where $\\\\ \\Delta y_t = y_t - y_{t-1}$",
"_____no_output_____"
],
[
"As we may se the model works pretty well",
"_____no_output_____"
],
[
"---\n\n## Automatic choice of the model\nIn this section we would like to play with autosetting parameters, which also include sesonal dependency",
"_____no_output_____"
]
],
[
[
"n = 50\ntrain, test = train_test_devision(n, data['Close'])\nmodel = auto_arima(train, start_p=1, start_q=1,\n max_p=3, max_q=3, m=12,\n start_P=0, seasonal=True,\n d=1, D=1, trace = True,\n error_action='ignore', \n suppress_warnings = True, \n stepwise = True)\n",
"Performing stepwise search to minimize aic\n ARIMA(1,1,1)(0,1,1)[12] : AIC=inf, Time=1.74 sec\n ARIMA(0,1,0)(0,1,0)[12] : AIC=5576.311, Time=0.06 sec\n ARIMA(1,1,0)(1,1,0)[12] : AIC=5269.709, Time=0.33 sec\n ARIMA(0,1,1)(0,1,1)[12] : AIC=inf, Time=1.32 sec\n ARIMA(1,1,0)(0,1,0)[12] : AIC=5555.152, Time=0.08 sec\n ARIMA(1,1,0)(2,1,0)[12] : AIC=4987.970, Time=0.89 sec\n ARIMA(1,1,0)(2,1,1)[12] : AIC=inf, Time=4.17 sec\n ARIMA(1,1,0)(1,1,1)[12] : AIC=inf, Time=1.78 sec\n ARIMA(0,1,0)(2,1,0)[12] : AIC=5005.838, Time=0.68 sec\n ARIMA(2,1,0)(2,1,0)[12] : AIC=4988.582, Time=1.08 sec\n ARIMA(1,1,1)(2,1,0)[12] : AIC=4988.071, Time=1.61 sec\n ARIMA(0,1,1)(2,1,0)[12] : AIC=4989.152, Time=0.82 sec\n ARIMA(2,1,1)(2,1,0)[12] : AIC=4990.030, Time=2.46 sec\n ARIMA(1,1,0)(2,1,0)[12] intercept : AIC=4989.964, Time=3.35 sec\n\nBest model: ARIMA(1,1,0)(2,1,0)[12] \nTotal fit time: 20.382 seconds\n"
],
[
"model.summary()",
"_____no_output_____"
],
[
"y_hat, conf_int = model.predict(n_periods = n, return_conf_int = True, alpha=0.05)\npredictions = pd.DataFrame(y_hat, index = test.index, columns = ['Prediction'])\nCI = pd.DataFrame({'CI lower': conf_int[:, 0], 'CI upper': conf_int[:, 1]}, index = test.index)",
"_____no_output_____"
],
[
"fig, (ax1, ax2) = plt.subplots(1, 2,figsize=(20,8))\n\nax1.plot(train[1400:], label = 'Train Set')\nax1.plot(test, label = 'Test Set')\nax1.plot(predictions, label = 'Prediction Set')\nax1.plot(CI['CI lower'], label = 'CI lower', c = 'r')\nax1.plot(CI['CI upper'], label = 'CI upper', c = 'r')\nax1.set_title('Close look at the predictions')\nax1.set_xlabel('Price')\nax1.set_ylabel('Date')\nax1.legend()\n\nax2.plot(train[900:], label = 'Train Set')\nax2.plot(test, label = 'Test Set')\nax2.plot(predictions, label = 'Prediction Set')\nax2.plot(CI['CI lower'], label = 'CI lower', c = 'r')\nax2.plot(CI['CI upper'], label = 'CI upper', c = 'r')\nax2.set_title('Global look at the predictions')\nax2.set_xlabel('Price')\nax2.set_ylabel('Date')\nax2.legend()",
"_____no_output_____"
]
],
[
[
"To observe the data we have built two graphs, the left one catches more localy than the right one.",
"_____no_output_____"
],
[
"---\n---\n---\n\nК сожалению, на вечер среды мы не успели выполнить все пункиы и дать подробное описание нашим шагам. Очень просим прокоммментировать выполненные этапы, дать советы и наставления :)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
]
] |
cbb3546dd044cd6382123ec494725ebf968ffc34
| 21,459 |
ipynb
|
Jupyter Notebook
|
intro-solutions.ipynb
|
mgeier/communication-acoustics-exercises
|
879b2ec3013bdf91d935dfe1455f486a3fd75f8a
|
[
"CC0-1.0"
] | 21 |
2015-04-14T20:10:40.000Z
|
2021-06-13T04:39:45.000Z
|
intro-solutions.ipynb
|
mgeier/communication-acoustics-exercises
|
879b2ec3013bdf91d935dfe1455f486a3fd75f8a
|
[
"CC0-1.0"
] | 2 |
2020-06-16T11:15:58.000Z
|
2021-03-06T13:04:38.000Z
|
intro-solutions.ipynb
|
mgeier/communication-acoustics-exercises
|
879b2ec3013bdf91d935dfe1455f486a3fd75f8a
|
[
"CC0-1.0"
] | 7 |
2016-12-04T11:33:11.000Z
|
2020-06-16T11:45:17.000Z
| 21.523571 | 183 | 0.484179 |
[
[
[
"[exercises](intro.ipynb)",
"_____no_output_____"
]
],
[
[
"import numpy as np",
"_____no_output_____"
],
[
"np.arange(6)",
"_____no_output_____"
],
[
"np.arange(0, 0.6, 0.1), np.arange(6) * 0.1 # two possibilities",
"_____no_output_____"
],
[
"np.arange(0.5, 1.1, 0.1), \"<-- wrong result!\"",
"_____no_output_____"
],
[
"np.arange(5, 11) * 0.1, \"<-- that's right!\"",
"_____no_output_____"
],
[
"np.linspace(0, 6, 7)",
"_____no_output_____"
],
[
"np.linspace(0, 6, 6, endpoint=False), np.linspace(0, 5, 6) # two possibilities",
"_____no_output_____"
],
[
"np.linspace(0, 0.6, 6, endpoint=False), np.linspace(0, 0.5, 6) # again two possibilities",
"_____no_output_____"
],
[
"np.linspace(0.5, 1.1, 6, endpoint=False), np.linspace(0.5, 1, 6) # and again ...",
"_____no_output_____"
]
],
[
[
"If the number of elements is known and the step size should be obtained automatically $\\Rightarrow$ `np.linspace()` \nIf the step size is known an if it's an integer and the number of elements should be obtained automatically $\\Rightarrow$ `np.arange()`\n\nIf the step size is not an integer:\n\n* If the step size is a fraction of integers, you can use `np.arange()` with integers and divide the result accordingly.\n\n* If that's not feasible, calculate the expected number of elements beforehand and use `np.linspace()`",
"_____no_output_____"
]
],
[
[
"dur, amp, freq, fs = 1, 0.3, 500, 44100\nt = np.arange(np.ceil(dur * fs)) / fs\ny = amp * np.sin(2 * np.pi * freq * t)",
"_____no_output_____"
]
],
[
[
"alternative (but inferior) methods to get $t$:",
"_____no_output_____"
]
],
[
[
"t1 = np.arange(0, dur, 1/fs) # implicit rounding of dur!\nt2 = np.arange(0, np.round(dur), 1/fs) # still problematic: arange with floats\n# wrong if dur isn't an integer multiple of 1/fs:\nt3 = np.linspace(0, dur, np.round(dur * fs), endpoint=False)",
"_____no_output_____"
]
],
[
[
"Length of `y` must be *exactly* 44100 (using a half-open interval for $t$), not 44101 (which would be longer than 1 second).\n\nPlotting: 2 ways to zoom (there are probably more): draw a rectangle, drag with the right mouse button in pan/zoom mode.\n\nClicks? Because of discontinuities (also in the derivatives) $\\Rightarrow$ Fade in/out! See [tools.fade()](tools.py).",
"_____no_output_____"
]
],
[
[
"import sounddevice as sd\nimport tools\n\ndef myplay(data):\n \"\"\"Apply fade in/out and play with 44.1 kHz.\"\"\"\n data = tools.fade(data, 2000, 5000)\n sd.play(data, 44100)",
"_____no_output_____"
],
[
"myplay(y)",
"_____no_output_____"
],
[
"def mysine(frequency, amplitude, duration):\n \"\"\"Generate sine tone with the given parameters @ 44.1 kHz.\"\"\"\n samplerate = 44100\n times = np.arange(np.ceil(duration * samplerate)) / samplerate\n return amplitude * np.sin(2 * np.pi * frequency * times)",
"_____no_output_____"
],
[
"z = mysine(440, 0.4, 3)",
"_____no_output_____"
],
[
"myplay(z)",
"_____no_output_____"
],
[
"%matplotlib\nimport matplotlib.pyplot as plt\n\ndef myplot(data):\n \"\"\"Create a simple plot @ 44.1 kHz.\"\"\"\n samplerate = 44100\n times = np.arange(len(data)) / samplerate\n plt.plot(times, data)\n plt.xlabel(\"Time / Seconds\")",
"Using matplotlib backend: TkAgg\n"
],
[
"myplot(mysine(440, 0.4, 3))",
"_____no_output_____"
],
[
"import soundfile as sf\n\ndur, amp = 1, 0.3\nfrequencies = 400, 500, 600 # Hz\nfadetime = 2000 # samples\n\nfor freq in frequencies:\n sig = mysine(freq, amp, dur)\n sig = tools.fade(sig, fadetime)\n sf.write(\"sine_{}hz.wav\".format(freq), sig, 44100)",
"_____no_output_____"
],
[
"from scipy import signal\n\nf0, f1 = 100, 5000 # Hz\namp = 0.2\ndur = 2 # seconds\nfadetime = 2000 # samples\nfs = 44100\n\nt = np.arange(np.ceil(dur * fs)) / fs\n\nfor method in 'linear', 'log':\n sweep = amp * signal.chirp(t, f0, dur, f1, method)\n sweep = tools.fade(sweep, fadetime)\n sf.write('sweep_{}.wav'.format(method), sweep, fs)",
"_____no_output_____"
],
[
"sinetone = mysine(frequency=500, amplitude=0.3, duration=1.5)\nnoise = np.random.normal(scale=0.1, size=len(sinetone))\nsine_plus_noise = sinetone + noise",
"_____no_output_____"
],
[
"myplay(sine_plus_noise)",
"_____no_output_____"
],
[
"myplot(sine_plus_noise)",
"_____no_output_____"
],
[
"dur = 2\namp = 0.2\n\ntwo_sines = mysine(500, amp, dur) + mysine(507, amp, dur)",
"_____no_output_____"
],
[
"myplay(two_sines)",
"_____no_output_____"
],
[
"myplot(two_sines)",
"_____no_output_____"
]
],
[
[
"Two sine tones with similar frequencies create \"beats\", see <http://en.wikipedia.org/wiki/Beat_(acoustics)>.\nThe sum of these two tones is equivalent to an amplitude modulation with a carrier frequency of $\\frac{f_1+f_2}{2}$ and a modulation frequency of $\\frac{f_1-f_2}{2}$.\n\n$$\\cos(2\\pi f_1t)+\\cos(2\\pi f_2t) = 2\\cos\\left(2\\pi\\frac{f_1+f_2}{2}t\\right)\\cos\\left(2\\pi\\frac{f_1-f_2}{2}t\\right)$$\n\nWe don't really *hear* the modulation frequency itself, we only hear the envelope of the modulation, therefore the *perceived* beat frequency is $f_{\\text{beat}} = f_1-f_2$.",
"_____no_output_____"
]
],
[
[
"stereo_sines = np.column_stack([mysine(400, amp, dur), mysine(600, amp, dur)])",
"_____no_output_____"
],
[
"myplay(stereo_sines)",
"_____no_output_____"
]
],
[
[
"The first column should be the left channel!",
"_____no_output_____"
]
],
[
[
"dur, amp = 1, 0.3\nfreq = 500 # Hz\ndelay = 0.5 # ms\nfs = 44100\n\nt = np.arange(np.ceil(dur * fs)) / fs\ntimes = np.column_stack((t, t - delay/1000))\nsig = amp * np.sin(2 * np.pi * freq * times)",
"_____no_output_____"
],
[
"myplay(sig)",
"_____no_output_____"
],
[
"dur, amp = 0.5, 0.3\nfrequencies = 500, 1000, 2000 # Hz\ndelays = 0.6, 0.4, 0.2, 0, -0.2, -0.4, -0.6 # ms\nfs = 44100\n\nt = np.arange(np.ceil(dur * fs)) / fs\n\nfor f in frequencies:\n for delay in delays:\n times = np.column_stack((t, t - delay/1000))\n sig = amp * np.sin(2 * np.pi * f * times)\n myplay(sig)\n sd.wait()",
"_____no_output_____"
]
],
[
[
"This is supposed to illustrate [Lord Rayleigh's Duplex Theory](http://en.wikipedia.org/wiki/Interaural_time_difference#Duplex_theory) (at least the part about time differences).",
"_____no_output_____"
]
],
[
[
"dur, amp = 2, 0.3\nfrequencies = np.array([200, 400, 600, 800, 1000])\nfs = 44100\nt = np.arange(np.ceil(dur * fs)) / fs\nt.shape = -1, 1\nt",
"_____no_output_____"
],
[
"amplitudes = amp * 1 / np.arange(1, len(frequencies)+1)\namplitudes",
"_____no_output_____"
],
[
"five_sines = amplitudes * np.sin(2 * np.pi * frequencies * t)\nfive_sines.shape",
"_____no_output_____"
],
[
"sum_of_sines = five_sines.sum(axis=1)",
"_____no_output_____"
],
[
"myplot(sum_of_sines)",
"_____no_output_____"
],
[
"myplay(five_sines[:, [0, 1, 2, 3, 4]].sum(axis=1))",
"_____no_output_____"
],
[
"myplay(five_sines[:, [0, 1, 2, 3]].sum(axis=1))",
"_____no_output_____"
],
[
"myplay(five_sines[:, [0, 1, 2, 4]].sum(axis=1))",
"_____no_output_____"
],
[
"myplay(five_sines[:, [0, 1, 3, 4]].sum(axis=1))",
"_____no_output_____"
],
[
"myplay(five_sines[:, [0, 2, 3, 4]].sum(axis=1))",
"_____no_output_____"
],
[
"myplay(five_sines[:, [1, 2, 3, 4]].sum(axis=1))",
"_____no_output_____"
]
],
[
[
"<https://en.wikipedia.org/wiki/Harmonic_series_(music)>",
"_____no_output_____"
]
],
[
[
"f0 = 200 # Hz\npartials = 20\n\nfrequencies = f0 * np.arange(1, partials + 1)\nfrequencies",
"_____no_output_____"
],
[
"amplitudes = amp * 1 / np.arange(1, len(frequencies)+1)\namplitudes",
"_____no_output_____"
],
[
"many_sines = amplitudes * np.sin(2 * np.pi * frequencies * t)\nmany_sines.shape",
"_____no_output_____"
],
[
"sawtooth = many_sines.sum(axis=1)",
"_____no_output_____"
],
[
"myplot(sawtooth)",
"_____no_output_____"
],
[
"myplay(sawtooth)",
"_____no_output_____"
]
],
[
[
"https://en.wikipedia.org/wiki/Sawtooth_wave",
"_____no_output_____"
]
],
[
[
"square = many_sines[:, ::2].sum(axis=1)",
"_____no_output_____"
],
[
"myplot(square)",
"_____no_output_____"
],
[
"myplay(square)",
"_____no_output_____"
]
],
[
[
"https://en.wikipedia.org/wiki/Square_wave",
"_____no_output_____"
]
],
[
[
"c = 343\nsamplerate = 44100\ndur = 0.01\n\nphat = 0.2\nfreq = 500\nomega = 2 * np.pi * freq\nkx = omega / c\nx = 0\n\ntime = np.arange(np.ceil(dur * fs)) / fs\np = phat * np.exp(1j*(kx*x - omega*time))\n\nplt.plot(time*1000, np.real(p))\nplt.xlabel('$t$ / ms')\nplt.ylabel('$\\mathcal{R}\\{p(x,t)\\}$ / Pa')\nplt.grid()\nplt.title('$f = {}$ Hz, $T = {}$ ms'.format(freq, 1000/freq));",
"_____no_output_____"
],
[
"xrange = 3\ndx = 0.001\ntime = 0\n\nx = np.arange(np.ceil(xrange/dx)) * dx\np = phat * np.exp(1j*(kx*x - omega*time))\n\nplt.plot(x*100, np.real(p))\nplt.xlabel('$x$ / cm')\nplt.ylabel('$\\mathcal{R}\\{p(x,t)\\}$ / Pa')\nplt.grid()\nplt.title('$f = {}$ Hz, $\\lambda = {}$ cm'.format(freq, c*100/freq));",
"_____no_output_____"
]
],
[
[
"<p xmlns:dct=\"http://purl.org/dc/terms/\">\n <a rel=\"license\"\n href=\"http://creativecommons.org/publicdomain/zero/1.0/\">\n <img src=\"http://i.creativecommons.org/p/zero/1.0/88x31.png\" style=\"border-style: none;\" alt=\"CC0\" />\n </a>\n <br />\n To the extent possible under law,\n <span rel=\"dct:publisher\" resource=\"[_:publisher]\">the person who associated CC0</span>\n with this work has waived all copyright and related or neighboring\n rights to this work.\n</p>",
"_____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",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cbb3611606e135e8d56d9f7559d33a683763493b
| 70,284 |
ipynb
|
Jupyter Notebook
|
docs/!ml/notebooks/Logistic Regression.ipynb
|
a-mt/dev-roadmap
|
0484e018b2a51019577b0f2caafa6182bce689d1
|
[
"MIT"
] | 1 |
2019-10-28T05:40:06.000Z
|
2019-10-28T05:40:06.000Z
|
docs/!ml/notebooks/Logistic Regression.ipynb
|
a-mt/dev-roadmap
|
0484e018b2a51019577b0f2caafa6182bce689d1
|
[
"MIT"
] | null | null | null |
docs/!ml/notebooks/Logistic Regression.ipynb
|
a-mt/dev-roadmap
|
0484e018b2a51019577b0f2caafa6182bce689d1
|
[
"MIT"
] | null | null | null | 102.305677 | 17,100 | 0.835183 |
[
[
[
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt",
"_____no_output_____"
]
],
[
[
"## Load data",
"_____no_output_____"
],
[
"On connaît l'âge et l'expérience d'une personne, on veut pouvoir déduire si une personne est badass dans son domaine ou non.",
"_____no_output_____"
]
],
[
[
"df = pd.DataFrame({\n 'Age': [20,16.2,20.2,18.8,18.9,16.7,13.6,20.0,18.0,21.2,\n 25,31.2,25.2,23.8,23.9,21.7,18.6,25.0,23.0,26.2],\n 'Experience': [2.3,2.2,1.8,1.4,3.2,3.9,1.4,1.4,3.6,4.3,\n 4.3,4.2,3.8,3.4,5.2,5.9,3.4,3.4,5.6,6.3],\n 'Badass': [0,0,0,0,0,0,0,0,0,0,\n 1,1,1,1,1,1,1,1,1,1]\n})\ndf",
"_____no_output_____"
],
[
"colors = np.full_like(df['Badass'], 'red', dtype='object')\ncolors[df['Badass'] == 1] = 'blue'\n\nplt.scatter(df['Age'], df['Experience'], color=colors)",
"_____no_output_____"
],
[
"X = df.drop('Badass', axis=1).values\nY = df['Badass'].values",
"_____no_output_____"
],
[
"# Cas à prédire\nx = [21.2, 4.3]",
"_____no_output_____"
]
],
[
[
"## Using sklearn\n\n### Fit",
"_____no_output_____"
]
],
[
[
"from sklearn.linear_model import LogisticRegression",
"_____no_output_____"
],
[
"model = LogisticRegression(C=1e20, solver='liblinear', random_state=0)\n%time model.fit(X, Y)",
"CPU times: user 7.7 ms, sys: 0 ns, total: 7.7 ms\nWall time: 6.07 ms\n"
],
[
"print(model.intercept_, model.coef_)",
"[-18.825058] [[0.7151625 1.0549935]]\n"
]
],
[
[
"### Plot Decision Boundary",
"_____no_output_____"
],
[
"<details>\n <summary>Where does the equation come from? ↓</summary>\n <img src=\"https://i.imgur.com/YxSDJZA.png?1\">\n</details>",
"_____no_output_____"
]
],
[
[
"b0 = model.intercept_[0]\nb1 = model.coef_[0][0]\nb2 = model.coef_[0][1]",
"_____no_output_____"
],
[
"plt.scatter(df['Age'], df['Experience'], color=colors)\n\n# Decision boundary (with threshold 0.5)\n_X = np.linspace(df['Age'].min(), df['Age'].max(),10)\n_Y = (-b1/b2)*_X + (-b0/b2)\n\nplt.plot(_X, _Y, '-k')",
"_____no_output_____"
],
[
"# Plot using contour\n_X1 = np.linspace(df['Age'].min(), df['Age'].max(),10)\n_X2 = np.linspace(df['Experience'].min(), df['Experience'].max(),10)\n\nxx1, xx2 = np.meshgrid(_X1, _X2)\ngrid = np.c_[xx1.ravel(), xx2.ravel()]\npreds = model.predict_proba(grid)[:, 1].reshape(xx1.shape)\n\nplt.scatter(df['Age'], df['Experience'], color=colors)\nplt.contour(xx1, xx2, preds, levels=[.5], cmap=\"Greys\", vmin=0, vmax=.6)",
"_____no_output_____"
]
],
[
[
"### Predict",
"_____no_output_____"
]
],
[
[
"print('Probabilité de badass:', model.predict_proba([x])[0][1])\nprint('Prediction:', model.predict([x])[0])",
"Probabilité de badass: 0.7053402697503758\nPrediction: 1\n"
]
],
[
[
"## From scratch\n\n### Fit\n\nSource: https://github.com/martinpella/logistic-reg/blob/master/logistic_reg.ipynb",
"_____no_output_____"
]
],
[
[
"def sigmoid(z):\n return 1 / (1 + np.exp(-z))",
"_____no_output_____"
],
[
"def loss(h, y):\n return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()",
"_____no_output_____"
],
[
"def gradientDescent(X, y, theta, alpha, epochs, verbose=True):\n m = len(y)\n\n for i in range(epochs):\n h = sigmoid(X.dot(theta))\n\n gradient = (X.T.dot(h - y)) / m\n theta -= alpha * gradient\n\n if(verbose and i % 1000 == 0):\n z = np.dot(X, theta)\n h = sigmoid(z)\n print('loss:', loss(h, y))\n\n return theta",
"_____no_output_____"
],
[
"# Add intercept\nm = len(X)\nb = np.ones((m,1))\nXb = np.concatenate([b, X], axis=1)\n\n# Fit\ntheta = np.random.rand(3)\ntheta = gradientDescent(Xb, Y, theta=theta, alpha=0.1, epochs=10000)\ntheta",
"loss: 1.124180592736419\nloss: 2.926929160297942\nloss: 2.7773598334658973\nloss: 2.601273225890172\nloss: 2.28331100018835\nloss: 1.6858248502625137\nloss: 1.3059903426752117\nloss: 0.27310846657132865\nloss: 0.2449326702085412\nloss: 0.24245990459602784\n"
]
],
[
[
"### Plot",
"_____no_output_____"
]
],
[
[
"b0 = theta[0]\nb1 = theta[1]\nb2 = theta[2]",
"_____no_output_____"
],
[
"plt.scatter(df['Age'], df['Experience'], color=colors)\n\n# Decision boundary (with threshold 0.5)\n_X = np.linspace(df['Age'].min(), df['Age'].max(),10)\n_Y = (-b1/b2)*_X + (-b0/b2)\n\nplt.plot(_X, _Y, '-k')",
"_____no_output_____"
]
],
[
[
"### Predict",
"_____no_output_____"
]
],
[
[
"z = b0 + b1 * x[0] + b2 * x[1]\np = 1 / (1 + np.exp(-z))\n\nprint('Probabilité de badass:', p)\nprint('Prediction:', (1 if p > 0.5 else 0))",
"Probabilité de badass: 0.7318688005720919\nPrediction: 1\n"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb373d2886942ac2404fa2bf866c718962b2ec9
| 2,725 |
ipynb
|
Jupyter Notebook
|
Other/Coursera_review_data.ipynb
|
HarshCasper/MargSetu
|
fce01bddb1672d33cf74cdd7338894e83013ec0e
|
[
"MIT"
] | 16 |
2020-07-25T14:30:34.000Z
|
2021-02-01T06:33:40.000Z
|
Other/Coursera_review_data.ipynb
|
HarshCasper/MargSetu
|
fce01bddb1672d33cf74cdd7338894e83013ec0e
|
[
"MIT"
] | 1 |
2020-07-25T20:23:45.000Z
|
2020-07-25T20:23:45.000Z
|
Other/Coursera_review_data.ipynb
|
HarshCasper/MargSetu
|
fce01bddb1672d33cf74cdd7338894e83013ec0e
|
[
"MIT"
] | 5 |
2020-07-25T14:25:30.000Z
|
2020-12-13T13:21:20.000Z
| 20.801527 | 362 | 0.537982 |
[
[
[
"This notebook pulls course reviews from Coursera.",
"_____no_output_____"
]
],
[
[
"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd",
"_____no_output_____"
],
[
"url = \"https://www.coursera.org/learn/machine-learning/reviews?page=1&sort=recent\"\nres = requests.get(url)\nres.status_code",
"_____no_output_____"
],
[
"soup = BeautifulSoup(res.content, 'lxml')",
"_____no_output_____"
],
[
"reviews_list = soup.find('div', {'data-e2e': 'reviews-list'})",
"_____no_output_____"
],
[
"review_text = reviews_list.find_all('div', {'class': \"reviewText\"})",
"_____no_output_____"
],
[
"reviews = []\nfor review in review_text:\n reviews.append(review.text)",
"_____no_output_____"
],
[
"reviews[0]",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb38587cc61b188572ea8e87823afacd43ea0ff
| 760,826 |
ipynb
|
Jupyter Notebook
|
customer_segments.ipynb
|
mouhamadibrahim/Customer-Segments-Clustering
|
76f8ad2d84f5ec4eceea3f80ca543bf2dfd63390
|
[
"MIT"
] | null | null | null |
customer_segments.ipynb
|
mouhamadibrahim/Customer-Segments-Clustering
|
76f8ad2d84f5ec4eceea3f80ca543bf2dfd63390
|
[
"MIT"
] | null | null | null |
customer_segments.ipynb
|
mouhamadibrahim/Customer-Segments-Clustering
|
76f8ad2d84f5ec4eceea3f80ca543bf2dfd63390
|
[
"MIT"
] | null | null | null | 305.06255 | 307,648 | 0.907177 |
[
[
[
"# Creating Customer Segments",
"_____no_output_____"
],
[
"## Introduction\n\nIn this project, I analyze a dataset containing data on various customers' annual spending amounts of diverse product categories for internal structure. \n\nThe dataset: [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Wholesale+customers). \n\nI have excluded the features `'Channel'` and `'Region'` ",
"_____no_output_____"
],
[
"# Import libraries",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm as cm\nfrom IPython.display import display # Allows the use of display() for DataFrames\n%matplotlib inline",
"_____no_output_____"
],
[
"data = pd.read_csv(\"customers.csv\")\ndata.drop(['Region', 'Channel'], axis = 1, inplace=True)\nprint(\"Wholesale customers dataset has {} samples with {} features each.\".format(*data.shape))",
"Wholesale customers dataset has 440 samples with 6 features each.\n"
]
],
[
[
"## Data Exploration",
"_____no_output_____"
]
],
[
[
"display(data.describe())",
"_____no_output_____"
]
],
[
[
"- we can see that the mean is larger than the medians in every category so we can conclude that there is a heavy positive skew in the data",
"_____no_output_____"
],
[
"### Selecting Samples\n\nunderstanding the customers and how their data is distributed can be done by visualizing some of the data",
"_____no_output_____"
]
],
[
[
"# Select three indices to sample from the dataset\nindices = [7,70,296]\n\n# Create a DataFrame of the chosen samples\nsamples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop=True)\nprint(\"Chosen samples of wholesale customers dataset:\")\ndisplay(samples)",
"Chosen samples of wholesale customers dataset:\n"
]
],
[
[
"### Feature Relevance\n\nto better understand the customers its worth noticing if there is one of the six categories is relevant for understanding the customer purchasing behavior or not.",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\n\n# Set random seed to allow reproducible results\nnp.random.seed(408)\n\n# Make a copy of the DataFrame\nnew_data = data.copy()\nnew_data.drop(['Grocery'], axis = 1, inplace=True)\n\n# Split the data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(new_data, data['Grocery'], \n test_size=0.25, random_state=408)\n\n# Create a decision tree regressor\nregressor = DecisionTreeRegressor()\nregressor.fit(X_train,y_train)\n\n# Report the score of the prediction using the testing set\nscore = regressor.score(X_test,y_test)\nprint (\"The decision tree regressor's r2_score is: {:.4f}\".format(score))",
"The decision tree regressor's r2_score is: 0.6819\n"
]
],
[
[
"- I used the grocery feature as a target at the beginning using regressor algorithm. the result was 0.6819. I can conclude that the grocery is not a factor to identify customers spending habits and it is a part of the other features",
"_____no_output_____"
],
[
"### Visualize Feature Distributions\n\nI created a scatter matrix in order to visualize every data properly ",
"_____no_output_____"
]
],
[
[
"# Produce a scatter matrix for each pair of features in the data\npd.plotting.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');\n\n# A more colorful visualization that allows for more convenient intepretation\n# Taken, with modifications, from http://datascience.stackexchange.com/questions/10459/calculation-and-visualization-of-correlation-matrix-with-pandas\nfig = plt.figure()\nfig.set_size_inches(10, 10)\nax1 = fig.add_subplot(111)\ncmap = cm.get_cmap('jet', 30)\ncax = ax1.imshow(data.corr(), interpolation=\"nearest\", cmap=cmap)\nax1.grid(True)\nplt.title('Customer Spending Feature Correlation')\nlabels=['Placeholder','Fresh','Milk','Grocery','Frozen','Deterg./Paper','Deli.']\nax1.set_xticklabels(labels, fontsize=12)\nax1.set_yticklabels(labels, fontsize=12)\ncbar = fig.colorbar(cax, ticks= np.linspace(0.0,1.0,5))\nplt.show()\n\n# Precise numeric breakdown\ndisplay(data.corr())",
"<ipython-input-31-fa8310eb65d8>:14: UserWarning: FixedFormatter should only be used together with FixedLocator\n ax1.set_xticklabels(labels, fontsize=12)\n<ipython-input-31-fa8310eb65d8>:15: UserWarning: FixedFormatter should only be used together with FixedLocator\n ax1.set_yticklabels(labels, fontsize=12)\n"
]
],
[
[
"###### Conclusions on Correlations\n\n- The following pairs of features exhibit a high degree of correlation, in order from greatest to least: `Grocery` and `Detergents_Paper`; `Grocery` and `Milk`, and `Detergents_Paper` and `Milk`. To be more precise, the correlation coefficients for these pairs are 0.924641, 0.728335, and 0.661816 respectively. This supports my previous claim that these three features are not orthonormal and individually significant in predicting customer spending habits. A new insight that this analysis does give is that while the features are highly correlated with each other, they are not particularly correlated with the other three features (`Fresh`, `Frozen`, and `Delicatessen`. This is especially true for `Detergents_Paper` and `Grocery`. This indicates that instead of discarding the three features outright, they should be \"repackaged\" into a new one that captures the information they contain. This new feature could maintain the predictive strength that they possess as a group, without being redundant.\n\n\n- The data for all features exhibits extreme positive skew, shown in the distribution plots. This was also evident in the median and mean calculations, which show mean values far in excess of the median for each feature - a tell-tale indicator of positive skew. The interpretation is that the majority of the samples consists of minor customers that purchase relatively small amounts of product, with a few major customers that buy in bulk spread throughout. My intuition tells me that the former group are mostly small businesses such as restaurants and convenience stores, while the latter are perhaps big-box retail warehouses.",
"_____no_output_____"
],
[
"## Data Preprocessing",
"_____no_output_____"
],
[
"### Feature Scaling\nscaling the features using logarithm",
"_____no_output_____"
]
],
[
[
"# Scale the data using the natural logarithm\nlog_data = np.log(data)\n\n# Scale the sample data using the natural logarithm\nlog_samples = np.log(samples)\n\n# Produce a scatter matrix for each pair of newly-transformed features\npd.plotting.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');\n\n# Numeric visualization\ndisplay(data.corr())",
"_____no_output_____"
]
],
[
[
"### Observation\nAfter applying a natural logarithm scaling to the data, the distribution of each feature appears much more normal. Correlations between various pairs of features is still clearly evident after the log transform.",
"_____no_output_____"
]
],
[
[
"# Display the log-transformed sample data\ndisplay(log_samples)",
"_____no_output_____"
]
],
[
[
"### Outlier Detection\n",
"_____no_output_____"
]
],
[
[
"# For each feature find the data points with extreme high or low values\nfor feature in log_data.keys():\n \n # Calculate Q1 (25th percentile of the data) for the given feature\n # Calculate Q3 (75th percentile of the data) for the given feature\n \n Q1, Q3 = np.percentile(log_data[feature], 25), np.percentile(log_data[feature], 75)\n \n # Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)\n step = 1.5 * (Q3 - Q1)\n \n # Display the outliers\n print(\"Data points considered outliers for the feature '{}':\".format(feature))\n display(log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))])\n \n# Select the indices for data points to be removed\noutliers = [65,66,75,128,154]\n\n# Remove the outliers, if any were specified\ngood_data = log_data.drop(log_data.index[outliers]).reset_index(drop=True)",
"Data points considered outliers for the feature 'Fresh':\n"
]
],
[
[
"###### Outliers talks\n\n- there were six data points that were flagged as outliers: 65,66,75,128,154. I made a decision to remove them as I am going to use the dataset later on in the algorithm and it will heavily impact this",
"_____no_output_____"
],
[
"## Feature Transformation\nIn this section I use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, I am looking for which compound combinations of features best describe customers.",
"_____no_output_____"
],
[
"### Visualization code",
"_____no_output_____"
]
],
[
[
"def pca_results(good_data, pca):\n '''\n Create a DataFrame of the PCA results\n Includes dimension feature weights and explained variance\n Visualizes the PCA results\n '''\n \n # Dimension indexing\n dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]\n \n # PCA components\n components = pd.DataFrame(np.round(pca.components_, 4), columns = good_data.keys())\n components.index = dimensions\n\n # PCA explained variance\n ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1)\n variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])\n variance_ratios.index = dimensions\n\n # Create a bar plot visualization\n fig, ax = plt.subplots(figsize = (14,8))\n\n # Plot the feature weights as a function of the components\n components.plot(ax = ax, kind = 'bar');\n ax.set_ylabel(\"Feature Weights\")\n ax.set_xticklabels(dimensions, rotation=0)\n\n\n # Display the explained variance ratios\n for i, ev in enumerate(pca.explained_variance_ratio_):\n ax.text(i-0.40, ax.get_ylim()[1] + 0.05, \"Explained Variance\\n %.4f\"%(ev))\n\n # Return a concatenated DataFrame\n return pd.concat([variance_ratios, components], axis = 1)\n\ndef cluster_results(reduced_data, preds, centers, pca_samples, border_data):\n '''\n Visualizes the PCA-reduced cluster data in two dimensions\n Adds cues for cluster centers and student-selected sample data\n '''\n\n predictions = pd.DataFrame(preds, columns = ['Cluster'])\n plot_data = pd.concat([predictions, reduced_data], axis = 1)\n\n # Generate the cluster plot\n fig, ax = plt.subplots(figsize = (14,8))\n\n # Color map\n cmap = cm.get_cmap('gist_rainbow')\n\n # Color the points based on assigned cluster\n for i, cluster in plot_data.groupby('Cluster'): \n cluster.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \\\n color = cmap((i)*1.0/(len(centers)-1)), label = 'Cluster %i'%(i), s=30);\n\n # Plot centers with indicators\n for i, c in enumerate(centers):\n ax.scatter(x = c[0], y = c[1], color = 'white', edgecolors = 'black', \\\n alpha = 1, linewidth = 2, marker = 'o', s=200);\n ax.scatter(x = c[0], y = c[1], marker='$%d$'%(i), alpha = 1, s=100);\n\n # Plot transformed sample points \n ax.scatter(x = pca_samples[:,0], y = pca_samples[:,1], \\\n s = 150, linewidth = 4, color = 'black', marker = 'x');\n\n ax.scatter(x = border_data[:,0], y = border_data[:,1], \\\n color = 'green', edgecolors = 'black', marker = '*', \n alpha = 1, s=80)\n\n # Set plot title\n ax.set_title(\"Cluster Learning on PCA-Reduced Data - Centroids Marked by Number\\nTransformed Sample Data Marked by Black Cross\");\n\n\ndef biplot(good_data, reduced_data, pca):\n '''\n Produce a biplot that shows a scatterplot of the reduced\n data and the projections of the original features.\n \n good_data: original data, before transformation.\n Needs to be a pandas dataframe with valid column names\n reduced_data: the reduced data (the first two dimensions are plotted)\n pca: pca object that contains the components_ attribute\n\n return: a matplotlib AxesSubplot object (for any additional customization)\n \n This procedure is inspired by the script:\n https://github.com/teddyroland/python-biplot\n '''\n\n fig, ax = plt.subplots(figsize = (14,8))\n # scatterplot of the reduced data \n ax.scatter(x=reduced_data.loc[:, 'Dimension 1'], y=reduced_data.loc[:, 'Dimension 2'], \n facecolors='b', edgecolors='b', s=70, alpha=0.5)\n \n feature_vectors = pca.components_.T\n\n # we use scaling factors to make the arrows easier to see\n arrow_size, text_pos = 7.0, 8.0,\n\n # projections of the original features\n for i, v in enumerate(feature_vectors):\n ax.arrow(0, 0, arrow_size*v[0], arrow_size*v[1], \n head_width=0.2, head_length=0.2, linewidth=2, color='red')\n ax.text(v[0]*text_pos, v[1]*text_pos, good_data.columns[i], color='black', \n ha='center', va='center', fontsize=18)\n\n ax.set_xlabel(\"Dimension 1\", fontsize=14)\n ax.set_ylabel(\"Dimension 2\", fontsize=14)\n ax.set_title(\"PC plane with original feature projections.\", fontsize=16);\n return ax\n \n\ndef channel_results(reduced_data, outliers, pca_samples):\n '''\n Visualizes the PCA-reduced cluster data in two dimensions using the full dataset\n Data is labeled by \"Channel\" and cues added for student-selected sample data\n '''\n\n # Check that the dataset is loadable\n try:\n full_data = pd.read_csv(\"customers.csv\")\n except:\n print (\"Dataset could not be loaded. Is the file missing?\")\n return False\n\n # Create the Channel DataFrame\n channel = pd.DataFrame(full_data['Channel'], columns = ['Channel'])\n channel = channel.drop(channel.index[outliers]).reset_index(drop = True)\n labeled = pd.concat([reduced_data, channel], axis = 1)\n \n # Generate the cluster plot\n fig, ax = plt.subplots(figsize = (14,8))\n\n # Color map\n cmap = cm.get_cmap('gist_rainbow')\n\n # Color the points based on assigned Channel\n labels = ['Hotel/Restaurant/Cafe', 'Retailer']\n grouped = labeled.groupby('Channel')\n for i, channel in grouped: \n channel.plot(ax = ax, kind = 'scatter', x = 'Dimension 1', y = 'Dimension 2', \\\n color = cmap((i-1)*1.0/2), label = labels[i-1], s=30);\n \n # Plot transformed sample points \n for i, sample in enumerate(pca_samples):\n ax.scatter(x = sample[0], y = sample[1], \\\n s = 200, linewidth = 3, color = 'black', marker = 'o', facecolors = 'none');\n ax.scatter(x = sample[0]+0.25, y = sample[1]+0.3, marker='$%d$'%(i), alpha = 1, s=125);\n\n # Set plot title\n ax.set_title(\"PCA-Reduced Data Labeled by 'Channel'\\nTransformed Sample Data Circled\");\n\n plt.axvline(x=1.8,color='r')\n plt.axvline(x=-3,color='r')\n",
"_____no_output_____"
]
],
[
[
"### PCA\n\nAfter removing the outliers I can now apply PCA to the remaining dataset in orde to discover which dimensions about the data best maximize the variance of features involved.",
"_____no_output_____"
]
],
[
[
"from sklearn.decomposition import PCA\n\n# Apply PCA by fitting the good data with the same number of dimensions as features\npca = PCA()\npca.fit(good_data)\n\n# Transform the sample log-data using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Generate PCA results plot\npca_results = pca_results(good_data, pca)",
"_____no_output_____"
]
],
[
[
"###### PCA Analysis\n\n- the first two principal explain a combined 70.68% of the variation in the dataset\n\n- PC 1, composed primarily of `Detergents_Paper`, `Grocery`, and `Milk` represents prepacked goods that can easily be stocked on shelves and resold to consumers. This feature contains items that are meant to be used or consumed in isolation. The name for this feature could be \"Packaged Goods.\" As products in `Fresh` and `Frozen` are commonly not consumed separately but instead jointly with other products, they have the same weight sign in this feature. PC 2, which consists of `Fresh`, `Frozen`, and `Delicatessen` represents food items that can be consumed either in isolation or in combination with one another. If one had to apply a name to this feature, it would be \"Meals.\" For example, a Turkey sandwhich with fries is a meal that uses items from each of the three categories in the feature. Because `Milk`, `Grocery`, and `Detergents_Paper` (in the form of a napkin) are typically included in meals as well, all six original features have the same weight sign here.\n\n\n- After the second principal component, interpretation becomes more confounded. A pattern that emerges however is that with each successive component, aspects of the data that the new features embody become more and more specific. As such, PC 1 is the most general and PC 6 is the most specific. The most outstanding aspect of the third component is the heavy negative weight assigned to `Fresh`. Perhaps this feature constitutes foods that have longer shelf lives than those captured in the second component. Even for those customers who order heavily in the \"Meal\" category defined previously, it is likely not the case that ALL of their orders need to be consumed immediately. Some can be stocked away and used at later dates. Cured meats (`Delicatessen`) and frozen pastries (`Frozen`), for example, would likely fall into such a new category. The negative weight on `Fresh`, which includes foods with very short shelf lives, makes sense with this interpretation as well. In the fourth component, `Frozen` stands tall above all the rest in its positive weight, while `Delicatessen` nearly balances it on the negative side. My interpretation of this feature is that it represents cheap food that can be stocked in refrigerators for long periods of time. In a sense, the fourth feature takes the third one and specializes it further. Whereas foods in `Delicatessen` are typically expensive and even luxurious sometimes, those in `Frozen` are usually processed and cheap. The first four principal components encapsulate variation in `Frozen` so well that it receives nearly no weight in the fifth and sixth components, as expected. ",
"_____no_output_____"
],
[
"### Observation\nThe code below shows how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points.",
"_____no_output_____"
]
],
[
[
"# Display sample log-data after having a PCA transformation applied\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))",
"_____no_output_____"
]
],
[
[
"### Dimensionality Reduction",
"_____no_output_____"
]
],
[
[
"# Apply PCA by fitting the good data with only two dimensions\npca = PCA(n_components=2)\npca.fit(good_data)\n\n# Transform the good data using the PCA fit above\nreduced_data = pca.transform(good_data)\n\n# Transform the sample log-data using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Create a DataFrame for the reduced data\nreduced_data = pd.DataFrame(reduced_data, columns=['Dimension 1', 'Dimension 2'])",
"_____no_output_____"
]
],
[
[
"### Observation\nThe code below shows how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions.",
"_____no_output_____"
]
],
[
[
"# Display sample log-data after applying PCA transformation in two dimensions\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns=['Dimension 1', 'Dimension 2']))",
"_____no_output_____"
]
],
[
[
"## Visualizing a Biplot\n",
"_____no_output_____"
]
],
[
[
"# Create a biplot\nbiplot(good_data, reduced_data, pca)",
"_____no_output_____"
]
],
[
[
"### Biplot Observations\n\nWith the original feature projection in red, it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the upper left corner of the figure will likely correspond to a customer that spends a lot on `'Milk'`, `'Grocery'` and `'Detergents_Paper'`, but not so much on the other product categories. \n\n- In order from greatest to least, `Detergents_Paper`, `Grocery`, and `Milk`, have the the strongest correlation with the first principal component. In fact, `Detergent_Paper` is nearly parallel with the new axis, indicating almost perfect correlation. These results also make sense in terms of the pca_results plot as well as the correlation matrix displayed earlier which shows significant correlation between the three features. \n\n\n- `Fresh`, `Frozen`, and `Delicatessen` are most strongly correlated with the second principal component, however not to the great extent of the features in the first component. `Fresh` is clearly the most dominant feature, while `Frozen` and `Delicatessen` are roughly equal, however pointing in different directions. This observation also agrees with the pca_results plot that I obtained earlier, which shows `Fresh` with the highest weight and the other two features tied for second and third.",
"_____no_output_____"
],
[
"## Clustering\n\nIn this section, I employ the Gaussian Mixture Model clustering algorithm to identify the various customer segments inherent in the data. I then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale. ",
"_____no_output_____"
],
[
"###### The Case for Gaussian Mixture Models over K-Means",
"_____no_output_____"
],
[
"- Between K-Means and Gaussian Mixture Models, K-Means is more simple and easy to implement even for someone without a background in machine learning. By grouping data into globular shapes, K-Means produces clusters that often make intuitive sense. Of course if the clusters are not structured in this manner, then this benefit will be outweighed by K-Means' inability to capture alternative structures. K-Means establishes \"hard clustering\" which makes for easier interpretation as well: each data point belongs to one and only one cluster center. Through applying PCA and selecting a small number of clusters, K-Means can be computationally very fast as well. Time complexity scales linearly with the number of data points given a fixed cluster parameter.\n\n\n- As mentioned, K-Means cannot model clusters that do not conform to spherical shapes. This is where the main advantage of Gaussian Mixture Models becomes apparent. GMMs can model clusters that take a variety of shapes, including those that are elongated or elliptical. GMM also allows mixed cluster membership by computing the probabilities that each data point belongs to each cluster. These two features make GMM a \"soft clustering\" approach that provides flexibility not granted in K-Means.\n\n\n- Based on what I have observed, I've decided to use Gaussian Mixture Models to attempt to cluster the data. GMM assumes that data comes from two to `n_samples - 1` clusters (Gaussian distributions in this case) and assigns each data point to one of them based on probability. After log-transforming the data, the feature distributions appear approximately normal, which satisfies the Gaussian distribution assumption of GMM. Looking at the biplot, I can discern two rough clusters, but they are far from non-overlapping. The boundary between the two clusters is ambiguous at best, which makes a strong case for GMM. To demostrate this, I found 31 points in the data that GMM could not definitively classify into one of two clusters. The meaning of \"definitive\" here is subjective, but I define it as a point having greater than 60% probability of belonging to one of the clusters. I marked these points as green stars in the `cluster_results` plot as well. This clear distinction between \"strong\" and \"weak\" cluster members is not possible with K-Means, which makes it appear as though all cluster members belong equally, betraying the truth of the data. This reinforces why I chose to use GMM instead.",
"_____no_output_____"
],
[
"### Creating Clusters",
"_____no_output_____"
]
],
[
[
"from sklearn.mixture import GaussianMixture\nfrom sklearn.metrics import silhouette_score\n\n# Apply clustering algorithm to the reduced data \nclusterer = GaussianMixture(n_components=2, n_init=10, random_state=42)\nclusterer.fit(reduced_data)\n\n# Predict the cluster for each data point\npreds = clusterer.predict(reduced_data)\n\n# Find the cluster centers\ncenters = clusterer.means_\n\n# Predict the cluster for each transformed sample data point\nsample_preds = clusterer.predict(pca_samples)\n\n# Calculate the mean silhouette coefficient for the number of clusters chosen\nscore = silhouette_score(reduced_data,preds)\n\nprint ('Silhouette score using GMM: {:.3f}'.format(score))",
"Silhouette score using GMM: 0.422\n"
]
],
[
[
"The table below displays the silhouette scores associated with various GMM clustering setups:\n\n| No. of Clusters | Silhouette Score |\n| :---------------: | :---------------------: |\n| 2 | 0.422 |\n| 3 | 0.394 |\n| 4 | 0.316 |\n| 5 | 0.278 |\n| 8 | 0.333 |\n| 12 | 0.301 |\n| 20 | 0.314 |\n| 50 | 0.307 |\n\n- `n_components=2` appears to be the optimal cluster size parameter for GMM with its silhouette score of 0.422. Furthermore, increasing the number of clusters does not appear to have a positive and consistent effect on the score, therefore two clusters was chosen as the optimal number of clusters.",
"_____no_output_____"
],
[
"### Cluster Visualization",
"_____no_output_____"
]
],
[
[
"# Added some functionality to display points that don't neatly fall into either cluster.\nprobs = pd.DataFrame(clusterer.predict_proba(reduced_data))\nborder_indexes = np.array(probs[(probs[0] >= 0.4) & (probs[0] <= 0.6)].index)\nborder_data = reduced_data.values[border_indexes]\n# Display the results of the clustering from implementation\ncluster_results(reduced_data, preds, centers, pca_samples, border_data)",
"_____no_output_____"
]
],
[
[
"### Data Recovery\nEach cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the *averages* of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to *the average customer of that segment*. Since the data is currently reduced in dimension and scaled by a logarithm, I recover the representative customer spending from these data points by applying the inverse transformations.",
"_____no_output_____"
]
],
[
[
"# Inverse transform the centers\nlog_centers = pca.inverse_transform(centers)\n\n# Exponentiate the centers\ntrue_centers = np.exp(log_centers)\n\n# Display the true centers\nsegments = ['Segment {}'.format(i) for i in range(0,len(centers))]\ntrue_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())\ntrue_centers.index = segments\ndisplay(true_centers)",
"_____no_output_____"
]
],
[
[
"###### Cluster Interpretations ",
"_____no_output_____"
],
[
"- Comparing with the medians in the earlier statistical description, I can say that the true means that were extracted are much more reasonable than the previous means that were found prior to data processing. Below I compare the true means to the original quartiles to determine which product categories are most important to each segment. This helps to refine the kinds of customers that each segment contains so that I can speculate what each cluster represents. I note that `Delicatessen` is not very useful in demarcating the customer segments.\n\n\n- Segment 0 represents small businesses. This category includes restaurants and farmers' markets who mainly order fresh and frozen food over the other product categories. Unlike Segment 1, they do not order large enough volumes of any product that they could reasonably resell directly to customers. Members of this segment are not bulk buyers, but instead use what they buy for their immediate needs. They buy small quantities of goods, use them as required, and likely need replenishing on a regular basis. Checking the true sales means of Segment 0 against the quartiles for each product, it can be seen that the average customer in this segment places in Q3, Q2, Q2, Q3, Q2, and Q2 for `Fresh`, `Milk`, `Grocery`, `Frozen`, `Detergents_Paper`, `Delicatessen` respectively. This further supports the assertion that `Fresh` and `Frozen` are most valuable categories for customers in Segment 0. These two categories are relatively more important to restaurants and farmers' markets compared to other kinds of establishments, giving additional support to the existence of this cluster.\n\n\n- Segment 1 represents bulk buyers. Supermarkets, convenience stores, and retail warehouses would fall into this category. Their average orders in `Milk`, `Grocery`, and `Detergent_Papers` are so many multiples higher than those of Segment 0, that one can assume they are buying enough to resell directly to their constumers. These customers order moderate to large quantities of detergents, cleaners, groceries, and other goods, and stock them for extended periods of time. They likely do not have an urgent need for their products at any particular moment in time. Comparing this segment's true sales means to their respective quartiles shows that a typical customer's orders place in Q2, Q3, Q3, Q2, Q3, and Q2 for `Fresh`, `Milk`, `Grocery`, `Frozen`, `Detergents_Paper`, `Delicatessen` respectively. This demonstrates that `Milk`, `Grocery`, and `Detergents_Paper` are categories most integral to Segment 1. All of these products can be purchased in large quantities, stocked easily on shelves, and sold to consumers, validating the retail aspect of this cluster.",
"_____no_output_____"
],
[
"###### Sample Descriptions ",
"_____no_output_____"
]
],
[
[
"# Display the predictions\nfor i, pred in enumerate(sample_preds):\n print (\"Sample point\", i, \"predicted to be in Cluster\", pred)",
"Sample point 0 predicted to be in Cluster 0\nSample point 1 predicted to be in Cluster 1\nSample point 2 predicted to be in Cluster 1\n"
]
],
[
[
"- To help me classify the samples into the clusters generated by GMM, I devised the simple method outlined below. Each table displays the differences in the true centers for both segments and purchases by each sample. I interpret that the segment with the lowest distances is the one to which each sample belongs. According to this, Sample 0 should belong to Segment 1, while both Sample 1 and 2 should belong to Segment 0. This is consistent with the predictions generated above.\n\n\n ***Sample 0 Difference Table (True Centers - Customer Purchases)***\n\n|| Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen\n|:---------:| :---------: | :---------: | :----------: | :---------: | :---------: | :---------:\n| **Segment 0** | 1233 | 2904 | 6737 | 389 | 2984 | 1854\n| **Segment 1**| 3263 | 1391 | 129 | 633 | 275 | 1621\n\n ***Sample 1 Difference Table (True Centers - Customer Purchases)***\n\n|| Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen\n|:---------:| :---------: | :----------: | :---------: | :---------: | :---------: | :---------:\n|**Segment 0**| 7893 | 15 | 513 | 8585 | 221 | 653\n|**Segment 1**| 12389 | 4310 | 6353 | 9607 | 2930 | 420\n\n ***Sample 2 Difference Table (True Centers - Customer Purchases)***\n\n|| Fresh | Milk | Grocery | Frozen | Detergents_Paper | Delicatessen\n|:---------:| :---------: | :---------: | :---------: | :---------: | :---------: | :---------:\n|**Segment 0**| 10275 | 748 | 954 | 987 | 373 | 186\n|**Segment 1**| 14771 | 5043 | 5912 | 2009 | 2336 | 47",
"_____no_output_____"
],
[
"###### Handling New Customers\n\nAdditional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a ***customer segment*** it best identifies with (depending on the clustering algorithm applied), *'customer segment'* can be considered as an **engineered feature** for the data. Consider the situation where the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor could classify each new customer to a ***customer segment*** to determine the most appropriate delivery service. The details for how this could be handled are explained below.",
"_____no_output_____"
],
[
"- The wholesale distributor could modify the customer segment data by adding a new column labeled \"Segment.\" In this column, customers would be labeled \"Segment 0\" or \"Segment 1.\" To determine the labels, one could first apply PCA and GMM as I have done above and classify each customer using GMM's prediction as the target label. At this point, the distributor could use the data plus labels with two dimensions or the original six for training various supervised learning algorithms. I would recommend starting with decision trees or random forests as it appears that the data is approximately separable with vertical and horizontal hyperplanes. A variety of supervised algorithms should then be trained, cross-validated, and tested on the original data using optimization methods such as grid search and randomized search. When an optimal model is discovered, the distributor can provide it with data on the ten new customers and allow it to classify them into the two segments. He or she can also visualize the new customers by plotting them on the PCA feature axes to see if their labels are reasonable. Once again, the closer the new customers to the cluster centers, the more confident one can be in the labels that the model assigns.",
"_____no_output_____"
],
[
"### Visualizing Underlying Distributions\n\nAt the beginning of this project, it was discussed that the `'Channel'` and `'Region'` features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the `'Channel'` feature into the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset.\n\nThe code block belows assigns a label to each data point - either `'HoReCa'` (Hotel/Restaurant/Cafe) or `'Retail'` in the reduced space. In addition, the sample points are circled in the plot, which will identify their labeling.",
"_____no_output_____"
]
],
[
[
"# Display the clustering results based on 'Channel' data\nchannel_results(reduced_data, outliers, pca_samples)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
]
] |
cbb39f021ce1c364e8d4ea54d3daa26612804f6f
| 9,093 |
ipynb
|
Jupyter Notebook
|
DistinguishUnitaries/DistinguishUnitaries.ipynb
|
mkostersitz/QuantumKatas
|
9f767eac937883b2b2d858dff833a567844291d7
|
[
"MIT"
] | 1 |
2020-07-25T23:40:22.000Z
|
2020-07-25T23:40:22.000Z
|
DistinguishUnitaries/DistinguishUnitaries.ipynb
|
mkostersitz/QuantumKatas
|
9f767eac937883b2b2d858dff833a567844291d7
|
[
"MIT"
] | null | null | null |
DistinguishUnitaries/DistinguishUnitaries.ipynb
|
mkostersitz/QuantumKatas
|
9f767eac937883b2b2d858dff833a567844291d7
|
[
"MIT"
] | null | null | null | 31.682927 | 269 | 0.588695 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbb3af5040ed026b9497e8d73bfb7fd57738bb45
| 56,821 |
ipynb
|
Jupyter Notebook
|
prediction/multitask/pre-training/api generation/base_model.ipynb
|
victory-hash/CodeTrans
|
ca5bdf6393cee5a53eb5e610fa3a18e4167d6ba2
|
[
"MIT"
] | 148 |
2020-11-02T13:21:00.000Z
|
2022-03-31T07:18:15.000Z
|
prediction/multitask/pre-training/api generation/base_model.ipynb
|
victory-hash/CodeTrans
|
ca5bdf6393cee5a53eb5e610fa3a18e4167d6ba2
|
[
"MIT"
] | 5 |
2021-05-12T17:12:26.000Z
|
2021-08-05T20:05:12.000Z
|
prediction/multitask/pre-training/api generation/base_model.ipynb
|
victory-hash/CodeTrans
|
ca5bdf6393cee5a53eb5e610fa3a18e4167d6ba2
|
[
"MIT"
] | 17 |
2021-04-07T06:24:58.000Z
|
2022-03-31T07:18:09.000Z
| 34.752905 | 372 | 0.491755 |
[
[
[
"<a href=\"https://colab.research.google.com/github/agemagician/CodeTrans/blob/main/prediction/multitask/pre-training/api%20generation/base_model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"**<h3>Generate the api based on the description using codeTrans multitask training model</h3>**\n<h4>You can make free prediction online through this \n<a href=\"https://huggingface.co/SEBIS/code_trans_t5_base_api_generation_multitask\">Link</a></h4> (When using the prediction online, you need to parse and tokenize the code first.)",
"_____no_output_____"
],
[
"**1. Load necessry libraries including huggingface transformers**",
"_____no_output_____"
]
],
[
[
"!pip install -q transformers sentencepiece",
"\u001b[K |████████████████████████████████| 1.4MB 12.7MB/s \n\u001b[K |████████████████████████████████| 1.1MB 51.6MB/s \n\u001b[K |████████████████████████████████| 2.9MB 48.3MB/s \n\u001b[K |████████████████████████████████| 890kB 53.2MB/s \n\u001b[?25h Building wheel for sacremoses (setup.py) ... \u001b[?25l\u001b[?25hdone\n"
],
[
"from transformers import AutoTokenizer, AutoModelWithLMHead, SummarizationPipeline",
"_____no_output_____"
]
],
[
[
"**2. Load the token classification pipeline and load it into the GPU if avilabile**",
"_____no_output_____"
]
],
[
[
"pipeline = SummarizationPipeline(\n model=AutoModelWithLMHead.from_pretrained(\"SEBIS/code_trans_t5_base_api_generation_multitask\"),\n tokenizer=AutoTokenizer.from_pretrained(\"SEBIS/code_trans_t5_base_api_generation_multitask\", skip_special_tokens=True),\n device=0\n)",
"/usr/local/lib/python3.6/dist-packages/transformers/models/auto/modeling_auto.py:852: FutureWarning: The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use `AutoModelForCausalLM` for causal language models, `AutoModelForMaskedLM` for masked language models and `AutoModelForSeq2SeqLM` for encoder-decoder models.\n FutureWarning,\n"
]
],
[
[
"**3 Give the description for generating api, parse and tokenize it**",
"_____no_output_____"
]
],
[
[
"description = \"parse the uses licence node of this package, if any, and returns the license definition if theres\" #@param {type:\"raw\"}",
"_____no_output_____"
],
[
"import nltk\nnltk.download('punkt')\nfrom nltk.tokenize import word_tokenize",
"[nltk_data] Downloading package punkt to /root/nltk_data...\n[nltk_data] Unzipping tokenizers/punkt.zip.\n"
],
[
"\ndef englishTokenizer(sentence):\n result = []\n tokens = word_tokenize(sentence)\n for t in tokens:\n if( not len(t)>50):\n result.append(t)\n return ' '.join(result)\n\ntokenized_description = englishTokenizer(description)\nprint(\"tokenized description: \" + tokenized_description)",
"tokenized description: parse the uses licence node of this package , if any , and returns the license definition if theres\n"
]
],
[
[
"**4. Make Prediction**",
"_____no_output_____"
]
],
[
[
"pipeline([tokenized_description])",
"Your max_length is set to 512, but you input_length is only 25. You might consider decreasing max_length manually, e.g. summarizer('...', max_length=50)\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb3c7404ba5d906a9b2399fcfdf711f4231ac06
| 119,035 |
ipynb
|
Jupyter Notebook
|
scripts/scripts_other/time_prediction.ipynb
|
jschnellbach/SupportClassifier
|
5a4eb04adc3f5a40406a902c1c379d03e03d80b5
|
[
"MIT"
] | null | null | null |
scripts/scripts_other/time_prediction.ipynb
|
jschnellbach/SupportClassifier
|
5a4eb04adc3f5a40406a902c1c379d03e03d80b5
|
[
"MIT"
] | null | null | null |
scripts/scripts_other/time_prediction.ipynb
|
jschnellbach/SupportClassifier
|
5a4eb04adc3f5a40406a902c1c379d03e03d80b5
|
[
"MIT"
] | null | null | null | 38.597601 | 9,628 | 0.465174 |
[
[
[
"import pandas as pd\nfrom datetime import datetime\nimport numpy as np",
"_____no_output_____"
],
[
"STATUS_LOG_PATH = '../../data/status_log.csv\"\nTICKETS_PATH = '../../data/tickets.csv\"\nTICKETS_FOLDER_PATH = '../../data/tickets/\"\nFAQ_QUESTIONS_PATH = '../../data/FAQ_questions.txt\"\n\nDATA_PATH = '../../data/tickets_postprp.pkl'\nDE_FLAT_PATH = '../../data/de_flat.csv'\n\ndf = pd.read_csv(STATUS_LOG_PATH)",
"_____no_output_____"
],
[
"df.head()",
"_____no_output_____"
],
[
"df_quit = df[df[\"Status Text\"] == \"Quittiert\"].reset_index()\ndf_neu = df[df[\"Status Text\"] == \"Neu\"].reset_index()",
"_____no_output_____"
],
[
"df_quit = df_quit[df_quit[\"ID\"].isin(df_neu[\"ID\"].to_list())]",
"_____no_output_____"
],
[
"df_quit.shape",
"_____no_output_____"
],
[
"df_neu = df_neu[df_neu[\"ID\"].isin(df_quit[\"ID\"].to_list())]",
"_____no_output_____"
],
[
"df_neu.shape",
"_____no_output_____"
],
[
"df_neu[\"time\"] = df_neu[\"Datum\"] + \" \" + df_neu[\"Uhrzeit\"]\ndf_quit[\"time\"] = df_quit[\"Datum\"] + \" \" + df_quit[\"Uhrzeit\"]",
"_____no_output_____"
],
[
"df_neu[\"timeStart\"] = df_neu[\"time\"].apply(lambda s: datetime.strptime(s, '%Y.%m.%d %H:%M:%S'))",
"_____no_output_____"
],
[
"df_quit[\"timeFinish\"] = df_quit[\"time\"].apply(lambda s: datetime.strptime(s, '%Y.%m.%d %H:%M:%S'))",
"_____no_output_____"
],
[
"df_quit.drop([\"index\", \"Datum\", \"Uhrzeit\", \"Geändert Von\", \"Status ID\", \"Status Text\", \"time\"], axis=1, inplace=True)\ndf_neu.drop([\"index\", \"Datum\", \"Uhrzeit\", \"Geändert Von\", \"Status ID\", \"Status Text\", \"time\"], axis=1, inplace=True)",
"_____no_output_____"
],
[
"df = pd.merge(df_neu, df_quit, on='ID')",
"_____no_output_____"
],
[
"df[\"Time Taken\"] = df[\"timeFinish\"] - df[\"timeStart\"]",
"_____no_output_____"
],
[
"df[\"Time Taken\"] = df[\"Time Taken\"].apply(lambda t: (t.total_seconds())/3600)",
"_____no_output_____"
],
[
"df",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nimport seaborn as sns",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,5))\nplt.xlim(0,2000)\nplt.xlabel('Time in hours')\nplt.ylabel('Tickets')\nsns.histplot(df['Time Taken'],bins=500,kde=False)\nplt.show()",
"_____no_output_____"
],
[
"df_tickets = pd.read_csv(TICKETS_PATH)",
"_____no_output_____"
],
[
"df_tickets = df_tickets[df_tickets[\"Angelegt Von\"] != \"SOLMAN_BTC \"]",
"_____no_output_____"
],
[
"df_tickets.shape",
"_____no_output_____"
],
[
"df = df[df[\"ID\"].isin(df_tickets[\"ID\"])]\n",
"_____no_output_____"
],
[
"df.shape",
"_____no_output_____"
],
[
"plt.figure(figsize=(10,5))\nplt.xlim(0,2000)\nplt.xlabel('Time in hours')\nplt.ylabel('Tickets')\nsns.histplot(df['Time Taken'],bins=500,kde=False)\nplt.show()",
"_____no_output_____"
],
[
"df_tickets[\"Kategorie ID\"].replace({\" \": \"AUTOMATED\"}, inplace=True)",
"_____no_output_____"
],
[
"df_tickets[df_tickets[\"Meldender\"] == \" \"]",
"_____no_output_____"
]
],
[
[
"\n# Data cleaning and encode non-numaric values",
"_____no_output_____"
]
],
[
[
"df = pd.read_pickle(DATA_PATH)",
"_____no_output_____"
],
[
"df[\"kategorie_id\"] = df[\"kategorie_id\"].astype('category')\ndf[\"kategorie_id\"] = df[\"kategorie_id\"].cat.codes\n\ndf[\"unterkategorie_id\"] = df[\"unterkategorie_id\"].astype('category')\ndf[\"unterkategorie_id\"] = df[\"unterkategorie_id\"].cat.codes\n\ndf[\"meldender\"] = df[\"meldender\"].astype('category')\ndf[\"meldender\"] = df[\"meldender\"].cat.codes\n\ndf[\"angelegt_von\"] = df[\"angelegt_von\"].astype('category')\ndf[\"angelegt_von\"] = df[\"angelegt_von\"].cat.codes\n\ndf[\"auftraggeber\"] = df[\"auftraggeber\"].astype('category')\ndf[\"auftraggeber\"] = df[\"auftraggeber\"].cat.codes\n\ndf",
"_____no_output_____"
],
[
"df = df.drop(columns=['id', 'beschreibung','kategorietext',\n 'unterkategorietext','bearbeiter', 'editors',\n 'num_editors', 'time_start', 'status', 'time_finish',\n 'num_messages', 'first_date', 'last_date', 'description', 'answer',\n 'initial_message', 'internal_note', 'similarity', 'differences',\n 'language', 'faq_index_max_sim',\n 'faq_index_min_dif'])\ndf.reset_index()\ndf",
"_____no_output_____"
],
[
"df_emb = pd.DataFrame(data=np.stack(df.embeddings.to_numpy()))",
"_____no_output_____"
],
[
" result = pd.concat([df, df_emb], axis=1, join=\"inner\")\n result = result.drop(columns=[\"embeddings\"])\n result",
"_____no_output_____"
],
[
"result.to_csv(DE_FLAT_PATH)",
"_____no_output_____"
]
],
[
[
"#Training",
"_____no_output_____"
]
],
[
[
"from google.colab import drive\ndrive.mount('/content/drive')",
"Mounted at /content/drive\n"
],
[
"from sklearn import preprocessing, utils\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport pandas as pd\nimport numpy as np\nfrom keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping\nfrom keras.metrics import MeanAbsoluteError, MeanAbsolutePercentageError\nfrom sklearn.model_selection import train_test_split",
"_____no_output_____"
],
[
"df = pd.read_csv(DE_FLAT_PATH)\ndf = df.drop(columns=[\"Unnamed: 0\", \"index\"])\ndf = df.fillna(0)\ndfLabel = df['time_taken']\ndf = df.drop(['time_taken'], axis=1)\nscaler = preprocessing.MinMaxScaler(feature_range=(-0.0, 1, 2))\ncol_names = df.columns\nd = scaler.fit_transform(df, )\ndf = pd.DataFrame(d, columns=col_names)",
"_____no_output_____"
],
[
"from sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression, Lasso\nfrom sklearn.decomposition import PCA\npca = PCA(0.95)\npca.fit(df)\ndf = pca.transform(df)\nprint(df.shape)\npoly_reg = PolynomialFeatures(degree=2)\ndf = poly_reg.fit_transform(df)\nX_train, X_test, y_train, y_test = train_test_split(df, dfLabel, test_size=0.30, random_state=42)\npol_reg = Lasso(alpha=0.155)\npol_reg.fit(X_train, y_train)\npol_reg.score(X_train, y_train)",
"(3859, 144)\n"
],
[
"pol_reg.score(X_test, y_test)",
"_____no_output_____"
]
],
[
[
"### **Deep Learning**",
"_____no_output_____"
]
],
[
[
"model = Sequential()\nmodel.add(Dense(2048, activation=\"relu\"))\nmodel.add(Dense(1024, activation=\"relu\"))\nmodel.add(Dense(2048, activation=\"softplus\"))\nmodel.add(Dense(512, activation=\"relu\"))\nmodel.add(Dense(1024, activation=\"selu\"))\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dense(256, activation=\"softplus\"))\nmodel.add(Dense(126, activation=\"relu\"))\nmodel.add(Dense(126, activation=\"tanh\"))\nmodel.add(Dense(32, activation=\"relu\"))\nmodel.add(Dense(64, activation=\"softplus\"))\nmodel.add(Dense(16, activation=\"relu\"))\nmodel.add(Dense(32, activation=\"tanh\"))\nmodel.add(Dense(16, activation=\"relu\"))\nmodel.add(Dense(32, activation=\"relu\"))\nmodel.add(Dense(1))",
"_____no_output_____"
],
[
"callback = EarlyStopping(monitor='loss', patience=20)",
"_____no_output_____"
],
[
"model.compile(loss='mean_squared_error', optimizer=Adam(learning_rate=0.0001), metrics=[MeanAbsoluteError()])\nmodel.fit(df, dfLabel, epochs=5000, shuffle=True, batch_size=500, callbacks=[callback])",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbb3ccf96a002c6c87ae87f7ca69f59425603d79
| 87,046 |
ipynb
|
Jupyter Notebook
|
single_perceptron.ipynb
|
mmeooo/test_deeplearning
|
5e3a9716de253e4bf864e680b3a47f8ae8d87bd6
|
[
"Apache-2.0"
] | null | null | null |
single_perceptron.ipynb
|
mmeooo/test_deeplearning
|
5e3a9716de253e4bf864e680b3a47f8ae8d87bd6
|
[
"Apache-2.0"
] | null | null | null |
single_perceptron.ipynb
|
mmeooo/test_deeplearning
|
5e3a9716de253e4bf864e680b3a47f8ae8d87bd6
|
[
"Apache-2.0"
] | null | null | null | 57.380356 | 14,734 | 0.414585 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbb3cf42d4cbd521201922cc44960825fe193ae0
| 102,092 |
ipynb
|
Jupyter Notebook
|
high_freq.ipynb
|
dinrker/Algorithms_DataStructures
|
7362ce0fae1509005c4004011b09ab2011eb1eb0
|
[
"MIT"
] | null | null | null |
high_freq.ipynb
|
dinrker/Algorithms_DataStructures
|
7362ce0fae1509005c4004011b09ab2011eb1eb0
|
[
"MIT"
] | null | null | null |
high_freq.ipynb
|
dinrker/Algorithms_DataStructures
|
7362ce0fae1509005c4004011b09ab2011eb1eb0
|
[
"MIT"
] | null | null | null | 25.059401 | 359 | 0.402588 |
[
[
[
"# Lecture 1: Interview Style of FLAG",
"_____no_output_____"
],
[
"### Decode Ways\n\nhttps://leetcode.com/problems/decode-ways/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n n = len(s)\n if n == 0 or s[0] == '0':\n return 0\n fn_2, fn_1, fn = 1, 1, 1\n for i in range(1, n):\n if s[i] == '0':\n if int(s[i-1]) > 2 or int(s[i-1]) == 0:\n return 0\n else:\n fn = fn_2\n else:\n fn = fn_1\n if 10 < int(s[i-1] + s[i]) < 27:\n fn += fn_2\n fn_2, fn_1 = fn_1, fn\n return fn",
"_____no_output_____"
],
[
"class Solution(object):\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n v, w, p = 0, int(s > ''), ''\n for c in s:\n v, w, p = w, (c > '0') * w + (9 < int(p + c) < 27) * v, c\n return w\n ",
"_____no_output_____"
]
],
[
[
"### Decode Ways II\n\nhttps://leetcode.com/problems/decode-ways-ii/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def numDecodings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n Mod = 10**9 + 7\n e0, e1, e2 = 1, 0, 0 \n for c in s:\n if c == '*':\n f0 = 9 * e0 + 9 * e1 + 6 * e2\n f1 = e0\n f2 = e0\n else:\n f0 = (c > '0') * e0 + e1 + (c < '7') * e2\n f1 = (c == '1') * e0\n f2 = (c == '2') * e0 \n e0, e1, e2 = f0 % Mod, f1, f2\n return e0\n \n ",
"_____no_output_____"
]
],
[
[
"• 怎样识别动态规划类题?\n– 最优化,问方法数,不需要打印所有路径的大概率是\n– 看下数据范围\n\n• 动态规划的解题步骤:\n0.考虑最后一步(怎么分解,怎么走) 直觉、解题灵感来源\n1.定状态\n2.写转移方程\n3.初始条件、边界情况",
"_____no_output_____"
],
[
"### Rectangle Overlap\n\nhttp://www.lintcode.com/en/problem/rectangle-overlap/",
"_____no_output_____"
]
],
[
[
"## consider about it from the opposite way\nclass Solution:\n \"\"\"\n @param: l1: top-left coordinate of first rectangle\n @param: r1: bottom-right coordinate of first rectangle\n @param: l2: top-left coordinate of second rectangle\n @param: r2: bottom-right coordinate of second rectangle\n @return: true if they are overlap or false\n \"\"\"\n def doOverlap(self, l1, r1, l2, r2):\n # write your code here\n if l1.x > r2.x or l2.x > r1.x:\n return False\n elif l1.y < r2.y or r1.y > l2.y:\n return False\n else:\n return True",
"_____no_output_____"
]
],
[
[
"## Abbreviation",
"_____no_output_____"
],
[
"### Check Word Abbreviation\nhttp://www.lintcode.com/en/problem/check-word-abbreviation/\n\nhttps://leetcode.com/problems/valid-word-abbreviation/description/\n\n* Corner case: c == '0'",
"_____no_output_____"
]
],
[
[
"class Solution:\n \"\"\"\n @param: word: a non-empty string\n @param: abbr: an abbreviation\n @return: true if string matches with the given abbr or false\n \"\"\"\n def validWordAbbreviation(self, word, abbr):\n # write your code here\n i, n = 0, '0'\n \n for c in abbr:\n if c.isdigit():\n if c == n:\n return False\n n += c\n else:\n i += int(n)\n if i >= len(word) or word[i] != c:\n return False\n i += 1\n n = '0'\n \n return len(word[i:]) == int(n) ",
"_____no_output_____"
]
],
[
[
"### Words Abbreviation\nhttp://www.lintcode.com/en/problem/words-abbreviation/\n\n* glist[abrr] = list of words\n* if len(glist[abrr]) > 1 --> solve until len == 1, record dic[word] = abbr\n* return map(dic.get, dict): map(func, *iterables)\n* traverse a dict: for key, values in dic.items():",
"_____no_output_____"
]
],
[
[
"import collections",
"_____no_output_____"
],
[
"class Solution:\n \"\"\"\n @param: dict: an array of n distinct non-empty strings\n @return: an array of minimal possible abbreviations for every word\n \"\"\"\n def wordsAbbreviation(self, dict):\n # write your code here\n self.dic = {}\n self.solve(dict, 0)\n return map(self.dic.get, dict)\n \n def abbr(self, word, size):\n if len(word) - size <= 3:\n return word\n else:\n return word[: size + 1] + str(len(word) - size - 2) + word[-1]\n \n def solve(self, dict, size):\n glist = collections.defaultdict(list)\n for word in dict:\n glist[self.abbr(word, size)].append(word)\n for abbr, words in glist.items():\n if len(words) == 1:\n self.dic[words[0]] = abbr\n else:\n self.solve(words, size+1)",
"_____no_output_____"
],
[
"dict = [\"like\", \"god\", \"internal\", \"me\", \"internet\", \"interval\", \"intension\", \"face\", \"intrusion\"]\ndic = {\"like\": \"l2e\", \"face\": \"f2e\"}",
"_____no_output_____"
],
[
"list(map(dic.get, dict))",
"_____no_output_____"
],
[
"dic.get(\"like\")",
"_____no_output_____"
],
[
"def abbr(word, size):\n if len(word) - size <= 3:\n return word\n return word[:size+1] + str(len(word) - size - 2) + word[-1]",
"_____no_output_____"
],
[
"glist = collections.defaultdict(list)\nfor word in dict:\n glist[abbr(word, 0)].append(word)",
"_____no_output_____"
],
[
"glist",
"_____no_output_____"
],
[
"for abbr, words in glist.items():\n print(abbr, words)",
"l2e ['like']\ngod ['god']\ni6l ['internal', 'interval']\nme ['me']\ni6t ['internet']\ni7n ['intension', 'intrusion']\nf2e ['face']\n"
],
[
"Solu = Solution()",
"_____no_output_____"
],
[
"Solu.wordsAbbreviation(dict)",
"_____no_output_____"
],
[
"list(Solu.wordsAbbreviation(dict))",
"_____no_output_____"
],
[
"list(Solu.wordsAbbreviation(dict))",
"_____no_output_____"
]
],
[
[
"### Generalized Abbreviation\n\nhttps://leetcode.com/problems/generalized-abbreviation/description/\n\n* nice problem!\n\n* a letter can be represented as a word or a number, so totally 2^n possibilities.",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def generateAbbreviations(self, word):\n \"\"\"\n :type word: str\n :rtype: List[str]\n \"\"\"\n \n def helper(word, pos, count, cur, result):\n if pos == len(word):\n result.append(cur + (str(count) if count > 0 else ''))\n else:\n helper(word, pos + 1, count + 1, cur, result)\n helper(word, pos + 1, 0, cur + (str(count) if count > 0 else '') + word[pos], result)\n \n result = []\n helper(word, 0, 0, '', result)\n return result\n ",
"_____no_output_____"
]
],
[
[
"### Unique Word Abbreviation\n\nhttps://leetcode.com/problems/unique-word-abbreviation/description/\n\n* check the last two lines!!",
"_____no_output_____"
]
],
[
[
"class ValidWordAbbr(object):\n\n def __init__(self, dictionary):\n \"\"\"\n :type dictionary: List[str]\n \"\"\"\n self.dic = collections.defaultdict(set)\n for word in dictionary:\n self.dic[self.abbr(word)].add(word)\n \n def abbr(self, word):\n if len(word) <= 2:\n return word\n else:\n return word[0] + str(len(word) -2) + word[-1]\n\n def isUnique(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n abbr = self.abbr(word)\n if abbr not in self.dic:\n return True\n else:\n return len(self.dic[abbr]) == 1 and word in self.dic[abbr]\n\n\n# Your ValidWordAbbr object will be instantiated and called as such:\n# obj = ValidWordAbbr(dictionary)\n# param_1 = obj.isUnique(word)",
"_____no_output_____"
]
],
[
[
"### Minimum Unique Word Abbreviation\n\nhttps://leetcode.com/problems/minimum-unique-word-abbreviation/description/\n\n* use bit minipulation to record the differences!\n* recover the abbreviation from bit record\n* optimization\n* min(abbrs, key=lambda x: len(x))\n* do not forget to change num in abbr function: num >>= 1",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def minAbbreviation(self, target, dictionary):\n \"\"\"\n :type target: str\n :type dictionary: List[str]\n :rtype: str\n \"\"\"\n \n def abbr(target, num):\n cur, count = '', 0\n for c in target:\n if num & 1 == 1:\n if count:\n cur += str(count)\n count = 0\n cur += c\n else:\n count += 1\n num >>= 1\n if count:\n cur += str(count)\n return cur\n \n \n m, diffs = len(target), []\n for word in dictionary:\n if len(word) != m:\n continue\n \n bits = 0\n for i, c in enumerate(word):\n if target[i] != c:\n bits += 2 ** i\n diffs += [bits]\n \n if not diffs:\n return str(m)\n \n abbrs = []\n for i in range(2 ** m):\n if all(i & d for d in diffs):\n abbrs.append(abbr(target, i))\n \n return min(abbrs, key=lambda x: len(x))\n ",
"_____no_output_____"
],
[
"import operator\nword = '1e4'\ntarget = '1r2'\nany(map(operator.eq, word, target))",
"_____no_output_____"
],
[
"num = 5\nnum >>= 1\nnum",
"_____no_output_____"
],
[
"num >> 1",
"_____no_output_____"
],
[
"num",
"_____no_output_____"
],
[
"diffs = []\nfor i in [1,2,3]:\n diffs += i,\ndiffs",
"_____no_output_____"
],
[
"?all",
"_____no_output_____"
]
],
[
[
"# Lecture 2: Simulation Algorithms & String Manipulation Skills",
"_____no_output_____"
],
[
"### Sliding window\nhttp://www.lintcode.com/zh-cn/problem/sliding-window-average-from-data-stream/\n\nhttps://leetcode.com/problems/moving-average-from-data-stream/description/",
"_____no_output_____"
]
],
[
[
"## straight foreward\nclass MovingAverage:\n \"\"\"\n @param: size: An integer\n \"\"\"\n def __init__(self, size):\n # do intialization if necessary\n self.idx = 0\n self.sum = 0\n self.list = []\n self.size = size\n\n \"\"\"\n @param: val: An integer\n @return: \n \"\"\"\n def next(self, val):\n # write your code here\n self.sum += val\n self.idx += 1\n if self.idx <= self.size:\n self.list += [self.sum]\n return float(self.list[-1]) / self.idx\n else:\n j = self.idx % self.size - 1\n prev = self.list[j]\n self.list[j] = self.sum\n return float(self.list[j] - prev) / self.size\n\n\n# Your MovingAverage object will be instantiated and called as such:\n# obj = MovingAverage(size)\n# param = obj.next(val)",
"_____no_output_____"
]
],
[
[
"* the usage of collcections, deque, deque.popleft(), deque.append(), float()\n* moving sum to save memory\n* mode to switch index & add new vals\n\n• 如何快速求和? 前缀和数组(dummy 0) \n• 如何节省储存空间呢? 链表/滚动 \n• 写滚动的技巧 先写程序最后加滚动 ",
"_____no_output_____"
]
],
[
[
"## data structure: queue\nclass MovingAverage(object):\n\n def __init__(self, size):\n \"\"\"\n Initialize your data structure here.\n :type size: int\n \"\"\"\n self.queue = collections.deque(maxlen=size)\n self.size = size\n self.sum = 0\n \n\n def next(self, val):\n \"\"\"\n :type val: int\n :rtype: float\n \"\"\"\n self.sum += val\n if len(self.queue) == self.size:\n self.sum -= self.queue.popleft()\n self.queue.append(val)\n return float(self.sum) / len(self.queue)\n\n# Your MovingAverage object will be instantiated and called as such:\n# obj = MovingAverage(size)\n# param_1 = obj.next(val)",
"_____no_output_____"
],
[
"import collections",
"_____no_output_____"
],
[
"collections.deque.popleft",
"_____no_output_____"
]
],
[
[
"### One Edit Distance\n\nhttps://leetcode.com/problems/one-edit-distance/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def isOneEditDistance(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n m, n = len(s), len(t)\n if abs(m - n) > 1:\n return False\n elif m < n:\n return self.isOneEditDistance(t, s)\n else:\n for i in range(n):\n if s[i] != t[i]:\n if m == n:\n return s[i+1:] == t[i+1:]\n else:\n return s[i+1:] == t[i:]\n \n return m != n\n ",
"_____no_output_____"
],
[
"s = '12dere'\nn = len(s)\ns[n:]",
"_____no_output_____"
]
],
[
[
"### Read N Characters Given Read4 (not clear)\n\nhttps://leetcode.com/problems/read-n-characters-given-read4/description/",
"_____no_output_____"
]
],
[
[
"# The read4 API is already defined for you.\n# @param buf, a list of characters\n# @return an integer\n# def read4(buf):\n\nclass Solution(object):\n def read(self, buf, n):\n \"\"\"\n :type buf: Destination buffer (List[str])\n :type n: Maximum number of characters to read (int)\n :rtype: The number of characters read (int)\n \"\"\"\n idx = 0\n while True:\n buf4 = [\"\"]*4\n curr = min(read4(buf4), n-idx)\n for i in range(curr):\n buf[idx] = buf4[i]\n idx += 1\n if curr != 4 or idx == n:\n return idx",
"_____no_output_____"
],
[
"buf4 = [\"\"]*4\nbuf4",
"_____no_output_____"
]
],
[
[
"### Read Characters From File - multiple calls\n\nhttps://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/description/\n\n* init function: def __inti__(self):\n* differece between append and extend\n\n难点: \n• 如果只读3个,剩下的一个怎么处理?(读多的怎么留着给下次用?) \n• Read4 这个函数只读了2个怎么办? (读到末尾时,没有读全4个)",
"_____no_output_____"
]
],
[
[
"# The read4 API is already defined for you.\n# @param buf, a list of characters\n# @return an integer\n# def read4(buf):\n\nclass Solution(object):\n def __init__(self):\n self.queue = []\n \n \n def read(self, buf, n):\n \"\"\"\n :type buf: Destination buffer (List[str])\n :type n: Maximum number of characters to read (int)\n :rtype: The number of characters read (int)\n \"\"\"\n idx = 0\n while True:\n buf4 = [\"\"]*4\n l = read4(buf4)\n self.queue.extend(buf4)\n curr = min(len(self.queue), n-idx)\n for i in range(curr):\n buf[idx] = self.queue.pop(0)\n idx += 1\n if curr == 0:\n break\n \n return idx",
"_____no_output_____"
],
[
"buf4 = [\"\"]*4\nqueue1, queue2 = [], []\nqueue1.append(buf4)\nqueue2.extend(buf4)\nqueue1, queue2",
"_____no_output_____"
]
],
[
[
"### Strings Serialization\n\nhttp://www.lintcode.com/zh-cn/problem/strings-serialization/\n\n• abc def -> abc:;def:; \n• ab:c def -> ab::c:;def:; \n• ab:;c def -> ab::;c:;def:; \n• 用‘:’表示转义,那么连接符就是’:;’ 表示‘:’本身就是‘::’",
"_____no_output_____"
]
],
[
[
"class Solution:\n \"\"\"\n @param: strs: a list of strings\n @return: encodes a list of strings to a single string.\n \"\"\"\n def encode(self, strs):\n # write your code here\n res = ''\n for s in strs:\n for c in s:\n if c == \":\":\n res += \"::\"\n else:\n res += c\n res += \":;\"\n return res\n\n \"\"\"\n @param: str: A string\n @return: dcodes a single string to a list of strings\n \"\"\"\n def decode(self, str):\n # write your code here\n res = []\n s = ''\n i = 0\n while i < len(str) - 1:\n if str[i] == \":\":\n if str[i+1] == \";\":\n res += [s]\n s = ''\n else:\n s += str[i+1]\n i += 2\n else:\n s += str[i]\n i += 1\n return res",
"_____no_output_____"
]
],
[
[
"### System Longest File Path\n\nhttps://leetcode.com/problems/longest-absolute-file-path/description/\n\n* splitlines() and lstrip('\\t')",
"_____no_output_____"
]
],
[
[
"len(\"dir/subdir2/subsubdir2/file2.ext\")",
"_____no_output_____"
],
[
"s = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"",
"_____no_output_____"
],
[
"s.splitlines()",
"_____no_output_____"
],
[
"line = '\\t\\tfile.ext'\nline.lstrip('\\t')",
"_____no_output_____"
],
[
"class Solution(object):\n def lengthLongestPath(self, input):\n \"\"\"\n :type input: str\n :rtype: int\n \"\"\"\n maxlen = 0\n pathlen = {0:0}\n for line in input.splitlines():\n name = line.lstrip('\\t')\n depth = len(line) - len(name)\n if '.' in name:\n maxlen = max(maxlen, pathlen[depth] + len(name))\n else:\n pathlen[depth+1] = pathlen[depth] + len(name) + 1\n \n return maxlen",
"_____no_output_____"
]
],
[
[
"### Roman to Integer\n\nhttps://leetcode.com/problems/roman-to-integer/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n roman = {\"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n if len(s) == 0:\n return 0\n res = roman[s[-1]]\n idx = len(s) - 2\n while idx >= 0:\n if roman[s[idx]] < roman[s[idx+1]]:\n res -= roman[s[idx]] \n else:\n res += roman[s[idx]] \n idx -= 1\n \n return res",
"_____no_output_____"
]
],
[
[
"### Integer to Roman\n\nhttps://leetcode.com/problems/roman-to-integer/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def parse(self, digit, index):\n nums = {1: \"I\", 2: \"II\", 3: \"III\", 4: \"IV\", 5: \"V\", 6: \"VI\", 7: \"VII\", 8: \"VIII\", 9: \"IX\"}\n roman = {\n \"I\": [\"I\", \"X\", \"C\", \"M\"],\n \"V\": [\"V\", \"L\", \"D\", \"?\"],\n \"X\": [\"X\", \"C\", \"M\", \"?\"]\n }\n s = nums[digit]\n return s.replace(\"X\", roman[\"X\"][index]).replace(\"V\", roman[\"V\"][index]).replace(\"I\", roman[\"I\"][index])\n \n \n def intToRoman(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n \n ans = \"\"\n index = 0\n while num > 0:\n digit = num % 10\n if digit != 0:\n ans = self.parse(digit, index) + ans\n num = int(num / 10)\n index += 1\n \n return ans\n\n \n# # solution 1\n# nums = [\n# [\"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"],\n# [\"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"],\n# [\"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"],\n# [\"M\", \"MM\", \"MMM\"]\n# ]\n \n# ans = \"\"\n# row = 0\n# while num > 0:\n# digit = num % 10\n# if digit != 0:\n# ans = nums[row][digit-1] + ans\n# num = num / 10\n# row += 1\n# return ans",
"_____no_output_____"
]
],
[
[
"### Find the Celebrity\n\nhttps://leetcode.com/problems/find-the-celebrity/description/",
"_____no_output_____"
]
],
[
[
"# The knows API is already defined for you.\n# @param a, person a\n# @param b, person b\n# @return a boolean, whether a knows b\n# def knows(a, b):\n\nclass Solution(object):\n def findCelebrity(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n candidate = 0\n for i in range(1, n):\n if knows(candidate, i):\n candidate = i\n \n for i in range(candidate):\n if not knows(i, candidate) or knows(candidate, i):\n return -1\n \n for i in range(candidate+1, n):\n if not knows(i, candidate) or knows(candidate, i):\n return -1\n \n return candidate\n \n ",
"_____no_output_____"
]
],
[
[
"# Lecture 3: Basic Algorithms & Data Structure I",
"_____no_output_____"
],
[
"### Missing Ranges\n\nhttps://leetcode.com/problems/missing-ranges/description/",
"_____no_output_____"
]
],
[
[
"nums = [0, 1, 3, 50, 75]",
"_____no_output_____"
],
[
"for k, v in enumerate(nums):\n print(k, v, nums[k])",
"0 0 0\n1 1 1\n2 3 3\n3 50 50\n4 75 75\n"
],
[
"class Solution(object):\n def findMissingRanges(self, nums, lower, upper):\n \"\"\"\n :type nums: List[int]\n :type lower: int\n :type upper: int\n :rtype: List[str]\n \"\"\"\n res = []\n start = lower\n for k, v in enumerate(nums): # 两端点和一头一尾形成的区间 + for循环扫描中间形成的区间\n if v < start:\n continue\n elif v == start:\n start += 1\n continue\n res.append(self.addRange(start, v-1))\n start = v + 1\n if start <= upper: # corner case\n res.append(self.addRange(start, upper))\n return res\n \n def addRange(self, start, end): # – 利用函数让自己的代码更简洁 (见代码)\n return str(start) if start == end else str(start) + \"->\" + str(end)",
"_____no_output_____"
]
],
[
[
"### Merge Intervals\n\nhttps://leetcode.com/problems/merge-intervals/description/",
"_____no_output_____"
]
],
[
[
"starts = [2, 1, 15, 8]\nidx = sorted(range(len(starts)), key=lambda x: starts[x])\nidx",
"_____no_output_____"
],
[
"intervals = [[8,10], [2,6]]\nintervals.sort()",
"_____no_output_____"
],
[
"intervals",
"_____no_output_____"
],
[
"# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def merge(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: List[Interval]\n \"\"\"\n intervals = sorted(intervals, key=lambda x: x.start) # sort skill !!!\n res = []\n for interval in intervals:\n if len(res) == 0 or res[-1].end < interval.start: # when to add interval\n res.append(interval)\n else:\n res[-1].end = max(res[-1].end, interval.end)\n return res",
"_____no_output_____"
]
],
[
[
"### Insert Interval\n\nhttps://leetcode.com/problems/insert-interval/description/",
"_____no_output_____"
]
],
[
[
"# Definition for an interval.\n# class Interval(object):\n# def __init__(self, s=0, e=0):\n# self.start = s\n# self.end = e\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n intervals = intervals + [newInterval]\n intervals = sorted(intervals, key=lambda x: x.start)\n res = []\n for interval in intervals:\n if len(res) == 0 or res[-1].end < interval.start:\n res.append(interval)\n else:\n res[-1].end = max(res[-1].end, interval.end)\n return res\n ",
"_____no_output_____"
]
],
[
[
"### First Position Unique Character\n\nhttp://www.lintcode.com/zh-cn/problem/first-position-unique-character/",
"_____no_output_____"
]
],
[
[
"dic = {'1':[1,5,8], '0':[2,4,3]}",
"_____no_output_____"
],
[
"for key, value in dic.items():\n print(key, value)",
"1 [1, 5, 8]\n0 [2, 4, 3]\n"
],
[
"class Solution:\n \"\"\"\n @param: s: a string\n @return: it's index\n \"\"\"\n def firstUniqChar(self, s):\n # write your code here\n dic = {}\n for c in s:\n dic[c] = dic.get(c, 0) + 1\n for i in range(len(s)):\n if dic[s[i]] == 1:\n return i\n return -1",
"_____no_output_____"
]
],
[
[
"### Substring Anagrams\n\nhttp://www.lintcode.com/zh-cn/problem/substring-anagrams/\n\nhttps://leetcode.com/problems/find-all-anagrams-in-a-string/description/",
"_____no_output_____"
]
],
[
[
"ord('a'), chr(97)",
"_____no_output_____"
],
[
"abs([1,2])",
"_____no_output_____"
],
[
"from collections import Counter\nCounter('aba')",
"_____no_output_____"
],
[
"dic = {'a': 2, 'b': 1}",
"_____no_output_____"
],
[
"del dic['a']\ndic",
"_____no_output_____"
],
[
"# class Solution(object):\n# def findAnagrams(self, s, p):\n# \"\"\"\n# :type s: str\n# :type p: str\n# :rtype: List[int]\n# \"\"\"\n# m, n = len(s), len(p)\n# res = []\n# if m < n:\n# return res\n# pc = collections.Counter(p)\n# sc = collections.Counter(s[:n-1])\n# for i in range(m-n+1):\n# sc[s[n-1+i]] += 1\n# if sc == pc:\n# res.append(i)\n# sc[s[i]] -= 1\n# if sc[s[i]] == 0:\n# del sc[s[i]]\n# return res\n\nclass Solution:\n \"\"\"\n @param: s: a string\n @param: p: a string\n @return: a list of index\n \"\"\"\n def findAnagrams(self, s, p):\n # write your code here\n m, n = len(s), len(p)\n res = []\n if m < n:\n return res\n det = [0 for i in range(26)]\n for i in range(n):\n jp = ord(p[i]) - ord('a')\n det[jp] -= 1\n js = ord(s[i]) - ord('a')\n det[js] += 1\n \n \n sum = 0\n for d in det:\n sum += abs(d)\n if sum == 0:\n res.append(0)\n for i in range(0, m-n):\n jl = ord(s[i]) - ord('a')\n sum -= abs(det[jl])\n det[jl] -= 1\n sum += abs(det[jl])\n jr = ord(s[i+n]) - ord('a')\n sum -= abs(det[jr])\n det[jr] += 1\n sum += abs(det[jr])\n if sum == 0:\n res.append(i+1)\n \n return res",
"_____no_output_____"
]
],
[
[
"### Word Abbreviation Set \n\nhttp://www.lintcode.com/zh-cn/problem/word-abbreviation-set/\n\nhttps://leetcode.com/problems/unique-word-abbreviation/description/",
"_____no_output_____"
]
],
[
[
"set().union('he'), set().union(['he'])",
"_____no_output_____"
],
[
"len(set().union('he'))",
"_____no_output_____"
],
[
"def getAbbr(word):\n if len(word) > 2:\n return word[0] + str(len(word) - 2) + word[-1]\n return word",
"_____no_output_____"
],
[
"d = collections.defaultdict(set)\nfor word in ['aa', 'bb', 'cc', 'cc','bb']:\n d[getAbbr(word)].add(word)\nd",
"_____no_output_____"
],
[
"collections.defaultdict?",
"_____no_output_____"
],
[
"class ValidWordAbbr(object):\n\n def __init__(self, dictionary):\n \"\"\"\n :type dictionary: List[str]\n \"\"\"\n self.dic = collections.defaultdict(set)\n for word in dictionary:\n self.dic[self.getAbbr(word)].add(word)\n \n \n def getAbbr(self, word):\n return word if len(word) < 3 else word[0] + str(len(word)-2) + word[-1]\n \n\n def isUnique(self, word):\n \"\"\"\n :type word: str\n :rtype: bool\n \"\"\"\n abbr = self.getAbbr(word)\n if abbr not in self.dic:\n return True\n else:\n return len(self.dic[abbr]) == 1 and word in self.dic[abbr]\n \n\n\n# class ValidWordAbbr(object):\n\n# def __init__(self, dictionary):\n# \"\"\"\n# :type dictionary: List[str]\n# \"\"\"\n# self.dic = {}\n# for word in dictionary:\n# abrr = self.abrr(word)\n# self.dic[abrr] = self.dic.get(abrr, set()).union([word])\n \n \n# def abrr(self, word):\n# return word if len(word) < 3 else word[0] + str(len(word)-2) + word[-1]\n \n\n# def isUnique(self, word):\n# \"\"\"\n# :type word: str\n# :rtype: bool\n# \"\"\"\n# abrr = self.abrr(word)\n# if abrr in self.dic:\n# if len(self.dic[abrr]) > 1 or word not in self.dic[abrr]:\n# return False\n# return True \n \n \n\n\n# # Your ValidWordAbbr object will be instantiated and called as such:\n# # obj = ValidWordAbbr(dictionary)\n# # param_1 = obj.isUnique(word)",
"_____no_output_____"
]
],
[
[
"### Longest Consecutive Sequence\n\nhttps://leetcode.com/problems/longest-consecutive-sequence/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def longestConsecutive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dic = {}\n for n in nums:\n dic[n] = False\n \n maxlen = 0\n for n in nums:\n if dic[n]:\n continue\n length = 1\n left, right = n - 1, n + 1\n while left in dic:\n length += 1\n dic[left] = True\n left -= 1\n while right in dic:\n length += 1\n dic[right] = True\n right += 1\n maxlen = max(maxlen, length)\n return maxlen",
"_____no_output_____"
]
],
[
[
"### Load Balancer\n\nhttp://www.lintcode.com/en/problem/load-balancer/",
"_____no_output_____"
]
],
[
[
"a = set().union('he')",
"_____no_output_____"
],
[
"a = [0, 1, 2]\na.pop()\na",
"_____no_output_____"
],
[
"import random\nfor i in range(15):\n print(random.randint(0, 5 - 1))",
"2\n1\n3\n4\n2\n2\n1\n4\n2\n1\n0\n2\n2\n4\n2\n"
],
[
"class LoadBalancer:\n def __init__(self):\n # do intialization if necessary\n self.ids = []\n self.index = {}\n\n \"\"\"\n @param: server_id: add a new server to the cluster\n @return: nothing\n \"\"\"\n def add(self, server_id):\n # write your code here\n self.ids.append(server_id)\n self.index[server_id] = len(self.ids) - 1\n\n \"\"\"\n @param: server_id: server_id remove a bad server from the cluster\n @return: nothing\n \"\"\"\n def remove(self, server_id):\n # write your code here\n idx = self.index[server_id]\n del self.index[server_id]\n last_id = self.ids[-1]\n self.index[last_id] = idx\n self.ids[idx] = last_id\n self.ids.pop()\n\n \"\"\"\n @return: pick a server in the cluster randomly with equal probability\n \"\"\"\n def pick(self):\n # write your code here\n import random\n idx = random.randint(0, len(self.ids)-1)\n return self.ids[idx]",
"_____no_output_____"
]
],
[
[
"# Lecture 4: Basic Algorithms & Data Structure II\n\n### Binary Search ",
"_____no_output_____"
],
[
"### Convert BST to Greater Tree\n\nhttps://leetcode.com/problems/convert-bst-to-greater-tree/description/",
"_____no_output_____"
]
],
[
[
"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def convertBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n self.sum = 0\n self.dfs(root)\n return root\n \n def dfs(self, root):\n if root is None:\n return \n if root.right:\n self.dfs(root.right)\n self.sum += root.val\n root.val = self.sum\n if root.left:\n self.dfs(root.left)",
"_____no_output_____"
]
],
[
[
"### Inorder Successor in BST\n\nhttps://leetcode.com/problems/inorder-successor-in-bst/description/\n\n* [Depth First Traversals](http://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/): \n\n(a) Inorder (Left, Root, Right) : 4 2 5 1 3\n\n(b) Preorder (Root, Left, Right) : 1 2 4 5 3\n\n(c) Postorder (Left, Right, Root) : 4 5 2 3 1\n",
"_____no_output_____"
]
],
[
[
"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def inorderSuccessor(self, root, p):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :rtype: TreeNode\n \"\"\"\n succ = None\n while root:\n if root.val <= p.val:\n root = root.right\n else:\n succ = root\n root = root.left\n return succ\n ",
"_____no_output_____"
]
],
[
[
"### Binary Tree Upside Down\n\nhttps://leetcode.com/problems/binary-tree-upside-down/description/",
"_____no_output_____"
]
],
[
[
"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def upsideDownBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n if root is None or root.left is None:\n return root\n \n new_root = self.upsideDownBinaryTree(root.left)\n root.left.left = root.right\n root.left.right = root\n root.left = None\n root.right = None\n return new_root",
"_____no_output_____"
]
],
[
[
"### Find Leaves of Binary Tree\n\nhttps://leetcode.com/problems/find-leaves-of-binary-tree/description/",
"_____no_output_____"
]
],
[
[
"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def findLeaves(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n result = []\n self.dfs(root, result)\n return result\n \n def dfs(self, root, result):\n if root is None:\n return 0\n \n level = max(self.dfs(root.left, result), self.dfs(root.right, result)) + 1\n if level > len(result):\n result.append([])\n result[level-1].append(root.val)\n return level\n ",
"_____no_output_____"
]
],
[
[
"### Binary Tree Vertical Order Traversal\n\nhttps://leetcode.com/problems/binary-tree-vertical-order-traversal/description/",
"_____no_output_____"
]
],
[
[
"a = []\na.append((1,2))\na",
"_____no_output_____"
],
[
"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def verticalOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n result = collections.defaultdict(list)\n level = [(root, 0)]\n while level:\n next_level = []\n for node, order in level:\n if node:\n result[order].append(node.val)\n next_level.append((node.left, order-1))\n next_level.append((node.right, order+1))\n level = next_level\n return [result[i] for i in sorted(result)]\n ",
"_____no_output_____"
]
],
[
[
"# Lecture 5: How to Implement Search Problem Effectively\n",
"_____no_output_____"
],
[
"\n1.BFS是用来搜索最短径路的解是比较合适的,比如求最少步数的解,最少交换次数的解,因为BFS搜索过程中遇到的解一定是离根最近的,所以遇到一个解,一定就是最优解,此时搜索算法可以终止。这个时候不适宜使用DFS,因为DFS搜索到的解不一定是离根最近的,只有全局搜索完毕,才能从所有解中找出离根的最近的解。(当然这个DFS的不足,可以使用迭代加深搜索ID-DFS去弥补)\n\n2.空间优劣上,DFS是有优势的,DFS不需要保存搜索过程中的状态,而BFS在搜索过程中需要保存搜索过的状态,而且一般情况需要一个队列来记录。\n\n3.DFS适合搜索全部的解,因为要搜索全部的解,那么BFS搜索过程中,遇到离根最近的解,并没有什么用,也必须遍历完整棵搜索树,DFS搜索也会搜索全部,但是相比DFS不用记录过多信息,所以搜素全部解的问题,DFS显然更加合适。\n\n4.基本原则:能用BFS的时候就用BFS,不能用的时候再用DFS。",
"_____no_output_____"
],
[
"## BFS\n\n### Template",
"_____no_output_____"
]
],
[
[
"## version 1: traversal\nqueue = [start]\nwhile queue:\n node = queue.pop(0)\n new_node = node + 1 # or other conditions\n queue.append(new_node)\n \n \n## version 2: length of shortest path\nlength, level = 0, [start]\nwhile level:\n new_level = []\n for node in level:\n new_node = node + 1\n new_level.append(new_node)\n length += 1\n level = new_level",
"_____no_output_____"
]
],
[
[
"#### Surrounded Regions\n\nhttps://leetcode.com/problems/surrounded-regions/description/\n\n小技巧总结:\n\n• 在网格图、矩阵图、棋盘上做多个方向扩展时,用dx dy数组会让程序写起\n来更方便",
"_____no_output_____"
]
],
[
[
"any?",
"_____no_output_____"
],
[
"any([[]])",
"_____no_output_____"
],
[
"row = 'XXSi'\n['XO'[c == 'S'] for c in row]",
"_____no_output_____"
],
[
"board = [\"XXXX\",\"XOOX\",\"XXOX\",\"XSXX\"]\nboard[:] = [['XO'[c == 'S'] for c in row] for row in board]\nboard",
"_____no_output_____"
],
[
"board = [list(\"XXXX\"),list(\"XOOX\"),list(\"XXOX\"),list(\"XSXX\")]\nfor row in board:\n for i, c in enumerate(row):\n row[i] = 'XO'[c == 'S']\nboard",
"_____no_output_____"
],
[
"class Solution(object):\n def solve(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n if not any(board):\n return \n \n m, n = len(board), len(board[0])\n save = [ij for k in range(max(m,n)) for ij in ((0, k), (m-1, k), (k, 0), (k, n-1))]\n while save:\n i, j = save.pop()\n if 0 <= i < m and 0 <= j < n and board[i][j] == 'O':\n board[i][j] = 'S'\n save += (i+1, j), (i-1, j), (i, j+1), (i, j-1)\n \n for row in board:\n for i, c in enumerate(row):\n if c == 'S':\n row[i] = 'O'\n else:\n row[i] = 'X'\n \n# for row in board:\n# for i, c in enumerate(row):\n# row[i] = 'XO'[c == 'S']\n \n# board[:] = [['XO'[c == 'S'] for c in row] for row in board]\n",
"_____no_output_____"
],
[
"c = Solution()\nboard = [list(\"XXXX\"),list(\"XOOX\"),list(\"XXOX\"),list(\"XOXX\")] # board is a list of list !!!\nc.solve(board)\nboard",
"_____no_output_____"
]
],
[
[
"#### Nearest Exit\n\nhttps://leetcode.com/problems/walls-and-gates/description/\n\n 小技巧总结:\n\n– 多源点单终点 --> 单源点多终点,最短路常用转化套路\n\n– 多源多终点 --> 单源多终点 (增加超级源,最短路常用转化套路)\n\n– BFS可以求边长=1的图的最短路(如此题的棋盘图)",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def wallsAndGates(self, rooms):\n \"\"\"\n :type rooms: List[List[int]]\n :rtype: void Do not return anything, modify rooms in-place instead.\n \"\"\"\n if not any(rooms): return \n IFN = 2147483647\n m, n = len(rooms), len(rooms[0])\n queue = [(i, j) for i, row in enumerate(rooms) for j, c in enumerate(row) if c == 0]\n while queue:\n i, j = queue.pop(0)\n for x, y in ((i+1, j), (i-1, j), (i, j+1), (i, j-1)):\n if 0 <= x < m and 0 <= y < n and rooms[x][y] == IFN:\n rooms[x][y] = rooms[i][j] + 1\n queue.append((x, y))",
"_____no_output_____"
]
],
[
[
"## DFS\n\n### Template",
"_____no_output_____"
]
],
[
[
"## version 1: traversal\nstack = [start]\nwhile stack:\n node = stack.pop()\n new_node = node + 1 # or other conditions\n stack.append(new_node)\n \n \n## version 2: Divide & Conquer\ndef dfs(root): # ex: binary tree\n ## null or leaf\n if root is None:\n ## do something and return;\n\n ## Divide\n left = dfs(root.left);\n right = dfs(root.right);\n\n ## Conquer\n result = Merge(left, right)\n return result",
"_____no_output_____"
]
],
[
[
"\n#### Letter Combinations of a Phone Number\n\nhttps://leetcode.com/problems/letter-combinations-of-a-phone-number/description/",
"_____no_output_____"
]
],
[
[
"digits ='23'\nchr = [\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"]\nres = []\n",
"_____no_output_____"
],
[
"for i in range(len(digits)):\n num = int(digits[i])\n temp = []\n for c in chr[num]:\n if len(res) == 0:\n temp += [c]\n else:\n for r in res:\n temp += [r + c]\n res[:] = temp\nres\n ",
"_____no_output_____"
],
[
"class Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n n, res = len(digits), []\n if n == 0: return res\n letters = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n for i in range(n):\n num = int(digits[i])\n temp = []\n for c in letters[num]:\n if len(res) == 0:\n temp.append(c)\n else:\n for j in range(len(res)):\n temp.append(res[j]+c)\n res[:] = temp\n return res\n ",
"_____no_output_____"
],
[
"# 思路:\n# • 基础枚举型DFS(按方法1 执行过程理解)\n# – 输入数字串长度为n,做n个阶段的选择,DFS n层\n# – 每一阶段枚举该位的数字对应的一个字母\n# – 直到所有情况都枚举完\n\nclass Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n def dfs(num, string, res):\n if num == n:\n res.append(string)\n return \n for c in letters[int(digits[num])]:\n dfs(num+1, string+c, res)\n \n n, res = len(digits), []\n if n == 0: return res\n letters = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n dfs(0, '', res)\n return res\n ",
"_____no_output_____"
]
],
[
[
"#### Factorization\n\nhttp://www.lintcode.com/zh-cn/problem/factorization/\n\n* Note: \n\n(1) the way to add path\n\n(2) the way to copy temp in the last problem",
"_____no_output_____"
]
],
[
[
"a = []\na.append([1,2,3])\na.append([2,3])\na",
"_____no_output_____"
],
[
"class Solution:\n \"\"\"\n @param: n: An integer\n @return: a list of combination\n \"\"\"\n def getFactors(self, n):\n # write your code here\n \n def dfs(start, remain):\n if remain == 1:\n if len(path) > 1:\n print(path, result)\n result.append(path)\n print(result)\n return \n \n for i in range(start, remain):\n if i > int(remain / i):\n break\n if remain % i == 0:\n path.append(i)\n dfs(i, int(remain/i))\n path.pop()\n \n path.append(remain)\n dfs(remain, 1)\n path.pop()\n# print(result)\n \n result, path = [], []\n dfs(2, n)\n return result",
"_____no_output_____"
],
[
"c = Solution()",
"_____no_output_____"
],
[
"c.getFactors(8)",
"[2, 2, 2] []\n[[2, 2, 2]]\n[2, 4] [[2, 4]]\n[[2, 4], [2, 4]]\n"
],
[
"a = [[2, 2, 2]]\na.append([2,4])\na += [[1]]\na",
"_____no_output_____"
],
[
"# 思路:\n# • DFS:\n# – 扩展:枚举每一个位置的因子\n# • 每次从前一个枚举的因子start开始枚举,以保证枚举因子的顺序是从小到大\n# – 退出条件:n除以已枚举因子之后还剩的数remain = 1 时\n\n# • 用什么方法记录状态\n# – start、remain采用方法1 放到DFS函数的参数中\n# – 记录已枚举因子的数组path采用方法3 成员变量手动模拟栈\n\n\nclass Solution:\n \"\"\"\n @param: n: An integer\n @return: a list of combination\n \"\"\"\n def getFactors(self, n):\n # write your code here\n def dfs(start, remain):\n if remain == 1:\n if len(path) > 1:\n result.append(path[:])\n return\n \n for i in range(start, int(remain**0.5) + 1):\n if remain % i == 0:\n path.append(i)\n dfs(i, remain/i)\n path.pop()\n \n path.append(remain)\n dfs(start, 1)\n path.pop()\n \n path, result = [], []\n dfs(2, n)\n return result",
"_____no_output_____"
]
],
[
[
"#### Word Squares\n\nhttps://leetcode.com/problems/word-squares/description/",
"_____no_output_____"
]
],
[
[
"alist = ['a1', 'a2', 'a3']\nblist = ['b1', 'b2', 'b3']\n\nfor i, (a, b) in enumerate(zip(alist, blist)):\n print(i, a, b)",
"0 a1 b1\n1 a2 b2\n2 a3 b3\n"
],
[
"class Solution(object):\n def wordSquares(self, words):\n \"\"\"\n :type words: List[str]\n :rtype: List[List[str]]\n \"\"\"\n n, res = len(words[0]), []\n starts = collections.defaultdict(list)\n for i in range(1, n):\n for word in words:\n starts[word[:i]].append(word)\n \n def dfs(square):\n k = len(square)\n if k == n:\n res.append(square)\n return\n start = ''\n for i in range(k):\n start += square[i][k]\n for word in starts[start]:\n dfs(square + [word])\n \n for word in words:\n dfs([word])\n \n return res",
"_____no_output_____"
]
],
[
[
"#### Expression Add Operators\n\nhttps://leetcode.com/problems/expression-add-operators/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def addOperators(self, num, target):\n \"\"\"\n :type num: str\n :type target: int\n :rtype: List[str]\n \"\"\"\n n, res = len(num), []\n def dfs(left, temp, cur, last):\n if len(left) == 0:\n if cur == target:\n res.append(temp[:])\n return\n \n for i in range(1, len(left)+1):\n val = left[:i]\n if i == 1 or (i > 1 and left[0] != '0'):\n dfs(left[i:], temp + '+' + val, cur + int(val), int(val))\n dfs(left[i:], temp + '-' + val, cur - int(val), -int(val))\n dfs(left[i:], temp + '*' + val, cur -last + last*int(val), last*int(val))\n \n for i in range(1, n+1):\n if i == 1 or (i > 1 and num[0] != '0'):\n dfs(num[i:], num[:i], int(num[:i]), int(num[:i]))\n \n return res\n ",
"_____no_output_____"
]
],
[
[
"# Lecture 6: Math, Computational Graphic, Bit Operation ",
"_____no_output_____"
],
[
"### Search a 2D Matrix (Binary search!!!)\n\nhttps://leetcode.com/problems/search-a-2d-matrix/description/",
"_____no_output_____"
]
],
[
[
"# binary search template\nwhile start + 1 < end:\n mid = start + (end - start) / 2\n if ....",
"_____no_output_____"
],
[
"class Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if len(matrix) == 0 or len(matrix[0]) == 0:\n return False\n m, n = len(matrix), len(matrix[0])\n start, end = 0, m*n - 1\n while start + 1 < end:\n mid = start + (end - start) / 2\n i = mid / n\n j = mid % n\n if matrix[i][j] == target:\n return True\n elif matrix[i][j] > target:\n end = mid - 1\n else:\n start = mid + 1\n \n i = start / n\n j = start % n\n if matrix[i][j] == target:\n return True\n \n i = end / n\n j = end % n\n if matrix[i][j] == target:\n return True\n \n return False",
"_____no_output_____"
]
],
[
[
"### Search a 2D Matrix II\n\nhttps://leetcode.com/problems/search-a-2d-matrix-ii/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if len(matrix) == 0 or len(matrix[0]) == 0:\n return False\n \n m, n = len(matrix), len(matrix[0])\n r, c = 0, n-1\n while r < m and c >= 0:\n if matrix[r][c] == target:\n return True\n elif matrix[r][c] > target:\n c -= 1\n else:\n r += 1\n \n return False",
"_____no_output_____"
]
],
[
[
"### Rotate Image\n\nhttps://leetcode.com/problems/rotate-image/description/",
"_____no_output_____"
]
],
[
[
"for i in range(-1):\n print(i)",
"_____no_output_____"
],
[
"class Solution(object):\n def rotate(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n :rtype: void Do not return anything, modify matrix in-place instead.\n \"\"\"\n m, n = len(matrix), len(matrix[0])\n for i in range(m):\n for j in range(i):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n \n for i in range(m):\n for j in range(n/2):\n matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j]\n",
"_____no_output_____"
]
],
[
[
"### Sparse Matrix Multiplication\n\nhttps://leetcode.com/problems/sparse-matrix-multiplication/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def multiply(self, A, B):\n \"\"\"\n :type A: List[List[int]]\n :type B: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n \n m, n, l = len(A), len(B), len(B[0])\n dicA, dicB = {}, {}\n for i in range(m):\n for j in range(n):\n if A[i][j] != 0:\n dicA[i] = dicA.get(i, []) + [(j, A[i][j])]\n \n for i in range(n):\n for j in range(l):\n if B[i][j] != 0:\n dicB[i] = dicB.get(i, []) + [(j, B[i][j])]\n \n C = [[0 for j in range(l)] for i in range(m)]\n \n for i in dicA:\n for a in dicA[i]:\n j = a[0]\n if j in dicB:\n for b in dicB[j]:\n k = b[0]\n C[i][k] += a[1]*b[1]\n return C\n \n \n# # faster \n# m, n, l = len(A), len(B), len(B[0])\n# C = [[0 for j in range(l)] for i in range(m)]\n \n# for i in range(m):\n# for j in range(n):\n# if A[i][j] != 0:\n# for k in range(l):\n# C[i][k] += A[i][j]*B[j][k]\n# return C\n ",
"_____no_output_____"
]
],
[
[
"## Bit operation",
"_____no_output_____"
],
[
"#### Big Integer Addition \n\nhttp://www.lintcode.com/zh-cn/problem/big-integer-addition/\n\nhttps://leetcode.com/problems/add-strings/description/\n\n* ord(num1[i]) - ord('0') is faster than int(num1[i])\n\n* do not forget i -= 1",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def addStrings(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n i, j = len(num1) - 1, len(num2) - 1\n carry, res = 0, ''\n while i >= 0 or j >= 0:\n if i >= 0:\n carry += ord(num1[i]) - ord('0')\n i -= 1\n if j >= 0:\n carry += ord(num2[j]) - ord('0')\n j -= 1\n res = str(carry % 10) + res\n carry /= 10\n \n return res if carry == 0 else str(carry) + res\n ",
"_____no_output_____"
]
],
[
[
"#### Add Binary\n\nhttps://leetcode.com/problems/add-binary/description/",
"_____no_output_____"
]
],
[
[
"class Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n i, j = len(a) - 1, len(b) - 1\n res, carry = '', 0\n while i >= 0 or j >= 0:\n if i >= 0:\n if a[i] == '1':\n carry += 1\n i -= 1\n if j >= 0:\n if b[j] == '1':\n carry += 1\n j -= 1\n res = str(carry % 2) + res\n carry /= 2\n return res if carry == 0 else '1' + res\n ",
"_____no_output_____"
]
],
[
[
"#### Add Two Numbers\n\nhttp://www.lintcode.com/en/problem/add-two-numbers/\n\nhttps://leetcode.com/problems/add-two-numbers/description/",
"_____no_output_____"
]
],
[
[
"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n p = dummy\n carry = 0\n while True:\n if l1 is not None:\n carry += l1.val\n l1 = l1.next\n if l2 is not None:\n carry += l2.val\n l2 = l2.next\n p.val = carry % 10\n carry /= 10\n if l1 is not None or l2 is not None or carry != 0:\n temp = ListNode(0)\n p.next = temp\n p = p.next\n else:\n break\n \n return dummy",
"_____no_output_____"
]
],
[
[
"#### Add Two Numbers¶ II\n\nhttps://leetcode.com/problems/add-two-numbers-ii/description/\n\n* stack\n\n* reverse a linked list !!!",
"_____no_output_____"
]
],
[
[
"a = [1,2,3]",
"_____no_output_____"
],
[
"a.pop()",
"_____no_output_____"
],
[
"a",
"_____no_output_____"
],
[
"a.pop(0)",
"_____no_output_____"
],
[
"a.pop()",
"_____no_output_____"
],
[
"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n nums1, nums2 = [], []\n while l1 is not None:\n nums1.append(l1.val)\n l1 = l1.next\n while l2 is not None:\n nums2.append(l2.val)\n l2 = l2.next\n \n res = ListNode(0)\n carry = 0\n while len(nums1) > 0 or len(nums2) > 0:\n if len(nums1) > 0:\n carry += nums1.pop()\n if len(nums2) > 0:\n carry += nums2.pop()\n res.val = carry % 10\n carry /= 10\n p = ListNode(carry)\n p.next = res\n res = p\n return res if res.val != 0 else res.next\n ",
"_____no_output_____"
],
[
"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n l1 = self.reverseList(l1)\n l2 = self.reverseList(l2)\n dummy = ListNode(0)\n p = dummy\n carry = 0\n while True:\n if l1 is not None:\n carry += l1.val\n l1 = l1.next\n if l2 is not None:\n carry += l2.val\n l2 = l2.next\n p.val = carry % 10\n carry /= 10\n if l1 is not None or l2 is not None or carry != 0:\n p.next = ListNode(0)\n p = p.next\n else:\n break\n return self.reverseList(dummy)\n \n \n \n def reverseList(self, l):\n prev = None\n while l:\n curr = l\n l = l.next\n curr.next = prev\n prev = curr\n return prev\n ",
"_____no_output_____"
]
],
[
[
"#### Big Integer multiplication\n\nhttp://www.lintcode.com/en/problem/big-integer-multiplication/\n\nhttps://leetcode.com/problems/multiply-strings/description/",
"_____no_output_____"
]
],
[
[
"'0'*0",
"_____no_output_____"
],
[
"class Solution(object):\n def multiply(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n len1, len2 = len(num1), len(num2)\n num3 = [0] * (len1 + len2)\n for i in range(len1-1, -1, -1):\n carry = 0\n for j in range(len2-1, -1, -1):\n product = num3[i + j + 1] + carry + (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0'))\n num3[i + j + 1] = product % 10\n carry = product / 10\n num3[i] = carry\n \n res = ''\n i = 0\n while i < len1 + len2 - 1 and num3[i] == 0:\n i += 1\n while i < len1 + len2:\n res += str(num3[i])\n i += 1\n return res\n \n \n ",
"_____no_output_____"
]
],
[
[
"### Pow(x, n)\n\nhttps://leetcode.com/problems/powx-n/description/",
"_____no_output_____"
]
],
[
[
"n = -3\n-n",
"_____no_output_____"
],
[
"class Solution(object):\n def myPow(self, x, n):\n \"\"\"\n :type x: float\n :type n: int\n :rtype: float\n \"\"\"\n if n == 0:\n return 1\n if n < 0:\n x = 1.0 / x\n n = -n\n \n res = 1\n temp = x\n while n != 0:\n if n % 2 == 1:\n res *= temp\n temp *= temp\n n /= 2\n \n return res\n ",
"_____no_output_____"
]
],
[
[
"### Reverse Linked List\n\nhttps://leetcode.com/problems/reverse-linked-list/description/\n\n* do not mass up the order !!!",
"_____no_output_____"
]
],
[
[
"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reverseList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n prev = None\n while head is not None:\n curr = head\n head = head.next # do not mass up the order !!!\n curr.next = prev\n prev = curr\n return prev\n ",
"_____no_output_____"
]
],
[
[
"### Reverse Linked List II\n\nhttps://leetcode.com/problems/reverse-linked-list-ii/description/",
"_____no_output_____"
]
],
[
[
"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def reverseBetween(self, head, m, n):\n \"\"\"\n :type head: ListNode\n :type m: int\n :type n: int\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n dummy.next = head\n mth_prev = self.find_kth(dummy, m-1)\n mth = mth_prev.next\n nth = self.find_kth(dummy, n)\n nth_next = nth.next\n nth.next = None\n self.reverse(mth)\n \n mth_prev.next = nth\n mth.next = nth_next\n return dummy.next\n\n \n def reverse(self, head):\n prev = None\n while head is not None:\n curr = head\n head = head.next\n curr.next = prev\n prev = curr\n return prev\n \n def find_kth(self, head, k):\n for i in range(k):\n if head is None:\n return None\n head = head.next\n return head\n ",
"_____no_output_____"
]
],
[
[
"### Remove Nth Node From End of List\n\nhttps://leetcode.com/problems/remove-nth-node-from-end-of-list/description/",
"_____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"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
]
] |
cbb3d6633c8f59d2cbbedac663f76821066ba6ae
| 73,816 |
ipynb
|
Jupyter Notebook
|
test/Test_Run4.ipynb
|
mack-the-psych/vdok3
|
f3ab898c1815d0d54822dbb18b82723a48fc71f7
|
[
"MIT"
] | null | null | null |
test/Test_Run4.ipynb
|
mack-the-psych/vdok3
|
f3ab898c1815d0d54822dbb18b82723a48fc71f7
|
[
"MIT"
] | null | null | null |
test/Test_Run4.ipynb
|
mack-the-psych/vdok3
|
f3ab898c1815d0d54822dbb18b82723a48fc71f7
|
[
"MIT"
] | null | null | null | 60.803954 | 12,299 | 0.529045 |
[
[
[
"'''\nPut a path file like \"vdok-custom.pth\" into any of your sys.path directories\n(e.g. C:\\Users\\macks\\Anaconda3\\Lib\\site-packages).\n\n# vdok-custom.pth ###############################\n\nC:\\Users\\macks\\Documents\\Research\\MELVA-S\\vdok3\\prep\nC:\\Users\\macks\\Documents\\Research\\MELVA-S\\vdok3\\extract\nC:\\Users\\macks\\Documents\\Research\\MELVA-S\\vdok3\\process\nC:\\Users\\macks\\Documents\\Research\\MELVA-S\\vdok3\\reorganize\nC:\\Users\\macks\\Documents\\Research\\MELVA-S\\vdok3\\train\n\n###################################################\n'''",
"_____no_output_____"
]
],
[
[
"data_dir = '../data/'\nsrc_file = 'Head4-Serialized-Def-ELVA.PILOT.POST-TEST.csv'\ndata_file = 'EN-QA-Head4-Serialized-Def-ELVA.PILOT.POST-TEST.csv'\ndef_file = 'Questin_ID_Definition.csv'\n\nfrom qa_serializer_lang_selector import qa_serializer_lang_selector\n\nq = qa_serializer_lang_selector(data_dir)\nq.serialize_record(src_file, r'Definition')\nq.select_lang([1], r'Definition').to_csv(data_dir + data_file, encoding= 'latin1')",
" Pre_Col_Name Content Student_Question_Index\n0 Definition-Question Inventor 2001-Inventor\n1 Definition-Answer To invent stuff 2001-Inventor\n Pre_Col_Name Content Student_Question_Index\n0 Definition-Question Hero 2001-Hero\n1 Definition-Answer Someone that saves a person 2001-Hero\n Pre_Col_Name Content Student_Question_Index\n0 Definition-Question Impossible 2001-Impossible\n1 Definition-Answer Something that is not possible 2001-Impossible\n Pre_Col_Name Content Student_Question_Index\n0 Definition-Question To erupt 2001-To erupt\n1 Definition-Answer When something explodes 2001-To erupt\n"
],
[
"def remove_non_extracted_stop_word(df_ac, stop_words):\n stop_words_buf = stop_words[:]\n for x in stop_words:\n if not df_ac.columns.isin([x]).any():\n print('Remove Stop Word: ', x)\n stop_words_buf.remove(x)\n return stop_words_buf",
"_____no_output_____"
],
[
"from basic_nlp import fex_basic_nlp\n\npipeline=['pos', 'lemma', 'synset', 'hype', 'hypo']\n\nbnlqd = fex_basic_nlp(data_file, data_dir)\nbnlqd.nlp_run(pipeline[0])\nbnlqd.nlp_run(pipeline[1])\nbnlqd.df_ac_lemma.to_csv(data_dir + 'Lemma-' + data_file, encoding= 'latin1')\nbnlqd.nlp_run(pipeline[2])\nbnlqd.df_ac_synset.to_csv(data_dir + 'Synset-' + data_file , encoding= 'latin1')\nbnlqd.nlp_run(pipeline[3])\nbnlqd.df_ac_hypernyms.to_csv(data_dir + 'Hypernyms-' + data_file, encoding= 'latin1')\nbnlqd.nlp_run(pipeline[4])\nbnlqd.df_ac_hyponyms.to_csv(data_dir + 'Hyponyms-' + data_file, encoding= 'latin1')\n\nbnlpd = fex_basic_nlp(def_file, data_dir, 'Definition')\nbnlpd.nlp_run(pipeline[0])\nbnlpd.df_ac_pos.to_csv(data_dir + 'POS-P-' + data_file, encoding= 'latin1')\nbnlpd.nlp_run(pipeline[1])\nbnlpd.df_ac_lemma.to_csv(data_dir + 'Lemma-P-' + data_file, encoding= 'latin1')",
"[('Inventor', 'NN')]\n[('To', 'TO'), ('invent', 'VB'), ('stuff', 'NN')]\n[('Hero', 'NN')]\n[('Someone', 'NN'), ('that', 'WDT'), ('saves', 'VBZ'), ('a', 'DT'), ('person', 'NN')]\n[('Impossible', 'JJ')]\n[('Something', 'VBG'), ('that', 'DT'), ('is', 'VBZ'), ('not', 'RB'), ('possible', 'JJ')]\n[('To', 'TO'), ('erupt', 'VB')]\n[('When', 'WRB'), ('something', 'NN'), ('explodes', 'NNS')]\ninventor\nto invent stuff\nhero\nsomeone that save a person\nimpossible\nsomething that be not possible\nto erupt\nwhen something explode\ninventor inventor discoverer artificer\nto invent stuff invent contrive devise excogitate formulate forge fabricate manufacture cook_up make_up invent material stuff stuff stuff clobber stuff stuff_and_nonsense hooey poppycock stuff stuff stuff stuff thrust stuff shove squeeze stuff lug choke_up block gorge ingurgitate overindulge glut englut stuff engorge overgorge overeat gormandize gormandise gourmandize binge pig_out satiate scarf_out stuff stuff farce stuff\nhero hero hero champion fighter hero paladin Hero Heron Hero_of_Alexandria hero Hero bomber grinder hero hero_sandwich hoagie hoagy Cuban_sandwich Italian_sandwich poor_boy sub submarine submarine_sandwich torpedo wedge zep\nsomeone that save a person person individual someone somebody mortal soul save salvage salve relieve save save preserve save carry_through pull_through bring_through save save lay_aside save_up save make_unnecessary deliver redeem save spare save save economize economise keep_open hold_open keep save write save angstrom angstrom_unit A vitamin_A antiophthalmic_factor axerophthol A deoxyadenosine_monophosphate A adenine A ampere amp A A a A type_A group_A person individual someone somebody mortal soul person person\nimpossible impossible impossible impossible inconceivable out_of_the_question unimaginable impossible insufferable unacceptable unsufferable\nsomething that be not possible beryllium Be glucinium atomic_number_4 be be be exist be be equal be constitute represent make_up comprise be be follow embody be personify be be live be cost be not non possible possible possible potential possible\nto erupt erupt break_out erupt irrupt flare_up flare break_open burst_out erupt ignite catch_fire take_fire combust conflagrate erupt come_out break_through push_through erupt belch extravasate break burst erupt erupt erupt recrudesce break_out\nwhen something explode explode detonate blow_up set_off explode burst explode explode burst_forth break_loose explode explode explode explode detonate explode blow_up explode irrupt\ncreator\ncreate_by_mental_act create_mentally think_up think_of dream_up hatch concoct substance object physical_object personal_property personal_estate personalty private_property nonsense bunk nonsensicality meaninglessness hokum quality information info kernel substance core center centre essence gist heart heart_and_soul inwardness marrow meat nub pith sum nitty-gritty cram push force clog choke_off clog_up back_up congest choke foul eat impregnate saturate fill fill_up make_full fill fill_up make_full\nleader character role theatrical_role part persona defender guardian protector shielder mythical_being sandwich\ncausal_agent cause causal_agency organism being prevention bar rescue deliver keep hold_on prevent forestall foreclose preclude forbid refrain forbear spend expend drop reserve hold book record tape metric_linear_unit fat-soluble_vitamin nucleotide base purine current_unit letter letter_of_the_alphabet alphabetic_character blood_group blood_type causal_agent cause causal_agency organism being human_body physical_body material_body soma build figure physique anatomy shape bod chassis frame form flesh grammatical_category syntactic_category\nimpossibility impossible_action\nmetallic_element metal typify symbolize symbolise stand_for represent take occupy use_up stay remain rest be possibility possible_action opening applicant applier\nbegin start intensify deepen change_state turn appear explode burst express_emotion express_feelings appear trouble ail pain\nchange_integrity change_integrity react respond change_state turn destroy ruin pronounce articulate enounce sound_out enunciate say condemn disprove confute increase\npatentee\nconfabulate mythologize mythologise spin trump_up concoct vamp vamp_up abrasive abradant abrasive_material adhesive_material adhesive_agent adhesive aggregate ammunition animal_material atom molecule particle corpuscle mote speck ballast bedding_material bedding litter bimetal builder detergent_builder chemical chemical_substance coloring_material colouring_material color colour composite_material conductor contaminant contamination detritus diamagnet discharge emission dust earth ground elastomer fiber fibre filling fill floccule floc fluff foam HAZMAT homogenate humate impregnation insulator dielectric nonconductor mineral packing_material packing wadding paper particulate particulate_matter plant_material plant_substance precursor radioactive_material raw_material staple rind rock stone sealing_material sorbate sorbent sorbent_material thickening thickener toner transparent_substance translucent_substance undercut vernix vernix_caseosa wad waste waste_material waste_matter waste_product doodad doohickey doojigger gimmick gizmo gismo gubbins thingamabob thingumabob thingmabob thingamajig thingumajig thingmajig thingummy whatchamacallit whatchamacallum whatsis widget etcetera sundries jam jampack ram chock_up cram wad overstuff pad fill_out cork\n\nabator abjurer abomination abstainer abstinent nondrinker achiever winner success succeeder acquaintance friend acquirer active actor doer worker adjudicator admirer adoptee adult grownup adventurer venturer adversary antagonist opponent opposer resister advisee advocate advocator proponent exponent affiant African agnostic doubter amateur Amerindian Native_American ancient anomaly unusual_person anti-American anti applicant applier appointee appointment appreciator apprehender Aquarius Water_Bearer archaist Aries Ram arrogator assessee asthmatic authority autodidact baby_boomer boomer baby_buster buster bad_guy bad_person baldhead baldpate baldy balker baulker noncompliant bather beard bedfellow bereaved bereaved_person best topper birth biter Black Black_person blackamoor Negro Negroid blogger blond blonde bluecoat bodybuilder muscle_builder muscle-builder musclebuilder muscleman bomber brunet brunette bullfighter toreador buster Cancer Crab candidate prospect capitalist Capricorn Goat captor capturer case cashier celebrant celebrator celebrater censor chameleon changer modifier charmer beguiler child baby chutzpanik closer clumsy_person collector aggregator color-blind_person combatant battler belligerent fighter scrapper commoner common_man common_person communicator complexifier compulsive computer_user contemplative contestant convert copycat imitator emulator ape aper counter counterterrorist coward crawler creeper creator creature wight creditor cripple dancer social_dancer dead_person dead_soul deceased_person deceased decedent departed deaf_person debaser degrader debtor debitor defecator voider shitter delayer deliverer demander dieter differentiator discriminator disentangler unraveler unraveller disputant controversialist eristic dissenter dissident protester objector contestant divider domestic_partner significant_other spousal_equivalent spouse_equivalent double image look-alike dresser dribbler driveller slobberer drooler drug_user substance_abuser user dyslectic ectomorph effecter effector Elizabethan emotional_person endomorph engineer applied_scientist technologist enjoyer enrollee entertainer ethnic experimenter expert explorer adventurer extrovert extravert face faddist faller fastener female female_person fiduciary first-rater follower free_agent free_spirit freewheeler friend fugitive runaway fleer gainer weight_gainer gainer gambler gatekeeper gatherer Gemini Twin gentile good_guy good_person granter greeter saluter welcomer grinner groaner grunter guesser handicapped_person hater heterosexual heterosexual_person straight_person straight homosexual homophile homo gay homunculus hope hoper huddler hugger immune individualist inhabitant habitant dweller denizen indweller innocent inexperienced_person insured insured_person intellectual intellect interpreter introvert Jat Jew Hebrew Israelite jewel gem jumper junior juvenile juvenile_person killer slayer kink kneeler knocker knower apprehender large_person Latin laugher leader learner scholar assimilator left-hander lefty southpaw Leo Lion Libra Balance life lightning_rod linguist polyglot literate literate_person liver longer thirster yearner loose_cannon loved_one lover machine mailer malcontent male male_person man man_jack manipulator married masturbator onanist measurer mesomorph mestizo ladino middlebrow miracle_man miracle_worker misogamist mixed-blood modern money_handler money_dealer monolingual mother_hen mouse mutilator maimer mangler namer namesake national subject native indigen indigene aborigine aboriginal native neglecter neighbor neighbour neutral nondescript nonmember nonparticipant nonpartisan nonpartizan nonperson unperson nonreligious_person nonresident nonsmoker nonworker nude nude_person nurser occultist optimist orphan ostrich ouster ejector outcaste outdoorsman owner possessor pamperer spoiler coddler mollycoddler pansexual pardoner forgiver excuser partner party passer peer equal match compeer perceiver percipient observer beholder percher person_of_color person_of_colour personage personification perspirer sweater philosopher picker chooser selector Pisces Fish pisser urinator planner contriver deviser player posturer powderer precursor forerunner preserver primitive primitive_person propositus public_relations_person pursuer pussycat quarter quitter radical realist rectifier redhead redheader red-header carrottop registrant relative relation reliever allayer comforter religious_person repeater rescuer recoverer saver rester restrainer controller revenant rich_person wealthy_person have right-hander right_hander righthander riser romper roundhead ruler swayer rusher Sagittarius Archer scientist Scorpio Scorpion scratcher second-rater mediocrity seeder cloud_seeder seeker searcher quester segregate self sensualist sentimentalist romanticist sex_object sex_symbol shaker mover_and_shaker showman signer signatory simpleton simple six-footer skidder slider slipper Slav slave slave sleepyhead sloucher small_person smasher smiler sneezer sniffer sniffler sniveler snuffer snuffler socializer socialiser sort sounding_board sphinx spitter expectorator sport sprawler spurner squinter squint-eye stifler smotherer stigmatic stigmatist stooper stranger struggler subject case guinea_pig supernumerary surrenderer yielder survivalist survivor suspect tagger tagger tapper Taurus Bull tempter termer terror scourge threat testator testate thin_person skin_and_bones scrag third-rater thrower tiger totemist toucher transfer transferee transsexual transexual transvestite cross-dresser traveler traveller trier attempter essayer turner tyrant undoer opener unfastener untier unfortunate unfortunate_person unskilled_person unwelcome_person persona_non_grata user vanisher victim dupe Victorian Virgo Virgin visionary visually_impaired_person waiter waker walk-in wanter needer ward warrior watcher weakling doormat wuss weasel White White_person Caucasian wiggler wriggler squirmer winker withholder witness worker worldling yawner conserve husband economize economise record enter put_down rescue deliver scrimp stint skimp hoard stash cache lay_away hive_up squirrel_away favor favour tighten_one's_belt overwrite vitamin_A1 retinol vitamin_A2 dehydroretinol abator abjurer abomination abstainer abstinent nondrinker achiever winner success succeeder acquaintance friend acquirer active actor doer worker adjudicator admirer adoptee adult grownup adventurer venturer adversary antagonist opponent opposer resister advisee advocate advocator proponent exponent affiant African agnostic doubter amateur Amerindian Native_American ancient anomaly unusual_person anti-American anti applicant applier appointee appointment appreciator apprehender Aquarius Water_Bearer archaist Aries Ram arrogator assessee asthmatic authority autodidact baby_boomer boomer baby_buster buster bad_guy bad_person baldhead baldpate baldy balker baulker noncompliant bather beard bedfellow bereaved bereaved_person best topper birth biter Black Black_person blackamoor Negro Negroid blogger blond blonde bluecoat bodybuilder muscle_builder muscle-builder musclebuilder muscleman bomber brunet brunette bullfighter toreador buster Cancer Crab candidate prospect capitalist Capricorn Goat captor capturer case cashier celebrant celebrator celebrater censor chameleon changer modifier charmer beguiler child baby chutzpanik closer clumsy_person collector aggregator color-blind_person combatant battler belligerent fighter scrapper commoner common_man common_person communicator complexifier compulsive computer_user contemplative contestant convert copycat imitator emulator ape aper counter counterterrorist coward crawler creeper creator creature wight creditor cripple dancer social_dancer dead_person dead_soul deceased_person deceased decedent departed deaf_person debaser degrader debtor debitor defecator voider shitter delayer deliverer demander dieter differentiator discriminator disentangler unraveler unraveller disputant controversialist eristic dissenter dissident protester objector contestant divider domestic_partner significant_other spousal_equivalent spouse_equivalent double image look-alike dresser dribbler driveller slobberer drooler drug_user substance_abuser user dyslectic ectomorph effecter effector Elizabethan emotional_person endomorph engineer applied_scientist technologist enjoyer enrollee entertainer ethnic experimenter expert explorer adventurer extrovert extravert face faddist faller fastener female female_person fiduciary first-rater follower free_agent free_spirit freewheeler friend fugitive runaway fleer gainer weight_gainer gainer gambler gatekeeper gatherer Gemini Twin gentile good_guy good_person granter greeter saluter welcomer grinner groaner grunter guesser handicapped_person hater heterosexual heterosexual_person straight_person straight homosexual homophile homo gay homunculus hope hoper huddler hugger immune individualist inhabitant habitant dweller denizen indweller innocent inexperienced_person insured insured_person intellectual intellect interpreter introvert Jat Jew Hebrew Israelite jewel gem jumper junior juvenile juvenile_person killer slayer kink kneeler knocker knower apprehender large_person Latin laugher leader learner scholar assimilator left-hander lefty southpaw Leo Lion Libra Balance life lightning_rod linguist polyglot literate literate_person liver longer thirster yearner loose_cannon loved_one lover machine mailer malcontent male male_person man man_jack manipulator married masturbator onanist measurer mesomorph mestizo ladino middlebrow miracle_man miracle_worker misogamist mixed-blood modern money_handler money_dealer monolingual mother_hen mouse mutilator maimer mangler namer namesake national subject native indigen indigene aborigine aboriginal native neglecter neighbor neighbour neutral nondescript nonmember nonparticipant nonpartisan nonpartizan nonperson unperson nonreligious_person nonresident nonsmoker nonworker nude nude_person nurser occultist optimist orphan ostrich ouster ejector outcaste outdoorsman owner possessor pamperer spoiler coddler mollycoddler pansexual pardoner forgiver excuser partner party passer peer equal match compeer perceiver percipient observer beholder percher person_of_color person_of_colour personage personification perspirer sweater philosopher picker chooser selector Pisces Fish pisser urinator planner contriver deviser player posturer powderer precursor forerunner preserver primitive primitive_person propositus public_relations_person pursuer pussycat quarter quitter radical realist rectifier redhead redheader red-header carrottop registrant relative relation reliever allayer comforter religious_person repeater rescuer recoverer saver rester restrainer controller revenant rich_person wealthy_person have right-hander right_hander righthander riser romper roundhead ruler swayer rusher Sagittarius Archer scientist Scorpio Scorpion scratcher second-rater mediocrity seeder cloud_seeder seeker searcher quester segregate self sensualist sentimentalist romanticist sex_object sex_symbol shaker mover_and_shaker showman signer signatory simpleton simple six-footer skidder slider slipper Slav slave slave sleepyhead sloucher small_person smasher smiler sneezer sniffer sniffler sniveler snuffer snuffler socializer socialiser sort sounding_board sphinx spitter expectorator sport sprawler spurner squinter squint-eye stifler smotherer stigmatic stigmatist stooper stranger struggler subject case guinea_pig supernumerary surrenderer yielder survivalist survivor suspect tagger tagger tapper Taurus Bull tempter termer terror scourge threat testator testate thin_person skin_and_bones scrag third-rater thrower tiger totemist toucher transfer transferee transsexual transexual transvestite cross-dresser traveler traveller trier attempter essayer turner tyrant undoer opener unfastener untier unfortunate unfortunate_person unskilled_person unwelcome_person persona_non_grata user vanisher victim dupe Victorian Virgo Virgin visionary visually_impaired_person waiter waker walk-in wanter needer ward warrior watcher weakling doormat wuss weasel White White_person Caucasian wiggler wriggler squirmer winker withholder witness worker worldling yawner first_person second_person third_person\n\nabound accept take account account_for act answer appear seem bake broil balance be_well beat begin begin start belong belong belong belong breathe buy clean cohere come_in_for come_in_handy compact pack compare confuse throw fox befuddle fuddle bedevil confound discombobulate connect consist consist comprise contain contain take hold continue cost be count matter weigh count cover cut cut_across deck adorn decorate grace embellish beautify depend deserve merit disagree disaccord discord distribute diverge draw end terminate fall come fall feel figure enter fit gape yawn yaw go gravitate hail come hang head head_up hold hoodoo hum buzz seethe impend incarnate body_forth embody substantiate iridesce jumble mingle kill lend let_go lie litter loiter lounge footle lollygag loaf lallygag hang_around mess_about tarry linger lurk mill_about mill_around look appear seem look lubricate make make_sense add_up measure mope moon_around moon_about object osculate owe pay point press promise prove turn_out turn_up put_out rage range run rank rate recognize relate interrelate remain represent rest retard run go run_into encounter rut seem seethe boil sell sell sell shine shine sparkle scintillate coruscate specify define delineate delimit delimitate squat stagnate stagnate stand stand stand_by stick_by stick adhere stay remain rest stay stay_on continue remain stick stink subtend delimit suck suffer hurt suffer suit swim swim drown swing tend be_given lean incline run test total number add_up come amount translate transplant trim underlie want need require wash wind twist curve work attend go_to belong go center_on come cover continue extend extend poke_out reach_out face follow go lead inhabit lie lie rest occupy fill populate dwell live inhabit reach extend_to touch run go pass lead extend sit sit_around sit stand_back keep_one's_eyes_off keep_one's_distance keep_one's_hands_off stay_away straddle stretch stretch_along coexist come distribute dwell consist lie lie_in dwell inhabit endanger jeopardize jeopardise menace threaten imperil peril flow indwell kick_around knock_about kick_about preexist prevail hold obtain equate correspond match fit correspond check jibe gibe tally agree represent stand_for correspond translate compose fall_into fall_under form constitute make make present pose range straddle supplement cox vet body personify exemplify represent set_back knock_back put_back\nblow_out catch light_up dehisce\ndynamite fulminate crump erupt belch extravasate go_off\n[('A', 'DT'), ('person', 'NN'), ('who', 'WP'), ('creates', 'VBZ'), ('something', 'NN'), ('new', 'JJ'), ('that', 'WDT'), ('has', 'VBZ'), ('never', 'RB'), ('been', 'VBN'), ('made', 'VBN'), ('before', 'IN')]\n"
],
[
"from bi_trigram import bi_trigram\n\nbtgqd = bi_trigram(data_file, data_dir)\nbtgqd.nlp_run(r'bigram')\nbtgqd.nlp_run(r'trigram')",
"\n[('to', 'invent'), ('invent', 'stuff')]\n\n[('someone', 'that'), ('that', 'save'), ('save', 'a'), ('a', 'person')]\n\n[('something', 'that'), ('that', 'be'), ('be', 'not'), ('not', 'possible')]\n[('to', 'erupt')]\n[('when', 'something'), ('something', 'explode')]\n\n[('to', 'invent', 'stuff')]\n\n[('someone', 'that', 'save'), ('that', 'save', 'a'), ('save', 'a', 'person')]\n\n[('something', 'that', 'be'), ('that', 'be', 'not'), ('be', 'not', 'possible')]\n\n[('when', 'something', 'explode')]\n"
],
[
"from oanc_lemma_frequency import odi_oanc_lemma_frequency\n\nstop_words = ['a', 'be', 'to', 'and', 'or']\nstop_words_d = remove_non_extracted_stop_word(bnlqd.df_ac_lemma, stop_words)\n\noanc_shelve = r'../../plimac3/Resource/OANC/ANC-all-lemma-04262014.db'\noalqd = odi_oanc_lemma_frequency(data_file, oanc_shelve, None, data_dir, stop_words_d) \noalqd.oanc_lemma_frequency('Lemma-' + data_file, r'Student_Question_Index', r'Pre_Col_Name')",
"Remove Stop Word: and\nRemove Stop Word: or\nQuestion:2001-Inventor\nKNOWN: inventor\nTERM COUNT: 1\nKNOWN: invent\nKNOWN: stuff\nTERM COUNT: 2\nQuestion:2001-Hero\nKNOWN: hero\nTERM COUNT: 1\nKNOWN: person\nKNOWN: save\nKNOWN: someone\nKNOWN: that\nTERM COUNT: 4\nQuestion:2001-Impossible\nKNOWN: impossible\nTERM COUNT: 1\nKNOWN: not\nKNOWN: possible\nKNOWN: something\nKNOWN: that\nTERM COUNT: 4\nQuestion:2001-To erupt\nKNOWN: erupt\nTERM COUNT: 1\nKNOWN: explode\nKNOWN: something\nKNOWN: when\nTERM COUNT: 3\n"
],
[
"from overlapping import odi_overlapping\n\nstop_words_hy = ['be']\nstop_words_hy_d = remove_non_extracted_stop_word(bnlqd.df_ac_lemma, stop_words_hy)\n\novlqd = odi_overlapping(data_file, r'Questin_ID_Definition.csv', data_dir, stop_words_d)\novlqd.count_overlapping('Lemma-' + data_file, r'Student_Question_Index',\n r'Pre_Col_Name', r'Question_ID', r'Question_ID_Sec',\n 'Lemma-P-' + data_file, r'Question_ID', r'Question_ID_Sec')\novlqd.count_overlapping_synset('Synset-' + data_file)\novlqd.count_overlapping_hypernyms('Hypernyms-' + data_file, stop_words_hy_d)\novlqd.count_overlapping_hyponyms('Hyponyms-' + data_file, stop_words_hy_d)",
"Question:2001-Inventor\nPassage:QP14001\nQuestion:2001-Hero\nPassage:QP14002\nQuestion:2001-Impossible\nPassage:QP14003\nQuestion:2001-To erupt\nPassage:QP14004\nQuestion:2001-Inventor\nPassage:QP14001\nQuestion:2001-Hero\nPassage:QP14002\nQuestion:2001-Impossible\nPassage:QP14003\nQuestion:2001-To erupt\nPassage:QP14004\nQuestion:2001-Inventor\nPassage:QP14001\nQuestion:2001-Hero\nPassage:QP14002\nQuestion:2001-Impossible\nPassage:QP14003\nQuestion:2001-To erupt\nPassage:QP14004\nQuestion:2001-Inventor\nPassage:QP14001\nQuestion:2001-Hero\nPassage:QP14002\nQuestion:2001-Impossible\nPassage:QP14003\nQuestion:2001-To erupt\nPassage:QP14004\n"
],
[
"import pandas as pd\nimport ac_bi_trigram_pmi_distribution as gpmd\n\ndef bi_trigram_pmi_distribution(csv_file_pmi_sum_t, data_dir, num_clm_in_q, df_ac_gram, \n gram = r'bigram', pmi_frq_min = 2, decimal_places = 4):\n df_ac_pmi_sum_t = pd.read_csv(data_dir + csv_file_pmi_sum_t, encoding= 'latin1')\n if gram == r'bigram':\n sum_clm = 'Bigram_sum'\n else: sum_clm = 'Trigram_sum'\n \n df_ac_pmi_gram = df_ac_pmi_sum_t[df_ac_pmi_sum_t[sum_clm] >= pmi_frq_min]\n df_ac_pmi_dist_gram = gpmd.ac_bi_trigram_pmi_distribution(df_ac_gram,\n num_clm_in_q + 1, df_ac_pmi_gram, gram, decimal_places)\n return df_ac_pmi_dist_gram",
"_____no_output_____"
],
[
"df_ac_pmi_dist_bigram = bi_trigram_pmi_distribution('PMI-Sum-T-Bigram-Def-PRE.csv', data_dir, \n bnlqd.num_clm_in, btgqd.df_ac_bigram, r'bigram')\ndf_ac_pmi_dist_bigram",
"_____no_output_____"
],
[
"df_ac_pmi_dist_trigram = bi_trigram_pmi_distribution('PMI-Sum-T-Trigram-Def-PRE.csv', data_dir, \n bnlqd.num_clm_in, btgqd.df_ac_trigram, r'Trigram')\ndf_ac_pmi_dist_trigram",
"_____no_output_____"
],
[
"import numpy as np\nimport ac_aggregate_plim as agpl\nimport ac_aggregate_item_level_plim as agpi\n\ndef aggregate_plim(bnlqd, oalqd, ovlqd, df_ac_pmi_dist_bigram, df_ac_pmi_dist_trigram, bnlpd,\n specific_count_lemmas = None, stop_words_pos = None, \n task_name = 'Definition', decimal_places = 4):\n stem_identifier = task_name + '-Question'\n option_identifier = task_name + '-Answer'\n df_ac_lemma_buf = bnlqd.df_ac_lemma.copy()\n\n if specific_count_lemmas is not None:\n for x in specific_count_lemmas:\n if not bnlqd.df_ac_lemma.columns.isin([x]).any():\n df_ac_lemma_buf[x] = 0\n\n df_ac_oanc_lemma_freq = oalqd.df_ac_oanc_lemma_freq_q.drop([oalqd.question_id_clm,\n oalqd.stem_option_name_clm], axis=1)\n df_ac_overlapping_lemma = ovlqd.df_ac_overlapping_lemma.drop([oalqd.question_id_clm,\n oalqd.stem_option_name_clm], axis=1)\n df_ac_overlapping_synset = ovlqd.df_ac_overlapping_syn_lemma.drop([oalqd.question_id_clm,\n oalqd.stem_option_name_clm], axis=1)\n df_ac_overlapping_hyper = ovlqd.df_ac_overlapping_hyper_lemma.drop([oalqd.question_id_clm,\n oalqd.stem_option_name_clm], axis=1)\n df_ac_overlapping_hypo = ovlqd.df_ac_overlapping_hypo_lemma.drop([oalqd.question_id_clm,\n oalqd.stem_option_name_clm], axis=1)\n\n df_ac_pmi_dist_bigram = df_ac_pmi_dist_bigram.iloc[:, oalqd.num_clm_in_q:]\n df_ac_pmi_dist_bigram['Cntnt_Bigram'] = df_ac_pmi_dist_bigram['Cntnt_Bigram'].fillna('')\n df_ac_pmi_dist_bigram['PMI_Bigram_SD'] = df_ac_pmi_dist_bigram['PMI_Bigram_SD'].fillna(0.0)\n df_ac_pmi_dist_bigram = df_ac_pmi_dist_bigram.fillna(-10.0)\n\n df_ac_pmi_dist_trigram = df_ac_pmi_dist_trigram.iloc[:, oalqd.num_clm_in_q:]\n df_ac_pmi_dist_trigram['Cntnt_Trigram'] = df_ac_pmi_dist_trigram['Cntnt_Trigram'].fillna('')\n df_ac_pmi_dist_trigram['PMI_Trigram_SD'] = df_ac_pmi_dist_trigram['PMI_Trigram_SD'].fillna(0.0)\n df_ac_pmi_dist_trigram = df_ac_pmi_dist_trigram.fillna(-10.0)\n\n if specific_count_lemmas == None:\n df_ac_lemma = None\n else:\n df_ac_lemma = df_ac_lemma_buf\n \n df_ac_aggregate = agpl.ac_aggregate_plim(bnlqd.df_ac_pos, oalqd.num_clm_in_q + 1, \n df_ac_overlapping_lemma, df_ac_overlapping_synset, \n None, df_ac_oanc_lemma_freq, oalqd.stem_option_name_clm, stem_identifier,\n list(oalqd.df_ac_in_q.columns), stop_words_pos, df_ac_lemma,\n specific_count_lemmas, bnlpd.df_ac_pos, ovlqd.passage_name_clm_q,\n ovlqd.passage_sec_clm_q, ovlqd.passage_name_clm_p, ovlqd.passage_sec_clm_p,\n bnlpd.num_clm_in + 1, decimal_places,\n df_ac_overlapping_hyper, df_ac_overlapping_hypo,\n df_ac_bigram_pmi_distribution = df_ac_pmi_dist_bigram, \n df_ac_trigram_pmi_distribution = df_ac_pmi_dist_trigram)\n\n key_dummy = r'Key_Dummy'\n t = df_ac_aggregate.shape\n row_lgth = t[0]\n df_key_dummy = pd.DataFrame(np.empty((row_lgth, 1),\n dtype=object), df_ac_aggregate.index,\n [key_dummy])\n df_key_dummy = df_key_dummy.fillna(option_identifier)\n df_ac_aggregate[key_dummy] = df_key_dummy[key_dummy]\n\n return df_ac_aggregate\n\ndef aggregate_item_level_plim(df_ac_aggregate, task_name = 'Definition', cntnt_clm = 'Content', decimal_places = 4):\n stem_identifier = task_name + '-Question'\n df_ac_aggregate_item_level = agpi.ac_aggregate_item_level_plim(df_ac_aggregate,\n r'Key_Dummy', oalqd.stem_option_name_clm, stem_identifier, \n None, decimal_places, cntnt_clm)\n return df_ac_aggregate_item_level",
"_____no_output_____"
],
[
"task_name = 'Definition'\nstop_words_pos = None\nspecific_count_lemmas = [r'dk', r'nr']\n\ndf_ac_aggregate = aggregate_plim(bnlqd, oalqd, ovlqd, df_ac_pmi_dist_bigram, df_ac_pmi_dist_trigram,\n bnlpd, specific_count_lemmas, stop_words_pos, task_name)\ndf_ac_aggregate.to_csv(data_dir + 'Aggregate_EN-QA-Head4-Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1')\ndf_ac_aggregate_item_level = aggregate_item_level_plim(df_ac_aggregate, task_name)\ndf_ac_aggregate_item_level.to_csv(data_dir + 'Key-Stem-Passage-Aggregate_EN-QA-Head4-Serialized-Def-ELVA.PILOT.POST-TEST.csv', encoding= 'latin1')\n",
"_____no_output_____"
]
]
] |
[
"raw",
"code"
] |
[
[
"raw"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb3d981d037e7a0b977614cdeeb1d8a05346619
| 7,397 |
ipynb
|
Jupyter Notebook
|
related_code/3-basics/4_gpu.ipynb
|
harshgrovr/Graphs_Thesis
|
9ffd0d23c8f8b4bd53db9fd5b9bf5776666814e0
|
[
"Apache-2.0"
] | null | null | null |
related_code/3-basics/4_gpu.ipynb
|
harshgrovr/Graphs_Thesis
|
9ffd0d23c8f8b4bd53db9fd5b9bf5776666814e0
|
[
"Apache-2.0"
] | null | null | null |
related_code/3-basics/4_gpu.ipynb
|
harshgrovr/Graphs_Thesis
|
9ffd0d23c8f8b4bd53db9fd5b9bf5776666814e0
|
[
"Apache-2.0"
] | null | null | null | 26.99635 | 269 | 0.53035 |
[
[
[
"# Speedup Training Using GPUs\n\nIn this tutorial, you will learn:\n\n* How to copy graph and feature data to GPU.\n* Train a GNN model on GPU.",
"_____no_output_____"
]
],
[
[
"import dgl\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport itertools",
"_____no_output_____"
]
],
[
[
"## Copy graph and feature data to GPU\n\nWe first load the Zachery's Karate club graph and node labels as from the previous sessions.",
"_____no_output_____"
]
],
[
[
"from tutorial_utils import load_zachery\n\n# ----------- 0. load graph -------------- #\ng = load_zachery()\nprint(g)",
"_____no_output_____"
]
],
[
[
"Right now the graph and all its feature data are stored in CPU. Use the `to` API to copy them to another device.",
"_____no_output_____"
]
],
[
[
"print('Current device:', g.device)\ng = g.to('cuda:0')\nprint('New device:', g.device)",
"_____no_output_____"
]
],
[
[
"Verify that features are also copied to GPU.",
"_____no_output_____"
]
],
[
[
"print(g.ndata['club'].device)\nprint(g.ndata['club_onehot'].device)",
"_____no_output_____"
]
],
[
[
"## Create a GNN model on GPU\n\nThe step is the same as creating a CNN or RNN model on GPU. In PyTorch, one can use the `to` API to achieve so.",
"_____no_output_____"
]
],
[
[
"# ----------- 1. node features -------------- #\nnode_embed = nn.Embedding(g.number_of_nodes(), 5) # Every node has an embedding of size 5.\n# Copy node embeddings to GPU\nnode_embed = node_embed.to('cuda:0')\ninputs = node_embed.weight # Use the embedding weight as the node features.\nnn.init.xavier_uniform_(inputs)",
"_____no_output_____"
]
],
[
[
"The community label is stored in the `'club'` node feature (0 for instructor, 1 for club president). Only nodes 0 and 33 are labeled.",
"_____no_output_____"
]
],
[
[
"labels = g.ndata['club']\nlabeled_nodes = [0, 33]\nprint('Labels', labels[labeled_nodes])",
"_____no_output_____"
]
],
[
[
"### Define a GraphSAGE model\n\nOur model consists of two layers, each computes new node representations by aggregating neighbor information. The equations are:\n\n$$\nh_{\\mathcal{N}(v)}^k\\leftarrow \\text{AGGREGATE}_k\\{h_u^{k-1},\\forall u\\in\\mathcal{N}(v)\\}\n$$\n\n$$\nh_v^k\\leftarrow \\sigma\\left(W^k\\cdot \\text{CONCAT}(h_v^{k-1}, h_{\\mathcal{N}(v)}^k) \\right)\n$$\n\nDGL provides implementation of many popular neighbor aggregation modules. They all can be invoked easily with one line of codes. See the full list of supported [graph convolution modules](https://docs.dgl.ai/api/python/nn.pytorch.html#module-dgl.nn.pytorch.conv).",
"_____no_output_____"
]
],
[
[
"from dgl.nn import SAGEConv\n\n# ----------- 2. create model -------------- #\n# build a two-layer GraphSAGE model\nclass GraphSAGE(nn.Module):\n def __init__(self, in_feats, h_feats, num_classes):\n super(GraphSAGE, self).__init__()\n self.conv1 = SAGEConv(in_feats, h_feats, 'mean')\n self.conv2 = SAGEConv(h_feats, num_classes, 'mean')\n \n def forward(self, g, in_feat):\n h = self.conv1(g, in_feat)\n h = F.relu(h)\n h = self.conv2(g, h)\n return h\n \n# Create the model with given dimensions \n# input layer dimension: 5, node embeddings\n# hidden layer dimension: 16\n# output layer dimension: 2, the two classes, 0 and 1\nnet = GraphSAGE(5, 16, 2)",
"_____no_output_____"
]
],
[
[
"Copy the network to GPU",
"_____no_output_____"
]
],
[
[
"net = net.to('cuda:0')",
"_____no_output_____"
],
[
"# ----------- 3. set up loss and optimizer -------------- #\n# in this case, loss will in training loop\noptimizer = torch.optim.Adam(itertools.chain(net.parameters(), node_embed.parameters()), lr=0.01)\n\n# ----------- 4. training -------------------------------- #\nall_logits = []\nfor e in range(100):\n # forward\n logits = net(g, inputs)\n \n # compute loss\n logp = F.log_softmax(logits, 1)\n loss = F.nll_loss(logp[labeled_nodes], labels[labeled_nodes])\n \n # backward\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n all_logits.append(logits.detach())\n \n if e % 5 == 0:\n print('In epoch {}, loss: {}'.format(e, loss))",
"_____no_output_____"
],
[
"# ----------- 5. check results ------------------------ #\npred = torch.argmax(logits, axis=1)\nprint('Accuracy', (pred == labels).sum().item() / len(pred))",
"_____no_output_____"
]
],
[
[
"**What if the graph and its feature data cannot fit into one GPU memory?**\n\n* Instead of running a GNN on the full graph, run it on some sample subgraphs till converge.\n* Issue different samples to different GPUs to enjoy even more acceleration.\n* Partition the graph to multiple machines and train it distributedly.\n\nOur later sessions will cover each of these methods.",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
]
] |
cbb3d9e33b7d54beb5ca3a82f723a661640513f4
| 6,621 |
ipynb
|
Jupyter Notebook
|
notebooks/5-nasa-hdf5.ipynb
|
rsignell-usgs/pangeo-binder-test
|
49913ac9890de104a0ef2b7157473320528db632
|
[
"CC-BY-4.0"
] | null | null | null |
notebooks/5-nasa-hdf5.ipynb
|
rsignell-usgs/pangeo-binder-test
|
49913ac9890de104a0ef2b7157473320528db632
|
[
"CC-BY-4.0"
] | null | null | null |
notebooks/5-nasa-hdf5.ipynb
|
rsignell-usgs/pangeo-binder-test
|
49913ac9890de104a0ef2b7157473320528db632
|
[
"CC-BY-4.0"
] | null | null | null | 27.5875 | 184 | 0.537079 |
[
[
[
"# Load HDF5 data w/ xarray\n\nA lot of NASA data is stored in HDF5 format. One example is data from the Sentinel-1 radar mission, which will be similar to the upcoming NISAR mission.\n\nhttps://aria.jpl.nasa.gov/node/97\n\nThis notebook illustrates loading the data into xarray for analysis",
"_____no_output_____"
]
],
[
[
"import xarray as xr\nimport h5netcdf\nimport rasterio\nimport h5py\nimport gcsfs\nimport os",
"_____no_output_____"
],
[
"print(xr.__version__)\nprint(h5netcdf.__version__)\nprint(rasterio.__version__)\nprint(h5py.__version__)\nprint(gcsfs.__version__)",
"0.11.1+64.g612d390f.dirty\n0.6.2\n1.0.18\n2.9.0\n0.2.0\n"
],
[
"# Copied data from ASF to Google Storage bucket\nfs = gcsfs.GCSFileSystem()\nimages = fs.ls('pangeo-data/grfn-v2/137/')\nfileObj = fs.open('pangeo-data/grfn-v2/137/S1-GUNW-A-R-137-tops-20181129_20181123-020010-43220N_41518N-PP-e2c7-v2_0_0.nc')",
"_____no_output_____"
],
[
"# Option 1) Copy file locally and read w/ xarray\ngsPath = 'pangeo-data/grfn-v2/137/S1-GUNW-A-R-137-tops-20181129_20181123-020010-43220N_41518N-PP-e2c7-v2_0_0.nc'\nlocalPath = os.path.basename(gsPath)\n#fs.get(gsPath, localPath)",
"_____no_output_____"
],
[
"# Data arrays are stored in \"science group\"\n#da = xr.open_dataset(localPath, group='/science/grids/data', engine='h5netcdf')\n#da ",
"_____no_output_____"
],
[
"# Seems that h5py >2.9.0 can handle file-like-objects:\n# https://github.com/h5py/h5py/pull/1105\nh5 = h5py.File(fileObj, 'r')",
"_____no_output_____"
],
[
"# Works but slow from home wifi (likely due to issues w/ number of network requests required)\n# http://matthewrocklin.com/blog/work/2018/02/06/hdf-in-the-cloud\nprint(h5.attrs.keys())\nds = h5['science/grids/data']\nprint(ds.items())\nprint(ds['coherence'].chunks)",
"<KeysViewHDF5 ['product_type', 'Conventions', 'title', 'version', 'author', 'institution', 'source', 'references', 'ogr_geometry_field', 'ogr_layer_name', 'ogr_layer_type']>\nItemsViewHDF5(<HDF5 group \"/science/grids/data\" (7 members)>)\n(682, 1386)\n"
],
[
"# but, can we open this w/ xarray anyway? Yes! with modifications to xarray and h5netcdf\nds = xr.open_dataset(fileObj, group='/science/grids/data', engine='h5netcdf')\nds ",
"_____no_output_____"
],
[
"# Try as Dask array\nds = xr.open_dataset(fileObj, group='/science/grids/data', engine='h5netcdf',\n chunks=dict(latitude=682, longitude=1386))\nds ",
"_____no_output_____"
],
[
"ds['coherence'].plot.imshow()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb3ed637b1465b2f4a55a9a0e37ddb138344a76
| 216,585 |
ipynb
|
Jupyter Notebook
|
python/projects/football/basicFootball.ipynb
|
BharathC15/NielitChennai
|
c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7
|
[
"MIT"
] | null | null | null |
python/projects/football/basicFootball.ipynb
|
BharathC15/NielitChennai
|
c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7
|
[
"MIT"
] | null | null | null |
python/projects/football/basicFootball.ipynb
|
BharathC15/NielitChennai
|
c817aaf63b741eb7a8e4c1df16b5038a0b4f0df7
|
[
"MIT"
] | 1 |
2020-06-11T08:04:43.000Z
|
2020-06-11T08:04:43.000Z
| 237.483553 | 68,548 | 0.892065 |
[
[
[
"https://www.kaggle.com/martj42/international-football-results-from-1872-to-2017",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.style.use(\"seaborn-whitegrid\")\nsns.set_style(\"whitegrid\")",
"_____no_output_____"
],
[
"df=pd.read_csv(\"football.csv\",index_col=0,parse_dates=True)\ndf.tail()",
"_____no_output_____"
]
],
[
[
"# What are the TOP 10 Tournaments",
"_____no_output_____"
]
],
[
[
"df['tournament'].value_counts()[:10]",
"_____no_output_____"
],
[
"plt.figure(dpi=120)\nsns.barplot(y=df['tournament'].value_counts()[:10].index,\n x=df['tournament'].value_counts()[:10].values, palette=\"rainbow\", orient='h')\nplt.ylabel('Tournament name')\nplt.xlabel('Number of tournaments')\nplt.title(\"TOP 10 TOURNAMENTS\")\nplt.show()",
"_____no_output_____"
]
],
[
[
"# Combine Home and Away in to single dataframe",
"_____no_output_____"
]
],
[
[
"df.head()",
"_____no_output_____"
],
[
"df1=df[[\"home_team\",\"home_score\"]]\ndf1.columns=[\"team\",\"score\"]\ndf2=df[[\"away_team\",\"away_score\"]]\ndf2.columns=[\"team\",\"score\"]",
"_____no_output_____"
],
[
"teams=pd.concat([df1,df2],axis=0).reset_index()\nteams.head()",
"_____no_output_____"
]
],
[
[
"## Calculate Aggregate function to the dataframe",
"_____no_output_____"
]
],
[
[
"teams_info=teams.groupby('team')['score'].agg(['sum','count','mean']).reset_index()\n#teams_info.index=teams_info.team\n#teams_info.drop(columns=\"team\",inplace=True)\nteams_info.columns=[\"teamName\",\"totalScores\",\"totalMatches\",\"averageScore\"]\nteams_info.head()",
"_____no_output_____"
],
[
"teamtop10=teams_info.sort_values(by=\"averageScore\",ascending=False).head(10)\nteamtop10",
"_____no_output_____"
]
],
[
[
"# Display the top 10 in each aggregation",
"_____no_output_____"
]
],
[
[
"plt.figure(dpi=120)\nsns.barplot(x=\"teamName\", y=\"averageScore\", data=teamtop10, palette=\"Set1\")\nplt.xlabel('Team Name')\nplt.ylabel('Goal average per match')\nplt.title(\"TOP 10 OF GOAL AVERAGE PER MATCH\")\nplt.xticks(rotation=45)\nplt.show()",
"_____no_output_____"
],
[
"teamMost10=teams_info.sort_values(by=\"totalMatches\",ascending=False).head(10)\nteamMost10",
"_____no_output_____"
],
[
"plt.figure(dpi=120)\nsns.barplot(x=\"teamName\", y=\"totalMatches\", data=teamMost10, palette=\"Set2\")\nplt.xlabel('Team Name')\nplt.ylabel('No of Matches')\nplt.title(\"Most played Top 10 Teams\")\nplt.xticks(rotation=45)\nplt.show()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbb3fa2bd9f11ac27b49c7834aa9753e497796d4
| 401,418 |
ipynb
|
Jupyter Notebook
|
demos/embeddings/stellargraph-metapath2vec.ipynb
|
cdawei/stellargraph
|
53206a0bf133b47261d5f96f5325aa72ad424138
|
[
"Apache-2.0"
] | 1 |
2019-08-03T09:21:08.000Z
|
2019-08-03T09:21:08.000Z
|
demos/embeddings/stellargraph-metapath2vec.ipynb
|
cdawei/stellargraph
|
53206a0bf133b47261d5f96f5325aa72ad424138
|
[
"Apache-2.0"
] | null | null | null |
demos/embeddings/stellargraph-metapath2vec.ipynb
|
cdawei/stellargraph
|
53206a0bf133b47261d5f96f5325aa72ad424138
|
[
"Apache-2.0"
] | null | null | null | 1,324.811881 | 390,864 | 0.958218 |
[
[
[
"### Introduction\n\nAn example of implementing the Metapath2Vec representation learning algorithm using components from the `stellargraph` and `gensim` libraries.\n\n**References**\n\n**1.** Metapath2Vec: Scalable Representation Learning for Heterogeneous Networks. Yuxiao Dong, Nitesh V. Chawla, and Ananthram Swami. ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), 135–144, 2017. ([link](https://ericdongyx.github.io/papers/KDD17-dong-chawla-swami-metapath2vec.pdf))\n\n**2.** Distributed representations of words and phrases and their compositionality. T. Mikolov, I. Sutskever, K. Chen, G. S. Corrado, and J. Dean. In Advances in Neural Information Processing Systems (NIPS), pp. 3111-3119, 2013. ([link](https://papers.nips.cc/paper/5021-distributed-representations-of-words-and-phrases-and-their-compositionality.pdf))\n\n**3.** Gensim: Topic modelling for humans. ([link](https://radimrehurek.com/gensim/))\n\n**4.** Social Computing Data Repository at ASU [http://socialcomputing.asu.edu]. R. Zafarani and H. Liu. Tempe, AZ: Arizona State University, School of Computing, Informatics and Decision Systems Engineering. 2009.",
"_____no_output_____"
]
],
[
[
"import matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nimport os\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom stellargraph.data.loader import load_dataset_BlogCatalog3\n\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### Load the dataset\n\nThe dataset is the BlogCatalog3 network.\n\nIt can be downloaded from [here.](http://socialcomputing.asu.edu/datasets/BlogCatalog3)\n\nThe following is the description of the dataset from the publisher [4]:\n\n> This is the data set crawled from BlogCatalog ( http://www.blogcatalog.com ). BlogCatalog is a social blog directory website. This contains the friendship network crawled and group memberships. For easier understanding, all the contents are organized in CSV file format.\n\nThe statistics of this network are,\n\n- Number of bloggers : 10,312\n- Number of friendship pairs: 333,983\n- Number of groups: 39\n\nWe assume that the dataset file `BlogCatalog-dataset.zip` has been downloaded and unzipped in the directory,\n\n`~/data`\n\nand the data in `csv` format (the files `edges.csv`, `nodes.csv`, `groups.csv`, and `group-edges.csv` can be found in directory,\n\n`~/data/BlogCatalog-dataset/data/`",
"_____no_output_____"
]
],
[
[
"dataset_location = os.path.expanduser(\"~/data/BlogCatalog-dataset/data\")\ng_nx = load_dataset_BlogCatalog3(location=dataset_location)\nprint(\"Number of nodes {} and number of edges {} in graph.\".format(g_nx.number_of_nodes(), g_nx.number_of_edges()))",
"Number of nodes 10351 and number of edges 348459 in graph.\n"
]
],
[
[
"### The Metapath2Vec algorithm\n\nThe Metapath2Vec algorithm introduced in [1] is a 2-step representation learning algorithm. The two steps are:\n\n1. Use uniform random walks to generate sentences from a graph. A sentence is a list of node IDs. The set of all sentences makes a corpus. The random walk is driven by a metapath that defines the node type order by which the random walker explores the graph.\n\n2. The corpus is then used to learn an embedding vector for each node in the graph. Each node ID is considered a unique word/token in a dictionary that has size equal to the number of nodes in the graph. The Word2Vec algorithm [2] is used for calculating the embedding vectors.",
"_____no_output_____"
],
[
"## Corpus generation using random walks\n\nThe `stellargraph` library provides an implementation for uniform, first order, random walks as required by Metapath2Vec. The random walks have fixed maximum length and are controlled by the list of metapath schemas specified in parameter `metapaths`. \n\nA metapath schema defines the type of node that the random walker is allowed to transition to from its current location. In the `stellargraph` implementation of metapath-driven random walks, the metapath schemas are given as a list of node types under the assumption that the input graph is not a multi-graph, i.e., two nodes are only connected by one edge type.\n\nSee [1] for a detailed description of metapath schemas and metapth-driven random walks.\n\nFor the **BlogCatalog3** dataset we use the following 3 metapaths.\n\n- \"user\", \"group\", \"user\"\n- \"user\", \"group\", \"user\", \"user\"\n- \"user\", \"user\"\n\n",
"_____no_output_____"
]
],
[
[
"from stellargraph.data import UniformRandomMetaPathWalk\nfrom stellargraph import StellarGraph\n\n# Create the random walker\nrw = UniformRandomMetaPathWalk(StellarGraph(g_nx))\n\n# specify the metapath schemas as a list of lists of node types.\nmetapaths = [\n [\"user\", \"group\", \"user\"],\n [\"user\", \"group\", \"user\", \"user\"],\n [\"user\", \"user\"],\n]\n\nwalks = rw.run(nodes=list(g_nx.nodes()), # root nodes\n length=100, # maximum length of a random walk\n n=1, # number of random walks per root node \n metapaths=metapaths # the metapaths\n )\n\nprint(\"Number of random walks: {}\".format(len(walks)))",
"Number of random walks: 30936\n"
]
],
[
[
"### Representation Learning using Word2Vec\n\nWe use the Word2Vec [2] implementation in the free Python library gensim [3] to learn representations for each node in the graph.\n\nWe set the dimensionality of the learned embedding vectors to 128 as in [1].",
"_____no_output_____"
]
],
[
[
"from gensim.models import Word2Vec\n\nmodel = Word2Vec(walks, size=128, window=5, min_count=0, sg=1, workers=2, iter=1)",
"_____no_output_____"
],
[
"model.wv.vectors.shape # 128-dimensional vector for each node in the graph",
"_____no_output_____"
]
],
[
[
"### Visualise Node Embeddings\n\nWe retrieve the Word2Vec node embeddings that are 128-dimensional vectors and then we project them down to 2 dimensions using the [t-SNE](http://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html) algorithm.",
"_____no_output_____"
]
],
[
[
"# Retrieve node embeddings and corresponding subjects\nnode_ids = model.wv.index2word # list of node IDs\nnode_embeddings = model.wv.vectors # numpy.ndarray of size number of nodes times embeddings dimensionality\nnode_targets = [ g_nx.node[node_id]['label'] for node_id in node_ids]",
"_____no_output_____"
]
],
[
[
"Transform the embeddings to 2d space for visualisation",
"_____no_output_____"
]
],
[
[
"transform = TSNE #PCA\n\ntrans = transform(n_components=2)\nnode_embeddings_2d = trans.fit_transform(node_embeddings)",
"_____no_output_____"
],
[
"# draw the points\nlabel_map = { l: i for i, l in enumerate(np.unique(node_targets))}\nnode_colours = [ label_map[target] for target in node_targets]\n\nplt.figure(figsize=(20,16))\nplt.axes().set(aspect=\"equal\")\nplt.scatter(node_embeddings_2d[:,0], \n node_embeddings_2d[:,1], \n c=node_colours, alpha=0.3)\nplt.title('{} visualization of node embeddings'.format(transform.__name__))\nplt.show()",
"_____no_output_____"
]
],
[
[
"### Downstream task\n\nThe node embeddings calculated using Metapath2Vec can be used as feature vectors in a downstream task such as node attribute inference (e.g., inferring the gender or age attribute of 'user' nodes), community detection (e.g., clustering of 'user' nodes based on the similarity of their embedding vectors), and link prediction (e.g., prediction of friendship relation between 'user' nodes).",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cbb406dcb44bbd2ef75283827c17b1173e548370
| 11,388 |
ipynb
|
Jupyter Notebook
|
doc/steps_to_make/2001_0501_work_on_tree.ipynb
|
ggservice007/my-happy-flow
|
a334040939f04d4ba02d3107dc0f990d69c976c9
|
[
"Apache-2.0"
] | null | null | null |
doc/steps_to_make/2001_0501_work_on_tree.ipynb
|
ggservice007/my-happy-flow
|
a334040939f04d4ba02d3107dc0f990d69c976c9
|
[
"Apache-2.0"
] | 20 |
2021-01-18T02:53:55.000Z
|
2021-01-24T06:04:57.000Z
|
doc/steps_to_make/2001_0501_work_on_tree.ipynb
|
ggservice007/my-happy-flow
|
a334040939f04d4ba02d3107dc0f990d69c976c9
|
[
"Apache-2.0"
] | null | null | null | 27.843521 | 317 | 0.491307 |
[
[
[
"# work on the tree",
"_____no_output_____"
]
],
[
[
"%reload_ext autoreload\n%autoreload 2\n\nimport sys\nfrom pathlib import Path\n\nmy_happy_flow_path = str(Path('../../src').resolve())\nmy_lib_path = str(Path('my_lib').resolve())\n\nif my_lib_path not in sys.path:\n sys.path.append(my_lib_path)\n\n\nif my_happy_flow_path not in sys.path:\n sys.path.append(my_happy_flow_path)\n \n",
"_____no_output_____"
]
],
[
[
"## ast.NodeVisitor",
"_____no_output_____"
],
[
"ast.NodeVisitor is the primary tool for ‘scanning’ the tree. ",
"_____no_output_____"
]
],
[
[
"import ast\nimport inspect\n\nprint(inspect.getsource(ast.NodeVisitor))",
"class NodeVisitor(object):\n \"\"\"\n A node visitor base class that walks the abstract syntax tree and calls a\n visitor function for every node found. This function may return a value\n which is forwarded by the `visit` method.\n\n This class is meant to be subclassed, with the subclass adding visitor\n methods.\n\n Per default the visitor functions for the nodes are ``'visit_'`` +\n class name of the node. So a `TryFinally` node visit function would\n be `visit_TryFinally`. This behavior can be changed by overriding\n the `visit` method. If no visitor function exists for a node\n (return value `None`) the `generic_visit` visitor is used instead.\n\n Don't use the `NodeVisitor` if you want to apply changes to nodes during\n traversing. For this a special visitor exists (`NodeTransformer`) that\n allows modifications.\n \"\"\"\n\n def visit(self, node):\n \"\"\"Visit a node.\"\"\"\n method = 'visit_' + node.__class__.__name__\n visitor = getattr(self, method, self.generic_visit)\n return visitor(node)\n\n def generic_visit(self, node):\n \"\"\"Called if no explicit visitor function exists for a node.\"\"\"\n for field, value in iter_fields(node):\n if isinstance(value, list):\n for item in value:\n if isinstance(item, AST):\n self.visit(item)\n elif isinstance(value, AST):\n self.visit(value)\n\n"
]
],
[
[
"To use it, subclass it and override methods visit_Foo, corresponding to the node classes. (see [Meet the Nodes](https://greentreesnakes.readthedocs.io/en/latest/nodes.html)).\n\nFor example, this visitor will print the names of any functions defined in the given code, including methods and functions defined within other functions:",
"_____no_output_____"
]
],
[
[
"import ast\nclass FuncLister(ast.NodeVisitor):\n def visit_FunctionDef(self, node):\n print('func_name: ', node.name)\n self.generic_visit(node)",
"_____no_output_____"
],
[
"source_code = \"\"\"\ndef a():\n print('i am a')\n \ndef b():\n print('call a')\n a()\n def c():\n print('i am c function')\n \nb()\n\"\"\".strip()\nFuncLister().visit(ast.parse(source_code))",
"func_name: a\nfunc_name: b\nfunc_name: c\n"
]
],
[
[
"If you want child nodes to be visited, remember to call self.generic_visit(node) in the methods you override.",
"_____no_output_____"
],
[
"Alternatively, you can run through a list of all the nodes in the tree using ast.walk(). There are no guarantees about the order in which nodes will appear. The following example again prints the names of any functions defined within the given code:",
"_____no_output_____"
]
],
[
[
"import ast\n\nsource_code = \"\"\"\ndef a():\n print('i am a')\n \ndef b():\n print('call a')\n a()\n def c():\n print('i am c function')\n \nb()\n\"\"\".strip()\n\ntree = ast.parse(source_code)\nfor node in ast.walk(tree):\n if isinstance(node, ast.FunctionDef):\n print('func_name: ', node.name)",
"func_name: a\nfunc_name: b\nfunc_name: c\n"
]
],
[
[
"You can also get the direct children of a node, using ast.iter_child_nodes(). Remember that many nodes have children in several sections: for example, an If has a node in the test field, and list of nodes in body and orelse. ast.iter_child_nodes() will go through all of these.\n\nFinally, you can navigate directly, using the attributes of the nodes. For example, if you want to get the last node within a function’s body, use node.body\\[-1\\]. Of course, all the normal Python tools for iterating and indexing work. In particular, isinstance() is very useful for checking what nodes are.\n",
"_____no_output_____"
],
[
"## Inspecting nodes",
"_____no_output_____"
],
[
"The ast module has a couple of functions for inspecting nodes:\n\n$\\large{🍞}$ ast.iter_fields() iterates over the fields defined for a node.\n\n$\\large{🍞}$ ast.get_docstring() gets the docstring of a FunctionDef, ClassDef or Module node.\n\n$\\large{🍞}$ ast.dump() returns a string showing the node and any children. \n",
"_____no_output_____"
],
[
"## Modifying the tree",
"_____no_output_____"
],
[
"The key tool is ast.NodeTransformer. Like ast.NodeVisitor, you subclass this and override visit_Foo methods. The method should return the original node, a replacement node, or None to remove that node from the tree.\n\nThe ast module docs have this example, which rewrites name lookups, so foo becomes data\\['foo'\\]:\n",
"_____no_output_____"
]
],
[
[
"import ast\n\nclass RewriteName(ast.NodeTransformer):\n def visit_Name(slef, node):\n return ast.copy_location(ast.Subscript(\n value=ast.Name(id='data', ctx=ast.Load()),\n slice=ast.Index(value=ast.Str(s=node.id)),\n ctx=node.ctx\n ), node)\n ",
"_____no_output_____"
],
[
"from __future__ import unicode_literals\n\nimport ast\nimport ast_utils\nfrom ast_utils import print_utils\nimport ujson\n\ntree = ast.parse(\"foo\")\nprint(ast_utils.dump(tree))\n\nprint_utils.print_separator()\n\nprint(ast_utils.dump_json(tree))\n\nnew_tree = ast.fix_missing_locations(RewriteName().visit(tree))\n\nprint_utils.print_separator()\n\nprint(ast_utils.unparse(new_tree))\n\nprint_utils.print_separator()\n\nprint(ast_utils.dump_json(new_tree))",
"Module(body=[Expr(value=Name(\n id='foo',\n ctx=Load()))])\n\n================================================================================\n\n{\n \"_PyType\": \"Module\",\n \"body\": [\n {\n \"_PyType\": \"Expr\",\n \"value\": {\n \"_PyType\": \"Name\",\n \"id\": \"foo\",\n \"ctx\": {\n \"_PyType\": \"Load\"\n }\n }\n }\n ]\n}\n\n================================================================================\n\n\ndata['foo']\n\n\n================================================================================\n\n{\n \"_PyType\": \"Module\",\n \"body\": [\n {\n \"_PyType\": \"Expr\",\n \"value\": {\n \"_PyType\": \"Subscript\",\n \"value\": {\n \"_PyType\": \"Name\",\n \"id\": \"data\",\n \"ctx\": {\n \"_PyType\": \"Load\"\n }\n },\n \"slice\": {\n \"_PyType\": \"Index\",\n \"value\": {\n \"_PyType\": \"Str\",\n \"s\": \"foo\"\n }\n },\n \"ctx\": {\n \"_PyType\": \"Load\"\n }\n }\n }\n ]\n}\n"
]
],
[
[
"Be careful when removing nodes. You can quite easily remove a node from a required field, such as the test field of an If node. Python won’t complain about the invalid AST until you try to compile() it, when a TypeError is raised.\n\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cbb40960c181fb9f94e1facedd37a3f9d2c29af4
| 82,724 |
ipynb
|
Jupyter Notebook
|
examples/Phenotyping Survival Data.ipynb
|
vedant-sanil/auton-survival
|
3e6c5ffed1dfe30d6edcfc57a952fce23455e585
|
[
"MIT"
] | null | null | null |
examples/Phenotyping Survival Data.ipynb
|
vedant-sanil/auton-survival
|
3e6c5ffed1dfe30d6edcfc57a952fce23455e585
|
[
"MIT"
] | null | null | null |
examples/Phenotyping Survival Data.ipynb
|
vedant-sanil/auton-survival
|
3e6c5ffed1dfe30d6edcfc57a952fce23455e585
|
[
"MIT"
] | null | null | null | 504.414634 | 76,962 | 0.940428 |
[
[
[
"import sys\n\nsys.path.append('../')\nfrom auton_survival import datasets\noutcomes, features = datasets.load_support()",
"_____no_output_____"
],
[
"import numpy as np\nhorizons = [0.25, 0.5, 0.75]\ntimes = np.quantile(outcomes.time[outcomes.event==1], horizons).tolist()",
"_____no_output_____"
],
[
"from auton_survival.phenotyping import IntersectionalPhenotyper",
"_____no_output_____"
],
[
"phenotypes = IntersectionalPhenotyper(cat_vars=['race'], num_vars=['age']).fit_phenotype(features)",
"/Users/chiragn/Research/auton-survival/examples/../auton_survival/phenotyping.py:79: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n features[num_var][features[num_var]>=var_max] = var_max\n/Users/chiragn/Research/auton-survival/examples/../auton_survival/phenotyping.py:80: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n features[num_var][features[num_var]<=var_min] = var_min\n"
],
[
"from auton_survival import reporting\n\nreporting.plot_kaplanmeier(outcomes, phenotypes)",
"_____no_output_____"
],
[
"from auton_survival.preprocessing import Preprocessor\n\ncat_feats = ['sex', 'dzgroup', 'dzclass', 'income', 'race', 'ca']\nnum_feats = ['age', 'num.co', 'meanbp', 'wblc', 'hrt', 'resp', \n\t 'temp', 'pafi', 'alb', 'bili', 'crea', 'sod', 'ph', \n 'glucose', 'bun', 'urine', 'adlp', 'adls']\n\nfeatures_processed = Preprocessor().fit_transform(features, cat_feats=cat_feats, num_feats=num_feats)",
"_____no_output_____"
],
[
"from auton_survival.phenotyping import ClusteringPhenotyper\n\nphenotypes = ClusteringPhenotyper(n_clusters=3, dim_red_method='pca', n_components=8).fit_phenotype(features_processed)\n\nreporting.plot_kaplanmeier(outcomes, phenotypes.argmax(axis=1))",
"Fitting the following Dimensionality Reduction Model:\n PCA(n_components=8)\nFitting the following Clustering Model:\n KMeans(n_clusters=3)\n"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb40ae2ee9643bf1cc79db86f69140feb423cd2
| 6,769 |
ipynb
|
Jupyter Notebook
|
Complete-Python-3-Bootcamp-master/02-Python Statements/07-Statements Assessment Test.ipynb
|
Larkinnjm1/UDEMY_Python_Megacourse
|
a8fd42e0ee69b0999c7679849bcab48b311f54e3
|
[
"MIT"
] | null | null | null |
Complete-Python-3-Bootcamp-master/02-Python Statements/07-Statements Assessment Test.ipynb
|
Larkinnjm1/UDEMY_Python_Megacourse
|
a8fd42e0ee69b0999c7679849bcab48b311f54e3
|
[
"MIT"
] | null | null | null |
Complete-Python-3-Bootcamp-master/02-Python Statements/07-Statements Assessment Test.ipynb
|
Larkinnjm1/UDEMY_Python_Megacourse
|
a8fd42e0ee69b0999c7679849bcab48b311f54e3
|
[
"MIT"
] | null | null | null | 18.196237 | 251 | 0.419855 |
[
[
[
"# Statements Assessment Test\nLet's test your knowledge!",
"_____no_output_____"
],
[
"_____\n**Use <code>for</code>, .split(), and <code>if</code> to create a Statement that will print out words that start with 's':**",
"_____no_output_____"
]
],
[
[
"st = 'Print only the words that start with s in this sentence'\n",
"_____no_output_____"
],
[
"#Code here\n\n\n\nfor b in st.split():\n if b[0].lower()=='s' and len(b)>1:\n print(b)\n ",
"start\nsentence\n"
]
],
[
[
"______\n**Use range() to print all the even numbers from 0 to 10.**",
"_____no_output_____"
]
],
[
[
"#Code Here\nfor num in range(0,11,2):\n print(num)\n",
"0\n2\n4\n6\n8\n10\n"
]
],
[
[
"___\n**Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.**",
"_____no_output_____"
]
],
[
[
"#Code in this cell\nx = [n for n in range(1,51) if n%3==0]\nx",
"_____no_output_____"
]
],
[
[
"_____\n**Go through the string below and if the length of a word is even print \"even!\"**",
"_____no_output_____"
]
],
[
[
"st = 'Print every word in this sentence that has an even number of letters'",
"_____no_output_____"
],
[
"#Code in this cell\n\n\n\n\nfor b in st.split():\n if len(b)%2==0:\n print(\"even\")",
"even\neven\neven\neven\neven\neven\n"
]
],
[
[
"____\n**Write a program that prints the integers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number, and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print \"FizzBuzz\".**",
"_____no_output_____"
]
],
[
[
"#Code in this cell\n\nn =[]\n\nfor n in range(1,101):\n if n%3==0 and n%5 ==0:\n print('Fizzbuzz')\n elif n%3==0:\n print('Fizz')\n elif n%5==0:\n print('buzz')\n else:\n print(n)\n \n",
"1\n2\nFizz\n4\nbuzz\nFizz\n7\n8\nFizz\nbuzz\n11\nFizz\n13\n14\nFizzbuzz\n16\n17\nFizz\n19\nbuzz\nFizz\n22\n23\nFizz\nbuzz\n26\nFizz\n28\n29\nFizzbuzz\n31\n32\nFizz\n34\nbuzz\nFizz\n37\n38\nFizz\nbuzz\n41\nFizz\n43\n44\nFizzbuzz\n46\n47\nFizz\n49\nbuzz\nFizz\n52\n53\nFizz\nbuzz\n56\nFizz\n58\n59\nFizzbuzz\n61\n62\nFizz\n64\nbuzz\nFizz\n67\n68\nFizz\nbuzz\n71\nFizz\n73\n74\nFizzbuzz\n76\n77\nFizz\n79\nbuzz\nFizz\n82\n83\nFizz\nbuzz\n86\nFizz\n88\n89\nFizzbuzz\n91\n92\nFizz\n94\nbuzz\nFizz\n97\n98\nFizz\nbuzz\n"
]
],
[
[
"____\n**Use List Comprehension to create a list of the first letters of every word in the string below:**",
"_____no_output_____"
]
],
[
[
"st = 'Create a list of the first letters of every word in this string'",
"_____no_output_____"
],
[
"#Code in this cell\n\n\n\nmy_letter =[letter[0] for letter in st.split()]\nmy_letter",
"_____no_output_____"
]
],
[
[
"### Great Job!",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
]
] |
cbb4192fdc87bc865852488a6f40b79219287e6a
| 372,556 |
ipynb
|
Jupyter Notebook
|
data_binning/feature_model_exploration_complete.ipynb
|
GrantXie/table-linker-pipelines
|
f7eb7760717cd9a9fc1039ce0cbbedfefb655104
|
[
"MIT"
] | null | null | null |
data_binning/feature_model_exploration_complete.ipynb
|
GrantXie/table-linker-pipelines
|
f7eb7760717cd9a9fc1039ce0cbbedfefb655104
|
[
"MIT"
] | 1 |
2021-07-16T22:45:20.000Z
|
2021-07-16T22:45:20.000Z
|
data_binning/feature_model_exploration_complete.ipynb
|
GrantXie/table-linker-pipelines
|
f7eb7760717cd9a9fc1039ce0cbbedfefb655104
|
[
"MIT"
] | 6 |
2021-04-05T10:59:55.000Z
|
2021-08-17T20:17:02.000Z
| 89.989372 | 19,508 | 0.773154 |
[
[
[
"\nimport glob\nimport time\nimport os\nimport pandas as pd\nimport sklearn.metrics\nfrom sklearn.preprocessing import MinMaxScaler\nimport pickle\nfrom argparse import ArgumentParser, Namespace\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.optim import Adam\nfrom itertools import chain\nfrom tqdm import tqdm\nimport copy\nimport shutil\nimport pickle\nimport json",
"_____no_output_____"
],
[
"dev_feature_set = 'SemTabRound4_T2DV2_train//dev-output/v26/features/'\npositive_features_path = 'positive_features_total.pkl'\nnegative_features_path = 'negative_features_total.pkl'\n\noutput_path = 'feature_model/'\nnum_of_epochs = 15\nlearning_rates = [0.01, 0.001]\n\nfinal_score_column = 'siamese_prediction'",
"_____no_output_____"
],
[
"positive_features = pickle.load(open(positive_features_path, \n 'rb'))",
"_____no_output_____"
],
[
"len(positive_features)",
"_____no_output_____"
],
[
"uniques = []\nfor i in positive_features:\n \n ",
"_____no_output_____"
],
[
"!mkdir -p {output_path}",
"_____no_output_____"
],
[
"# Deciding up the features\n# All the features \nfeatures = [\"monge_elkan\",\"monge_elkan_aliases\",\"jaro_winkler\",\n \"levenshtein\",\"singleton\",\"context_score_3\",\"pgt_centroid_score\",\"pgt_class_count_tf_idf_score\",\n \"pgt_property_count_tf_idf_score\", \"num_occurences\", \"incorrectness_scores\"]\nstring_similarity_features = [\"monge_elkan\",\"monge_elkan_aliases\",\"jaro_winkler\", \"levenshtein\"]\nsemantic_features = [\"singleton\",\"context_score_3\",\"pgt_centroid_score\",\"pgt_class_count_tf_idf_score\",\n \"pgt_property_count_tf_idf_score\", \"num_occurences\", \"incorrectness_scores\"]\nextra_feature_exp_1 = [\"monge_elkan\",\"monge_elkan_aliases\",\"jaro_winkler\", \"levenshtein\", \"context_score_3\"]\nextra_feature_exp_2 = [\"monge_elkan\",\"monge_elkan_aliases\",\"jaro_winkler\", \"levenshtein\", \"context_score_3\", \"pgt_class_count_tf_idf_score\",\n \"pgt_property_count_tf_idf_score\"]\nextra_feature_exp_3 = [\"monge_elkan\",\"monge_elkan_aliases\", \"levenshtein\", \"context_score_3\", \"pgt_class_count_tf_idf_score\",\n \"pgt_property_count_tf_idf_score\"]\nexperiment_feature_list = [string_similarity_features, semantic_features, extra_feature_exp_1, extra_feature_exp_2, extra_feature_exp_3]",
"_____no_output_____"
],
[
"# Create a dataframe with this as list and add the min_max_scaler",
"_____no_output_____"
],
[
"# For now apply min_max_scaler only on num_occurences\n",
"_____no_output_____"
],
[
"class T2DV2Dataset(Dataset):\n def __init__(self, pos_features, neg_features):\n #print(type(pos_features), type(neg_features))\n self.pos_features = pos_features\n self.neg_features = neg_features\n # self.transform = transforms.Compose([transforms.ToTensor()]) \n \n def __len__(self):\n #print(type(len(self.pos_features)))\n return min(len(self.pos_features), len(self.neg_features))\n \n def __getitem__(self, idx):\n # print(\"here\", (self.pos_features[idx]), (self.neg_features[idx]))\n return self.pos_features[idx], self.neg_features[idx]\n\n# Model\nclass PairwiseNetwork(nn.Module):\n def __init__(self, hidden_size):\n super().__init__()\n #original 12x24, 24x12, 12x12, 12x1\n self.fc1 = nn.Linear(hidden_size, 2*hidden_size)\n self.fc2 = nn.Linear(hidden_size*2, hidden_size)\n self.fc3 = nn.Linear(hidden_size, hidden_size)\n self.fc4 = nn.Linear(hidden_size, 1)\n \n def forward(self, pos_features, neg_features):\n # Positive pass\n x = F.relu(self.fc1(pos_features))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n pos_out = torch.sigmoid(self.fc4(x))\n \n # Negative Pass\n x = F.relu(self.fc1(neg_features))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n neg_out = torch.sigmoid(self.fc4(x))\n \n return pos_out, neg_out\n \n def predict(self, test_feat):\n x = F.relu(self.fc1(test_feat))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n test_out = torch.sigmoid(self.fc4(x))\n return test_out\n\n# Pairwise Loss\nclass PairwiseLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.m = 0\n \n def forward(self, pos_out, neg_out):\n distance = (1 - pos_out) + neg_out\n loss = torch.mean(torch.max(torch.tensor(0), distance))\n return loss",
"_____no_output_____"
],
[
"def data_creator(positive_feature_path, negative_feature_path, curr_features):\n positive_feature_set = []\n negative_feature_set = []\n # Defining feature_true\n feature_true = [0] * len(features)\n for i in range(len(features)):\n if features[i] in curr_features:\n feature_true[i] = 1\n p_feat_load = pickle.load(open(positive_feature_path, \"rb\"))\n n_feat_load = pickle.load(open(negative_feature_path, \"rb\"))\n for i in p_feat_load:\n\n singular_feature_list = []\n list_features = i[-1]\n for j in range(len(list_features)):\n if feature_true[j]:\n singular_feature_list.append(list_features[j])\n positive_feature_set.append(np.array(singular_feature_list))\n for i in n_feat_load:\n singular_feature_list = []\n list_features = i[-1]\n for j in range(len(list_features)):\n if feature_true[j]:\n singular_feature_list.append(list_features[j])\n negative_feature_set.append(np.array(singular_feature_list))\n print(positive_feature_set[0], negative_feature_set[0])\n print(len(positive_feature_set), len(negative_feature_set))\n return positive_feature_set, negative_feature_set",
"_____no_output_____"
],
[
"def generate_dataloader(positive_feature_set, negative_feature_set): \n pos_features_flatten = np.array(positive_feature_set)\n neg_features_flatten = np.array(negative_feature_set)\n print(pos_features_flatten.shape, neg_features_flatten.shape)\n #print(type(pos_features_flatten), neg_features_flatten[0], type(neg_features_flatten[0])) \n train_dataset = T2DV2Dataset(pos_features_flatten, neg_features_flatten)\n train_dataloader = DataLoader(train_dataset, batch_size=32, shuffle = False)\n return train_dataloader\n\ndef infer_scores(min_max_scaler_path, input_table_path, output_table_path, model):\n # scaler = pickle.load(open(min_max_scaler_path, 'rb'))\n normalize_features = curr_features\n for file in glob.glob(input_table_path + '/*.csv'):\n file_name = file.split('/')[-1]\n if os.path.getsize(file) == 0:\n continue\n \n d_sample = pd.read_csv(file)\n# d_sample['context_score'].fillna(0.0, inplace=True)\n grouped_obj = d_sample.groupby(['column', 'row'])\n new_df_list = []\n pred = []\n for cell in grouped_obj:\n # cell[1][normalize_features] = scaler.transform(cell[1][normalize_features])\n sorted_df = cell[1].sort_values('context_score', ascending=False)\n sorted_df_features = sorted_df[normalize_features]\n new_df_list.append(sorted_df)\n arr = sorted_df_features.to_numpy()\n test_inp = []\n for a in arr:\n test_inp.append(a)\n test_tensor = torch.tensor(test_inp).float()\n scores = model.predict(test_tensor)\n scores_list = torch.squeeze(scores).tolist()\n if not type(scores_list) is list:\n pred.append(scores_list)\n else:\n pred.extend(scores_list)\n test_df = pd.concat(new_df_list)\n test_df[final_score_column] = pred\n test_df.to_csv(f\"{output_table_path}/{file_name}\", index=False)\n\ndef train(args):\n if torch.cuda.is_available():\n device = torch.device('cuda')\n \n else:\n device = torch.device('cpu')\n device = torch.device('cpu')\n use_scheduler = False\n train_dataloader = generate_dataloader(args.positive_feat_path, args.negative_feat_path)\n criterion = PairwiseLoss()\n EPOCHS = args.num_epochs\n model = PairwiseNetwork(len(curr_features)).to(device=device)\n optimizer = Adam(model.parameters(), lr=args.lr)\n if use_scheduler:\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.01)\n top1_max_prec = 0\n for epoch in range(EPOCHS):\n train_epoch_loss = 0\n avg_loss = 0\n model.train()\n for bid, batch in tqdm(enumerate(train_dataloader), position=0, leave=True):\n # print(\"--------------\")\n positive_feat = torch.tensor(batch[0].float())\n negative_feat = torch.tensor(batch[1].float())\n optimizer.zero_grad()\n pos_out, neg_out = model(positive_feat, negative_feat)\n loss = criterion(pos_out, neg_out)\n loss.backward()\n optimizer.step()\n train_epoch_loss += loss\n avg_loss = train_epoch_loss / bid\n if use_scheduler:\n scheduler.step()\n # Evaluation\n model.eval()\n infer_scores(args.min_max_scaler_path, args.dev_path, args.dev_output, model)\n eval_data = merge_eval_files(args.dev_output)\n res, candidate_eval_data = parse_eval_files_stats(eval_data, final_score_column)\n top1_precision = res['num_tasks_with_model_score_top_one_accurate']/res['num_tasks_with_gt']\n if top1_precision >= top1_max_prec:\n top1_max_prec = top1_precision\n model_save_name = 'scheduler_{}_lr_{}_epoch_{}_loss_{}_top1_{}.pth'.format(use_scheduler, args.lr, epoch, avg_loss, top1_max_prec)\n best_model_path = os.path.join(args.model_save_path, model_save_name)\n torch.save(model.state_dict(), best_model_path)\n \n print(\"Epoch {}, Avg Loss is {}, epoch top1 {}, max top1 {}\".format(epoch, avg_loss, top1_precision, top1_max_prec))\n return best_model_path",
"_____no_output_____"
],
[
"def merge_eval_files(final_score_path):\n eval_file_names = []\n df_list = []\n for (dirpath, dirnames, filenames) in os.walk(final_score_path):\n for fn in filenames:\n if \"csv\" not in fn:\n continue\n abs_fn = os.path.join(dirpath, fn)\n assert os.path.isfile(abs_fn)\n if os.path.getsize(abs_fn) == 0:\n continue\n eval_file_names.append(abs_fn)\n \n for fn in eval_file_names:\n fid = fn.split('/')[-1].split('.csv')[0]\n # print(fn)\n df = pd.read_csv(fn)\n df['table_id'] = fid\n df_list.append(df)\n return pd.concat(df_list)\n\ndef parse_eval_files_stats(eval_data, method):\n res = {}\n candidate_eval_data = eval_data.groupby(['table_id', 'column', 'row'])['table_id'].count().reset_index(name=\"count\")\n res['num_tasks_with_gt'] = len(eval_data[pd.notna(eval_data['GT_kg_id'])].groupby(['table_id', 'column', 'row']))\n num_tasks_with_model_score_top_one_accurate = []\n num_tasks_with_model_score_top_five_accurate = []\n num_tasks_with_model_score_top_ten_accurate = []\n has_gt_list = []\n has_gt_in_candidate = []\n for i, row in candidate_eval_data.iterrows():\n table_id, row_idx, col_idx = row['table_id'], row['row'], row['column']\n c_e_data = eval_data[(eval_data['table_id'] == table_id) & (eval_data['row'] == row_idx) & (eval_data['column'] == col_idx)]\n assert len(c_e_data) > 0\n if np.nan not in set(c_e_data['GT_kg_id']):\n has_gt_list.append(1)\n else:\n has_gt_list.append(0)\n if 1 in set(c_e_data['evaluation_label']):\n has_gt_in_candidate.append(1)\n else:\n has_gt_in_candidate.append(0)\n \n #rank on model score\n s_data = c_e_data.sort_values(by=[method], ascending=False)\n if s_data.iloc[0]['evaluation_label'] == 1:\n num_tasks_with_model_score_top_one_accurate.append(1)\n else:\n num_tasks_with_model_score_top_one_accurate.append(0)\n if 1 in set(s_data.iloc[0:5]['evaluation_label']):\n num_tasks_with_model_score_top_five_accurate.append(1)\n else:\n num_tasks_with_model_score_top_five_accurate.append(0)\n if 1 in set(s_data.iloc[0:10]['evaluation_label']):\n num_tasks_with_model_score_top_ten_accurate.append(1)\n else:\n num_tasks_with_model_score_top_ten_accurate.append(0)\n \n res['num_tasks_with_model_score_top_one_accurate'] = sum(num_tasks_with_model_score_top_one_accurate)\n res['num_tasks_with_model_score_top_five_accurate'] = sum(num_tasks_with_model_score_top_five_accurate)\n res['num_tasks_with_model_score_top_ten_accurate'] = sum(num_tasks_with_model_score_top_ten_accurate)\n return res, candidate_eval_data",
"_____no_output_____"
],
[
"curr_features = features\npositive_feature_set, negative_feature_set = data_creator(positive_features_path, negative_features_path, curr_features)",
"[0. 1. 0. 0. 0. 0.\n 0.64788039 0.2114032 0.32691692 1. 0.5 ] [0.72103175 0.60103175 0.70726496 0.53846154 0. 0.\n 0.54664618 0.12153565 0.03171066 2. 0. ]\n454185 454185\n"
],
[
"positive_feature_set[0]",
"_____no_output_____"
],
[
"len(positive_feature_set)",
"_____no_output_____"
],
[
"j = np.array(positive_feature_set).reshape(454185, 11)",
"_____no_output_____"
],
[
"k = np.unique(j, axis = 0)",
"_____no_output_____"
],
[
"k[0]",
"_____no_output_____"
],
[
"pk[0]",
"_____no_output_____"
],
[
"training_args = Namespace(num_epochs=20, lr=0.001, positive_feat_path=k, negative_feat_path=negative_feature_set,\n dev_path=dev_feature_set, dev_output='Experiment_5/',\n model_save_path='_rn', min_max_scaler_path=None)",
"ERROR! Session/line number was not unique in database. History logging moved to new session 1198\n"
],
[
"best_model_path = train(training_args)",
"0it [00:00, ?it/s]<ipython-input-33-c56c4f869aac>:65: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).\n positive_feat = torch.tensor(batch[0].float())\n<ipython-input-33-c56c4f869aac>:66: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).\n negative_feat = torch.tensor(batch[1].float())\n55it [00:00, 540.89it/s]"
],
[
"import json",
"_____no_output_____"
],
[
"len(experiment_feature_list)",
"_____no_output_____"
],
[
"best_model_paths_experiment = {}\nignore = 4\nfor experiment in experiment_feature_list:\n if ignore > 0:\n ignore = ignore - 1\n continue\n curr_features = experiment\n pos_feature_set, neg_feature_set = data_creator(positive_features_path, negative_features_path, curr_features)\n feature_version = \"Experiment_\" + str(experiment_feature_list.index(experiment)) + '/'\n save_model = output_path + feature_version + \"saved_models/\"\n dev_predictions = output_path + feature_version + \"dev_predictions/\"\n !mkdir -p {feature_version}\n !mkdir -p {save_model}\n !mkdir -p {dev_predictions}\n # for l_rate in learning_rates:\n training_args = Namespace(num_epochs=20, lr=0.00005, positive_feat_path=pos_feature_set, negative_feat_path=neg_feature_set,\n dev_path=dev_feature_set, dev_output=dev_predictions,\n model_save_path=save_model, min_max_scaler_path=None)\n best_model_path = train(training_args)\n best_model_paths_experiment[f\"{feature_version}_0.0001\"] = best_model_path\n json.dump(best_model_paths_experiment, open('experiments_result.json', \"w\"))",
"[0. 1. 0. 0. 0. 0.\n 0.64788039 0.2114032 0.32691692 1. 0.5 ] [0.72103175 0.60103175 0.70726496 0.53846154 0. 0.\n 0.54664618 0.12153565 0.03171066 2. 0. ]\n"
],
[
"print (\"List in proper method\", '[%s]' % ', '.join(map(str, features)))",
"List in proper method [monge_elkan, monge_elkan_aliases, jaro_winkler, levenshtein, singleton, context_score_3, pgt_centroid_score, pgt_class_count_tf_idf_score, pgt_property_count_tf_idf_score, num_occurences, incorrectness_scores]\n"
],
[
"merged_files = None\ndef top_k_and_add_color(saved_model, features, dev_features_path, dev_top_k_path, dev_metrics_path, \n dev_predictions_path, dev_colorized, final_score_column, dev_metrics):\n file_list = glob.glob(dev_features_path + '*.csv')\n min_max_scaler_path = \"tl_pipeline_normalization_factor.pkl\"\n df_list = []\n feature_str = \",\".join(features)\n for file in file_list:\n # Predicting\n filename = file.split('/')[-1]\n print(filename)\n pred_file = dev_predictions_path + filename\n print(os.path.exists(dev_predictions_path), pred_file)\n top_5_file = dev_top_k_path + filename\n color_file = dev_colorized + filename.replace('.csv', '.xlsx')\n metrics_file = dev_metrics_path + filename\n !tl predict-using-model $file -o $final_score_column \\\n --features $feature_str \\\n --ranking-model $saved_model \\\n --normalization-factor $min_max_scaler_path > $pred_file\n merged_files = merge_eval_files(dev_predictions_path)\n !tl get-kg-links $pred_file --k-rows -k 5 -c $final_score_column > $top_5_file\n !tl add-color $top_5_file -k 5 -c $final_score_column,evaluation_label --output $color_file\n !tl metrics $top_5_file -k 1 -c $final_score_column --tag $filename> $metrics_file\n if os.path.getsize(metrics_file) > 2:\n df = pd.read_csv(metrics_file)\n df_list.append(df)\n #get the top 5\n # colorize\n return pd.concat(df_list)",
"_____no_output_____"
],
[
"#All features\nfeature_version = 'Experiment_5/'\ncurr_features = features\nsaved_model = 'feature_model/Experiment_5/saved_models/scheduler_False_lr_0.0001_epoch_8_loss_0.3135864734649658_top1_0.9553264604810997.pth'\ndev_predictions_path = output_path + feature_version + 'dev_predictions/'\ndev_predictions_top_k = output_path + feature_version + 'dev_predictions_top_k/'\ndev_colorized = output_path + feature_version + 'dev_predictions_colorized/'\ndev_metrics_path = output_path + feature_version + 'dev_metrics/'\nfinal_score_column = 'siamese_prediction'\n!mkdir -p $dev_predictions_path\n!mkdir -p $dev_predictions_top_k\n!mkdir -p $dev_colorized\n!mkdir -p $dev_metrics_path\n",
"_____no_output_____"
],
[
"dev_predictions_path",
"_____no_output_____"
],
[
"metrics_df = top_k_and_add_color(saved_model, curr_features, dev_feature_set, dev_predictions_top_k, dev_metrics_path, \n dev_predictions_path, dev_colorized, final_score_column, dev_metrics_path)",
"0CETTKTA.csv\nTrue feature_model/Experiment_5/dev_predictions/0CETTKTA.csv\npredict-using-model Time: 3.332609176635742s\nget-kg-links-siamese_prediction Time: 0.18154621124267578s\nadd-color Time: 0.2581980228424072s\nmetrics Time: 0.07976818084716797s\n2E6QBLCA.csv\nTrue feature_model/Experiment_5/dev_predictions/2E6QBLCA.csv\npredict-using-model Time: 1.4089138507843018s\nget-kg-links-siamese_prediction Time: 0.3766336441040039s\nadd-color Time: 0.18762993812561035s\nmetrics Time: 0.18978476524353027s\n29D1VZHF.csv\nTrue feature_model/Experiment_5/dev_predictions/29D1VZHF.csv\npredict-using-model Time: 2.1484029293060303s\nget-kg-links-siamese_prediction Time: 0.5128324031829834s\nadd-color Time: 0.24450898170471191s\nmetrics Time: 0.2597193717956543s\n2FXR6BX7.csv\nTrue feature_model/Experiment_5/dev_predictions/2FXR6BX7.csv\npredict-using-model Time: 3.295865774154663s\nget-kg-links-siamese_prediction Time: 0.6033022403717041s\nadd-color Time: 0.23527908325195312s\nmetrics Time: 0.28812336921691895s\n53OUTCE4.csv\nTrue feature_model/Experiment_5/dev_predictions/53OUTCE4.csv\npredict-using-model Time: 1.0708537101745605s\nget-kg-links-siamese_prediction Time: 0.3075144290924072s\nadd-color Time: 0.22302937507629395s\nmetrics Time: 0.1342167854309082s\n39W7XXTI.csv\nTrue feature_model/Experiment_5/dev_predictions/39W7XXTI.csv\npredict-using-model Time: 1.4999887943267822s\nget-kg-links-siamese_prediction Time: 0.5072999000549316s\nadd-color Time: 0.290834903717041s\nmetrics Time: 0.2156686782836914s\n0LZ0M8W4.csv\nTrue feature_model/Experiment_5/dev_predictions/0LZ0M8W4.csv\npredict-using-model Time: 4.425828695297241s\nget-kg-links-siamese_prediction Time: 0.4803183078765869s\nadd-color Time: 0.35031962394714355s\nmetrics Time: 0.2799241542816162s\n4SOL8H0M.csv\nTrue feature_model/Experiment_5/dev_predictions/4SOL8H0M.csv\npredict-using-model Time: 1.7397053241729736s\nget-kg-links-siamese_prediction Time: 0.7795171737670898s\nadd-color Time: 0.2503376007080078s\nmetrics Time: 0.3509550094604492s\n4DC5O5I4.csv\nTrue feature_model/Experiment_5/dev_predictions/4DC5O5I4.csv\npredict-using-model Time: 1.4222044944763184s\nget-kg-links-siamese_prediction Time: 0.18302297592163086s\nadd-color Time: 0.16637825965881348s\nmetrics Time: 0.0728907585144043s\n1T91CHXV.csv\nTrue feature_model/Experiment_5/dev_predictions/1T91CHXV.csv\npredict-using-model Time: 3.172729253768921s\nget-kg-links-siamese_prediction Time: 0.6352660655975342s\nadd-color Time: 0.2039196491241455s\nmetrics Time: 0.21072173118591309s\n3OAZEVOY.csv\nTrue feature_model/Experiment_5/dev_predictions/3OAZEVOY.csv\npredict-using-model Time: 1.4114506244659424s\nget-kg-links-siamese_prediction Time: 0.6098837852478027s\nadd-color Time: 0.2504384517669678s\nmetrics Time: 0.30161476135253906s\n1PTL0CX1.csv\nTrue feature_model/Experiment_5/dev_predictions/1PTL0CX1.csv\npredict-using-model Time: 1.6363177299499512s\nget-kg-links-siamese_prediction Time: 0.3164951801300049s\nadd-color Time: 0.21344637870788574s\nmetrics Time: 0.15122151374816895s\n0WBTX8LY.csv\nTrue feature_model/Experiment_5/dev_predictions/0WBTX8LY.csv\npredict-using-model Time: 2.929537534713745s\nget-kg-links-siamese_prediction Time: 0.48143982887268066s\nadd-color Time: 0.432232141494751s\nmetrics Time: 0.19914913177490234s\n1GUVMENF.csv\nTrue feature_model/Experiment_5/dev_predictions/1GUVMENF.csv\npredict-using-model Time: 1.4943761825561523s\nget-kg-links-siamese_prediction Time: 0.16757798194885254s\nadd-color Time: 0.1210629940032959s\nmetrics Time: 0.11905598640441895s\n13BLTPJD.csv\nTrue feature_model/Experiment_5/dev_predictions/13BLTPJD.csv\nCommand: predict-using-model\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/predict-using-model.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: get-kg-links\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/get-kg-links.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: add color\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/add-color.py\", line 56, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: metrics\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/metrics.py\", line 42, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\n50NWQJ1T.csv\nTrue feature_model/Experiment_5/dev_predictions/50NWQJ1T.csv\npredict-using-model Time: 3.118166446685791s\nget-kg-links-siamese_prediction Time: 0.5020017623901367s\nadd-color Time: 0.47922468185424805s\nmetrics Time: 0.19893288612365723s\n3B54GZSX.csv\nTrue feature_model/Experiment_5/dev_predictions/3B54GZSX.csv\npredict-using-model Time: 2.1682801246643066s\nget-kg-links-siamese_prediction Time: 0.4926285743713379s\nadd-color Time: 0.20521211624145508s\nmetrics Time: 0.1939389705657959s\n0G9YPQC0.csv\nTrue feature_model/Experiment_5/dev_predictions/0G9YPQC0.csv\npredict-using-model Time: 1.1902227401733398s\nget-kg-links-siamese_prediction Time: 0.5536026954650879s\nadd-color Time: 0.14905595779418945s\nmetrics Time: 0.22632145881652832s\n2YCSL7OH.csv\nTrue feature_model/Experiment_5/dev_predictions/2YCSL7OH.csv\npredict-using-model Time: 3.633835792541504s\nget-kg-links-siamese_prediction Time: 0.4734175205230713s\nadd-color Time: 0.19179105758666992s\nmetrics Time: 0.20341062545776367s\n28D7RBJT.csv\nTrue feature_model/Experiment_5/dev_predictions/28D7RBJT.csv\npredict-using-model Time: 1.5669972896575928s\nget-kg-links-siamese_prediction Time: 0.31067943572998047s\nadd-color Time: 0.22481989860534668s\nmetrics Time: 0.14548659324645996s\n1ZFRQBQS.csv\nTrue feature_model/Experiment_5/dev_predictions/1ZFRQBQS.csv\npredict-using-model Time: 1.5713391304016113s\nget-kg-links-siamese_prediction Time: 0.9574089050292969s\nadd-color Time: 0.26700758934020996s\nmetrics Time: 0.3600585460662842s\n2FSRG0OI.csv\nTrue feature_model/Experiment_5/dev_predictions/2FSRG0OI.csv\npredict-using-model Time: 3.0929372310638428s\nget-kg-links-siamese_prediction Time: 0.18305730819702148s\nadd-color Time: 0.19375872611999512s\nmetrics Time: 0.08331847190856934s\n4FG1UN8O.csv\nTrue feature_model/Experiment_5/dev_predictions/4FG1UN8O.csv\npredict-using-model Time: 1.6355478763580322s\nget-kg-links-siamese_prediction Time: 0.807422399520874s\nadd-color Time: 0.18117713928222656s\nmetrics Time: 0.3189244270324707s\n5TJI4XTK.csv\nTrue feature_model/Experiment_5/dev_predictions/5TJI4XTK.csv\npredict-using-model Time: 1.3094654083251953s\nget-kg-links-siamese_prediction Time: 0.15921735763549805s\nadd-color Time: 0.21002864837646484s\nmetrics Time: 0.07077312469482422s\n5IXA0RAI.csv\nTrue feature_model/Experiment_5/dev_predictions/5IXA0RAI.csv\npredict-using-model Time: 3.7301816940307617s\nget-kg-links-siamese_prediction Time: 0.17868971824645996s\nadd-color Time: 0.14222288131713867s\nmetrics Time: 0.08846855163574219s\n0TQXSY28.csv\nTrue feature_model/Experiment_5/dev_predictions/0TQXSY28.csv\npredict-using-model Time: 1.546363115310669s\nget-kg-links-siamese_prediction Time: 0.15900158882141113s\nadd-color Time: 0.15140795707702637s\nmetrics Time: 0.07866477966308594s\n58E7A5WL.csv\nTrue feature_model/Experiment_5/dev_predictions/58E7A5WL.csv\npredict-using-model Time: 1.909006118774414s\nget-kg-links-siamese_prediction Time: 0.3753926753997803s\nadd-color Time: 0.13143515586853027s\nmetrics Time: 0.1488037109375s\n59W76Q0Y.csv\nTrue feature_model/Experiment_5/dev_predictions/59W76Q0Y.csv\npredict-using-model Time: 3.4225542545318604s\nget-kg-links-siamese_prediction Time: 0.18224740028381348s\nadd-color Time: 0.2102055549621582s\nmetrics Time: 0.07863354682922363s\n2TGNKH1P.csv\nTrue feature_model/Experiment_5/dev_predictions/2TGNKH1P.csv\npredict-using-model Time: 1.8509752750396729s\nget-kg-links-siamese_prediction Time: 0.3430190086364746s\nadd-color Time: 0.14866399765014648s\nmetrics Time: 0.13908028602600098s\n00ECUL14.csv\nTrue feature_model/Experiment_5/dev_predictions/00ECUL14.csv\npredict-using-model Time: 2.0002517700195312s\nget-kg-links-siamese_prediction Time: 0.3425180912017822s\nadd-color Time: 0.16762375831604004s\nmetrics Time: 0.14602446556091309s\n0FQOOJPU.csv\nTrue feature_model/Experiment_5/dev_predictions/0FQOOJPU.csv\npredict-using-model Time: 2.947985887527466s\nget-kg-links-siamese_prediction Time: 0.5153975486755371s\nadd-color Time: 0.35764193534851074s\nmetrics Time: 0.2135608196258545s\n0P8H49LQ.csv\nTrue feature_model/Experiment_5/dev_predictions/0P8H49LQ.csv\npredict-using-model Time: 1.4573185443878174s\nget-kg-links-siamese_prediction Time: 0.4984760284423828s\nadd-color Time: 0.18067097663879395s\nmetrics Time: 0.21327543258666992s\n2PKG4E2V.csv\nTrue feature_model/Experiment_5/dev_predictions/2PKG4E2V.csv\npredict-using-model Time: 1.6249022483825684s\nget-kg-links-siamese_prediction Time: 0.6144180297851562s\nadd-color Time: 0.23719525337219238s\nmetrics Time: 0.2752041816711426s\n0JSF530F.csv\nTrue feature_model/Experiment_5/dev_predictions/0JSF530F.csv\npredict-using-model Time: 2.087050199508667s\nget-kg-links-siamese_prediction Time: 0.1873018741607666s\nadd-color Time: 0.2699167728424072s\nmetrics Time: 0.07827877998352051s\n1YPLVLS9.csv\nTrue feature_model/Experiment_5/dev_predictions/1YPLVLS9.csv\npredict-using-model Time: 1.4465711116790771s\nget-kg-links-siamese_prediction Time: 0.3437631130218506s\nadd-color Time: 0.1507117748260498s\nmetrics Time: 0.14592337608337402s\n5PKTGQ6Q.csv\nTrue feature_model/Experiment_5/dev_predictions/5PKTGQ6Q.csv\npredict-using-model Time: 0.935431957244873s\nget-kg-links-siamese_prediction Time: 0.1836528778076172s\nadd-color Time: 0.17129182815551758s\nmetrics Time: 0.0789940357208252s\n0QWF60VG.csv\nTrue feature_model/Experiment_5/dev_predictions/0QWF60VG.csv\npredict-using-model Time: 3.5857439041137695s\nget-kg-links-siamese_prediction Time: 0.5117321014404297s\nadd-color Time: 0.24937081336975098s\nmetrics Time: 0.21256780624389648s\n3M5QXPWN.csv\nTrue feature_model/Experiment_5/dev_predictions/3M5QXPWN.csv\npredict-using-model Time: 1.4233667850494385s\nget-kg-links-siamese_prediction Time: 0.5858869552612305s\nadd-color Time: 0.21129775047302246s\nmetrics Time: 0.21734213829040527s\n0LF7RI6N.csv\nTrue feature_model/Experiment_5/dev_predictions/0LF7RI6N.csv\npredict-using-model Time: 1.1982128620147705s\nget-kg-links-siamese_prediction Time: 0.3490786552429199s\nadd-color Time: 0.25951313972473145s\nmetrics Time: 0.13498520851135254s\n44NDHWR1.csv\nTrue feature_model/Experiment_5/dev_predictions/44NDHWR1.csv\npredict-using-model Time: 3.321277618408203s\nget-kg-links-siamese_prediction Time: 0.5181663036346436s\nadd-color Time: 0.2448117733001709s\nmetrics Time: 0.1983203887939453s\n4PKEEJU4.csv\nTrue feature_model/Experiment_5/dev_predictions/4PKEEJU4.csv\npredict-using-model Time: 1.6957848072052002s\nget-kg-links-siamese_prediction Time: 0.5089101791381836s\nadd-color Time: 0.3143937587738037s\nmetrics Time: 0.21712017059326172s\n1NS33P8C.csv\nTrue feature_model/Experiment_5/dev_predictions/1NS33P8C.csv\npredict-using-model Time: 1.4607570171356201s\nget-kg-links-siamese_prediction Time: 0.18328142166137695s\nadd-color Time: 0.18017077445983887s\nmetrics Time: 0.07920598983764648s\n1GOKLC0K.csv\nTrue feature_model/Experiment_5/dev_predictions/1GOKLC0K.csv\npredict-using-model Time: 3.4271438121795654s\nget-kg-links-siamese_prediction Time: 0.5069353580474854s\nadd-color Time: 0.24692511558532715s\nmetrics Time: 0.20250964164733887s\n3WXFYEAX.csv\nTrue feature_model/Experiment_5/dev_predictions/3WXFYEAX.csv\npredict-using-model Time: 1.579714059829712s\nget-kg-links-siamese_prediction Time: 0.18416881561279297s\nadd-color Time: 0.20859074592590332s\nmetrics Time: 0.07755899429321289s\n2QFYH2N9.csv\nTrue feature_model/Experiment_5/dev_predictions/2QFYH2N9.csv\npredict-using-model Time: 1.7754027843475342s\nget-kg-links-siamese_prediction Time: 0.45334625244140625s\nadd-color Time: 0.16486001014709473s\nmetrics Time: 0.21915817260742188s\n3OCW1LDZ.csv\nTrue feature_model/Experiment_5/dev_predictions/3OCW1LDZ.csv\npredict-using-model Time: 4.490596055984497s\nget-kg-links-siamese_prediction Time: 0.6627523899078369s\nadd-color Time: 0.29096031188964844s\nmetrics Time: 0.21905279159545898s\n4V4O0CTS.csv\nTrue feature_model/Experiment_5/dev_predictions/4V4O0CTS.csv\npredict-using-model Time: 1.3449387550354004s\nget-kg-links-siamese_prediction Time: 0.3212580680847168s\nadd-color Time: 0.16220998764038086s\nmetrics Time: 0.14726614952087402s\n080HU8A5.csv\nTrue feature_model/Experiment_5/dev_predictions/080HU8A5.csv\npredict-using-model Time: 1.353914499282837s\nget-kg-links-siamese_prediction Time: 0.18686127662658691s\nadd-color Time: 0.16777467727661133s\nmetrics Time: 0.07887506484985352s\n3JNFST2K.csv\nTrue feature_model/Experiment_5/dev_predictions/3JNFST2K.csv\npredict-using-model Time: 3.211719274520874s\nget-kg-links-siamese_prediction Time: 0.16345667839050293s\nadd-color Time: 0.2960350513458252s\nmetrics Time: 0.07870030403137207s\n1XIWQBSF.csv\nTrue feature_model/Experiment_5/dev_predictions/1XIWQBSF.csv\npredict-using-model Time: 0.9492573738098145s\nget-kg-links-siamese_prediction Time: 0.3253302574157715s\nadd-color Time: 0.19497418403625488s\nmetrics Time: 0.1718451976776123s\n4DPRZWVL.csv\nTrue feature_model/Experiment_5/dev_predictions/4DPRZWVL.csv\npredict-using-model Time: 1.006347417831421s\nget-kg-links-siamese_prediction Time: 0.1928417682647705s\nadd-color Time: 0.17418551445007324s\nmetrics Time: 0.07688641548156738s\n"
],
[
"merged_files = merge_eval_files('feature_model/Experiment_5/dev_predictions/')",
"/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (29,30,31,36,38,42,43,44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n"
],
[
"from sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import auc\nfrom matplotlib import pyplot\ntesty = merged_files['evaluation_label'].replace({-1:0})\nlr_probs = merged_files['siamese_prediction']\nlr_precision, lr_recall, _ = precision_recall_curve(testy.ravel(), lr_probs.ravel())\n# , lr_auc = f1_score(testy, yhat), auc(lr_recall, lr_precision)\npyplot.plot(lr_recall, lr_precision, marker='.', label='Experiment_5')\npyplot.xlabel('Recall')\npyplot.ylabel('Precision')\npyplot.legend()\npyplot.show()",
"_____no_output_____"
],
[
"from numpy import sqrt, argmax\nfpr, tpr, thresholds = roc_curve(testy, lr_probs)\ngmeans = sqrt(tpr * (1-fpr))\nix = argmax(gmeans)\nprint('Best Threshold=%f, G-Mean=%.3f' % (thresholds[ix], gmeans[ix]))\npyplot.plot(fpr, tpr, marker='.', label='AUC Curve')\npyplot.scatter(fpr[ix], tpr[ix], marker='o', color='black', label='Best')\npyplot.xlabel('False Positive Rate')\npyplot.ylabel('True Positive Rate')\npyplot.legend()\npyplot.show()",
"Best Threshold=0.385917, G-Mean=0.983\n"
],
[
"merged_files",
"_____no_output_____"
],
[
"metrics_df.to_csv(dev_metrics_path + \"metrics_1.csv\", index = False)",
"_____no_output_____"
],
[
"pos_feature_set[:10]",
"_____no_output_____"
],
[
"#All features\nfeature_version = 'Experiment_0/'\ncurr_features = experiment_feature_list[0]\nsaved_model = 'feature_model/Experimentf_0/saved_models/scheduler_False_lr_5e-05_epoch_4_loss_0.4877758026123047_top1_0.8526632302405498.pth'\ndev_predictions_path = output_path + feature_version + 'dev_predictions/'\ndev_predictions_top_k = output_path + feature_version + 'dev_predictions_top_k/'\ndev_colorized = output_path + feature_version + 'dev_predictions_colorized/'\ndev_metrics_path = output_path + feature_version + 'dev_metrics/'\nfinal_score_column = 'siamese_prediction'\n!mkdir -p $dev_predictions_path\n!mkdir -p $dev_predictions_top_k\n!mkdir -p $dev_colorized\n!mkdir -p $dev_metrics_path\nmetrics_df = top_k_and_add_color(saved_model, curr_features, dev_feature_set, dev_predictions_top_k, dev_metrics_path, \n dev_predictions_path, dev_colorized, final_score_column, dev_metrics_path)\nmetrics_df.to_csv(dev_metrics_path + \"metrics_1.csv\", index = False)",
"0CETTKTA.csv\nTrue feature_model/Experiment_0/dev_predictions/0CETTKTA.csv\npredict-using-model Time: 3.2482519149780273s\nget-kg-links-siamese_prediction Time: 0.5788123607635498s\nadd-color Time: 0.45508837699890137s\nmetrics Time: 0.20576715469360352s\n2E6QBLCA.csv\nTrue feature_model/Experiment_0/dev_predictions/2E6QBLCA.csv\npredict-using-model Time: 2.2794647216796875s\nget-kg-links-siamese_prediction Time: 0.7483980655670166s\nadd-color Time: 0.47511792182922363s\nmetrics Time: 0.36243438720703125s\n29D1VZHF.csv\nTrue feature_model/Experiment_0/dev_predictions/29D1VZHF.csv\npredict-using-model Time: 2.126075267791748s\nget-kg-links-siamese_prediction Time: 1.132673740386963s\nadd-color Time: 0.6068651676177979s\nmetrics Time: 0.4392101764678955s\n2FXR6BX7.csv\nTrue feature_model/Experiment_0/dev_predictions/2FXR6BX7.csv\npredict-using-model Time: 2.470524549484253s\nget-kg-links-siamese_prediction Time: 1.6597883701324463s\nadd-color Time: 0.5137591361999512s\nmetrics Time: 0.8148491382598877s\n53OUTCE4.csv\nTrue feature_model/Experiment_0/dev_predictions/53OUTCE4.csv\npredict-using-model Time: 2.041635513305664s\nget-kg-links-siamese_prediction Time: 1.1384177207946777s\nadd-color Time: 0.47357654571533203s\nmetrics Time: 0.4435427188873291s\n39W7XXTI.csv\nTrue feature_model/Experiment_0/dev_predictions/39W7XXTI.csv\npredict-using-model Time: 2.6436262130737305s\nget-kg-links-siamese_prediction Time: 1.0829696655273438s\nadd-color Time: 0.47800755500793457s\nmetrics Time: 0.6065962314605713s\n0LZ0M8W4.csv\nTrue feature_model/Experiment_0/dev_predictions/0LZ0M8W4.csv\npredict-using-model Time: 2.1166298389434814s\nget-kg-links-siamese_prediction Time: 1.276367425918579s\nadd-color Time: 0.5686626434326172s\nmetrics Time: 0.5430529117584229s\n4SOL8H0M.csv\nTrue feature_model/Experiment_0/dev_predictions/4SOL8H0M.csv\npredict-using-model Time: 2.2953929901123047s\nget-kg-links-siamese_prediction Time: 1.5629119873046875s\nadd-color Time: 0.4138786792755127s\nmetrics Time: 0.8095147609710693s\n4DC5O5I4.csv\nTrue feature_model/Experiment_0/dev_predictions/4DC5O5I4.csv\npredict-using-model Time: 1.8812026977539062s\nget-kg-links-siamese_prediction Time: 0.523759126663208s\nadd-color Time: 0.3342258930206299s\nmetrics Time: 0.16168475151062012s\n1T91CHXV.csv\nTrue feature_model/Experiment_0/dev_predictions/1T91CHXV.csv\npredict-using-model Time: 2.135272741317749s\nget-kg-links-siamese_prediction Time: 1.432008981704712s\nadd-color Time: 0.486675500869751s\nmetrics Time: 0.5001785755157471s\n3OAZEVOY.csv\nTrue feature_model/Experiment_0/dev_predictions/3OAZEVOY.csv\npredict-using-model Time: 2.2468149662017822s\nget-kg-links-siamese_prediction Time: 1.720475435256958s\nadd-color Time: 0.67508864402771s\nmetrics Time: 0.6347851753234863s\n1PTL0CX1.csv\nTrue feature_model/Experiment_0/dev_predictions/1PTL0CX1.csv\npredict-using-model Time: 2.3256988525390625s\nget-kg-links-siamese_prediction Time: 0.806816816329956s\nadd-color Time: 0.5368516445159912s\nmetrics Time: 0.4888930320739746s\n0WBTX8LY.csv\nTrue feature_model/Experiment_0/dev_predictions/0WBTX8LY.csv\npredict-using-model Time: 2.371021270751953s\nget-kg-links-siamese_prediction Time: 1.8272626399993896s\nadd-color Time: 0.43508315086364746s\nmetrics Time: 0.6198277473449707s\n1GUVMENF.csv\nTrue feature_model/Experiment_0/dev_predictions/1GUVMENF.csv\npredict-using-model Time: 1.8501152992248535s\nget-kg-links-siamese_prediction Time: 0.410614013671875s\nadd-color Time: 0.37096309661865234s\nmetrics Time: 0.26130080223083496s\n13BLTPJD.csv\nTrue feature_model/Experiment_0/dev_predictions/13BLTPJD.csv\nCommand: predict-using-model\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/predict-using-model.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: get-kg-links\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/get-kg-links.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: add color\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/add-color.py\", line 56, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: metrics\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/metrics.py\", line 42, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\n50NWQJ1T.csv\nTrue feature_model/Experiment_0/dev_predictions/50NWQJ1T.csv\npredict-using-model Time: 2.349587917327881s\nget-kg-links-siamese_prediction Time: 1.7072525024414062s\nadd-color Time: 0.4948451519012451s\nmetrics Time: 0.7994804382324219s\n3B54GZSX.csv\nTrue feature_model/Experiment_0/dev_predictions/3B54GZSX.csv\npredict-using-model Time: 2.1692137718200684s\nget-kg-links-siamese_prediction Time: 1.249220371246338s\nadd-color Time: 0.4696791172027588s\nmetrics Time: 0.7525265216827393s\n0G9YPQC0.csv\nTrue feature_model/Experiment_0/dev_predictions/0G9YPQC0.csv\npredict-using-model Time: 2.2900543212890625s\nget-kg-links-siamese_prediction Time: 1.4973292350769043s\nadd-color Time: 0.5796394348144531s\nmetrics Time: 0.5128395557403564s\n2YCSL7OH.csv\nTrue feature_model/Experiment_0/dev_predictions/2YCSL7OH.csv\npredict-using-model Time: 2.4827353954315186s\nget-kg-links-siamese_prediction Time: 1.6021299362182617s\nadd-color Time: 0.5182406902313232s\nmetrics Time: 0.4933183193206787s\n28D7RBJT.csv\nTrue feature_model/Experiment_0/dev_predictions/28D7RBJT.csv\npredict-using-model Time: 2.3583476543426514s\nget-kg-links-siamese_prediction Time: 1.1107845306396484s\nadd-color Time: 0.4718947410583496s\nmetrics Time: 0.3693544864654541s\n1ZFRQBQS.csv\nTrue feature_model/Experiment_0/dev_predictions/1ZFRQBQS.csv\npredict-using-model Time: 2.028252363204956s\nget-kg-links-siamese_prediction Time: 2.2731661796569824s\nadd-color Time: 0.5486397743225098s\nmetrics Time: 0.863478422164917s\n2FSRG0OI.csv\nTrue feature_model/Experiment_0/dev_predictions/2FSRG0OI.csv\npredict-using-model Time: 1.7991054058074951s\nget-kg-links-siamese_prediction Time: 0.42963504791259766s\nadd-color Time: 0.3147916793823242s\nmetrics Time: 0.14905285835266113s\n4FG1UN8O.csv\nTrue feature_model/Experiment_0/dev_predictions/4FG1UN8O.csv\npredict-using-model Time: 2.500943660736084s\nget-kg-links-siamese_prediction Time: 1.964336633682251s\nadd-color Time: 0.44953107833862305s\nmetrics Time: 0.7909488677978516s\n5TJI4XTK.csv\nTrue feature_model/Experiment_0/dev_predictions/5TJI4XTK.csv\npredict-using-model Time: 1.9540941715240479s\nget-kg-links-siamese_prediction Time: 0.5221207141876221s\nadd-color Time: 0.26951074600219727s\nmetrics Time: 0.15547633171081543s\n5IXA0RAI.csv\nTrue feature_model/Experiment_0/dev_predictions/5IXA0RAI.csv\npredict-using-model Time: 1.8046627044677734s\nget-kg-links-siamese_prediction Time: 0.3736228942871094s\nadd-color Time: 0.42696094512939453s\nmetrics Time: 0.1519618034362793s\n0TQXSY28.csv\nTrue feature_model/Experiment_0/dev_predictions/0TQXSY28.csv\npredict-using-model Time: 1.8346264362335205s\nget-kg-links-siamese_prediction Time: 0.6424565315246582s\nadd-color Time: 0.2613708972930908s\nmetrics Time: 0.2056734561920166s\n58E7A5WL.csv\nTrue feature_model/Experiment_0/dev_predictions/58E7A5WL.csv\npredict-using-model Time: 2.2223565578460693s\nget-kg-links-siamese_prediction Time: 0.8362288475036621s\nadd-color Time: 0.6334874629974365s\nmetrics Time: 0.353377103805542s\n59W76Q0Y.csv\nTrue feature_model/Experiment_0/dev_predictions/59W76Q0Y.csv\npredict-using-model Time: 1.7742912769317627s\nget-kg-links-siamese_prediction Time: 0.4921102523803711s\nadd-color Time: 0.3279404640197754s\nmetrics Time: 0.2027904987335205s\n2TGNKH1P.csv\nTrue feature_model/Experiment_0/dev_predictions/2TGNKH1P.csv\npredict-using-model Time: 2.403730630874634s\nget-kg-links-siamese_prediction Time: 0.9049355983734131s\nadd-color Time: 0.40348172187805176s\nmetrics Time: 0.4451467990875244s\n00ECUL14.csv\nTrue feature_model/Experiment_0/dev_predictions/00ECUL14.csv\npredict-using-model Time: 1.5507595539093018s\nget-kg-links-siamese_prediction Time: 0.9915750026702881s\nadd-color Time: 0.35164570808410645s\nmetrics Time: 0.4400782585144043s\n0FQOOJPU.csv\nTrue feature_model/Experiment_0/dev_predictions/0FQOOJPU.csv\npredict-using-model Time: 2.163877487182617s\nget-kg-links-siamese_prediction Time: 1.3990731239318848s\nadd-color Time: 0.525763750076294s\nmetrics Time: 0.6040730476379395s\n0P8H49LQ.csv\nTrue feature_model/Experiment_0/dev_predictions/0P8H49LQ.csv\npredict-using-model Time: 2.2529520988464355s\nget-kg-links-siamese_prediction Time: 1.4699361324310303s\nadd-color Time: 0.5955760478973389s\nmetrics Time: 0.5993585586547852s\n2PKG4E2V.csv\nTrue feature_model/Experiment_0/dev_predictions/2PKG4E2V.csv\npredict-using-model Time: 2.4153852462768555s\nget-kg-links-siamese_prediction Time: 1.8297555446624756s\nadd-color Time: 0.3743317127227783s\nmetrics Time: 0.7119498252868652s\n0JSF530F.csv\nTrue feature_model/Experiment_0/dev_predictions/0JSF530F.csv\npredict-using-model Time: 1.8719711303710938s\nget-kg-links-siamese_prediction Time: 0.5940761566162109s\nadd-color Time: 0.41377902030944824s\nmetrics Time: 0.34502100944519043s\n1YPLVLS9.csv\nTrue feature_model/Experiment_0/dev_predictions/1YPLVLS9.csv\npredict-using-model Time: 2.099836826324463s\nget-kg-links-siamese_prediction Time: 0.8978662490844727s\nadd-color Time: 0.42412304878234863s\nmetrics Time: 0.35158371925354004s\n5PKTGQ6Q.csv\nTrue feature_model/Experiment_0/dev_predictions/5PKTGQ6Q.csv\npredict-using-model Time: 1.7930009365081787s\nget-kg-links-siamese_prediction Time: 0.6473615169525146s\nadd-color Time: 0.31005072593688965s\nmetrics Time: 0.1923835277557373s\n0QWF60VG.csv\nTrue feature_model/Experiment_0/dev_predictions/0QWF60VG.csv\npredict-using-model Time: 1.9115312099456787s\nget-kg-links-siamese_prediction Time: 1.3608272075653076s\nadd-color Time: 0.3946528434753418s\nmetrics Time: 0.565122127532959s\n3M5QXPWN.csv\nTrue feature_model/Experiment_0/dev_predictions/3M5QXPWN.csv\npredict-using-model Time: 1.9092092514038086s\nget-kg-links-siamese_prediction Time: 0.9756014347076416s\nadd-color Time: 0.4466123580932617s\nmetrics Time: 0.47066831588745117s\n0LF7RI6N.csv\nTrue feature_model/Experiment_0/dev_predictions/0LF7RI6N.csv\npredict-using-model Time: 1.9595744609832764s\nget-kg-links-siamese_prediction Time: 0.9918780326843262s\nadd-color Time: 0.35688042640686035s\nmetrics Time: 0.2713170051574707s\n44NDHWR1.csv\nTrue feature_model/Experiment_0/dev_predictions/44NDHWR1.csv\npredict-using-model Time: 2.3067986965179443s\nget-kg-links-siamese_prediction Time: 1.303394079208374s\nadd-color Time: 0.5899827480316162s\nmetrics Time: 0.5097446441650391s\n4PKEEJU4.csv\nTrue feature_model/Experiment_0/dev_predictions/4PKEEJU4.csv\npredict-using-model Time: 2.064344644546509s\nget-kg-links-siamese_prediction Time: 1.3065242767333984s\nadd-color Time: 0.4185152053833008s\nmetrics Time: 0.4065990447998047s\n1NS33P8C.csv\nTrue feature_model/Experiment_0/dev_predictions/1NS33P8C.csv\npredict-using-model Time: 1.854724645614624s\nget-kg-links-siamese_prediction Time: 0.6028003692626953s\nadd-color Time: 0.2157895565032959s\nmetrics Time: 0.17458653450012207s\n1GOKLC0K.csv\nTrue feature_model/Experiment_0/dev_predictions/1GOKLC0K.csv\npredict-using-model Time: 1.984095811843872s\nget-kg-links-siamese_prediction Time: 1.7065973281860352s\nadd-color Time: 0.7088665962219238s\nmetrics Time: 0.5014255046844482s\n3WXFYEAX.csv\nTrue feature_model/Experiment_0/dev_predictions/3WXFYEAX.csv\npredict-using-model Time: 1.606370449066162s\nget-kg-links-siamese_prediction Time: 0.7698655128479004s\nadd-color Time: 0.25163888931274414s\nmetrics Time: 0.2484898567199707s\n2QFYH2N9.csv\nTrue feature_model/Experiment_0/dev_predictions/2QFYH2N9.csv\npredict-using-model Time: 1.9207990169525146s\nget-kg-links-siamese_prediction Time: 1.543835163116455s\nadd-color Time: 0.4151294231414795s\nmetrics Time: 0.5135157108306885s\n3OCW1LDZ.csv\nTrue feature_model/Experiment_0/dev_predictions/3OCW1LDZ.csv\npredict-using-model Time: 2.0369832515716553s\nget-kg-links-siamese_prediction Time: 1.2348620891571045s\nadd-color Time: 0.4792165756225586s\nmetrics Time: 0.5684771537780762s\n4V4O0CTS.csv\nTrue feature_model/Experiment_0/dev_predictions/4V4O0CTS.csv\npredict-using-model Time: 2.0304365158081055s\nget-kg-links-siamese_prediction Time: 1.027151107788086s\nadd-color Time: 0.35413527488708496s\nmetrics Time: 0.2399592399597168s\n080HU8A5.csv\nTrue feature_model/Experiment_0/dev_predictions/080HU8A5.csv\npredict-using-model Time: 1.696422815322876s\nget-kg-links-siamese_prediction Time: 0.49567747116088867s\nadd-color Time: 0.460557222366333s\nmetrics Time: 0.11754703521728516s\n3JNFST2K.csv\nTrue feature_model/Experiment_0/dev_predictions/3JNFST2K.csv\npredict-using-model Time: 1.7260565757751465s\nget-kg-links-siamese_prediction Time: 0.6023037433624268s\nadd-color Time: 0.2949669361114502s\nmetrics Time: 0.26934003829956055s\n1XIWQBSF.csv\nTrue feature_model/Experiment_0/dev_predictions/1XIWQBSF.csv\npredict-using-model Time: 1.7923355102539062s\nget-kg-links-siamese_prediction Time: 0.7361116409301758s\nadd-color Time: 0.34220147132873535s\nmetrics Time: 0.33296775817871094s\n4DPRZWVL.csv\nTrue feature_model/Experiment_0/dev_predictions/4DPRZWVL.csv\npredict-using-model Time: 1.9022526741027832s\nget-kg-links-siamese_prediction Time: 0.6886591911315918s\nadd-color Time: 0.2996680736541748s\nmetrics Time: 0.11947345733642578s\n"
],
[
"merged_files = merge_eval_files('feature_model/Experiment_0/dev_predictions/')\nfrom sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import auc\nfrom matplotlib import pyplot\ntesty = merged_files['evaluation_label'].replace({-1:0})\nlr_probs = merged_files['siamese_prediction']\nlr_precision, lr_recall, _ = precision_recall_curve(testy.ravel(), lr_probs.ravel())\n# , lr_auc = f1_score(testy, yhat), auc(lr_recall, lr_precision)\npyplot.plot(lr_recall, lr_precision, marker='.', label='Experiment_0')\npyplot.xlabel('Recall')\npyplot.ylabel('Precision')\npyplot.legend()\npyplot.show()\nfrom numpy import sqrt, argmax\nfpr, tpr, thresholds = roc_curve(testy, lr_probs)\ngmeans = sqrt(tpr * (1-fpr))\nix = argmax(gmeans)\nprint('Best Threshold=%f, G-Mean=%.3f' % (thresholds[ix], gmeans[ix]))\npyplot.plot(fpr, tpr, marker='.', label='AUC Curve')\npyplot.scatter(fpr[ix], tpr[ix], marker='o', color='black', label='Best')\npyplot.xlabel('False Positive Rate')\npyplot.ylabel('True Positive Rate')\npyplot.legend()\npyplot.show()",
"/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (29,30,31,36,38,42,43,44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n"
],
[
"#All features\nfeature_version = 'Experiment_1/'\ncurr_features = experiment_feature_list[1]\nsaved_model = 'feature_model/Experiment_1/saved_models/scheduler_False_lr_0.0001_epoch_1_loss_0.33893075585365295_top1_0.9493127147766323.pth'\ndev_predictions_path = output_path + feature_version + 'dev_predictions/'\ndev_predictions_top_k = output_path + feature_version + 'dev_predictions_top_k/'\ndev_colorized = output_path + feature_version + 'dev_predictions_colorized/'\ndev_metrics_path = output_path + feature_version + 'dev_metrics/'\nfinal_score_column = 'siamese_prediction'\n!mkdir -p $dev_predictions_path\n!mkdir -p $dev_predictions_top_k\n!mkdir -p $dev_colorized\n!mkdir -p $dev_metrics_path\nmetrics_df = top_k_and_add_color(saved_model, curr_features, dev_feature_set, dev_predictions_top_k, dev_metrics_path, \n dev_predictions_path, dev_colorized, final_score_column, dev_metrics_path)\nmetrics_df.to_csv(dev_metrics_path + \"metrics_1.csv\", index = False)",
"0CETTKTA.csv\nTrue feature_model/Experiment_1/dev_predictions/0CETTKTA.csv\npredict-using-model Time: 2.3923561573028564s\nget-kg-links-siamese_prediction Time: 0.3849484920501709s\nadd-color Time: 0.3363220691680908s\nmetrics Time: 0.14985442161560059s\n2E6QBLCA.csv\nTrue feature_model/Experiment_1/dev_predictions/2E6QBLCA.csv\npredict-using-model Time: 2.089045524597168s\nget-kg-links-siamese_prediction Time: 0.8307502269744873s\nadd-color Time: 0.32142019271850586s\nmetrics Time: 0.40329480171203613s\n29D1VZHF.csv\nTrue feature_model/Experiment_1/dev_predictions/29D1VZHF.csv\npredict-using-model Time: 2.1651804447174072s\nget-kg-links-siamese_prediction Time: 1.2582557201385498s\nadd-color Time: 0.403339147567749s\nmetrics Time: 0.5518407821655273s\n2FXR6BX7.csv\nTrue feature_model/Experiment_1/dev_predictions/2FXR6BX7.csv\npredict-using-model Time: 2.3106675148010254s\nget-kg-links-siamese_prediction Time: 1.769784927368164s\nadd-color Time: 0.6839048862457275s\nmetrics Time: 0.77130126953125s\n53OUTCE4.csv\nTrue feature_model/Experiment_1/dev_predictions/53OUTCE4.csv\npredict-using-model Time: 2.541430950164795s\nget-kg-links-siamese_prediction Time: 1.1140615940093994s\nadd-color Time: 0.3124873638153076s\nmetrics Time: 0.30643653869628906s\n39W7XXTI.csv\nTrue feature_model/Experiment_1/dev_predictions/39W7XXTI.csv\npredict-using-model Time: 2.5648353099823s\nget-kg-links-siamese_prediction Time: 1.3109071254730225s\nadd-color Time: 0.5508213043212891s\nmetrics Time: 0.65824294090271s\n0LZ0M8W4.csv\nTrue feature_model/Experiment_1/dev_predictions/0LZ0M8W4.csv\npredict-using-model Time: 2.366154193878174s\nget-kg-links-siamese_prediction Time: 1.3853535652160645s\nadd-color Time: 0.3956735134124756s\nmetrics Time: 0.6043221950531006s\n4SOL8H0M.csv\nTrue feature_model/Experiment_1/dev_predictions/4SOL8H0M.csv\npredict-using-model Time: 2.373852252960205s\nget-kg-links-siamese_prediction Time: 2.08436918258667s\nadd-color Time: 0.5351407527923584s\nmetrics Time: 0.706218957901001s\n4DC5O5I4.csv\nTrue feature_model/Experiment_1/dev_predictions/4DC5O5I4.csv\npredict-using-model Time: 2.1684460639953613s\nget-kg-links-siamese_prediction Time: 0.3215193748474121s\nadd-color Time: 0.5110931396484375s\nmetrics Time: 0.2797558307647705s\n1T91CHXV.csv\nTrue feature_model/Experiment_1/dev_predictions/1T91CHXV.csv\npredict-using-model Time: 2.07092022895813s\nget-kg-links-siamese_prediction Time: 1.1073496341705322s\nadd-color Time: 0.5631897449493408s\nmetrics Time: 0.604529619216919s\n3OAZEVOY.csv\nTrue feature_model/Experiment_1/dev_predictions/3OAZEVOY.csv\npredict-using-model Time: 2.4912731647491455s\nget-kg-links-siamese_prediction Time: 1.8101329803466797s\nadd-color Time: 0.4447774887084961s\nmetrics Time: 0.7786293029785156s\n1PTL0CX1.csv\nTrue feature_model/Experiment_1/dev_predictions/1PTL0CX1.csv\npredict-using-model Time: 2.1389858722686768s\nget-kg-links-siamese_prediction Time: 0.8708076477050781s\nadd-color Time: 0.40471458435058594s\nmetrics Time: 0.26338744163513184s\n0WBTX8LY.csv\nTrue feature_model/Experiment_1/dev_predictions/0WBTX8LY.csv\npredict-using-model Time: 3.037415027618408s\nget-kg-links-siamese_prediction Time: 1.419541597366333s\nadd-color Time: 0.48818516731262207s\nmetrics Time: 0.40918684005737305s\n1GUVMENF.csv\nTrue feature_model/Experiment_1/dev_predictions/1GUVMENF.csv\npredict-using-model Time: 1.8199677467346191s\nget-kg-links-siamese_prediction Time: 0.4283936023712158s\nadd-color Time: 0.18687677383422852s\nmetrics Time: 0.20914530754089355s\n13BLTPJD.csv\nTrue feature_model/Experiment_1/dev_predictions/13BLTPJD.csv\nCommand: predict-using-model\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/predict-using-model.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: get-kg-links\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/get-kg-links.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: add color\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/add-color.py\", line 56, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: metrics\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/metrics.py\", line 42, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\n50NWQJ1T.csv\nTrue feature_model/Experiment_1/dev_predictions/50NWQJ1T.csv\npredict-using-model Time: 2.5533857345581055s\nget-kg-links-siamese_prediction Time: 1.108015775680542s\nadd-color Time: 0.5063295364379883s\nmetrics Time: 0.6199681758880615s\n3B54GZSX.csv\nTrue feature_model/Experiment_1/dev_predictions/3B54GZSX.csv\npredict-using-model Time: 2.525869846343994s\nget-kg-links-siamese_prediction Time: 1.0941321849822998s\nadd-color Time: 0.4935612678527832s\nmetrics Time: 0.4136240482330322s\n0G9YPQC0.csv\nTrue feature_model/Experiment_1/dev_predictions/0G9YPQC0.csv\npredict-using-model Time: 2.6327550411224365s\nget-kg-links-siamese_prediction Time: 1.3529281616210938s\nadd-color Time: 0.39110708236694336s\nmetrics Time: 0.5769758224487305s\n2YCSL7OH.csv\nTrue feature_model/Experiment_1/dev_predictions/2YCSL7OH.csv\npredict-using-model Time: 2.6119046211242676s\nget-kg-links-siamese_prediction Time: 1.135868787765503s\nadd-color Time: 0.549534797668457s\nmetrics Time: 0.749284029006958s\n28D7RBJT.csv\nTrue feature_model/Experiment_1/dev_predictions/28D7RBJT.csv\npredict-using-model Time: 2.0893890857696533s\nget-kg-links-siamese_prediction Time: 1.2456207275390625s\nadd-color Time: 0.38045620918273926s\nmetrics Time: 0.5197803974151611s\n1ZFRQBQS.csv\nTrue feature_model/Experiment_1/dev_predictions/1ZFRQBQS.csv\npredict-using-model Time: 2.275970220565796s\nget-kg-links-siamese_prediction Time: 2.5243325233459473s\nadd-color Time: 0.8726305961608887s\nmetrics Time: 0.8649914264678955s\n2FSRG0OI.csv\nTrue feature_model/Experiment_1/dev_predictions/2FSRG0OI.csv\npredict-using-model Time: 2.079714059829712s\nget-kg-links-siamese_prediction Time: 0.5222091674804688s\nadd-color Time: 0.4080073833465576s\nmetrics Time: 0.2710146903991699s\n4FG1UN8O.csv\nTrue feature_model/Experiment_1/dev_predictions/4FG1UN8O.csv\npredict-using-model Time: 3.0070981979370117s\nget-kg-links-siamese_prediction Time: 2.664395332336426s\nadd-color Time: 0.6778712272644043s\nmetrics Time: 0.7009439468383789s\n5TJI4XTK.csv\nTrue feature_model/Experiment_1/dev_predictions/5TJI4XTK.csv\npredict-using-model Time: 2.1545708179473877s\nget-kg-links-siamese_prediction Time: 0.708704948425293s\nadd-color Time: 0.28284287452697754s\nmetrics Time: 0.15870451927185059s\n5IXA0RAI.csv\nTrue feature_model/Experiment_1/dev_predictions/5IXA0RAI.csv\npredict-using-model Time: 1.9373993873596191s\nget-kg-links-siamese_prediction Time: 0.696044921875s\nadd-color Time: 0.39244771003723145s\nmetrics Time: 0.23950481414794922s\n0TQXSY28.csv\nTrue feature_model/Experiment_1/dev_predictions/0TQXSY28.csv\npredict-using-model Time: 2.1698124408721924s\nget-kg-links-siamese_prediction Time: 0.4174683094024658s\nadd-color Time: 0.2675130367279053s\nmetrics Time: 0.20435023307800293s\n58E7A5WL.csv\nTrue feature_model/Experiment_1/dev_predictions/58E7A5WL.csv\npredict-using-model Time: 2.488605260848999s\nget-kg-links-siamese_prediction Time: 1.21341872215271s\nadd-color Time: 0.4385254383087158s\nmetrics Time: 0.3296084403991699s\n59W76Q0Y.csv\nTrue feature_model/Experiment_1/dev_predictions/59W76Q0Y.csv\npredict-using-model Time: 2.1282286643981934s\nget-kg-links-siamese_prediction Time: 0.6363139152526855s\nadd-color Time: 0.22484064102172852s\nmetrics Time: 0.14730095863342285s\n2TGNKH1P.csv\nTrue feature_model/Experiment_1/dev_predictions/2TGNKH1P.csv\npredict-using-model Time: 2.065783739089966s\nget-kg-links-siamese_prediction Time: 0.8080558776855469s\nadd-color Time: 0.2516045570373535s\nmetrics Time: 0.25575900077819824s\n00ECUL14.csv\nTrue feature_model/Experiment_1/dev_predictions/00ECUL14.csv\npredict-using-model Time: 2.3762807846069336s\nget-kg-links-siamese_prediction Time: 0.8619673252105713s\nadd-color Time: 0.3615763187408447s\nmetrics Time: 0.31554484367370605s\n0FQOOJPU.csv\nTrue feature_model/Experiment_1/dev_predictions/0FQOOJPU.csv\npredict-using-model Time: 2.2933850288391113s\nget-kg-links-siamese_prediction Time: 1.2775788307189941s\nadd-color Time: 0.5209827423095703s\nmetrics Time: 0.565699577331543s\n0P8H49LQ.csv\nTrue feature_model/Experiment_1/dev_predictions/0P8H49LQ.csv\npredict-using-model Time: 2.291630506515503s\nget-kg-links-siamese_prediction Time: 1.2347404956817627s\nadd-color Time: 0.6472487449645996s\nmetrics Time: 0.7738068103790283s\n2PKG4E2V.csv\nTrue feature_model/Experiment_1/dev_predictions/2PKG4E2V.csv\npredict-using-model Time: 2.3746745586395264s\nget-kg-links-siamese_prediction Time: 1.5233445167541504s\nadd-color Time: 0.5423183441162109s\nmetrics Time: 0.6169407367706299s\n0JSF530F.csv\nTrue feature_model/Experiment_1/dev_predictions/0JSF530F.csv\npredict-using-model Time: 1.7675344944000244s\nget-kg-links-siamese_prediction Time: 0.2749326229095459s\nadd-color Time: 0.25406885147094727s\nmetrics Time: 0.2290968894958496s\n1YPLVLS9.csv\nTrue feature_model/Experiment_1/dev_predictions/1YPLVLS9.csv\npredict-using-model Time: 2.5092458724975586s\nget-kg-links-siamese_prediction Time: 1.1944835186004639s\nadd-color Time: 0.34122490882873535s\nmetrics Time: 0.5622007846832275s\n5PKTGQ6Q.csv\nTrue feature_model/Experiment_1/dev_predictions/5PKTGQ6Q.csv\npredict-using-model Time: 1.8005883693695068s\nget-kg-links-siamese_prediction Time: 0.46839141845703125s\nadd-color Time: 0.28150010108947754s\nmetrics Time: 0.23852109909057617s\n0QWF60VG.csv\nTrue feature_model/Experiment_1/dev_predictions/0QWF60VG.csv\npredict-using-model Time: 2.435567617416382s\nget-kg-links-siamese_prediction Time: 1.322033166885376s\nadd-color Time: 0.5123367309570312s\nmetrics Time: 0.4859323501586914s\n3M5QXPWN.csv\nTrue feature_model/Experiment_1/dev_predictions/3M5QXPWN.csv\npredict-using-model Time: 1.9669365882873535s\nget-kg-links-siamese_prediction Time: 1.3808012008666992s\nadd-color Time: 0.728663444519043s\nmetrics Time: 0.5943443775177002s\n0LF7RI6N.csv\nTrue feature_model/Experiment_1/dev_predictions/0LF7RI6N.csv\npredict-using-model Time: 2.570199966430664s\nget-kg-links-siamese_prediction Time: 0.9356060028076172s\nadd-color Time: 0.407670259475708s\nmetrics Time: 0.32657551765441895s\n44NDHWR1.csv\nTrue feature_model/Experiment_1/dev_predictions/44NDHWR1.csv\npredict-using-model Time: 2.346184015274048s\nget-kg-links-siamese_prediction Time: 1.7580394744873047s\nadd-color Time: 0.656630277633667s\nmetrics Time: 0.33096933364868164s\n4PKEEJU4.csv\nTrue feature_model/Experiment_1/dev_predictions/4PKEEJU4.csv\npredict-using-model Time: 2.647582769393921s\nget-kg-links-siamese_prediction Time: 1.61527419090271s\nadd-color Time: 0.3262143135070801s\nmetrics Time: 0.7736654281616211s\n1NS33P8C.csv\nTrue feature_model/Experiment_1/dev_predictions/1NS33P8C.csv\npredict-using-model Time: 1.899970293045044s\nget-kg-links-siamese_prediction Time: 0.3917827606201172s\nadd-color Time: 0.33298635482788086s\nmetrics Time: 0.1868908405303955s\n1GOKLC0K.csv\nTrue feature_model/Experiment_1/dev_predictions/1GOKLC0K.csv\npredict-using-model Time: 2.365800142288208s\nget-kg-links-siamese_prediction Time: 1.066185712814331s\nadd-color Time: 0.44699883460998535s\nmetrics Time: 0.6204423904418945s\n3WXFYEAX.csv\nTrue feature_model/Experiment_1/dev_predictions/3WXFYEAX.csv\npredict-using-model Time: 2.0307326316833496s\nget-kg-links-siamese_prediction Time: 0.510404109954834s\nadd-color Time: 0.4069094657897949s\nmetrics Time: 0.19423770904541016s\n2QFYH2N9.csv\nTrue feature_model/Experiment_1/dev_predictions/2QFYH2N9.csv\npredict-using-model Time: 1.8490941524505615s\nget-kg-links-siamese_prediction Time: 1.0671122074127197s\nadd-color Time: 0.5124356746673584s\nmetrics Time: 0.6352791786193848s\n3OCW1LDZ.csv\nTrue feature_model/Experiment_1/dev_predictions/3OCW1LDZ.csv\npredict-using-model Time: 2.8561060428619385s\nget-kg-links-siamese_prediction Time: 1.4695720672607422s\nadd-color Time: 0.5776965618133545s\nmetrics Time: 0.7739176750183105s\n4V4O0CTS.csv\nTrue feature_model/Experiment_1/dev_predictions/4V4O0CTS.csv\npredict-using-model Time: 2.3017709255218506s\nget-kg-links-siamese_prediction Time: 0.7907273769378662s\nadd-color Time: 0.3593618869781494s\nmetrics Time: 0.2971930503845215s\n080HU8A5.csv\nTrue feature_model/Experiment_1/dev_predictions/080HU8A5.csv\npredict-using-model Time: 2.2674710750579834s\nget-kg-links-siamese_prediction Time: 0.2753119468688965s\nadd-color Time: 0.44302940368652344s\nmetrics Time: 0.27297496795654297s\n3JNFST2K.csv\nTrue feature_model/Experiment_1/dev_predictions/3JNFST2K.csv\npredict-using-model Time: 2.107815980911255s\nget-kg-links-siamese_prediction Time: 0.7135448455810547s\nadd-color Time: 0.40291309356689453s\nmetrics Time: 0.21889042854309082s\n1XIWQBSF.csv\nTrue feature_model/Experiment_1/dev_predictions/1XIWQBSF.csv\npredict-using-model Time: 2.5282888412475586s\nget-kg-links-siamese_prediction Time: 0.8423986434936523s\nadd-color Time: 0.591984748840332s\nmetrics Time: 0.2724182605743408s\n4DPRZWVL.csv\nTrue feature_model/Experiment_1/dev_predictions/4DPRZWVL.csv\npredict-using-model Time: 1.9544014930725098s\nget-kg-links-siamese_prediction Time: 0.4226226806640625s\nadd-color Time: 0.31214475631713867s\nmetrics Time: 0.31232309341430664s\n"
],
[
"merged_files = merge_eval_files('feature_model/Experiment_1/dev_predictions/')\nfrom sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import auc\nfrom matplotlib import pyplot\ntesty = merged_files['evaluation_label'].replace({-1:0})\nlr_probs = merged_files['siamese_prediction']\nlr_precision, lr_recall, _ = precision_recall_curve(testy.ravel(), lr_probs.ravel())\n# , lr_auc = f1_score(testy, yhat), auc(lr_recall, lr_precision)\npyplot.plot(lr_recall, lr_precision, marker='.', label='Experiment_1')\npyplot.xlabel('Recall')\npyplot.ylabel('Precision')\npyplot.legend()\npyplot.show()\nfrom numpy import sqrt, argmax\nfpr, tpr, thresholds = roc_curve(testy, lr_probs)\ngmeans = sqrt(tpr * (1-fpr))\nix = argmax(gmeans)\nprint('Best Threshold=%f, G-Mean=%.3f' % (thresholds[ix], gmeans[ix]))\npyplot.plot(fpr, tpr, marker='.', label='AUC Curve')\npyplot.scatter(fpr[ix], tpr[ix], marker='o', color='black', label='Best')\npyplot.xlabel('False Positive Rate')\npyplot.ylabel('True Positive Rate')\npyplot.legend()\npyplot.show()",
"/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (29,30,31,36,38,42,43,44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n"
],
[
"#All features\nfeature_version = 'Experiment_2/'\ncurr_features = experiment_feature_list[2]\nsaved_model = 'feature_model/Experiment_2/saved_models/scheduler_False_lr_0.0001_epoch_4_loss_0.3986770808696747_top1_0.9407216494845361.pth'\ndev_predictions_path = output_path + feature_version + 'dev_predictions/'\ndev_predictions_top_k = output_path + feature_version + 'dev_predictions_top_k/'\ndev_colorized = output_path + feature_version + 'dev_predictions_colorized/'\ndev_metrics_path = output_path + feature_version + 'dev_metrics/'\nfinal_score_column = 'siamese_prediction'\n!mkdir -p $dev_predictions_path\n!mkdir -p $dev_predictions_top_k\n!mkdir -p $dev_colorized\n!mkdir -p $dev_metrics_path\nmetrics_df = top_k_and_add_color(saved_model, curr_features, dev_feature_set, dev_predictions_top_k, dev_metrics_path, \n dev_predictions_path, dev_colorized, final_score_column, dev_metrics_path)\nmetrics_df.to_csv(dev_metrics_path + \"metrics_1.csv\", index = False)",
"0CETTKTA.csv\nTrue feature_model/Experiment_2/dev_predictions/0CETTKTA.csv\npredict-using-model Time: 2.38728928565979s\nget-kg-links-siamese_prediction Time: 0.5535478591918945s\nadd-color Time: 0.2631034851074219s\nmetrics Time: 0.1934196949005127s\n2E6QBLCA.csv\nTrue feature_model/Experiment_2/dev_predictions/2E6QBLCA.csv\npredict-using-model Time: 3.6499245166778564s\nget-kg-links-siamese_prediction Time: 0.9281034469604492s\nadd-color Time: 0.23736834526062012s\nmetrics Time: 0.30437302589416504s\n29D1VZHF.csv\nTrue feature_model/Experiment_2/dev_predictions/29D1VZHF.csv\npredict-using-model Time: 1.9363048076629639s\nget-kg-links-siamese_prediction Time: 1.6534290313720703s\nadd-color Time: 0.4402942657470703s\nmetrics Time: 0.5147294998168945s\n2FXR6BX7.csv\nTrue feature_model/Experiment_2/dev_predictions/2FXR6BX7.csv\npredict-using-model Time: 2.2690224647521973s\nget-kg-links-siamese_prediction Time: 2.1170759201049805s\nadd-color Time: 0.5243716239929199s\nmetrics Time: 0.5473644733428955s\n53OUTCE4.csv\nTrue feature_model/Experiment_2/dev_predictions/53OUTCE4.csv\npredict-using-model Time: 2.2779626846313477s\nget-kg-links-siamese_prediction Time: 1.0251665115356445s\nadd-color Time: 0.4427468776702881s\nmetrics Time: 0.35259246826171875s\n39W7XXTI.csv\nTrue feature_model/Experiment_2/dev_predictions/39W7XXTI.csv\npredict-using-model Time: 2.2879583835601807s\nget-kg-links-siamese_prediction Time: 1.3390445709228516s\nadd-color Time: 0.5709376335144043s\nmetrics Time: 0.4881908893585205s\n0LZ0M8W4.csv\nTrue feature_model/Experiment_2/dev_predictions/0LZ0M8W4.csv\npredict-using-model Time: 1.9446542263031006s\nget-kg-links-siamese_prediction Time: 1.5863304138183594s\nadd-color Time: 0.4228219985961914s\nmetrics Time: 0.6104154586791992s\n4SOL8H0M.csv\nTrue feature_model/Experiment_2/dev_predictions/4SOL8H0M.csv\npredict-using-model Time: 2.006962537765503s\nget-kg-links-siamese_prediction Time: 2.1128907203674316s\nadd-color Time: 0.41160058975219727s\nmetrics Time: 0.7283680438995361s\n4DC5O5I4.csv\nTrue feature_model/Experiment_2/dev_predictions/4DC5O5I4.csv\npredict-using-model Time: 1.7432591915130615s\nget-kg-links-siamese_prediction Time: 0.5669558048248291s\nadd-color Time: 0.30170750617980957s\nmetrics Time: 0.204301118850708s\n1T91CHXV.csv\nTrue feature_model/Experiment_2/dev_predictions/1T91CHXV.csv\npredict-using-model Time: 1.9285073280334473s\nget-kg-links-siamese_prediction Time: 1.569897174835205s\nadd-color Time: 0.5626857280731201s\nmetrics Time: 0.5450761318206787s\n3OAZEVOY.csv\nTrue feature_model/Experiment_2/dev_predictions/3OAZEVOY.csv\npredict-using-model Time: 2.6857779026031494s\nget-kg-links-siamese_prediction Time: 1.883131742477417s\nadd-color Time: 0.5379476547241211s\nmetrics Time: 0.881584882736206s\n1PTL0CX1.csv\nTrue feature_model/Experiment_2/dev_predictions/1PTL0CX1.csv\npredict-using-model Time: 1.8417141437530518s\nget-kg-links-siamese_prediction Time: 0.7917203903198242s\nadd-color Time: 0.3204648494720459s\nmetrics Time: 0.3811767101287842s\n0WBTX8LY.csv\nTrue feature_model/Experiment_2/dev_predictions/0WBTX8LY.csv\npredict-using-model Time: 2.1957099437713623s\nget-kg-links-siamese_prediction Time: 1.5928077697753906s\nadd-color Time: 0.6476342678070068s\nmetrics Time: 0.5926849842071533s\n1GUVMENF.csv\nTrue feature_model/Experiment_2/dev_predictions/1GUVMENF.csv\npredict-using-model Time: 1.886305332183838s\nget-kg-links-siamese_prediction Time: 0.525620698928833s\n"
],
[
"merged_files = merge_eval_files('feature_model/Experiment_2/dev_predictions/')\nfrom sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import auc\nfrom matplotlib import pyplot\ntesty = merged_files['evaluation_label'].replace({-1:0})\nlr_probs = merged_files['siamese_prediction']\nlr_precision, lr_recall, _ = precision_recall_curve(testy.ravel(), lr_probs.ravel())\n# , lr_auc = f1_score(testy, yhat), auc(lr_recall, lr_precision)\npyplot.plot(lr_recall, lr_precision, marker='.', label='Experiment_2')\npyplot.xlabel('Recall')\npyplot.ylabel('Precision')\npyplot.legend()\npyplot.show()\nfrom numpy import sqrt, argmax\nfpr, tpr, thresholds = roc_curve(testy, lr_probs)\ngmeans = sqrt(tpr * (1-fpr))\nix = argmax(gmeans)\nprint('Best Threshold=%f, G-Mean=%.3f' % (thresholds[ix], gmeans[ix]))\npyplot.plot(fpr, tpr, marker='.', label='AUC Curve')\npyplot.scatter(fpr[ix], tpr[ix], marker='o', color='black', label='Best')\npyplot.xlabel('False Positive Rate')\npyplot.ylabel('True Positive Rate')\npyplot.legend()\npyplot.show()",
"/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (29,30,31,36,38,42,43,44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n"
],
[
"df = pd.read_csv('feature_model/Experiment_5/dev_metrics/metrics_1.csv')\ndf.head()",
"_____no_output_____"
],
[
"df['f1'].mean()",
"_____no_output_____"
],
[
"#All features\nfeature_version = 'Experiment_4/'\ncurr_features = experiment_feature_list[4]\nsaved_model = 'feature_model/Experimentf_4/saved_models/scheduler_False_lr_5e-05_epoch_8_loss_0.3923964202404022_top1_0.959192439862543.pth'\ndev_predictions_path = output_path + feature_version + 'dev_predictions/'\ndev_predictions_top_k = output_path + feature_version + 'dev_predictions_top_k/'\ndev_colorized = output_path + feature_version + 'dev_predictions_colorized/'\ndev_metrics_path = output_path + feature_version + 'dev_metrics/'\nfinal_score_column = 'siamese_prediction'\n!mkdir -p $dev_predictions_path\n!mkdir -p $dev_predictions_top_k\n!mkdir -p $dev_colorized\n!mkdir -p $dev_metrics_path\nmetrics_df = top_k_and_add_color(saved_model, curr_features, dev_feature_set, dev_predictions_top_k, dev_metrics_path, \n dev_predictions_path, dev_colorized, final_score_column, dev_metrics_path)\nmetrics_df.to_csv(dev_metrics_path + \"metrics_1.csv\", index = False)",
"0CETTKTA.csv\nTrue feature_model/Experiment_4/dev_predictions/0CETTKTA.csv\npredict-using-model Time: 4.977765798568726s\nget-kg-links-siamese_prediction Time: 0.503943920135498s\nadd-color Time: 0.27644991874694824s\nmetrics Time: 0.17095565795898438s\n2E6QBLCA.csv\nTrue feature_model/Experiment_4/dev_predictions/2E6QBLCA.csv\npredict-using-model Time: 1.9954547882080078s\nget-kg-links-siamese_prediction Time: 0.7740478515625s\nadd-color Time: 0.4377932548522949s\nmetrics Time: 0.27657294273376465s\n29D1VZHF.csv\nTrue feature_model/Experiment_4/dev_predictions/29D1VZHF.csv\npredict-using-model Time: 2.09439754486084s\nget-kg-links-siamese_prediction Time: 1.0388543605804443s\nadd-color Time: 0.4943351745605469s\nmetrics Time: 0.7239813804626465s\n2FXR6BX7.csv\nTrue feature_model/Experiment_4/dev_predictions/2FXR6BX7.csv\npredict-using-model Time: 2.0522539615631104s\nget-kg-links-siamese_prediction Time: 1.4053313732147217s\nadd-color Time: 0.4007875919342041s\nmetrics Time: 0.6531333923339844s\n53OUTCE4.csv\nTrue feature_model/Experiment_4/dev_predictions/53OUTCE4.csv\npredict-using-model Time: 2.177565574645996s\nget-kg-links-siamese_prediction Time: 0.8717615604400635s\nadd-color Time: 0.3159496784210205s\nmetrics Time: 0.5941004753112793s\n39W7XXTI.csv\nTrue feature_model/Experiment_4/dev_predictions/39W7XXTI.csv\npredict-using-model Time: 2.4075069427490234s\nget-kg-links-siamese_prediction Time: 1.2994327545166016s\nadd-color Time: 0.41161203384399414s\nmetrics Time: 0.5082416534423828s\n0LZ0M8W4.csv\nTrue feature_model/Experiment_4/dev_predictions/0LZ0M8W4.csv\npredict-using-model Time: 2.35444974899292s\nget-kg-links-siamese_prediction Time: 1.2736663818359375s\nadd-color Time: 0.34119486808776855s\nmetrics Time: 0.5370843410491943s\n4SOL8H0M.csv\nTrue feature_model/Experiment_4/dev_predictions/4SOL8H0M.csv\npredict-using-model Time: 2.339414119720459s\nget-kg-links-siamese_prediction Time: 1.27781081199646s\nadd-color Time: 0.36866021156311035s\nmetrics Time: 0.8366701602935791s\n4DC5O5I4.csv\nTrue feature_model/Experiment_4/dev_predictions/4DC5O5I4.csv\npredict-using-model Time: 1.704948902130127s\nget-kg-links-siamese_prediction Time: 0.3190317153930664s\nadd-color Time: 0.3128669261932373s\nmetrics Time: 0.15283989906311035s\n1T91CHXV.csv\nTrue feature_model/Experiment_4/dev_predictions/1T91CHXV.csv\npredict-using-model Time: 2.2119007110595703s\nget-kg-links-siamese_prediction Time: 1.5574147701263428s\nadd-color Time: 0.4952096939086914s\nmetrics Time: 0.5854203701019287s\n3OAZEVOY.csv\nTrue feature_model/Experiment_4/dev_predictions/3OAZEVOY.csv\npredict-using-model Time: 2.709601402282715s\nget-kg-links-siamese_prediction Time: 1.923964500427246s\nadd-color Time: 0.5099949836730957s\nmetrics Time: 0.7394511699676514s\n1PTL0CX1.csv\nTrue feature_model/Experiment_4/dev_predictions/1PTL0CX1.csv\npredict-using-model Time: 2.091013193130493s\nget-kg-links-siamese_prediction Time: 0.7556295394897461s\nadd-color Time: 0.37508344650268555s\nmetrics Time: 0.33055686950683594s\n0WBTX8LY.csv\nTrue feature_model/Experiment_4/dev_predictions/0WBTX8LY.csv\npredict-using-model Time: 2.1212966442108154s\nget-kg-links-siamese_prediction Time: 1.2108471393585205s\nadd-color Time: 0.5699021816253662s\nmetrics Time: 0.5576863288879395s\n1GUVMENF.csv\nTrue feature_model/Experiment_4/dev_predictions/1GUVMENF.csv\npredict-using-model Time: 1.70029878616333s\nget-kg-links-siamese_prediction Time: 0.37624669075012207s\nadd-color Time: 0.3185274600982666s\nmetrics Time: 0.13263225555419922s\n13BLTPJD.csv\nTrue feature_model/Experiment_4/dev_predictions/13BLTPJD.csv\nCommand: predict-using-model\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/predict-using-model.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: get-kg-links\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/get-kg-links.py\", line 46, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: add color\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/add-color.py\", line 56, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\nCommand: metrics\nError Message: Traceback (most recent call last):\n File \"/nas/home/hrathod/table-linker/tl/cli/metrics.py\", line 42, in run\n df = pd.read_csv(kwargs['input_file'], dtype=object)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/util/_decorators.py\", line 311, in wrapper\n return func(*args, **kwargs)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 586, in read_csv\n return _read(filepath_or_buffer, kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 482, in _read\n parser = TextFileReader(filepath_or_buffer, **kwds)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 811, in __init__\n self._engine = self._make_engine(self.engine)\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/readers.py\", line 1040, in _make_engine\n return mapping[engine](self.f, **self.options) # type: ignore[call-arg]\n File \"/nas/home/hrathod/table-linker/tl_env/lib/python3.8/site-packages/pandas/io/parsers/c_parser_wrapper.py\", line 69, in __init__\n self._reader = parsers.TextReader(self.handles.handle, **kwds)\n File \"pandas/_libs/parsers.pyx\", line 549, in pandas._libs.parsers.TextReader.__cinit__\npandas.errors.EmptyDataError: No columns to parse from file\n\n50NWQJ1T.csv\nTrue feature_model/Experiment_4/dev_predictions/50NWQJ1T.csv\npredict-using-model Time: 2.1272478103637695s\nget-kg-links-siamese_prediction Time: 1.589555263519287s\nadd-color Time: 0.45031070709228516s\nmetrics Time: 0.8091104030609131s\n3B54GZSX.csv\nTrue feature_model/Experiment_4/dev_predictions/3B54GZSX.csv\npredict-using-model Time: 2.445624589920044s\nget-kg-links-siamese_prediction Time: 1.200709342956543s\nadd-color Time: 0.3430812358856201s\nmetrics Time: 0.6165335178375244s\n0G9YPQC0.csv\nTrue feature_model/Experiment_4/dev_predictions/0G9YPQC0.csv\npredict-using-model Time: 2.3070530891418457s\nget-kg-links-siamese_prediction Time: 1.1154913902282715s\nadd-color Time: 0.47570180892944336s\nmetrics Time: 0.5744845867156982s\n2YCSL7OH.csv\nTrue feature_model/Experiment_4/dev_predictions/2YCSL7OH.csv\npredict-using-model Time: 2.3486320972442627s\nget-kg-links-siamese_prediction Time: 1.3185148239135742s\nadd-color Time: 0.39600396156311035s\nmetrics Time: 0.48488807678222656s\n28D7RBJT.csv\nTrue feature_model/Experiment_4/dev_predictions/28D7RBJT.csv\npredict-using-model Time: 2.121316909790039s\nget-kg-links-siamese_prediction Time: 0.9381284713745117s\nadd-color Time: 0.3607666492462158s\nmetrics Time: 0.27336668968200684s\n1ZFRQBQS.csv\nTrue feature_model/Experiment_4/dev_predictions/1ZFRQBQS.csv\npredict-using-model Time: 2.5158324241638184s\nget-kg-links-siamese_prediction Time: 2.1091816425323486s\nadd-color Time: 0.6347098350524902s\nmetrics Time: 1.1493630409240723s\n2FSRG0OI.csv\nTrue feature_model/Experiment_4/dev_predictions/2FSRG0OI.csv\npredict-using-model Time: 1.9761371612548828s\nget-kg-links-siamese_prediction Time: 0.4094812870025635s\nadd-color Time: 0.18355202674865723s\nmetrics Time: 0.2594761848449707s\n4FG1UN8O.csv\nTrue feature_model/Experiment_4/dev_predictions/4FG1UN8O.csv\npredict-using-model Time: 1.9813973903656006s\nget-kg-links-siamese_prediction Time: 2.1265199184417725s\nadd-color Time: 0.3580784797668457s\nmetrics Time: 1.16709303855896s\n5TJI4XTK.csv\nTrue feature_model/Experiment_4/dev_predictions/5TJI4XTK.csv\npredict-using-model Time: 1.6762115955352783s\nget-kg-links-siamese_prediction Time: 0.5334351062774658s\nadd-color Time: 0.21640300750732422s\nmetrics Time: 0.16980791091918945s\n5IXA0RAI.csv\nTrue feature_model/Experiment_4/dev_predictions/5IXA0RAI.csv\npredict-using-model Time: 1.885678768157959s\nget-kg-links-siamese_prediction Time: 0.595587968826294s\nadd-color Time: 0.22745728492736816s\nmetrics Time: 0.2380681037902832s\n0TQXSY28.csv\nTrue feature_model/Experiment_4/dev_predictions/0TQXSY28.csv\npredict-using-model Time: 2.033801794052124s\nget-kg-links-siamese_prediction Time: 0.2796604633331299s\nadd-color Time: 0.23064613342285156s\nmetrics Time: 0.21874523162841797s\n58E7A5WL.csv\nTrue feature_model/Experiment_4/dev_predictions/58E7A5WL.csv\npredict-using-model Time: 2.0826570987701416s\nget-kg-links-siamese_prediction Time: 0.8846511840820312s\nadd-color Time: 0.37014007568359375s\nmetrics Time: 0.5209767818450928s\n59W76Q0Y.csv\nTrue feature_model/Experiment_4/dev_predictions/59W76Q0Y.csv\npredict-using-model Time: 2.018171787261963s\nget-kg-links-siamese_prediction Time: 0.4100494384765625s\nadd-color Time: 0.41719961166381836s\nmetrics Time: 0.265352725982666s\n2TGNKH1P.csv\nTrue feature_model/Experiment_4/dev_predictions/2TGNKH1P.csv\npredict-using-model Time: 2.3569393157958984s\nget-kg-links-siamese_prediction Time: 1.1375362873077393s\nadd-color Time: 0.34426093101501465s\nmetrics Time: 0.4030947685241699s\n00ECUL14.csv\nTrue feature_model/Experiment_4/dev_predictions/00ECUL14.csv\npredict-using-model Time: 1.9870455265045166s\nget-kg-links-siamese_prediction Time: 0.7686171531677246s\nadd-color Time: 0.5566980838775635s\nmetrics Time: 0.34863877296447754s\n0FQOOJPU.csv\nTrue feature_model/Experiment_4/dev_predictions/0FQOOJPU.csv\npredict-using-model Time: 2.2269437313079834s\nget-kg-links-siamese_prediction Time: 1.39764404296875s\nadd-color Time: 0.46552419662475586s\nmetrics Time: 0.8294961452484131s\n0P8H49LQ.csv\nTrue feature_model/Experiment_4/dev_predictions/0P8H49LQ.csv\npredict-using-model Time: 2.0915234088897705s\nget-kg-links-siamese_prediction Time: 1.4795124530792236s\nadd-color Time: 0.533480167388916s\nmetrics Time: 0.5775282382965088s\n2PKG4E2V.csv\nTrue feature_model/Experiment_4/dev_predictions/2PKG4E2V.csv\npredict-using-model Time: 2.3365485668182373s\nget-kg-links-siamese_prediction Time: 1.8313307762145996s\nadd-color Time: 0.5794978141784668s\nmetrics Time: 0.6635303497314453s\n0JSF530F.csv\nTrue feature_model/Experiment_4/dev_predictions/0JSF530F.csv\npredict-using-model Time: 1.5591752529144287s\nget-kg-links-siamese_prediction Time: 0.3577921390533447s\nadd-color Time: 0.22298121452331543s\nmetrics Time: 0.31488919258117676s\n1YPLVLS9.csv\nTrue feature_model/Experiment_4/dev_predictions/1YPLVLS9.csv\npredict-using-model Time: 1.8408551216125488s\nget-kg-links-siamese_prediction Time: 0.8134803771972656s\nadd-color Time: 0.3016972541809082s\nmetrics Time: 0.4237179756164551s\n5PKTGQ6Q.csv\nTrue feature_model/Experiment_4/dev_predictions/5PKTGQ6Q.csv\npredict-using-model Time: 1.849212884902954s\nget-kg-links-siamese_prediction Time: 0.4633793830871582s\nadd-color Time: 0.3249988555908203s\nmetrics Time: 0.25080060958862305s\n0QWF60VG.csv\nTrue feature_model/Experiment_4/dev_predictions/0QWF60VG.csv\npredict-using-model Time: 2.6947219371795654s\nget-kg-links-siamese_prediction Time: 1.196183204650879s\nadd-color Time: 0.6302235126495361s\nmetrics Time: 0.5334343910217285s\n3M5QXPWN.csv\nTrue feature_model/Experiment_4/dev_predictions/3M5QXPWN.csv\npredict-using-model Time: 2.1244895458221436s\nget-kg-links-siamese_prediction Time: 1.333806037902832s\nadd-color Time: 0.4082167148590088s\nmetrics Time: 0.7157597541809082s\n0LF7RI6N.csv\nTrue feature_model/Experiment_4/dev_predictions/0LF7RI6N.csv\npredict-using-model Time: 1.876493215560913s\nget-kg-links-siamese_prediction Time: 0.8000423908233643s\nadd-color Time: 0.4342997074127197s\nmetrics Time: 0.37240147590637207s\n44NDHWR1.csv\nTrue feature_model/Experiment_4/dev_predictions/44NDHWR1.csv\npredict-using-model Time: 2.0372226238250732s\nget-kg-links-siamese_prediction Time: 1.2845752239227295s\nadd-color Time: 0.3646049499511719s\nmetrics Time: 0.5463500022888184s\n4PKEEJU4.csv\nTrue feature_model/Experiment_4/dev_predictions/4PKEEJU4.csv\npredict-using-model Time: 1.8503522872924805s\nget-kg-links-siamese_prediction Time: 1.4439504146575928s\nadd-color Time: 0.4748687744140625s\nmetrics Time: 0.4749305248260498s\n1NS33P8C.csv\nTrue feature_model/Experiment_4/dev_predictions/1NS33P8C.csv\npredict-using-model Time: 1.6500210762023926s\nget-kg-links-siamese_prediction Time: 0.375255823135376s\nadd-color Time: 0.2810201644897461s\nmetrics Time: 0.23900508880615234s\n1GOKLC0K.csv\nTrue feature_model/Experiment_4/dev_predictions/1GOKLC0K.csv\npredict-using-model Time: 2.1593363285064697s\nget-kg-links-siamese_prediction Time: 0.9676432609558105s\nadd-color Time: 0.4649622440338135s\nmetrics Time: 0.41695475578308105s\n3WXFYEAX.csv\nTrue feature_model/Experiment_4/dev_predictions/3WXFYEAX.csv\npredict-using-model Time: 1.964216947555542s\nget-kg-links-siamese_prediction Time: 0.38086533546447754s\nadd-color Time: 0.46136474609375s\nmetrics Time: 0.15697288513183594s\n2QFYH2N9.csv\nTrue feature_model/Experiment_4/dev_predictions/2QFYH2N9.csv\npredict-using-model Time: 2.0543508529663086s\nget-kg-links-siamese_prediction Time: 1.2016925811767578s\nadd-color Time: 0.3762791156768799s\nmetrics Time: 0.5079977512359619s\n3OCW1LDZ.csv\nTrue feature_model/Experiment_4/dev_predictions/3OCW1LDZ.csv\npredict-using-model Time: 2.415144920349121s\nget-kg-links-siamese_prediction Time: 1.6117117404937744s\nadd-color Time: 0.5206904411315918s\nmetrics Time: 0.6320018768310547s\n4V4O0CTS.csv\nTrue feature_model/Experiment_4/dev_predictions/4V4O0CTS.csv\npredict-using-model Time: 2.254556894302368s\nget-kg-links-siamese_prediction Time: 1.180032730102539s\nadd-color Time: 0.3858218193054199s\nmetrics Time: 0.4033083915710449s\n080HU8A5.csv\nTrue feature_model/Experiment_4/dev_predictions/080HU8A5.csv\npredict-using-model Time: 1.728126049041748s\nget-kg-links-siamese_prediction Time: 0.38815760612487793s\nadd-color Time: 0.4907500743865967s\nmetrics Time: 0.17386651039123535s\n3JNFST2K.csv\nTrue feature_model/Experiment_4/dev_predictions/3JNFST2K.csv\npredict-using-model Time: 1.8671953678131104s\nget-kg-links-siamese_prediction Time: 0.7211868762969971s\nadd-color Time: 0.22279000282287598s\nmetrics Time: 0.15195631980895996s\n1XIWQBSF.csv\nTrue feature_model/Experiment_4/dev_predictions/1XIWQBSF.csv\npredict-using-model Time: 2.241870403289795s\nget-kg-links-siamese_prediction Time: 0.7653210163116455s\nadd-color Time: 0.33577680587768555s\nmetrics Time: 0.529473066329956s\n4DPRZWVL.csv\nTrue feature_model/Experiment_4/dev_predictions/4DPRZWVL.csv\npredict-using-model Time: 1.8124608993530273s\nget-kg-links-siamese_prediction Time: 0.42856764793395996s\nadd-color Time: 0.3738679885864258s\nmetrics Time: 0.20772242546081543s\n"
],
[
"merged_files = merge_eval_files('feature_model/Experiment_4/dev_predictions/')\nfrom sklearn.datasets import make_classification\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve, roc_curve\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import auc\nfrom matplotlib import pyplot\ntesty = merged_files['evaluation_label'].replace({-1:0})\nlr_probs = merged_files['siamese_prediction']\nlr_precision, lr_recall, _ = precision_recall_curve(testy.ravel(), lr_probs.ravel())\n# , lr_auc = f1_score(testy, yhat), auc(lr_recall, lr_precision)\npyplot.plot(lr_recall, lr_precision, marker='.', label='Experiment_4')\npyplot.xlabel('Recall')\npyplot.ylabel('Precision')\npyplot.legend()\npyplot.show()\nfrom numpy import sqrt, argmax\nfpr, tpr, thresholds = roc_curve(testy, lr_probs)\n#gmeans = 2*fpr*tpr / (fpr + tpr)\n#print(gmeans)\ngmeans = sqrt(tpr * (1-fpr))\nix = argmax(gmeans)\nprint('Best Threshold=%f, G-Mean=%.3f' % (thresholds[ix], gmeans[ix]))\npyplot.plot(fpr, tpr, marker='.', label='AUC Curve')\npyplot.scatter(fpr[ix], tpr[ix], marker='o', color='black', label='Best')\npyplot.xlabel('False Positive Rate')\npyplot.ylabel('True Positive Rate')\npyplot.legend()\npyplot.show()",
"/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (29,30,31,36,38,42,43,44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n/nas/home/hrathod/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3338: DtypeWarning: Columns (44) have mixed types.Specify dtype option on import or set low_memory=False.\n if (await self.run_code(code, result, async_=asy)):\n"
],
[
"def calc_precision_recall(y_true, y_pred):\n \n # Convert predictions to series with index matching y_true\n y_pred = pd.Series(y_pred, index=y_true.index)\n \n # Instantiate counters\n TP = 0\n FP = 0\n FN = 0\n\n # Determine whether each prediction is TP, FP, TN, or FN\n \n for i in y_true.index: \n try:\n if y_true[i]==y_pred[i]==1:\n TP += 1\n if y_pred[i]==1 and y_true[i]!=y_pred[i]:\n FP += 1\n if y_pred[i]==0 and y_true[i]!=y_pred[i]:\n FN += 1\n except:\n print(y_true[i], y_pred[i])\n # Calculate true positive rate and false positive rate\n # Use try-except statements to avoid problem of dividing by 0\n # print(TP, FP, FN)\n try:\n precision = TP / (TP + FP)\n except:\n precision = 1\n \n try:\n recall = TP / (TP + FN)\n except:\n recall = 1\n\n return precision, recall\n#precision, recall = calc_precision_recall(testy, lr_probs)",
"_____no_output_____"
],
[
"probability_thresholds = np.linspace(0, 1, num=1000)\nlen(probability_thresholds)",
"_____no_output_____"
],
[
"# probability_thresholds[:-30]",
"_____no_output_____"
],
[
"print(sklearn.metrics.classification_report(y_test, y_test_probs))",
"_____no_output_____"
],
[
"precision_scores = []\nrecall_scores = []\nprecision_scores_1 = []\nrecall_scores_1 = []\ny_test_probs = lr_probs\ny_test = testy\n# Define probability thresholds to use, between 0 and 1\nprobability_thresholds = np.linspace(0, 1, num=500)\ny_test = y_test.reset_index(drop = True)\ny_test_probs = y_test_probs.reset_index(drop = True)\n# Find true positive / false positive rate for each threshold\nfor p in probability_thresholds:\n \n y_test_preds = []\n \n for prob in y_test_probs:\n if prob > p:\n y_test_preds.append(1)\n else:\n y_test_preds.append(0)\n \n #precision, recall = sklearn.metrics.precision_score(y_test, y_test_preds), sklearn.metrics.recall_score(y_test, y_test_preds)\n precision_1, recall_1 = calc_precision_recall(y_test, y_test_preds)\n \n precision_scores.append(precision_1)\n recall_scores.append(recall_1)\n #precision_scores_1.append(precision_1)\n #recall_scores_1.append(recall_1)",
"_____no_output_____"
],
[
"len(recall_scores)",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nfig, ax = plt.subplots(figsize=(6,6))\nax.plot(recall_scores, precision_scores, label='Logistic Regression')\n# ax.plot(l2_recall_scores, l2_precision_scores, label='L2 Logistic Regression')\nbaseline = len(y_test[y_test==1]) / len(y_test)\nax.plot([0, 1], [baseline, baseline], linestyle='--', label='Baseline')\nax.set_xlabel('Recall')\nax.set_ylabel('Precision')\nax.legend(loc='center left');",
"_____no_output_____"
],
[
"import matplotlib.pyplot as plt\nfig, ax = plt.subplots(figsize=(6,6))\nax.plot(recall_scores_1, precision_scores_1, label='Logistic Regression')\n# ax.plot(l2_recall_scores, l2_precision_scores, label='L2 Logistic Regression')\nbaseline = len(y_test[y_test==1]) / len(y_test)\nax.plot([0, 1], [baseline, baseline], linestyle='--', label='Baseline')\nax.set_xlabel('Recall')\nax.set_ylabel('Precision')\nax.legend(loc='center left');",
"_____no_output_____"
]
]
] |
[
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb439f3a86b87dfe9e2cdaf36805d804f30db55
| 77,615 |
ipynb
|
Jupyter Notebook
|
examples/mnist.ipynb
|
simaki/deep-gamblers
|
47704ebea82c01f08208e352edb23a948d0c4ac4
|
[
"MIT"
] | 3 |
2021-02-23T12:39:01.000Z
|
2021-12-04T18:13:43.000Z
|
examples/mnist.ipynb
|
simaki/deep-gamblers
|
47704ebea82c01f08208e352edb23a948d0c4ac4
|
[
"MIT"
] | null | null | null |
examples/mnist.ipynb
|
simaki/deep-gamblers
|
47704ebea82c01f08208e352edb23a948d0c4ac4
|
[
"MIT"
] | 3 |
2020-12-08T00:14:50.000Z
|
2021-12-26T23:22:16.000Z
| 260.45302 | 43,784 | 0.912298 |
[
[
[
"!pip install --quiet git+https://github.com/simaki/deep-gamblers",
"\u001b[33mWARNING: You are using pip version 20.0.2; however, version 20.1.1 is available.\nYou should consider upgrading via the '/usr/local/opt/[email protected]/bin/python3.8 -m pip install --upgrade pip' command.\u001b[0m\n"
],
[
"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom deep_gamblers import coverage, GamblerLoss",
"_____no_output_____"
]
],
[
[
"## Load",
"_____no_output_____"
]
],
[
[
"def normalize(x):\n return x / 255.0\n\n\ndef split_tr_va(a, p=0.2):\n n = a.shape[0]\n a_tr, a_va = a[: int(n * p)], a[int(n * p) :]\n return (a_tr, a_va)\n\n\ndef get_onehot(y):\n return np.eye(10)[y]\n\n\ndef add_newaxis(x):\n return x[..., np.newaxis]",
"_____no_output_____"
],
[
"from tensorflow.keras.datasets import mnist\n\n(x_tr, y_tr), (x_te, y_te) = mnist.load_data()\n\nx_tr, x_te = normalize(x_tr), normalize(x_te)\nx_tr, x_te = add_newaxis(x_tr), add_newaxis(x_te)\ny_tr, y_te = get_onehot(y_tr), get_onehot(y_te)\nx_tr, x_va = split_tr_va(x_tr)\ny_tr, y_va = split_tr_va(y_tr)",
"_____no_output_____"
],
[
"plt.figure(figsize=(24, 4))\n\nh, w = 2, 12\n\nfor i in range(h * w):\n plt.subplot(h, w, i + 1)\n plt.imshow(x_tr[i, ..., 0], cmap=\"gray\")\n plt.axis(\"off\")\n plt.title(np.argmax(y_tr[i]))\n\nplt.show()",
"_____no_output_____"
]
],
[
[
"## Predict",
"_____no_output_____"
]
],
[
[
"tf.keras.backend.clear_session()\ntf.random.set_seed(42)",
"_____no_output_____"
],
[
"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dense, Flatten\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nmodel = Sequential(\n [\n Conv2D(10, 4, activation=\"relu\"),\n Conv2D(10, 4, activation=\"relu\"),\n Conv2D(10, 4, activation=\"relu\"),\n Conv2D(10, 4, activation=\"relu\"),\n Flatten(),\n Dense(10 + 1, activation=\"softmax\"),\n ]\n)",
"_____no_output_____"
],
[
"model.compile(optimizer=\"adam\", loss=GamblerLoss(10.0), metrics=[coverage, \"accuracy\"])\nmodel.fit(x_tr, y_tr, epochs=1)",
"375/375 [==============================] - 12s 31ms/step - loss: 0.3540 - coverage: 1.0000 - accuracy: 0.8913\n"
],
[
"model.compile(optimizer=\"adam\", loss=GamblerLoss(2.6), metrics=[coverage, \"accuracy\"])\nmodel.fit(\n x_tr,\n y_tr,\n validation_data=(x_va, y_va),\n epochs=30,\n callbacks=[EarlyStopping(patience=2,),],\n)\nmodel.evaluate(x_te, y_te)",
"Epoch 1/30\n375/375 [==============================] - 27s 72ms/step - loss: 0.1179 - coverage: 0.9988 - accuracy: 0.9640 - val_loss: 0.1296 - val_coverage: 0.9997 - val_accuracy: 0.9595\nEpoch 2/30\n375/375 [==============================] - 26s 69ms/step - loss: 0.0787 - coverage: 0.9959 - accuracy: 0.9718 - val_loss: 0.1040 - val_coverage: 0.9996 - val_accuracy: 0.9675\nEpoch 3/30\n375/375 [==============================] - 30s 80ms/step - loss: 0.0548 - coverage: 0.9970 - accuracy: 0.9804 - val_loss: 0.0950 - val_coverage: 0.9952 - val_accuracy: 0.9701\nEpoch 4/30\n375/375 [==============================] - 29s 77ms/step - loss: 0.0417 - coverage: 0.9962 - accuracy: 0.9837 - val_loss: 0.1105 - val_coverage: 0.9976 - val_accuracy: 0.9671\nEpoch 5/30\n375/375 [==============================] - 27s 73ms/step - loss: 0.0321 - coverage: 0.9966 - accuracy: 0.9872 - val_loss: 0.1188 - val_coverage: 0.9976 - val_accuracy: 0.9697\n313/313 [==============================] - 3s 8ms/step - loss: 0.1104 - coverage: 0.9981 - accuracy: 0.9717\n"
],
[
"y_pr = model.predict(x_te)\ni_top_reject = np.argsort(-y_pr[:, -1])\nx_top_reject = x_te[i_top_reject]\ny_top_reject = y_te[i_top_reject]\n\nplt.figure(figsize=(24, 8))\n\nh, w = 4, 12\n\nfor i in range(h * w):\n plt.subplot(h, w, i + 1)\n plt.imshow(x_top_reject[i, ..., 0], cmap=\"gray\")\n plt.axis(\"off\")\n plt.title(np.argmax(y_top_reject[i]))\n\nplt.show()",
"_____no_output_____"
]
]
] |
[
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbb43caa0a75b0d75a7d82b41667e82e7831492e
| 49,694 |
ipynb
|
Jupyter Notebook
|
.ipynb_checkpoints/Model1 - grid approximation-checkpoint.ipynb
|
drbenvincent/bayesian2afc-julia
|
566e97a8f3aa4e7ff4efd4554060542ca2af90db
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Model1 - grid approximation-checkpoint.ipynb
|
drbenvincent/bayesian2afc-julia
|
566e97a8f3aa4e7ff4efd4554060542ca2af90db
|
[
"MIT"
] | null | null | null |
.ipynb_checkpoints/Model1 - grid approximation-checkpoint.ipynb
|
drbenvincent/bayesian2afc-julia
|
566e97a8f3aa4e7ff4efd4554060542ca2af90db
|
[
"MIT"
] | null | null | null | 57.85099 | 243 | 0.596792 |
[
[
[
"empty"
]
]
] |
[
"empty"
] |
[
[
"empty"
]
] |
cbb44ab389b0984610e4e7bf789025437caf3097
| 15,352 |
ipynb
|
Jupyter Notebook
|
MeanMedianMode.ipynb
|
hao44le/DataScience
|
9c3278041e07208ad05d5185072daf0bdd8d03d5
|
[
"MIT"
] | 4 |
2018-07-04T22:14:23.000Z
|
2018-07-04T22:22:07.000Z
|
MeanMedianMode.ipynb
|
hao44le/DataScience
|
9c3278041e07208ad05d5185072daf0bdd8d03d5
|
[
"MIT"
] | null | null | null |
MeanMedianMode.ipynb
|
hao44le/DataScience
|
9c3278041e07208ad05d5185072daf0bdd8d03d5
|
[
"MIT"
] | null | null | null | 50.834437 | 7,860 | 0.715737 |
[
[
[
"# Mean, Median, Mode, and introducing NumPy",
"_____no_output_____"
],
[
"## Mean vs. Median",
"_____no_output_____"
],
[
"Let's create some fake income data, centered around 27,000 with a normal distribution and standard deviation of 15,000, with 10,000 data points. (We'll discuss those terms more later, if you're not familiar with them.)\n\nThen, compute the mean (average) - it should be close to 27,000:",
"_____no_output_____"
]
],
[
[
"import numpy as np\n\nincomes = np.random.normal(27000, 15000, 10000)\nnp.mean(incomes)",
"_____no_output_____"
]
],
[
[
"We can segment the income data into 50 buckets, and plot it as a histogram:",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nplt.hist(incomes, 50)\nplt.show()",
"_____no_output_____"
]
],
[
[
"Now compute the median - since we have a nice, even distribution it too should be close to 27,000:",
"_____no_output_____"
]
],
[
[
"np.median(incomes)",
"_____no_output_____"
]
],
[
[
"Now we'll add Donald Trump into the mix. Darn income inequality!",
"_____no_output_____"
]
],
[
[
"incomes = np.append(incomes, [1000000000])",
"_____no_output_____"
]
],
[
[
"The median won't change much, but the mean does:",
"_____no_output_____"
]
],
[
[
"np.median(incomes)",
"_____no_output_____"
],
[
"np.mean(incomes)",
"_____no_output_____"
]
],
[
[
"## Mode",
"_____no_output_____"
],
[
"Next, let's generate some fake age data for 500 people:",
"_____no_output_____"
]
],
[
[
"ages = np.random.randint(18, high=90, size=500)\nages",
"_____no_output_____"
],
[
"from scipy import stats\nstats.mode(ages)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cbb44de5301a5708b1d958dbc8d928802894daf7
| 11,218 |
ipynb
|
Jupyter Notebook
|
templates/2_create_tma_mibi_run.ipynb
|
angelolab/toffy
|
4d6c50fe0dfbf1568ee3f9db2182a04dc9ac85c6
|
[
"Apache-2.0"
] | null | null | null |
templates/2_create_tma_mibi_run.ipynb
|
angelolab/toffy
|
4d6c50fe0dfbf1568ee3f9db2182a04dc9ac85c6
|
[
"Apache-2.0"
] | 46 |
2022-01-26T18:21:21.000Z
|
2022-03-30T19:19:12.000Z
|
templates/2_create_tma_mibi_run.ipynb
|
angelolab/toffy
|
4d6c50fe0dfbf1568ee3f9db2182a04dc9ac85c6
|
[
"Apache-2.0"
] | null | null | null | 34.516923 | 434 | 0.629078 |
[
[
[
"# Autolabel TMA Cores\n\n## This notebook is an example: create a copy before running it or you will get merge conflicts!",
"_____no_output_____"
],
[
"**NOTE**: Before running this notebook for the first time, make sure you've coregistered your instrument using the *update coregistration parameters* section of `1_set_up_toffy.ipynb`. This will ensure your FOVs display correctly on the slide.\n\n",
"_____no_output_____"
],
[
"### Background\nThis notebook automatically checks the names assigned to the cores on a TMA. In order to get the most benefit out of the notebook, make sure that you've named your FOVs appropriately. The expected format is RNCM, where N is the row and M is the column of the TMA. For example, a core on the third row and second column would be R3C2, and one on the 7th row and first column would be R7C1. \n\nThe script expects that you have already generated and moved the necessary files into the appropriate directory before starting.\n- A JSON file defining the four corners of the TMA. It's important that you have selected them in the correct order; top left, top right, bottom left, bottom right. Even if one of the cores on the corner is missing, make sure the FOV is located where that corner of the TMA *would* be located, as this is used to define the dimensions of the TMA. You can create this file by exporting the FOVs from the MIBIControl software. \n- A JSON file containing all of the FOVs that you have selected from the TMA, named appropriately. You can create this file by exporting the FOVs from the MIBIControl software. \n- The optical image of your TMA slide. This is automatically created when you load your slide, and is saved to the *Data/optical-image* subfolder",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('../')",
"_____no_output_____"
],
[
"import json\nimport os\nfrom skimage.io import imread\n\nfrom toffy import tiling_utils, json_utils\n\n# suppress mpl deprecation\nimport warnings\nfrom matplotlib.cbook import mplDeprecation\nwarnings.filterwarnings(\"ignore\", category=mplDeprecation)",
"_____no_output_____"
]
],
[
[
"### 1. Copy over the necessary files to start the script",
"_____no_output_____"
],
[
"You will first need to define the prefix to use for all of the files associated with this specific TMA. The default is `tma_name`, but you should change it to something relevant to your study, such as BRCA_TMA_1.\n\nOnce you have picked your prefix for this specific TMA, you'll need to ensure that all of the necessary files are in the appropriate directory with the correct names\n\n* `tma corners file`: this file, which contains the FOVs defining the four corners of the TMA, should be named `tma_name_corners.json`, where `tma_name` is replaced with the `tma_prefix`. \n* `manual run file`: this file, which contains the manually selected FOVs from your TMA, should be named `tma_name_manual.json`.\n* `optical image file`: this file, which contains the image of your slide, should be named `tma_name.bmp`\n\nEach of these files should be copied to `C:\\\\Users\\\\Customer.ION\\\\Documents\\\\autolabeled_tma_jsons`",
"_____no_output_____"
]
],
[
[
"# define the prefix for each file\ntma_prefix = 'example_tma'",
"_____no_output_____"
],
[
"# user created files\ntma_dir = os.path.join('C:\\\\Users\\\\Customer.ION\\\\Documents\\\\autolabeled_tma_jsons')\ntma_corners_path = os.path.join(tma_dir, '%s_corners.json' % tma_prefix)\nmanual_run_path = os.path.join(tma_dir, '%s_manual.json' % tma_prefix)\nslide_path = os.path.join(tma_dir, tma_prefix + '.bmp')\n\n# files the notebook will create\nauto_fov_names_path = os.path.join(tma_dir, '%s_automatic_fov_names.json' % tma_prefix)\nmapping_path = os.path.join(tma_dir, '%s_mapping.json' % tma_prefix)\nremapped_fov_path = os.path.join(tma_dir, '%s_automatic_run.json' % tma_prefix)\nmoly_path = os.path.join(tma_dir, '%s_moly_point.json' % tma_prefix)",
"_____no_output_____"
]
],
[
[
"### 2. Generate the automatic mapping of FOV names",
"_____no_output_____"
]
],
[
[
"# Define TMA grid dimensions\ntma_num_row = 7\ntma_num_col = 4\n\n# generate automatically named TMA\nauto_fov_regions = tiling_utils.generate_tma_fov_list(\n tma_corners_path,\n tma_num_row,\n tma_num_col\n)\n\n# save the automatically-named TMA FOVs to centroids mapping\nwith open(auto_fov_names_path, 'w', encoding='utf-8') as afrp:\n json.dump(auto_fov_regions, afrp)",
"_____no_output_____"
],
[
"# load the user-defined set of FOVs in\nwith open(manual_run_path, 'r', encoding='utf-8') as mfop:\n manual_fov_regions = json.load(mfop)\n \n# ensure missing and duplicate FOV names get identified\nmanual_fov_regions = json_utils.rename_missing_fovs(manual_fov_regions)\nmanual_fov_regions = json_utils.rename_duplicate_fovs(manual_fov_regions)",
"_____no_output_____"
],
[
"# load the slide image in\nslide_data = imread(slide_path)",
"_____no_output_____"
]
],
[
[
"### 3. Set thresholds for identifying incorrect FOV names",
"_____no_output_____"
],
[
"The variables below control the tolerance for identifying when a core has been named incorrectly.\n\n* `check_dist`: set to a positive value to notify of FOV mappings at a distance greater than this value (measured in microns), sorted by decreasing distance. Set to `None` to bypass.\n* `check_duplicates`: set to `True` to flag FOVs in `auto_fov_regions` with multiple FOVs mapping to it. Set to `False` to bypass.\n* `check_mismatches`: set to `True` to flag FOVs with mismatched names. Set to `False` to bypass. Assumes FOVs have been named R1C1, R1C2, etc. ",
"_____no_output_____"
]
],
[
[
"check_dist = 2000\ncheck_duplicates = True\ncheck_mismatches = True",
"_____no_output_____"
]
],
[
[
"Each FOV in `manual_fov_regions` are mapped to their closest corresponding FOV in `auto_fov_regions` by default. To see the current mappings, select FOVs in the `Manually-defined FOV` menu. To remap a manual FOV to a different auto FOV, use the `Automatically-generated FOV` menu.\n\nAfter you're done finished, click `Save mapping` and run the cells afterward (ignore any error messages that may appear there beforehand). You can always come back here and redo your mappings if you change your mind.",
"_____no_output_____"
]
],
[
[
"%matplotlib widget\ntiling_utils.tma_interactive_remap(\n manual_fov_regions,\n auto_fov_regions,\n slide_data,\n mapping_path,\n draw_radius=7,\n figsize=(7, 7),\n check_dist=check_dist,\n check_duplicates=check_duplicates,\n check_mismatches=check_mismatches\n)",
"_____no_output_____"
]
],
[
[
"### 4. Set parameters for created remapped JSON",
"_____no_output_____"
],
[
"The variables below will control how the remapped JSON is created\n\n* `randomize`: shuffle the order of the FOVs in `remapped_fov_regions` to avoid potential batch effects of acquisition order\n* `moly_insert`: insert a moly FOV between a specified interval of FOVs\n* `moly_interval`: if `moly_insert` is set, controls how many FOVs are between each subsequent moly FOV",
"_____no_output_____"
]
],
[
[
"randomize = True\nmoly_insert = True\nmoly_interval = 5",
"_____no_output_____"
],
[
"# load the mapping saved by the interactive visualization\nwith open(mapping_path, 'r', encoding='utf-8') as mp:\n mapping = json.load(mp)\n\n# rename FOVs, randomize the order, and insert moly points at a specified interval\nremapped_fov_regions = tiling_utils.remap_and_reorder_fovs(\n manual_fov_regions,\n mapping,\n moly_path,\n randomize=randomize,\n moly_insert=moly_insert,\n moly_interval=moly_interval\n)\n\n# save remapped_fov_regions\nwith open(remapped_fov_path, 'w', encoding='utf-8') as rtp:\n json.dump(remapped_fov_regions, rtp)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code",
"code"
]
] |
cbb4521b4c2c12740fdd8eb8a8296cdb4366f526
| 94,060 |
ipynb
|
Jupyter Notebook
|
notebooks/tf/nmt_with_attention.ipynb
|
motazsaad/NLP-ICTS6361
|
1d44a187dc966ac45bbd236384d059347efbde50
|
[
"Apache-2.0"
] | 10 |
2019-09-20T21:40:03.000Z
|
2021-06-22T23:42:44.000Z
|
notebooks/tf/nmt_with_attention.ipynb
|
motazsaad/NLP-ICTS6361
|
1d44a187dc966ac45bbd236384d059347efbde50
|
[
"Apache-2.0"
] | null | null | null |
notebooks/tf/nmt_with_attention.ipynb
|
motazsaad/NLP-ICTS6361
|
1d44a187dc966ac45bbd236384d059347efbde50
|
[
"Apache-2.0"
] | 9 |
2019-10-26T07:12:29.000Z
|
2022-03-29T03:39:08.000Z
| 72.18726 | 14,556 | 0.791963 |
[
[
[
"##### Copyright 2019 The TensorFlow Authors.",
"_____no_output_____"
]
],
[
[
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"_____no_output_____"
]
],
[
[
"# Neural machine translation with attention",
"_____no_output_____"
],
[
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/text/nmt_with_attention\">\n <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/text/nmt_with_attention.ipynb\">\n <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/nmt_with_attention.ipynb\">\n <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/text/nmt_with_attention.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>",
"_____no_output_____"
],
[
"This notebook trains a sequence to sequence (seq2seq) model for Spanish to English translation. This is an advanced example that assumes some knowledge of sequence to sequence models.\n\nAfter training the model in this notebook, you will be able to input a Spanish sentence, such as *\"¿todavia estan en casa?\"*, and return the English translation: *\"are you still at home?\"*\n\nThe translation quality is reasonable for a toy example, but the generated attention plot is perhaps more interesting. This shows which parts of the input sentence has the model's attention while translating:\n\n<img src=\"https://tensorflow.org/images/spanish-english.png\" alt=\"spanish-english attention plot\">\n\nNote: This example takes approximately 10 mintues to run on a single P100 GPU.",
"_____no_output_____"
]
],
[
[
"from __future__ import absolute_import, division, print_function, unicode_literals\n\ntry:\n # %tensorflow_version only exists in Colab.\n %tensorflow_version 2.x\nexcept Exception:\n pass\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom sklearn.model_selection import train_test_split\n\nimport unicodedata\nimport re\nimport numpy as np\nimport os\nimport io\nimport time",
"_____no_output_____"
]
],
[
[
"## Download and prepare the dataset\n\nWe'll use a language dataset provided by http://www.manythings.org/anki/. This dataset contains language translation pairs in the format:\n\n```\nMay I borrow this book?\t¿Puedo tomar prestado este libro?\n```\n\nThere are a variety of languages available, but we'll use the English-Spanish dataset. For convenience, we've hosted a copy of this dataset on Google Cloud, but you can also download your own copy. After downloading the dataset, here are the steps we'll take to prepare the data:\n\n1. Add a *start* and *end* token to each sentence.\n2. Clean the sentences by removing special characters.\n3. Create a word index and reverse word index (dictionaries mapping from word → id and id → word).\n4. Pad each sentence to a maximum length.",
"_____no_output_____"
]
],
[
[
"# Download the file\npath_to_zip = tf.keras.utils.get_file(\n 'spa-eng.zip', origin='http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip',\n extract=True)\n\npath_to_file = os.path.dirname(path_to_zip)+\"/spa-eng/spa.txt\"",
"Downloading data from http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip\n2646016/2638744 [==============================] - 0s 0us/step\n"
],
[
"# Converts the unicode file to ascii\ndef unicode_to_ascii(s):\n return ''.join(c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn')\n\n\ndef preprocess_sentence(w):\n w = unicode_to_ascii(w.lower().strip())\n\n # creating a space between a word and the punctuation following it\n # eg: \"he is a boy.\" => \"he is a boy .\"\n # Reference:- https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation\n w = re.sub(r\"([?.!,¿])\", r\" \\1 \", w)\n w = re.sub(r'[\" \"]+', \" \", w)\n\n # replacing everything with space except (a-z, A-Z, \".\", \"?\", \"!\", \",\")\n w = re.sub(r\"[^a-zA-Z?.!,¿]+\", \" \", w)\n\n w = w.rstrip().strip()\n\n # adding a start and an end token to the sentence\n # so that the model know when to start and stop predicting.\n w = '<start> ' + w + ' <end>'\n return w",
"_____no_output_____"
],
[
"en_sentence = u\"May I borrow this book?\"\nsp_sentence = u\"¿Puedo tomar prestado este libro?\"\nprint(preprocess_sentence(en_sentence))\nprint(preprocess_sentence(sp_sentence).encode('utf-8'))",
"<start> may i borrow this book ? <end>\nb'<start> \\xc2\\xbf puedo tomar prestado este libro ? <end>'\n"
],
[
"# 1. Remove the accents\n# 2. Clean the sentences\n# 3. Return word pairs in the format: [ENGLISH, SPANISH]\ndef create_dataset(path, num_examples):\n lines = io.open(path, encoding='UTF-8').read().strip().split('\\n')\n\n word_pairs = [[preprocess_sentence(w) for w in l.split('\\t')] for l in lines[:num_examples]]\n\n return zip(*word_pairs)",
"_____no_output_____"
],
[
"en, sp = create_dataset(path_to_file, None)\nprint(en[-1])\nprint(sp[-1])",
"<start> if you want to sound like a native speaker , you must be willing to practice saying the same sentence over and over in the same way that banjo players practice the same phrase over and over until they can play it correctly and at the desired tempo . <end>\n<start> si quieres sonar como un hablante nativo , debes estar dispuesto a practicar diciendo la misma frase una y otra vez de la misma manera en que un musico de banjo practica el mismo fraseo una y otra vez hasta que lo puedan tocar correctamente y en el tiempo esperado . <end>\n"
],
[
"def max_length(tensor):\n return max(len(t) for t in tensor)",
"_____no_output_____"
],
[
"def tokenize(lang):\n lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(\n filters='')\n lang_tokenizer.fit_on_texts(lang)\n\n tensor = lang_tokenizer.texts_to_sequences(lang)\n\n tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor,\n padding='post')\n\n return tensor, lang_tokenizer",
"_____no_output_____"
],
[
"def load_dataset(path, num_examples=None):\n # creating cleaned input, output pairs\n targ_lang, inp_lang = create_dataset(path, num_examples)\n\n input_tensor, inp_lang_tokenizer = tokenize(inp_lang)\n target_tensor, targ_lang_tokenizer = tokenize(targ_lang)\n\n return input_tensor, target_tensor, inp_lang_tokenizer, targ_lang_tokenizer",
"_____no_output_____"
]
],
[
[
"### Limit the size of the dataset to experiment faster (optional)\n\nTraining on the complete dataset of >100,000 sentences will take a long time. To train faster, we can limit the size of the dataset to 30,000 sentences (of course, translation quality degrades with less data):",
"_____no_output_____"
]
],
[
[
"# Try experimenting with the size of that dataset\nnum_examples = 30000\ninput_tensor, target_tensor, inp_lang, targ_lang = load_dataset(path_to_file, num_examples)\n\n# Calculate max_length of the target tensors\nmax_length_targ, max_length_inp = max_length(target_tensor), max_length(input_tensor)",
"_____no_output_____"
],
[
"# Creating training and validation sets using an 80-20 split\ninput_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)\n\n# Show length\nprint(len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val))",
"24000 24000 6000 6000\n"
],
[
"def convert(lang, tensor):\n for t in tensor:\n if t!=0:\n print (\"%d ----> %s\" % (t, lang.index_word[t]))",
"_____no_output_____"
],
[
"print (\"Input Language; index to word mapping\")\nconvert(inp_lang, input_tensor_train[0])\nprint ()\nprint (\"Target Language; index to word mapping\")\nconvert(targ_lang, target_tensor_train[0])",
"Input Language; index to word mapping\n1 ----> <start>\n265 ----> compre\n15 ----> un\n6648 ----> nopal\n3 ----> .\n2 ----> <end>\n\nTarget Language; index to word mapping\n1 ----> <start>\n4 ----> i\n222 ----> bought\n9 ----> a\n2787 ----> cactus\n3 ----> .\n2 ----> <end>\n"
]
],
[
[
"### Create a tf.data dataset",
"_____no_output_____"
]
],
[
[
"BUFFER_SIZE = len(input_tensor_train)\nBATCH_SIZE = 64\nsteps_per_epoch = len(input_tensor_train)//BATCH_SIZE\nembedding_dim = 256\nunits = 1024\nvocab_inp_size = len(inp_lang.word_index)+1\nvocab_tar_size = len(targ_lang.word_index)+1\n\ndataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)\ndataset = dataset.batch(BATCH_SIZE, drop_remainder=True)",
"_____no_output_____"
],
[
"example_input_batch, example_target_batch = next(iter(dataset))\nexample_input_batch.shape, example_target_batch.shape",
"_____no_output_____"
]
],
[
[
"## Write the encoder and decoder model\n\nImplement an encoder-decoder model with attention which you can read about in the TensorFlow [Neural Machine Translation (seq2seq) tutorial](https://github.com/tensorflow/nmt). This example uses a more recent set of APIs. This notebook implements the [attention equations](https://github.com/tensorflow/nmt#background-on-the-attention-mechanism) from the seq2seq tutorial. The following diagram shows that each input words is assigned a weight by the attention mechanism which is then used by the decoder to predict the next word in the sentence. The below picture and formulas are an example of attention mechanism from [Luong's paper](https://arxiv.org/abs/1508.04025v5). \n\n<img src=\"https://www.tensorflow.org/images/seq2seq/attention_mechanism.jpg\" width=\"500\" alt=\"attention mechanism\">\n\nThe input is put through an encoder model which gives us the encoder output of shape *(batch_size, max_length, hidden_size)* and the encoder hidden state of shape *(batch_size, hidden_size)*.\n\nHere are the equations that are implemented:\n\n<img src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_0.jpg\" alt=\"attention equation 0\" width=\"800\">\n<img src=\"https://www.tensorflow.org/images/seq2seq/attention_equation_1.jpg\" alt=\"attention equation 1\" width=\"800\">\n\nThis tutorial uses [Bahdanau attention](https://arxiv.org/pdf/1409.0473.pdf) for the encoder. Let's decide on notation before writing the simplified form:\n\n* FC = Fully connected (dense) layer\n* EO = Encoder output\n* H = hidden state\n* X = input to the decoder\n\nAnd the pseudo-code:\n\n* `score = FC(tanh(FC(EO) + FC(H)))`\n* `attention weights = softmax(score, axis = 1)`. Softmax by default is applied on the last axis but here we want to apply it on the *1st axis*, since the shape of score is *(batch_size, max_length, hidden_size)*. `Max_length` is the length of our input. Since we are trying to assign a weight to each input, softmax should be applied on that axis.\n* `context vector = sum(attention weights * EO, axis = 1)`. Same reason as above for choosing axis as 1.\n* `embedding output` = The input to the decoder X is passed through an embedding layer.\n* `merged vector = concat(embedding output, context vector)`\n* This merged vector is then given to the GRU\n\nThe shapes of all the vectors at each step have been specified in the comments in the code:",
"_____no_output_____"
]
],
[
[
"class Encoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):\n super(Encoder, self).__init__()\n self.batch_sz = batch_sz\n self.enc_units = enc_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.enc_units,\n return_sequences=True,\n return_state=True,\n recurrent_initializer='glorot_uniform')\n\n def call(self, x, hidden):\n x = self.embedding(x)\n output, state = self.gru(x, initial_state = hidden)\n return output, state\n\n def initialize_hidden_state(self):\n return tf.zeros((self.batch_sz, self.enc_units))",
"_____no_output_____"
],
[
"encoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n\n# sample input\nsample_hidden = encoder.initialize_hidden_state()\nsample_output, sample_hidden = encoder(example_input_batch, sample_hidden)\nprint ('Encoder output shape: (batch size, sequence length, units) {}'.format(sample_output.shape))\nprint ('Encoder Hidden state shape: (batch size, units) {}'.format(sample_hidden.shape))",
"Encoder output shape: (batch size, sequence length, units) (64, 16, 1024)\nEncoder Hidden state shape: (batch size, units) (64, 1024)\n"
],
[
"class BahdanauAttention(tf.keras.layers.Layer):\n def __init__(self, units):\n super(BahdanauAttention, self).__init__()\n self.W1 = tf.keras.layers.Dense(units)\n self.W2 = tf.keras.layers.Dense(units)\n self.V = tf.keras.layers.Dense(1)\n\n def call(self, query, values):\n # hidden shape == (batch_size, hidden size)\n # hidden_with_time_axis shape == (batch_size, 1, hidden size)\n # we are doing this to perform addition to calculate the score\n hidden_with_time_axis = tf.expand_dims(query, 1)\n\n # score shape == (batch_size, max_length, 1)\n # we get 1 at the last axis because we are applying score to self.V\n # the shape of the tensor before applying self.V is (batch_size, max_length, units)\n score = self.V(tf.nn.tanh(\n self.W1(values) + self.W2(hidden_with_time_axis)))\n\n # attention_weights shape == (batch_size, max_length, 1)\n attention_weights = tf.nn.softmax(score, axis=1)\n\n # context_vector shape after sum == (batch_size, hidden_size)\n context_vector = attention_weights * values\n context_vector = tf.reduce_sum(context_vector, axis=1)\n\n return context_vector, attention_weights",
"_____no_output_____"
],
[
"attention_layer = BahdanauAttention(10)\nattention_result, attention_weights = attention_layer(sample_hidden, sample_output)\n\nprint(\"Attention result shape: (batch size, units) {}\".format(attention_result.shape))\nprint(\"Attention weights shape: (batch_size, sequence_length, 1) {}\".format(attention_weights.shape))",
"Attention result shape: (batch size, units) (64, 1024)\nAttention weights shape: (batch_size, sequence_length, 1) (64, 16, 1)\n"
],
[
"class Decoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):\n super(Decoder, self).__init__()\n self.batch_sz = batch_sz\n self.dec_units = dec_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.dec_units,\n return_sequences=True,\n return_state=True,\n recurrent_initializer='glorot_uniform')\n self.fc = tf.keras.layers.Dense(vocab_size)\n\n # used for attention\n self.attention = BahdanauAttention(self.dec_units)\n\n def call(self, x, hidden, enc_output):\n # enc_output shape == (batch_size, max_length, hidden_size)\n context_vector, attention_weights = self.attention(hidden, enc_output)\n\n # x shape after passing through embedding == (batch_size, 1, embedding_dim)\n x = self.embedding(x)\n\n # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)\n x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n\n # passing the concatenated vector to the GRU\n output, state = self.gru(x)\n\n # output shape == (batch_size * 1, hidden_size)\n output = tf.reshape(output, (-1, output.shape[2]))\n\n # output shape == (batch_size, vocab)\n x = self.fc(output)\n\n return x, state, attention_weights",
"_____no_output_____"
],
[
"decoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)\n\nsample_decoder_output, _, _ = decoder(tf.random.uniform((BATCH_SIZE, 1)),\n sample_hidden, sample_output)\n\nprint ('Decoder output shape: (batch_size, vocab size) {}'.format(sample_decoder_output.shape))",
"Decoder output shape: (batch_size, vocab size) (64, 4935)\n"
]
],
[
[
"## Define the optimizer and the loss function",
"_____no_output_____"
]
],
[
[
"optimizer = tf.keras.optimizers.Adam()\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True, reduction='none')\n\ndef loss_function(real, pred):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_mean(loss_)",
"_____no_output_____"
]
],
[
[
"## Checkpoints (Object-based saving)",
"_____no_output_____"
]
],
[
[
"checkpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(optimizer=optimizer,\n encoder=encoder,\n decoder=decoder)",
"_____no_output_____"
]
],
[
[
"## Training\n\n1. Pass the *input* through the *encoder* which return *encoder output* and the *encoder hidden state*.\n2. The encoder output, encoder hidden state and the decoder input (which is the *start token*) is passed to the decoder.\n3. The decoder returns the *predictions* and the *decoder hidden state*.\n4. The decoder hidden state is then passed back into the model and the predictions are used to calculate the loss.\n5. Use *teacher forcing* to decide the next input to the decoder.\n6. *Teacher forcing* is the technique where the *target word* is passed as the *next input* to the decoder.\n7. The final step is to calculate the gradients and apply it to the optimizer and backpropagate.",
"_____no_output_____"
]
],
[
[
"@tf.function\ndef train_step(inp, targ, enc_hidden):\n loss = 0\n\n with tf.GradientTape() as tape:\n enc_output, enc_hidden = encoder(inp, enc_hidden)\n\n dec_hidden = enc_hidden\n\n dec_input = tf.expand_dims([targ_lang.word_index['<start>']] * BATCH_SIZE, 1)\n\n # Teacher forcing - feeding the target as the next input\n for t in range(1, targ.shape[1]):\n # passing enc_output to the decoder\n predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)\n\n loss += loss_function(targ[:, t], predictions)\n\n # using teacher forcing\n dec_input = tf.expand_dims(targ[:, t], 1)\n\n batch_loss = (loss / int(targ.shape[1]))\n\n variables = encoder.trainable_variables + decoder.trainable_variables\n\n gradients = tape.gradient(loss, variables)\n\n optimizer.apply_gradients(zip(gradients, variables))\n\n return batch_loss",
"_____no_output_____"
],
[
"EPOCHS = 10\n\nfor epoch in range(EPOCHS):\n start = time.time()\n\n enc_hidden = encoder.initialize_hidden_state()\n total_loss = 0\n\n for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)):\n batch_loss = train_step(inp, targ, enc_hidden)\n total_loss += batch_loss\n\n if batch % 100 == 0:\n print('Epoch {} Batch {} Loss {:.4f}'.format(epoch + 1,\n batch,\n batch_loss.numpy()))\n # saving (checkpoint) the model every 2 epochs\n if (epoch + 1) % 2 == 0:\n checkpoint.save(file_prefix = checkpoint_prefix)\n\n print('Epoch {} Loss {:.4f}'.format(epoch + 1,\n total_loss / steps_per_epoch))\n print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))",
"Epoch 1 Batch 0 Loss 4.7473\nEpoch 1 Batch 100 Loss 2.1733\nEpoch 1 Batch 200 Loss 1.8787\nEpoch 1 Batch 300 Loss 1.7222\nEpoch 1 Loss 2.0324\nTime taken for 1 epoch 33.9479820728302 sec\n\nEpoch 2 Batch 0 Loss 1.5579\nEpoch 2 Batch 100 Loss 1.4370\nEpoch 2 Batch 200 Loss 1.4042\nEpoch 2 Batch 300 Loss 1.2848\nEpoch 2 Loss 1.3962\nTime taken for 1 epoch 17.57913875579834 sec\n\nEpoch 3 Batch 0 Loss 1.0146\nEpoch 3 Batch 100 Loss 0.9916\nEpoch 3 Batch 200 Loss 1.0946\nEpoch 3 Batch 300 Loss 0.9436\nEpoch 3 Loss 0.9849\nTime taken for 1 epoch 17.110281229019165 sec\n\nEpoch 4 Batch 0 Loss 0.6478\nEpoch 4 Batch 100 Loss 0.6424\nEpoch 4 Batch 200 Loss 0.7041\nEpoch 4 Batch 300 Loss 0.6307\nEpoch 4 Loss 0.6634\nTime taken for 1 epoch 17.549187421798706 sec\n\nEpoch 5 Batch 0 Loss 0.4491\nEpoch 5 Batch 100 Loss 0.3657\nEpoch 5 Batch 200 Loss 0.4612\nEpoch 5 Batch 300 Loss 0.4688\nEpoch 5 Loss 0.4508\nTime taken for 1 epoch 17.02736186981201 sec\n\nEpoch 6 Batch 0 Loss 0.3293\nEpoch 6 Batch 100 Loss 0.3074\nEpoch 6 Batch 200 Loss 0.3077\nEpoch 6 Batch 300 Loss 0.2849\nEpoch 6 Loss 0.3147\nTime taken for 1 epoch 17.503292560577393 sec\n\nEpoch 7 Batch 0 Loss 0.1896\nEpoch 7 Batch 100 Loss 0.2028\nEpoch 7 Batch 200 Loss 0.2070\nEpoch 7 Batch 300 Loss 0.1809\nEpoch 7 Loss 0.2236\nTime taken for 1 epoch 17.121249437332153 sec\n\nEpoch 8 Batch 0 Loss 0.1307\nEpoch 8 Batch 100 Loss 0.2151\nEpoch 8 Batch 200 Loss 0.1595\nEpoch 8 Batch 300 Loss 0.1825\nEpoch 8 Loss 0.1683\nTime taken for 1 epoch 17.56266689300537 sec\n\nEpoch 9 Batch 0 Loss 0.1091\nEpoch 9 Batch 100 Loss 0.1238\nEpoch 9 Batch 200 Loss 0.1262\nEpoch 9 Batch 300 Loss 0.1245\nEpoch 9 Loss 0.1290\nTime taken for 1 epoch 17.148908615112305 sec\n\nEpoch 10 Batch 0 Loss 0.0939\nEpoch 10 Batch 100 Loss 0.1082\nEpoch 10 Batch 200 Loss 0.1149\nEpoch 10 Batch 300 Loss 0.0957\nEpoch 10 Loss 0.1038\nTime taken for 1 epoch 17.501878261566162 sec\n\n"
]
],
[
[
"## Translate\n\n* The evaluate function is similar to the training loop, except we don't use *teacher forcing* here. The input to the decoder at each time step is its previous predictions along with the hidden state and the encoder output.\n* Stop predicting when the model predicts the *end token*.\n* And store the *attention weights for every time step*.\n\nNote: The encoder output is calculated only once for one input.",
"_____no_output_____"
]
],
[
[
"def evaluate(sentence):\n attention_plot = np.zeros((max_length_targ, max_length_inp))\n\n sentence = preprocess_sentence(sentence)\n\n inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]\n inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],\n maxlen=max_length_inp,\n padding='post')\n inputs = tf.convert_to_tensor(inputs)\n\n result = ''\n\n hidden = [tf.zeros((1, units))]\n enc_out, enc_hidden = encoder(inputs, hidden)\n\n dec_hidden = enc_hidden\n dec_input = tf.expand_dims([targ_lang.word_index['<start>']], 0)\n\n for t in range(max_length_targ):\n predictions, dec_hidden, attention_weights = decoder(dec_input,\n dec_hidden,\n enc_out)\n\n # storing the attention weights to plot later on\n attention_weights = tf.reshape(attention_weights, (-1, ))\n attention_plot[t] = attention_weights.numpy()\n\n predicted_id = tf.argmax(predictions[0]).numpy()\n\n result += targ_lang.index_word[predicted_id] + ' '\n\n if targ_lang.index_word[predicted_id] == '<end>':\n return result, sentence, attention_plot\n\n # the predicted ID is fed back into the model\n dec_input = tf.expand_dims([predicted_id], 0)\n\n return result, sentence, attention_plot",
"_____no_output_____"
],
[
"# function for plotting the attention weights\ndef plot_attention(attention, sentence, predicted_sentence):\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1)\n ax.matshow(attention, cmap='viridis')\n\n fontdict = {'fontsize': 14}\n\n ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)\n ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)\n\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n plt.show()",
"_____no_output_____"
],
[
"def translate(sentence):\n result, sentence, attention_plot = evaluate(sentence)\n\n print('Input: %s' % (sentence))\n print('Predicted translation: {}'.format(result))\n\n attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]\n plot_attention(attention_plot, sentence.split(' '), result.split(' '))",
"_____no_output_____"
]
],
[
[
"## Restore the latest checkpoint and test",
"_____no_output_____"
]
],
[
[
"# restoring the latest checkpoint in checkpoint_dir\ncheckpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))",
"_____no_output_____"
],
[
"translate(u'hace mucho frio aqui.')",
"Input: <start> hace mucho frio aqui . <end>\nPredicted translation: it s very cold here . <end> \n"
],
[
"translate(u'esta es mi vida.')",
"Input: <start> esta es mi vida . <end>\nPredicted translation: this is my life . <end> \n"
],
[
"translate(u'¿todavia estan en casa?')",
"Input: <start> ¿ todavia estan en casa ? <end>\nPredicted translation: are you still at home ? <end> \n"
],
[
"# wrong translation\ntranslate(u'trata de averiguarlo.')",
"Input: <start> trata de averiguarlo . <end>\nPredicted translation: try to figure it out . <end> \n"
]
],
[
[
"## Next steps\n\n* [Download a different dataset](http://www.manythings.org/anki/) to experiment with translations, for example, English to German, or English to French.\n* Experiment with training on a larger dataset, or using more epochs\n",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
]
] |
cbb4580c7f26554eec5c41be68362acbbdf00d78
| 13,264 |
ipynb
|
Jupyter Notebook
|
test/ry/2-features.ipynb
|
JayKamat99/rai
|
d475bca3c6fcab1546cba3c8ee31e41f36022713
|
[
"MIT"
] | null | null | null |
test/ry/2-features.ipynb
|
JayKamat99/rai
|
d475bca3c6fcab1546cba3c8ee31e41f36022713
|
[
"MIT"
] | null | null | null |
test/ry/2-features.ipynb
|
JayKamat99/rai
|
d475bca3c6fcab1546cba3c8ee31e41f36022713
|
[
"MIT"
] | null | null | null | 35.276596 | 554 | 0.570869 |
[
[
[
"# Features and Objectives\n\nThis doc is mostly text, explaining the general concept of features, listing the ones defined in rai, and explaining how they define objectives for optimization.\n\nAt the bottom there are also examples on the collision features.",
"_____no_output_____"
],
[
"## Features\n\nWe assume a single configuration $x$, or a whole set of configurations\n$\\{x_1,..,x_T\\}$. Each $x_i \\in\\mathbb{R}$ are the DOFs of that\nconfiguration.\n\nA feature $\\phi$ is a differentiable mapping\n$$\\phi: x \\mapsto \\mathbb{R}^D$$\nof a single configuration into some $D$-dimensional space, or a mapping\n$$\\phi: (x_0,x_2,..,x_k) \\mapsto \\mathbb{R}^D$$\nof a $(k+1)$-tuple of configurations to a $D$-dimensional space.\n\nThe rai code implements many features, most of them are accessible via\na feature symbol (FS). They are declared in\nhttps://github.com/MarcToussaint/rai/blob/master/rai/Kin/featureSymbols.h\n\nHere is a table of feature symbols, with the\nrespective dimensionality $D$, the default order $k$, and a\ndescription\n\n| FS | frames | $D$ | $k$ | description |\n|:---:|:---:|:---:|:---:|:---:|\n| position | {o1} | 3 || 3D position of o1 in world coordinates |\n| positionDiff | {o1,o2} | 3 || difference of 3D positions of o1 and o2 in world coordinates |\n| positionRel | {o1,o2} | 3 || 3D position of o1 in o2 coordinates |\n| quaternion | {o1} | 4 || 4D quaternion of o1 in world coordinates\\footnote{There is ways to handle the invariance w.r.t.\\ quaternion sign properly.} |\n| quaternionDiff | {o1,o2} | 4 || ... |\n| quaternionRel | {o1,o2} | 4 || ... |\n| pose | {o1} | 7 || 7D pose of o1 in world coordinates |\n| poseDiff | {o1,o2} | 7 || ... |\n| poseRel | {o1,o2} | 7 || ... |\n| vectorX | {o1} | 3 || The x-axis of frame o1 rotated back to world coordinates |\n| vectorXDiff | {o1,o2} | 3 || The difference of the above for two frames o1 and o2 |\n| vectorXRel | {o1,o2} | 3 || The x-axis of frame o1 rotated as to be seend from the frame o2 |\n| vectorY... | | | | same as above |\n| scalarProductXX | {o1,o2} | 1 || The scalar product of the x-axis fo frame o1 with the x-axis of frame o2 |\n| scalarProduct... | {o1,o2} | | | as above |\n| gazeAt | {o1,o2} | 2 | | The 2D projection of the origin of frame o2 onto the xy-plane of frame o1 |\n| angularVel | {o1} | 3 | 1 | The angular velocity of frame o1 across two configurations |\n| accumulatedCollisions | {} | 1 | | The sum of collision penetrations; when negative/zero, nothing is colliding |\n| jointLimits | {} | 1 | | The sum of joint limit penetrations; when negative/zero, all joint limits are ok |\n| distance | {o1,o1} | 1 | | The NEGATIVE distance between convex meshes o1 and o2, positive for penetration |\n| qItself | {} | $n$ | | The configuration joint vector |\n| aboveBox | {o1,o2} | 4 | | when all negative, o1 is above (inside support of) the box o2 |\n| insideBox | {o1,o2} | 6 | | when all negative, o1 is inside the box o2 |\n| standingAbove | | | | ? |\n\nA features is typically defined by\n* The feature symbol (`FS_...` in cpp; `FS....` in python)\n* The set of frames it refers to\n* Optionally: A target, which changes the zero-point of the features (optimization typically try to drive features to zero, see below)\n* Optionally: A scaling, that can also be a matrix to down-project a feature\n* Optionally: The order $k$, which can make the feature a velocity or acceleration feature\n\nTarget and scale redefine a feature to become\n$$\n \\phi(x) \\gets \\texttt{scale} \\cdot (\\phi(x) - \\texttt{target})\n$$\nThe target needs to be a $D$-dim vector. The scale can be a matrix, which projects features; e.g., and 3D position to just $x$-position.\n\nThe order of a feature is usually $k=0$, meaning that it is defined over a single configuration only. $k=1$ means that it is defined over two configurations (1st oder Markov), and redefines the feature to become the difference or velocity\n$$\n \\phi(x_1,x_2) \\gets \\frac{1}{\\tau}(\\phi(x_2) - \\phi(x_1))\n$$\n$k=2$ means that it is defined over three configurations (2nd order Markov), and redefines the feature to become the acceleration\n$$\n \\phi(x_1,x_2,x_3) \\equiv \\frac{1}{\\tau^2}(\\phi(x_1) + \\phi(x_3) - 2 \\phi(x_2))\n$$",
"_____no_output_____"
],
[
"### Examples\n\n```\n(FS.position, {'hand'})\n```\nis the 3D position of the hand in world coordinates\n\n```\n(FS.positionRel, {'handL', 'handR'}, scale=[[0,0,1]], target=[0.1])\n```\nis the z-position position of the left hand measured in the frame of the right hand, with target 10centimeters.\n\n```\n(FS.position, {'handL'}, order=1)\n```\nis the 3D velocity of the left hand in world coordinates\n\n```\n(FS.scalarProductXX, {'handL', 'handR'}, target=[1])\n```\nsays that the scalar product of the x-axes (e.g. directions of the index finger) of both hands should equal 1, which means they are aligned.\n\n```\n(FS.scalarProductXY, {'handL', 'handR'})\n(FS.scalarProductXZ, {'handL', 'handR'})\n```\nsays that the the x-axis of handL should be orthogonal (zero scalar product) to the y- and z-axis of handR. So this also describes aligning both x-axes. However, this formulation is much more robust, as it has good error gradients around the optimum.",
"_____no_output_____"
],
[
"## Objectives\n\nFeatures are meant to define objectives in an optimization problem. An objective is\n* a feature\n* an indicator $\\rho_k\n\\in\\{\\texttt{ineq, eq, sos}\\}$ that states whether the features\nimplies an inequality, an equality, or a sum-of-square objective\n* and an index tuple $\\pi_k \\subseteq \\{1,..,n\\}$ that states which\nconfigurations this feature is defined over.\n\nThen, given a set\n$\\{\\phi_1,..,\\phi_K\\}$ of $K$ features, and a set $\\{x_1,..,x_n\\}$ of\n$n$ configurations, this defines the mathematical program\n\n\\begin{align}\n \\min_{x_1,..,x_n} \\sum_{k : \\rho_k=\\texttt{sos}} \\phi_k(x_{\\pi_k})^T \\phi_k(x_{\\pi_k})\n ~\\text{s.t.}~ \\mathop\\forall_{k : \\rho_k=\\texttt{ineq}} \\phi_k(x_{\\pi_k}) \\le 0 ~,\\quad\n \\mathop\\forall_{k : \\rho_k=\\texttt{eq}} \\phi_k(x_{\\pi_k}) = 0 ~,\\quad\n\\end{align}",
"_____no_output_____"
],
[
"## Code example for collision features\n\n* Get list of collisions and proximities for the whole configuration\n* Get a accumulative, differentiable collision measure\n* Get proximity/penetration specifically for a pair of shapes\n* Other geometric collision features for a pair of shapes (witness points, normal, etc) -- all differentiable",
"_____no_output_____"
]
],
[
[
"import sys\nsys.path.append('../../../build')\nimport numpy as np\nimport libry as ry\n\nC = ry.Config()\nC.addFile('../../../rai-robotModels/pr2/pr2.g');\nC.addFile('../../../rai-robotModels/objects/kitchen.g');\n\nC.view()",
"**ry-c++-log** /home/jay/git/optimization-course/rai/rai/ry/ry.cpp:init_LogToPythonConsole:34(0) initializing ry log callback\n\n"
]
],
[
[
"Let's evaluate the accumulative collision scalar and its Jacobian",
"_____no_output_____"
]
],
[
[
"coll = C.feature(ry.FS.accumulatedCollisions, [])\n\nC.computeCollisions() #collisions/proxies are not automatically computed on set...State\ncoll.eval(C)",
"_____no_output_____"
]
],
[
[
"Let's move into collision and redo this",
"_____no_output_____"
]
],
[
[
"C.selectJointsByTag([\"base\"])\nC.setJointState([1.5,1,0])\n\nC.computeCollisions()\ncoll.eval(C)",
"_____no_output_____"
]
],
[
[
"We can get more verbose information like this:",
"_____no_output_____"
]
],
[
[
"C.getCollisions()",
"_____no_output_____"
],
[
"C.getCollisions(0) #only report proxies with distance<0 (penetrations)",
"_____no_output_____"
]
],
[
[
"The computeCollisions() method calls a collision detection engine (SWIFT++) for the whole configuration, checking all shapes that are collision-activated. The activation/deactivation of collision computations is a nuissance! the 'contact' flag in g-files specifies which shapes are activated by default, and if the value is negative, that collisions with parent shapes are not included. (In the KOMO class, you can use activateCollisionPairs and deactivateCollisionPairs to modify these defaults in optimization problems... TODO: also in Config)\n\nWhen you're interested in the distance or penetration of one specific pair of objects, you don't need to call computeCollisions() and instead query a feature that calls the GJK (and others) algorithm directly only for this pair:",
"_____no_output_____"
]
],
[
[
"dist = C.feature(ry.FS.distance, ['coll_wrist_r', '_10'])\ndist.eval(C)",
"_____no_output_____"
]
],
[
[
"Note that this returns the NEGATIVE distance (because one typically wants to put an inequality (<=0) on this). The C++ code implements many more features of the collision geometry, including the normal, witness points, etc. Can be added to python easily on request.",
"_____no_output_____"
]
],
[
[
"C.view_close()",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb45a35e74d9029c4d29fc132feb33b9e75f5b2
| 18,761 |
ipynb
|
Jupyter Notebook
|
notebooks/Extract titanic data.ipynb
|
DanielZajkowski/Titanic-Disaster-Data-Science-project
|
25e3359cf1d917c5ce73d53337f9179ca40830aa
|
[
"MIT"
] | null | null | null |
notebooks/Extract titanic data.ipynb
|
DanielZajkowski/Titanic-Disaster-Data-Science-project
|
25e3359cf1d917c5ce73d53337f9179ca40830aa
|
[
"MIT"
] | null | null | null |
notebooks/Extract titanic data.ipynb
|
DanielZajkowski/Titanic-Disaster-Data-Science-project
|
25e3359cf1d917c5ce73d53337f9179ca40830aa
|
[
"MIT"
] | null | null | null | 35.940613 | 390 | 0.518043 |
[
[
[
"!pip install python-dotenv",
"Collecting python-dotenv\n Downloading python_dotenv-0.15.0-py2.py3-none-any.whl (18 kB)\nInstalling collected packages: python-dotenv\nSuccessfully installed python-dotenv-0.15.0\n"
],
[
"from dotenv import load_dotenv, find_dotenv",
"_____no_output_____"
],
[
"# find .env automatically by walking up directories until it's found\ndotenv_path = find_dotenv()\n#load up the entries as enviroment variables\nload_dotenv(dotenv_path)",
"_____no_output_____"
],
[
"# extrating env var using os.environ.get\nimport os\nKAGGLE_USERNAME = os.environ.get(\"KAGGLE_USERNAME\")\nprint(KAGGLE_USERNAME)",
"dawidesurulak\n"
],
[
"# import\nimport requests\nfrom requests import session\nimport os\nfrom dotenv import load_dotenv, find_dotenv",
"_____no_output_____"
],
[
"# payload for post\npayload = {\n 'action': 'login',\n 'username': os.environ.get('KAGGLE_USERNAME'),\n 'password': os.environ.get('KAGGLE_PASSWORD')\n}\n\n# url for train file (get the link from Kaggle websites)\nurl = 'https://www.kaggle.com/c/titanic/download/train.csv'\n\n# setup session\nwith session() as c:\n # post request\n c.post('https://www.kaggle.com/account/login', data=payload)\n # get request\n response = c.get(url)\n # print response text\n print(response.text)",
"<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n <title>Kaggle: Your Home for Data Science</title>\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"robots\" content=\"index, follow\" />\r\n <meta name=\"description\" content=\"Kaggle is the world’s largest data science community with powerful tools and resources to help you achieve your data science goals.\" />\r\n <meta name=\"turbolinks-cache-control\" content=\"no-cache\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=5.0, minimum-scale=1.0\">\r\n <meta name=\"theme-color\" content=\"#008ABC\" />\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" type=\"text/javascript\">\r\n if ('serviceWorker' in navigator) {\r\n navigator.serviceWorker.getRegistrations()\r\n .then(function(registrations) {\r\n for (let registration of registrations) {\r\n registration.unregister();\r\n }\r\n })\r\n .catch(function(err) {\r\n console.error(\"Service worker unregister failed: \", err);\r\n });\r\n }\r\n </script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" type=\"text/javascript\">\r\n window[\"pageRequestStartTime\"] = 1613409269289;\r\n window[\"pageRequestEndTime\"] = 1613409269292;\r\n window[\"initialPageLoadStartTime\"] = new Date().getTime();\r\n </script>\r\n <link rel=\"preconnect\" href=\"https://www.google-analytics.com\" crossorigin=\"anonymous\" /><link rel=\"preconnect\" href=\"https://stats.g.doubleclick.net\" /><link rel=\"preconnect\" href=\"https://storage.googleapis.com\" /><link rel=\"preconnect\" href=\"https://apis.google.com\" />\r\n <link href=\"/static/images/favicon.ico\" rel=\"shortcut icon\" type=\"image/x-icon\" />\r\n <link rel=\"manifest\" href=\"/static/json/manifest.json\" crossorigin=\"use-credentials\">\r\n <link href=\"//fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic\" rel='stylesheet' type='text/css'>\r\n <link href=\"https://fonts.googleapis.com/icon?family=Google+Material+Icons\" rel=\"stylesheet\" type='text/css' />\r\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/static/assets/vendor.css?v=e67a2699a0a166d43c75\" />\r\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/static/assets/app.css?v=1c5093ee484d25db7398\" />\r\n \r\n \r\n \r\n \r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\">\r\n try{(function(a,s,y,n,c,h,i,d,e){d=s.createElement(\"style\");\r\n d.appendChild(s.createTextNode(\"\"));s.head.appendChild(d);d=d.sheet;\r\n y=y.map(x => d.insertRule(x + \"{ opacity: 0 !important }\"));\r\n h.start=1*new Date;h.end=i=function(){y.forEach(x => x<d.cssRules.length ? d.deleteRule(x) : {})};\r\n (a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;\r\n })(window,document,['.site-header-react__nav'],'dataLayer',2000,{'GTM-52LNT9S':true});}catch(ex){}\r\n </script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\">\r\n window.dataLayer = window.dataLayer || [];\r\n function gtag() { dataLayer.push(arguments); }\r\n gtag('js', new Date());\r\n gtag('config', 'UA-12629138-1', {\r\n 'optimize_id': 'GTM-52LNT9S',\r\n 'displayFeaturesTask': null,\r\n 'send_page_view': false,\r\n 'content_group1': 'Account'\r\n });\r\n </script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" async src=\"https://www.googletagmanager.com/gtag/js?id=UA-12629138-1\"></script>\r\n\r\n \r\n \r\n\r\n \r\n \r\n\r\n \r\n \r\n \r\n<script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" type=\"text/javascript\">\r\n var Kaggle = window.Kaggle || {};\r\n\r\n Kaggle.Current = {\r\n antiForgeryToken: 'CfDJ8LdUzqlsSWBPr4Ce3rb9VL_s97pT-OTTCifbLlHeipZR46_B5YQKpkfv8gLlpGR3ro4aTSU6wXQs0o8hl274ul3dSuV7eTajqTRRRo9kmfyrJZjZn9iv79QPkXv9JMABYlAlUbDURMo5wtqlbwdcImU',\r\n isAnonymous: true,\r\n analyticsToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTM0MTAxNjksIlVzZXJJZCI6MH0.mtlypyueUJhMO2DY7s3IK26xbDYacxijc-ryYYBWaMM',\r\n analyticsTokenExpiry: 15,\r\n \r\n \r\n \r\n \r\n \r\n \r\n mdeImageUploader: true,\r\n \r\n enableRapidash: true, \r\n }\r\n Kaggle.Current.log = function(){};\r\n Kaggle.Current.warn = function(){};\r\n\r\n var decodeUserDisplayName = function () {\r\n var escapedUserDisplayName = Kaggle.Current.userDisplayNameEscaped || \"\";\r\n try {\r\n var textVersion = new DOMParser().parseFromString(escapedUserDisplayName, \"text/html\").documentElement.textContent;\r\n if (textVersion) {\r\n return textVersion;\r\n }\r\n } catch(ex) {}\r\n return escapedUserDisplayName;\r\n }\r\n Kaggle.Current.userDisplayName = decodeUserDisplayName();\r\n</script>\r\n\r\n \r\n\r\n<script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" type=\"text/javascript\">\r\n var Kaggle = window.Kaggle || {};\r\n Kaggle.PageMessages = [];\r\n</script>\r\n\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" type=\"text/javascript\">\r\n/* <![CDATA[ */\r\ngoog_snippet_vars = function() {\r\n var w = window;\r\n w.google_conversion_id = 955616553;\r\n w.google_conversion_label = \"QSjvCKDksHMQqZrWxwM\";\r\n w.google_conversion_value = 0.00;\r\n w.google_conversion_currency = \"USD\";\r\n w.google_remarketing_only = false;\r\n w.google_conversion_language = \"en\";\r\n w.google_conversion_format = \"3\";\r\n w.google_conversion_color = \"ffffff\";\r\n}\r\n// DO NOT CHANGE THE CODE BELOW.\r\ngoog_report_conversion = function(url) {\r\n goog_snippet_vars();\r\n window.google_conversion_format = \"3\";\r\n var opt = new Object();\r\n opt.onload_callback = function() {\r\n if (typeof(url) != 'undefined') {\r\n window.location = url;\r\n }\r\n }\r\n var conv_handler = window['google_trackConversion'];\r\n if (typeof(conv_handler) == 'function') {\r\n conv_handler(opt);\r\n }\r\n}\r\n/* ]]> */\r\n </script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" type=\"text/javascript\"\r\n src=\"//www.googleadservices.com/pagead/conversion_async.js\">\r\n </script>\r\n\r\n\r\n\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\">window['useKaggleAnalytics'] = true;</script>\r\n\r\n <script id=\"gapi-target\" nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" src=\"https://apis.google.com/js/api.js\" defer async></script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" src=\"/static/assets/runtime.js?v=45022bf76308854669dc\" data-turbolinks-track=\"reload\"></script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" src=\"/static/assets/vendor.js?v=f439ab83cf0f69999e7f\" data-turbolinks-track=\"reload\"></script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" src=\"/static/assets/app.js?v=d028843fc489bef42456\" data-turbolinks-track=\"reload\"></script>\r\n <script nonce=\"8LIFo8FWjeAJW13tsIx8cg==\" type=\"text/javascript\">\r\n window.kaggleStackdriverConfig = {\r\n key: 'AIzaSyDANGXFHtSIVc51MIdGwg4mQFgm3oNrKoo',\r\n projectId: 'kaggle-161607',\r\n service: 'web-fe',\r\n version: 'ci',\r\n context: {\r\n user: '0',\r\n },\r\n };\r\n </script>\r\n</head>\r\n<body data-turbolinks=\"false\">\r\n <main>\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n<div id=\"site-container\"></div>\r\n\r\n<div id=\"site-body\" class=\"hide\">\r\n \r\n\r\n<div data-component-name=\"LoginRegisterPage\" style=\"display: flex; flex-direction: column; flex: 1 0 auto;\"></div><script class=\"kaggle-component\" nonce=\"8LIFo8FWjeAJW13tsIx8cg==\">var Kaggle=window.Kaggle||{};Kaggle.State=Kaggle.State||[];Kaggle.State.push({});performance && performance.mark && performance.mark(\"LoginRegisterPage.componentCouldBootstrap\");</script>\r\n\r\n</div>\r\n\r\n\r\n\r\n\r\n </main>\r\n</body>\r\n</html>\r\n\n"
],
[
"from requests import session\n# payload for post\npayload = {\n 'action': 'login',\n 'username': os.environ.get('KAGGLE_USERNAME'),\n 'password': os.environ.get('KAGGLE_PASSWORD')\n}\n\ndef extract_data(url, file_path):\n '''\n extract data from kaggle\n '''\n # setup session\n with session() as c:\n c.post('https://www.kaggle.com/account/login', data=payload)\n # open file to write\n with open(file_path, 'wb') as handle:\n response = c.get(url, stream=True)\n for block in response.iter_content(1024):\n handle.write(block)",
"_____no_output_____"
],
[
"# urls\ntrain_url = 'https://www.kaggle.com/c/titanic/download/train.csv'\ntest_url = 'https://www.kaggle.com/c/titanic/download/test.csv'\n\n#file path\nraw_data_path = os.path.join(os.path.pardir,'data','raw')\ntrain_data_path = os.path.join(raw_data_path,'train.csv')\ntest_data_path = os.path.join(raw_data_path,'test.csv')\n\n# etract data\nextract_data(train_url,train_data_path)\nextract_data(test_url,test_data_path)",
"_____no_output_____"
],
[
"!ls -l ../data/raw",
"'ls' is not recognized as an internal or external command,\noperable program or batch file.\n"
]
],
[
[
"## Building the file script",
"_____no_output_____"
]
],
[
[
"get_raw_data_script_file = os.path.join(os.path.pardir,'src','data','get_raw_data.py')",
"_____no_output_____"
],
[
"%%writefile $get_raw_data_script_file\n# coding utf-8\nimport os\nfrom dotenv import load_dotenv, find_dotenv\nfrom requests import session\nimport logging\n\n# payload for login to kaggle\npayload = {\n 'action': 'login',\n 'username': os.environ.get('KAGGLE_USERNAME'),\n 'password': os.environ.get('KAGGLE_PASSWORD')\n}\n\nurl_login = 'https://www.kaggle.com/account/login'\n\ndef extract_data(url, file_path):\n '''\n method to extract data\n '''\n # setup session\n with session() as c:\n c.post(url_login, data=payload)\n # open file to write\n with open(file_path, 'wb') as handle:\n response = c.get(url, stream=True)\n for block in response.iter_content(1024):\n handle.write(block)\n \ndef main(project_dir):\n '''\n main method\n '''\n # get logger\n logger = logging.getLogger(__name__)\n logger.info('getting raw data')\n \n #urls\n train_url = 'https://www.kaggle.com/c/titanic/download/train.csv'\n test_url = 'https://www.kaggle.com/c/titanic/download/test.csv'\n\n #file path\n raw_data_path = os.path.join(os.path.pardir,'data','raw')\n train_data_path = os.path.join(raw_data_path,'train.csv')\n test_data_path = os.path.join(raw_data_path,'test.csv')\n\n # etract data\n extract_data(train_url,train_data_path)\n extract_data(test_url,test_data_path)\n logger.info('downloaded raw training and test data')\n \nif __name__ == '__main__':\n # getting root directory\n project_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)\n \n # setup logger\n log_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n \n # find .env automatically by walking up directories until it's found\n dotenv_path = find_dotenv()\n # load up the entries as enviroment variables\n load_dotenv(dotenv_path)\n \n # call the main\n main(project_dir)",
"Writing ..\\src\\data\\get_raw_data.py\n"
],
[
"!python $get_raw_data_script_file",
"2021-02-15 18:53:49,595 - __main__ - INFO - getting raw data\n2021-02-15 18:53:50,597 - __main__ - INFO - downloaded raw training and test data\n"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
]
] |
cbb4620bcfef1144417663ffbf7aa85ec635ed42
| 77,646 |
ipynb
|
Jupyter Notebook
|
assignments/assignment2/PyTorch.ipynb
|
iStarikov/dlcourse_ai
|
d3791e8148cc9811c0f10b39850200638c4c7bd1
|
[
"MIT"
] | null | null | null |
assignments/assignment2/PyTorch.ipynb
|
iStarikov/dlcourse_ai
|
d3791e8148cc9811c0f10b39850200638c4c7bd1
|
[
"MIT"
] | null | null | null |
assignments/assignment2/PyTorch.ipynb
|
iStarikov/dlcourse_ai
|
d3791e8148cc9811c0f10b39850200638c4c7bd1
|
[
"MIT"
] | null | null | null | 86.273333 | 41,628 | 0.79194 |
[
[
[
"# Задание 2.2 - Введение в PyTorch\n\nДля этого задания потребуется установить версию PyTorch 1.0\n\nhttps://pytorch.org/get-started/locally/\n\nВ этом задании мы познакомимся с основными компонентами PyTorch и натренируем несколько небольших моделей.<br>\nGPU нам пока не понадобится.\n\nОсновные ссылки: \nhttps://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html \nhttps://pytorch.org/docs/stable/nn.html \nhttps://pytorch.org/docs/stable/torchvision/index.html ",
"_____no_output_____"
]
],
[
[
"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.datasets as dset\nfrom torch.utils.data.sampler import SubsetRandomSampler, Sampler\n\nfrom torchvision import transforms\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport numpy as np",
"_____no_output_____"
]
],
[
[
"## Как всегда, начинаем с загрузки данных\n\nPyTorch поддерживает загрузку SVHN из коробки.",
"_____no_output_____"
]
],
[
[
"data_train = dset.SVHN('./data/', split='train', download=False,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.43,0.44,0.47],\n std=[0.20,0.20,0.20]) \n ])\n )",
"_____no_output_____"
],
[
"# First, lets load the dataset\ndata_test = dset.SVHN('./data/', split='test', download=False, \n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.43,0.44,0.47],\n std=[0.20,0.20,0.20]) \n ]))",
"Using downloaded and verified file: ./data/train_32x32.mat\n"
]
],
[
[
"Теперь мы разделим данные на training и validation с использованием классов `SubsetRandomSampler` и `DataLoader`.\n\n`DataLoader` подгружает данные, предоставляемые классом `Dataset`, во время тренировки и группирует их в батчи.\nОн дает возможность указать `Sampler`, который выбирает, какие примеры из датасета использовать для тренировки. Мы используем это, чтобы разделить данные на training и validation.\n\nПодробнее: https://pytorch.org/tutorials/beginner/data_loading_tutorial.html",
"_____no_output_____"
]
],
[
[
"batch_size = 64\n\ndata_size = data_train.data.shape[0]\nvalidation_split = .2\nsplit = int(np.floor(validation_split * data_size))\nindices = list(range(data_size))\nnp.random.shuffle(indices)\n\ntrain_indices, val_indices = indices[split:], indices[:split]\n\ntrain_sampler = SubsetRandomSampler(train_indices)\nval_sampler = SubsetRandomSampler(val_indices)\n\ntrain_loader = torch.utils.data.DataLoader(data_train, batch_size=batch_size, \n sampler=train_sampler)\nval_loader = torch.utils.data.DataLoader(data_train, batch_size=batch_size,\n sampler=val_sampler)",
"_____no_output_____"
]
],
[
[
"В нашей задаче мы получаем на вход изображения, но работаем с ними как с одномерными массивами. Чтобы превратить многомерный массив в одномерный, мы воспользуемся очень простым вспомогательным модулем `Flattener`.",
"_____no_output_____"
]
],
[
[
"sample, label = data_train[0]\nprint(\"SVHN data sample shape: \", sample.shape)\n# As you can see, the data is shaped like an image\n\n# We'll use a special helper module to shape it into a tensor\nclass Flattener(nn.Module):\n def forward(self, x):\n batch_size, *_ = x.shape\n return x.view(batch_size, -1)",
"SVHN data sample shape: torch.Size([3, 32, 32])\n"
]
],
[
[
"И наконец, мы создаем основные объекты PyTorch:\n- `nn_model` - собственно, модель с нейросетью\n- `loss` - функцию ошибки, в нашем случае `CrossEntropyLoss`\n- `optimizer` - алгоритм оптимизации, в нашем случае просто `SGD`",
"_____no_output_____"
]
],
[
[
"nn_model = nn.Sequential(\n Flattener(),\n nn.Linear(3*32*32, 100),\n nn.ReLU(inplace=True),\n nn.Linear(100, 10), \n )\nnn_model.type(torch.FloatTensor)\n\n# We will minimize cross-entropy between the ground truth and\n# network predictions using an SGD optimizer\nloss = nn.CrossEntropyLoss().type(torch.FloatTensor)\noptimizer = optim.SGD(nn_model.parameters(), lr=1e-2, weight_decay=1e-1)",
"_____no_output_____"
]
],
[
[
"## Тренируем!\n\nНиже приведена функция `train_model`, реализующая основной цикл тренировки PyTorch.\n\nКаждую эпоху эта функция вызывает функцию `compute_accuracy`, которая вычисляет точность на validation, эту последнюю функцию предлагается реализовать вам.",
"_____no_output_____"
]
],
[
[
"scheduler.optimizer = optimizer",
"_____no_output_____"
],
[
"scheduler.optimizer",
"_____no_output_____"
],
[
"# This is how to implement the same main train loop in PyTorch. Pretty easy, right?\n\ndef train_model(model, train_loader, val_loader, loss, optimizer, num_epochs, scheduler=None): \n loss_history = []\n train_history = []\n val_history = []\n if scheduler.optimizer == optimizer:\n pass\n else:\n scheduler.optimizer = optimizer\n \n for epoch in range(num_epochs):\n model.train() # Enter train mode\n \n loss_accum = 0\n correct_samples = 0\n total_samples = 0\n \n for i_step, (x, y) in enumerate(train_loader):\n prediction = model(x) \n loss_value = loss(prediction, y)\n optimizer.zero_grad() \n loss_value.backward()\n optimizer.step() \n \n _, indices = torch.max(prediction, 1)\n correct_samples += torch.sum(indices == y)\n total_samples += y.shape[0]\n \n loss_accum += loss_value\n \n scheduler.step()\n\n ave_loss = loss_accum / (i_step + 1)\n train_accuracy = float(correct_samples) / total_samples\n val_accuracy = compute_accuracy(model, val_loader)\n \n loss_history.append(float(ave_loss))\n train_history.append(train_accuracy)\n val_history.append(val_accuracy)\n \n print(\"Average loss: %f, Train accuracy: %f, Val accuracy: %f\" % (ave_loss, train_accuracy, val_accuracy))\n \n return loss_history, train_history, val_history\n \ndef compute_accuracy(model, loader):\n \"\"\"\n Computes accuracy on the dataset wrapped in a loader\n \n Returns: accuracy as a float value between 0 and 1\n \"\"\"\n model.eval() # Evaluation mode\n # TODO: Implement the inference of the model on all of the batches from loader,\n # and compute the overall accuracy.\n # Hint: PyTorch has the argmax function!\n correct_samples = 0\n total_samples = 0\n for i_step, (x, y) in enumerate(loader):\n prediction = model(x) \n \n indices = torch.argmax(prediction, dim=1) # output.shape == (prediction.shape[0], 1)\n indices.view(y.shape)\n correct_samples += torch.sum(indices == y)\n total_samples += y.shape[0]\n# print(correct_samples)\n# print(total_samples)\n\n accuracy = float(correct_samples) / total_samples\n return accuracy",
"_____no_output_____"
],
[
"loss_history, train_history, val_history = train_model(nn_model, train_loader, val_loader, loss, optimizer, 3)",
"Average loss: 1.655162, Train accuracy: 0.452155, Val accuracy: 0.453143\nAverage loss: 1.650774, Train accuracy: 0.453964, Val accuracy: 0.451232\nAverage loss: 1.645850, Train accuracy: 0.454783, Val accuracy: 0.444475\n"
]
],
[
[
"## После основного цикла\n\nПосмотрим на другие возможности и оптимизации, которые предоставляет PyTorch.\n\nДобавьте еще один скрытый слой размера 100 нейронов к модели",
"_____no_output_____"
]
],
[
[
"# Since it's so easy to add layers, let's add some!\n\n# TODO: Implement a model with 2 hidden layers of the size 100\nnn_model = nn.Sequential(\n Flattener(),\n nn.Linear(3*32*32, 100),\n nn.ReLU(inplace=True),\n nn.Linear(100, 100),\n nn.ReLU(inplace=True),\n nn.Linear(100, 10)\n)\nnn_model.type(torch.FloatTensor)\n\noptimizer = optim.SGD(nn_model.parameters(), lr=1e-2, weight_decay=1e-1)\nloss_history, train_history, val_history = train_model(nn_model, train_loader, val_loader, loss, optimizer, 5)",
"Average loss: 2.169072, Train accuracy: 0.195338, Val accuracy: 0.221487\nAverage loss: 1.992016, Train accuracy: 0.283367, Val accuracy: 0.354310\nAverage loss: 1.776039, Train accuracy: 0.401887, Val accuracy: 0.429117\nAverage loss: 1.698507, Train accuracy: 0.428233, Val accuracy: 0.434851\nAverage loss: 1.677851, Train accuracy: 0.439563, Val accuracy: 0.444680\n"
]
],
[
[
"Добавьте слой с Batch Normalization",
"_____no_output_____"
]
],
[
[
"# We heard batch normalization is powerful, let's use it!\n# TODO: Add batch normalization after each of the hidden layers of the network, before or after non-linearity\n# Hint: check out torch.nn.BatchNorm1d\n\nnn_model = nn.Sequential(\n Flattener(),\n nn.Linear(3*32*32, 100),\n nn.ReLU(inplace=True),\n nn.BatchNorm1d(100),\n nn.Linear(100, 100),\n nn.ReLU(inplace=True),\n nn.BatchNorm1d(100),\n nn.Linear(100, 10)\n )\n\noptimizer = optim.SGD(nn_model.parameters(), lr=1e-3, weight_decay=1e-1)\nloss_history, train_history, val_history = train_model(nn_model, train_loader, val_loader, loss, optimizer, 5)",
"Average loss: 1.950653, Train accuracy: 0.361072, Val accuracy: 0.547949\nAverage loss: 1.512698, Train accuracy: 0.588199, Val accuracy: 0.643233\nAverage loss: 1.332864, Train accuracy: 0.645685, Val accuracy: 0.687257\nAverage loss: 1.227591, Train accuracy: 0.677388, Val accuracy: 0.693127\nAverage loss: 1.167344, Train accuracy: 0.693342, Val accuracy: 0.709917\n"
]
],
[
[
"Добавьте уменьшение скорости обучения по ходу тренировки.",
"_____no_output_____"
]
],
[
[
"from torch.optim.lr_scheduler import LambdaLR, StepLR",
"_____no_output_____"
],
[
"scheduler = StepLR(optimizer, step_size=2, gamma=0.5)",
"_____no_output_____"
],
[
"# Learning rate annealing\n# Reduce your learning rate 2x every 2 epochs\n# Hint: look up learning rate schedulers in PyTorch. You might need to extend train_model function a little bit too!\n\nnn_model = nn.Sequential(\n Flattener(),\n nn.Linear(3*32*32, 100),\n nn.ReLU(inplace=True),\n nn.BatchNorm1d(100),\n nn.Linear(100, 100),\n nn.ReLU(inplace=True),\n nn.BatchNorm1d(100),\n nn.Linear(100, 10)\n)\n\noptimizer = optim.SGD(nn_model.parameters(), lr=1e-2, weight_decay=1e-1)\n# lambda1 = lambda epoch: 0.95 ** epoch\nscheduler = StepLR(optimizer, step_size=2, gamma=0.5)\nloss_history, train_history, val_history = train_model(nn_model, train_loader, val_loader, loss, optimizer, 5, scheduler=scheduler)",
"Average loss: 1.609196, Train accuracy: 0.514708, Val accuracy: 0.590813\nAverage loss: 1.442233, Train accuracy: 0.602344, Val accuracy: 0.629786\nAverage loss: 1.403399, Train accuracy: 0.649643, Val accuracy: 0.597843\nAverage loss: 1.412195, Train accuracy: 0.647016, Val accuracy: 0.660160\nAverage loss: 1.338642, Train accuracy: 0.690510, Val accuracy: 0.692035\n"
]
],
[
[
"# Визуализируем ошибки модели\n\nПопробуем посмотреть, на каких изображениях наша модель ошибается.\nДля этого мы получим все предсказания модели на validation set и сравним их с истинными метками (ground truth).\n\nПервая часть - реализовать код на PyTorch, который вычисляет все предсказания модели на validation set. \nЧтобы это сделать мы приводим код `SubsetSampler`, который просто проходит по всем заданным индексам последовательно и составляет из них батчи. \n\nРеализуйте функцию `evaluate_model`, которая прогоняет модель через все сэмплы validation set и запоминает предсказания модели и истинные метки.",
"_____no_output_____"
]
],
[
[
"class SubsetSampler(Sampler):\n r\"\"\"Samples elements with given indices sequentially\n\n Arguments:\n indices (ndarray): indices of the samples to take\n \"\"\"\n\n def __init__(self, indices):\n self.indices = indices\n\n def __iter__(self):\n return (self.indices[i] for i in range(len(self.indices)))\n\n def __len__(self):\n return len(self.indices)\n \n \ndef evaluate_model(model, dataset, indices):\n \"\"\"\n Computes predictions and ground truth labels for the indices of the dataset\n \n Returns: \n predictions: np array of ints - model predictions\n grount_truth: np array of ints - actual labels of the dataset\n \"\"\"\n model.eval() # Evaluation mode\n \n sampler = SubsetSampler(indices)\n loader = torch.utils.data.DataLoader(dataset, batch_sampler=sampler)\n predictions = []\n ground_truth = []\n# for i, (x, y) in loader:\n\n for i_step, (x, y) in enumerate(loader):\n prediction = model(x) \n prediction_idx = torch.argmax(prediction, 1)\n \n predictions.append(prediction_idx)\n ground_truth.append(y)\n\n print(f\"prediction: {prediction_idx}\")\n print(f\"ground_truth: {y}\")\n \n \n # TODO: Evaluate model on the list of indices and capture predictions\n # and ground truth labels\n # Hint: SubsetSampler above could be useful!\n \n return predictions, ground_truth",
"_____no_output_____"
],
[
"len(val_indices)",
"_____no_output_____"
],
[
"# Evaluate model on validation\npredictions, gt = evaluate_model(nn_model, data_train, val_indices)\nassert len(predictions) == len(val_indices)\nassert len(gt) == len(val_indices)\nassert gt[100] == data_train[val_indices[100]][1]\nassert np.any(np.not_equal(gt, predictions))",
"_____no_output_____"
],
[
"val_sampler = SubsetRandomSampler(val_indices)\n\ntrain_loader = torch.utils.data.DataLoader(data_train, batch_size=batch_size, \n sampler=train_sampler)\nval_loader = torch.utils.data.DataLoader(data_train, batch_size=batch_size,\n sampler=val_sampler)",
"_____no_output_____"
]
],
[
[
"## Confusion matrix\nПервая часть визуализации - вывести confusion matrix (https://en.wikipedia.org/wiki/Confusion_matrix ).\n\nConfusion matrix - это матрица, где каждой строке соответствуют классы предсказанный, а столбцу - классы истинных меток (ground truth). Число с координатами `i,j` - это количество сэмплов класса `j`, которые модель считает классом `i`.\n\n\n\nДля того, чтобы облегчить вам задачу, ниже реализована функция `visualize_confusion_matrix` которая визуализирует такую матрицу. \nВам осталось реализовать функцию `build_confusion_matrix`, которая ее вычислит.\n\nРезультатом должна быть матрица 10x10.",
"_____no_output_____"
]
],
[
[
"def visualize_confusion_matrix(confusion_matrix):\n \"\"\"\n Visualizes confusion matrix\n \n confusion_matrix: np array of ints, x axis - predicted class, y axis - actual class\n [i][j] should have the count of samples that were predicted to be class i,\n but have j in the ground truth\n \n \"\"\"\n # Adapted from \n # https://stackoverflow.com/questions/2897826/confusion-matrix-with-number-of-classified-misclassified-instances-on-it-python\n assert confusion_matrix.shape[0] == confusion_matrix.shape[1]\n size = confusion_matrix.shape[0]\n fig = plt.figure(figsize=(10,10))\n plt.title(\"Confusion matrix\")\n plt.ylabel(\"predicted\")\n plt.xlabel(\"ground truth\")\n res = plt.imshow(confusion_matrix, cmap='GnBu', interpolation='nearest')\n cb = fig.colorbar(res)\n plt.xticks(np.arange(size))\n plt.yticks(np.arange(size))\n for i, row in enumerate(confusion_matrix):\n for j, count in enumerate(row):\n plt.text(j, i, count, fontsize=14, horizontalalignment='center', verticalalignment='center')\n \ndef build_confusion_matrix(predictions, ground_truth):\n \"\"\"\n Builds confusion matrix from predictions and ground truth\n\n predictions: np array of ints, model predictions for all validation samples\n ground_truth: np array of ints, ground truth for all validation samples\n \n Returns:\n np array of ints, (10,10), counts of samples for predicted/ground_truth classes\n \"\"\"\n \n confusion_matrix = np.zeros((10,10), np.int)\n \n confusion_matrix\n # TODO: Implement filling the prediction matrix\n return np.array([[40, 2, 3], [10, 50,0], [0, 2, 80]])\n\nconfusion_matrix = build_confusion_matrix(predictions, gt)\nvisualize_confusion_matrix(confusion_matrix)",
"_____no_output_____"
]
],
[
[
"Наконец, посмотрим на изображения, соответствующие некоторым элементам этой матрицы.\n\nКак и раньше, вам дана функция `visualize_images`, которой нужно воспрользоваться при реализации функции `visualize_predicted_actual`. Эта функция должна вывести несколько примеров, соответствующих заданному элементу матрицы.\n\nВизуализируйте наиболее частые ошибки и попробуйте понять, почему модель их совершает.",
"_____no_output_____"
]
],
[
[
"data_train_images = dset.SVHN('./data/', split='train')\n\ndef visualize_images(indices, data, title='', max_num=10):\n \"\"\"\n Visualizes several images from the dataset\n \n indices: array of indices to visualize\n data: torch Dataset with the images\n title: string, title of the plot\n max_num: int, max number of images to display\n \"\"\"\n to_show = min(len(indices), max_num)\n fig = plt.figure(figsize=(10,1.5))\n fig.suptitle(title)\n for i, index in enumerate(indices[:to_show]):\n plt.subplot(1,to_show, i+1)\n plt.axis('off')\n sample = data[index][0]\n plt.imshow(sample)\n \ndef visualize_predicted_actual(predicted_class, gt_class, predictions, groud_truth, val_indices, data):\n \"\"\"\n Visualizes images of a ground truth class which were predicted as the other class \n \n predicted: int 0-9, index of the predicted class\n gt_class: int 0-9, index of the ground truth class\n predictions: np array of ints, model predictions for all validation samples\n ground_truth: np array of ints, ground truth for all validation samples\n val_indices: np array of ints, indices of validation samples\n \"\"\"\n\n # TODO: Implement visualization using visualize_images above\n # predictions and ground_truth are provided for validation set only, defined by val_indices\n # Hint: numpy index arrays might be helpful\n # https://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays\n # Please make the title meaningful!\n \n raise Exception(\"Not implemented\")\n\nvisualize_predicted_actual(6, 8, predictions, gt, np.array(val_indices), data_train_images)\nvisualize_predicted_actual(1, 7, predictions, gt, np.array(val_indices), data_train_images)",
"_____no_output_____"
],
[
"predictions",
"_____no_output_____"
]
],
[
[
"# Переходим к свободным упражнениям!\n\nНатренируйте модель как можно лучше - экспериментируйте сами!\nЧто следует обязательно попробовать:\n- перебор гиперпараметров с помощью валидационной выборки\n- другие оптимизаторы вместо SGD\n- изменение количества слоев и их размеров\n- наличие Batch Normalization\n\nНо ограничиваться этим не стоит!\n\nТочность на тестовой выборке должна быть доведена до **80%**",
"_____no_output_____"
]
],
[
[
"# Experiment here!",
"_____no_output_____"
],
[
"# Как всегда, в конце проверяем на test set\ntest_loader = torch.utils.data.DataLoader(data_test, batch_size=batch_size)\ntest_accuracy = compute_accuracy(nn_model, test_loader)\nprint(\"Test accuracy: %2.4f\" % test_accuracy)",
"Test accuracy: 0.6679\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",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
]
] |
cbb46306db5b88f7198c3452555c866a65f7059b
| 34,668 |
ipynb
|
Jupyter Notebook
|
_labs/Lab07/Lab07.1-RelationshipsCategoricalVariable.ipynb
|
Icasas101/cmps3160
|
e86b7fa92ce5bbeb5ba19d642fb2bcecc6e7137e
|
[
"MIT"
] | null | null | null |
_labs/Lab07/Lab07.1-RelationshipsCategoricalVariable.ipynb
|
Icasas101/cmps3160
|
e86b7fa92ce5bbeb5ba19d642fb2bcecc6e7137e
|
[
"MIT"
] | null | null | null |
_labs/Lab07/Lab07.1-RelationshipsCategoricalVariable.ipynb
|
Icasas101/cmps3160
|
e86b7fa92ce5bbeb5ba19d642fb2bcecc6e7137e
|
[
"MIT"
] | 15 |
2020-08-24T00:54:02.000Z
|
2021-11-10T00:06:19.000Z
| 36.608237 | 514 | 0.638283 |
[
[
[
"# Lab 07.1: Relationships Between Categorical Variables\n\nThis lab is presented with some revisions from [Dennis Sun at Cal Poly](https://web.calpoly.edu/~dsun09/index.html) and his [Data301 Course](http://users.csc.calpoly.edu/~dsun09/data301/lectures.html)\n\n### When you have filled out all the questions, submit via [Tulane Canvas](https://tulane.instructure.com/)\n\nSo far, we have seen different ways to summarize and visualize _individual_ variables in a data set. But we have not really discussed how to summarize and visualize relationships between _multiple_ variables. This chapter is all about how to understand relationships between the columns in a `DataFrame`. The methods will be different, depending on whether the variables are categorical or quantitative.",
"_____no_output_____"
],
[
"In this section, we look at ways to summarize the relationship between two _categorical_ variables. To do this, we will again use the Titanic data set.",
"_____no_output_____"
]
],
[
[
"%matplotlib inline\nimport pandas as pd\nimport numpy as np\n\ntitanic_df = pd.read_csv(\"../data/titanic.csv\")",
"_____no_output_____"
]
],
[
[
"Suppose we want to understand the relationship between where a passenger embarked and what class they were in. We can completely summarize this relationship by counting the number of passengers in each class that embarked at each location. We can create a pivot table that summarizes this information.",
"_____no_output_____"
]
],
[
[
"embarked_pclass_counts = titanic_df.pivot_table(\n index=\"embarked\", columns=\"pclass\",\n values=\"name\", # We can pretty much count any column, as long as there are no NaNs.\n aggfunc=\"count\" # The count function will count the number of non-null values.\n)\nembarked_pclass_counts",
"_____no_output_____"
]
],
[
[
"Recall that the field embarked is coded categorically using: `embarked - Port of Embarkation (C = Cherbourg; Q = Queenstown; S = Southampton)`\n\nA pivot table that stores counts is also called a **contigency table** or a **cross-tabulation**. This type of pivot table is common enough that there is a specific function in `pandas` to calculate one, allowing you to bypass `.pivot_table`:",
"_____no_output_____"
]
],
[
[
"counts = pd.crosstab(titanic_df.embarked, titanic_df.pclass)\ncounts",
"_____no_output_____"
]
],
[
[
"## Joint Distributions",
"_____no_output_____"
],
[
"It is common to normalize the counts in a table so that they add up to 1. These proportions represent the **joint distribution** of the two variables.\n\nTo calculate the joint distribution, we need to divide the table of counts above by the total count. To find the total count, we call `.sum()` twice; the first call gives us the sum of each column, and the second call adds those numbers together.",
"_____no_output_____"
]
],
[
[
"print(counts.sum().sum())\njoint = counts / counts.sum().sum()\njoint",
"_____no_output_____"
]
],
[
[
"Note that this is yet another example of broadcasting. When we divided the `DataFrame` `counts` by the number 1307, the division was applied elementwise, producing another `DataFrame`.\n\nEach cell in this `DataFrame` tells us a joint proportion. For example, the cell in the bottom right tells us the proportion of all passengers that embarked at Southampton and were in 3rd class. We notate this joint proportion as follows:\n\n$$ P(\\text{embarked at Southampton and in 3rd class}) = .379. $$\n\nThe joint distribution above could also have been obtained by specifying `normalize=True` when the contingency table was first created:",
"_____no_output_____"
]
],
[
[
"pd.crosstab(titanic_df.embarked, titanic_df.pclass,\n normalize=True)",
"_____no_output_____"
]
],
[
[
"The above joint distribution is not, strictly speaking, a contingency table. A contingency table is a table of all counts, while the above table is a table of proportions.",
"_____no_output_____"
],
[
"## Marginal Distributions\n\nThe **marginal distribution** of a variable is simply the distribution of that variable, ignoring the other variables. To calculate the marginal distribution from a joint distribution of two variables, we sum the rows or the columns of the joint distribution.\n\nFor example, to calculate the marginal distribution of `embarked`, we have to sum the joint distribution over the columns---in other words, _roll-up_ or _marginalize over_ the `pclass` variable:",
"_____no_output_____"
]
],
[
[
"joint.sum(axis=1)",
"_____no_output_____"
]
],
[
[
"We can check this answer by calculating the distribution of `embarked` directly from the original data, ignoring `pclass` entirely.",
"_____no_output_____"
]
],
[
[
"embarked_counts = titanic_df.groupby(\"embarked\")[\"name\"].count()\nembarked_counts / embarked_counts.sum()",
"_____no_output_____"
]
],
[
[
"The numbers match!\n\nLikewise, we calculate the marginal distribution of `pclass` by summing the joint distribution over the rows---in other words, by _rolling-up_ or _marginalizing over_ the `embarked` variable:",
"_____no_output_____"
]
],
[
[
"joint.sum(axis=0)",
"_____no_output_____"
]
],
[
[
"So given the joint distribution of two categorical variables, there are two marginal distributions: one for each of the variables. These marginal distributions are obtained by summing the joint distribution table over the rows and over the columns.\n\nThe _marginal distribution_ is so-named because these row and column totals would typically be included alongside the joint distribution, in the _margins_ of the table. A contingency table with the marginal distributions included can be obtained by specifying `margins=True` in `pd.crosstab`:",
"_____no_output_____"
]
],
[
[
"pd.crosstab(titanic_df.embarked, titanic_df.pclass,\n normalize=True, margins=True)",
"_____no_output_____"
]
],
[
[
"Notice in the above that the sum over all elements of the join distribution (the bottom right corner) is a probability distribution (sums to 1.0). Likewise the sum over either of the computed marginal distributions is also a probability distribution (sums to 1.0).",
"_____no_output_____"
],
[
"## Conditional Distributions\n\nThe **conditional distribution** tells us about the distribution of one variable, _conditional on_ the value of another. For example, we might want to know the proportion of 3rd class passengers that embarked at each location. In other words, what is the distribution of where a passenger embarked, _conditional on_ being in 3rd class?\n\nIf we go back to the contingency table:",
"_____no_output_____"
]
],
[
[
"embarked_pclass_counts",
"_____no_output_____"
]
],
[
[
"there were $101 + 113 + 495 = 709$ passengers in 3rd class, of whom \n\n- $101 / 709 = .142$ were in 1st class,\n- $113 / 709 = .159$ were in 2nd class, and\n- $495 / 709 = .698$ were in 3rd class.\n\nWe can calculate these proportions in code by dividing the `pclass=3` column by its sum:",
"_____no_output_____"
]
],
[
[
"embarked_pclass_counts[3] / embarked_pclass_counts[3].sum()",
"_____no_output_____"
]
],
[
[
"Notice that these three proportions add up to 1, making this a proper distribution.\n\nThis conditional distribution helps us answer questions such as, \"What proportion of 3rd class passengers embarked at Southampton?\" We notate this conditional proportion as follows:\n\n$$ P\\big(\\textrm{embarked at Southampton}\\ \\big|\\ \\textrm{in 3rd class}\\big) = 0.698. $$\n\nThe pipe $\\big|$ is read \"given\". So we are interested in the proportion of passengers who embarked at Southampton, _given_ that they were in 3rd class.\n\nWe could have also calculated this conditional distribution from the joint distribution (i.e., proportions instead of counts):",
"_____no_output_____"
]
],
[
[
"joint[3] / joint[3].sum()",
"_____no_output_____"
]
],
[
[
"We have just calculated _one_ of the conditional distributions of `embarked`: the distribution conditional on being in 3rd class. There are two more conditional distributions of `embarked`: \n\n- the distribution conditional on being in 1st class \n- the distribution conditional on being in 2nd class\n\nIt is common to report _all_ of the conditional distributions of one variable given another variable.\n\nOf course, it is straightforward to calculate these conditional distributions manually:",
"_____no_output_____"
]
],
[
[
"embarked_pclass_counts[1] / embarked_pclass_counts[1].sum()",
"_____no_output_____"
],
[
"embarked_pclass_counts[2] / embarked_pclass_counts[2].sum()",
"_____no_output_____"
]
],
[
[
"But there is a nifty trick for calculating all three conditional distributions at once. By summing the counts over `embarked`, we obtain the total number of people in each `pclass`:",
"_____no_output_____"
]
],
[
[
"pclass_counts = embarked_pclass_counts.sum(axis=0)\npclass_counts",
"_____no_output_____"
]
],
[
[
"This is exactly what we need to divide each column of `embarked_pclass_counts` by:",
"_____no_output_____"
]
],
[
[
"embarked_given_pclass = embarked_pclass_counts.divide(pclass_counts, axis=1)\nembarked_given_pclass",
"_____no_output_____"
]
],
[
[
"(This is yet another example of _broadcasting_, since we are dividing a `DataFrame` by a `Series`.)\n\nCompare each column with the numbers we obtained earlier. Notice also that each column sums to 1, a reminder that each column represents a separate distribution.\n\nWhen comparing numbers across distributions, it is important to be careful. For example, the 87.4% and the 69.8% in the \"Southampton\" row represent **percentages of different populations that have different sizes!**. Just because 87.4% is higher than 69.8% does not mean that more 2nd class passengers boarded at Southampton than 3rd class passengers. In fact, if we go back to the original contingency table, we see that more 3rd class passengers actually boarded at Southampton than 2nd class passengers!",
"_____no_output_____"
],
[
"There is also another set of conditional distributions for these two variables: the distribution of class, conditional on where they embarked. To calculate these conditional distributions, we instead divide `embarked_pclass_counts` by the sum of each row:",
"_____no_output_____"
]
],
[
[
"embarked_counts = embarked_pclass_counts.sum(axis=1)\npclass_given_embarked = embarked_pclass_counts.divide(embarked_counts, axis=0)\npclass_given_embarked",
"_____no_output_____"
]
],
[
[
"These conditional distributions answer questions like, \"What proportion of Southampton passengers were in 3rd class?\" \n\nNotice that these proportions are _not_ the same as the proportions for the other set of conditional distributions. That is because the two questions below are fundamentally different:\n\n_Question 1._ What proportion of 3rd class passengers embarked at Southampton?\n\n$$P\\big(\\textrm{embarked at Southampton}\\ \\big|\\ \\textrm{in 3rd class}\\big) = \\frac{\\text{# passengers who embarked at Southampton and in 3rd class}}{\\text{# passengers who in 3rd class}}$$\n\n_Question 2._ What proportion of Southampton passengers were in 3rd class? \n\n$$P\\big(\\textrm{in 3rd class}\\ \\big|\\ \\textrm{embarked at Southampton}\\big) = \\frac{\\text{# passengers who embarked at Southampton and in 3rd class}}{\\text{# passengers who embarked at Southampton}} \\\\ $$\n\n\n\nIn the first case, the reference population is all passengers who embarked at Southampton. In the second case, the reference population is all passengers who were in 3rd class. The numerators may be the same, but the denominators are different. In general, the conditional distributions of $X$ given $Y$ are _not_ the same as the conditional distributions of $Y$ given $X$. \n\nIf we rephrase the question slightly, we get yet another answer:\n\n_Question 3._ What proportion of passengers embarked at Southampton _and_ were in 3rd class?\n\n$$P(\\text{embarked at Southampton and in 3rd class}) = \\frac{\\text{# passengers who embarked at Southampton and in 3rd class}}{\\text{# passengers (total)}}$$\n\nThe reference population here is all passengers. This is the proportion that one would get from the joint distribution.\n\nIt is important to pay attention to the wording of the question, to determine whether a joint distribution or a conditional distribution is called for---and, if the latter, which of the two conditional distributions is appropriate.",
"_____no_output_____"
],
[
"## Visualization\n\nHow do we visualize the joint and conditional distributions of two categorical variables? (Marginal distributions are summaries of a single variable and can be visualized using the techniques of Chapter 1.)\n\nTo visualize a joint distribution, we need to be able to represent three dimensions: two dimensions for the two categorical variables and a third dimension for the proportions. Although one option is a 3D graph, humans are not good at judging the sizes of 3D objects printed on a page. For this reason, **heat maps**, which use a color scale to represent the third dimension, are usually preferred. \n\nUnfortunately, heat maps are still not easy to create in `pandas`. We use the `seaborn` library to make a heat map:",
"_____no_output_____"
]
],
[
[
"import seaborn as sns\n\nsns.heatmap(joint)",
"_____no_output_____"
]
],
[
[
"A heat map encourages comparison across cells. So we see that 3rd class passengers who embarked at Southampton were by far the most common.\n\nAlthough a heat map can also be used to visualize conditional distributions, it is not ideal because it does not tell us which variable we are conditioning on, and it is difficult to judge visually which dimension sums to 1. A stacked bar graph is better because it visually shows values summing to 1.\n\nTo make a stacked bar graph, we simply specify `stacked=True` in `.plot.bar()`, to get the bars to show up on top of one another, instead of side-by-side:",
"_____no_output_____"
]
],
[
[
"pclass_given_embarked.plot.bar(stacked=True)",
"_____no_output_____"
]
],
[
[
"However, the same code does not work on the other set of conditional distributions:",
"_____no_output_____"
]
],
[
[
"embarked_given_pclass.plot.bar(stacked=True)",
"_____no_output_____"
]
],
[
[
"What went wrong? Recall that `.plot.bar()` automatically plots the (row) index of the `DataFrame` on the $x$-axis. To plot the distribution of `embarked` conditional on `pclass`, we need `pclass` to be on the $x$-axis, but ",
"_____no_output_____"
]
],
[
[
"embarked_given_pclass",
"_____no_output_____"
]
],
[
[
"has `embarked` as the index. To make `pclass` the index, we can **transpose** this `DataFrame` so that the rows become columns and the columns become rows. The syntax for transposing a `DataFrame` is `.T`, which is inspired by the notation for transposing a matrix in linear algebra.",
"_____no_output_____"
]
],
[
[
"embarked_given_pclass.T",
"_____no_output_____"
]
],
[
[
"Now, we can make a stacked bar graph from this _transposed_ `DataFrame`:",
"_____no_output_____"
]
],
[
[
"(embarked_given_pclass.T).plot.bar(stacked=True)",
"_____no_output_____"
]
],
[
[
"## Summing Up About Conditionals Probabilities\n\nWe have discussed three different types of distributions (probabilities). Remember that for two events $X$ and $Y$:\n\n* Joint Distribution: The probabilitiy of two events occuring at the same time. Formally: $P(X \\cap Y)$. We typically use heatmaps to show joint distributions.\n* Marginal Distribution: The probabilitiy of a single event, irrespective of any other event (i.e., marginalizing the other event). Formally: $P(X)$. We can use the graphs learned before (pie charts, bar graphs) to visualize these.\n* Conditional Distribution: The probability of an event $X$ happening given that some event $Y$ has also happened. Formally: $P(X|Y) = \\frac{P(X \\cap Y)}{P(Y)}$. We typically use stacked bar graphs to visualize these distributions.\n\nWhen comparing across variables it is important to think about the relationship you want to present so that you can clearly and precisely discuss the relationship using the concepts from this notebook.",
"_____no_output_____"
],
[
"## Independence\n\nWe would like to measure the strength of the relationship between two variables. _Independence_ is a way to quantify the intuitive notion that two variables are _unrelated_. Once we have defined independence, we can quantify the relationship between two variables by calculating how far they are from independence.\n\nFormally, two variables $X$ and $Y$ are **independent** if the conditional distributions of $Y$ given $X$ (or vice versa) are all _identical_. In other words, the value of $X$ does not affect the distribution of $Y$.",
"_____no_output_____"
]
],
[
[
"titanic_df[\"adult\"] = (titanic_df[\"age\"] >= 18)",
"_____no_output_____"
]
],
[
[
"For example, consider the relationship between sex and age group (adult or not). First, let's calculate the contingency table:",
"_____no_output_____"
]
],
[
[
"counts = pd.crosstab(titanic_df.sex, titanic_df.adult)\ncounts",
"_____no_output_____"
]
],
[
[
"Although there are more male adults (576) than female adults (316), the _conditional proportion_ of adults, given sex, are actually very close (about $0.68$).",
"_____no_output_____"
]
],
[
[
"adult_given_sex = counts.divide(counts.sum(axis=1), axis=0)\nadult_given_sex.plot.bar(stacked=True)\nadult_given_sex ",
"_____no_output_____"
]
],
[
[
"Because the conditional distribution of `adult` is (approximately) the same, regardless of whether we are conditioning on `sex` = male or `sex` = female, we say that the two variables are (approximately) independent. \n\nFor an example of two non-independent variables, consider passenger class and age group. If we look at the conditional distributions of `adult` given `pclass`, they are not all the same:",
"_____no_output_____"
]
],
[
[
"adult_pclass_counts = pd.crosstab(titanic_df.pclass, titanic_df.adult)\n(adult_pclass_counts.divide(\n adult_pclass_counts.sum(axis=1), axis=0)\n).plot.bar(stacked=True)",
"_____no_output_____"
]
],
[
[
"The conditional distribution of `adult` given `pclass` = 3 is quite different from the other two conditional distributions. Because the conditional distributions are not all equal, the two variables are _not_ independent. Note that it only takes _one_ conditional distribution to be off to render two variables _not_ independent.",
"_____no_output_____"
],
[
"## The Joint Distribution Assuming Independence\n\nWhat would the joint distribution of passenger class (`pclass`) and age group (`adult`) be, if the two variables were independent? If two variables are independent, then their joint distribution is the product of the marginal distributions. That is,\n\n- $P(\\text{1st class and adult}) = P(\\text{1st class}) \\cdot P(\\text{adult})$\n- $P(\\text{2nd class and adult}) = P(\\text{2nd class}) \\cdot P(\\text{adult})$\n- $P(\\text{3rd class and adult}) = P(\\text{3rd class}) \\cdot P(\\text{adult})$\n- $P(\\text{1st class and not adult}) = P(\\text{1st class}) \\cdot P(\\text{not adult})$\n- $P(\\text{2nd class and not adult}) = P(\\text{2nd class}) \\cdot P(\\text{not adult})$\n- $P(\\text{3rd class and not adult}) = P(\\text{3rd class}) \\cdot P(\\text{not adult})$\n\nWe can calculate the marginal distributions:",
"_____no_output_____"
]
],
[
[
"# Calculate the total number of passengers.\nN = adult_pclass_counts.sum().sum()\n\n# Calculate the marginal distribution of adult by summing over pclass.\nadult = adult_pclass_counts.sum(axis=0) / N\nadult",
"_____no_output_____"
],
[
"# Calculate the marginal distributio of pclass by summing over adult.\npclass = adult_pclass_counts.sum(axis=1) / N\npclass",
"_____no_output_____"
]
],
[
[
"How do we multiply these two distributions to get a $3 \\times 2$ table of the joint distribution, assuming independence? We can use matrix multiplication. We can think of one `Series` as a matrix with 1 column and the other as a matrix with 1 row. Multiplying the two matrices using the usual definition of matrix multiplication gives the desired joint proportions.\n\n$$ {\\bf u} {\\bf v}^T = \\begin{pmatrix} u_1 \\\\ u_2 \\\\ u_3 \\end{pmatrix} \\begin{pmatrix} v_1 & v_2 \\end{pmatrix} = \\begin{pmatrix} u_1 v_1 & u_1 v_2 \\\\ u_2 v_1 & u_2 v_2 \\\\ u_3 v_1 & u_3 v_2 \\end{pmatrix} $$\n\nThis is an operation in linear algebra known as an **outer product**. To calculate the outer product of two `numpy` arrays, we can use the function `np.outer`:",
"_____no_output_____"
]
],
[
[
"np.outer(pclass, adult)",
"_____no_output_____"
]
],
[
[
"Note that this returns a plain `numpy` `array` instead of a `pandas` `DataFrame`. It turns out that this will be good enough for our purposes. You can always turn this into a DataFrame by passing it to `pd.DataFrame`.",
"_____no_output_____"
],
[
"## Measuring Distance from Independence\n\nWe now have, for every combination of our two variables, two proportions:\n\n- the proportion that was actually observed, $P(A \\text{ and } B)$\n- the proportion that we would expect assuming independence, $P(A) P(B)$\n\nTo measure the relationship between two variables, we calculate how far the observed proportions are from what we would expect if the variables were independent. It turns out that there are several ways to calculate the \"distance\" between two distributions.\n\n**Total Variation Distance**\n\n**Total variation distance** is probably the first distance metric that comes to mind. We calculate the difference and take absolute values before summing so that negative errors don't cancel out positive ones (the motivation for taking absolute values is the same as in MAD, which we learned in Chapter 1): \n\n$$ TV = \\sum_{\\text{A, B}} \\big|P(A \\text{ and } B) - P(A) P(B)\\big|. $$",
"_____no_output_____"
]
],
[
[
"joint = adult_pclass_counts / N\nexpected = np.outer(pclass, adult)\n\n# Total Variation Distance\n(joint - expected).abs().sum().sum()",
"_____no_output_____"
]
],
[
[
"Unfortunately, differences turn out to be a bad way to measure distances between proportions. For example, most people would agree that the difference between $0.42$ and $0.41$ is insignificant, but the difference between $0.01$ and $0.00$ is vast. But total variation distance treats both differences the same.\n\n**Chi-Square Distance**\n\n**Chi-square distance** solves the problem of total variation distance by dividing by the difference by expected proportion, effectively calculating the _relative_ difference between the two proportions:\n\n$$ \\chi^2 = \\sum_{\\text{A, B}} \\frac{(P(A \\text{ and } B) - P(A) P(B))^2}{P(A) P(B)}. $$",
"_____no_output_____"
]
],
[
[
"(((joint - expected) ** 2) / expected).sum().sum()",
"_____no_output_____"
]
],
[
[
"You might be familiar with the chi-square test from a previous statistics class. The chi-square distance is essentially the same as the chi-square test statistic, except for a normalizing constant.\n\n**Mutual Information**\n\nAnother popular distance metric is **mutual information**. Whereas chi-square distance tends to be more popular among statisticians, mututal information tends to be more popular among engineers. (It arises from a field called _information theory_ which you can take a course on here at Tulane if you wish!.)\n\n$$ I = \\sum_{\\text{A, B}} P(A \\text{ and } B) \\log \\left( \\frac{P(A \\text{ and } B)}{P(A) P(B)} \\right) $$",
"_____no_output_____"
]
],
[
[
"(joint * np.log(joint / expected)).sum().sum()",
"_____no_output_____"
]
],
[
[
"There is no best distance metric for measuring departures from independence. All three distance metrics above are used in practice. The distances themselves can also be difficult to interpret. But the distance metric can give a rough sense of how closely two variables are related.",
"_____no_output_____"
],
[
"# Exercises",
"_____no_output_____"
],
[
"Exercises 1-4 deal with the Tips data set (`../data/tips.csv`). Load this dataset below.",
"_____no_output_____"
]
],
[
[
"# CODE HERE\ndf_tips = pd.read_csv(\"../data/tips.csv\")\ndf_tips.head()",
"_____no_output_____"
]
],
[
[
"**Exercise 1.** Make a visualization (both a table and a graph) that displays the relationship between the day of the week and party size. Which type of distribution did you pick to represent this? Why?\n\nHint: There may be some missing data that you need to make sure you are [handling correctly](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.crosstab.html).",
"_____no_output_____"
]
],
[
[
"# ENTER YOUR CODE HERE",
"_____no_output_____"
]
],
[
[
"**Exercise 2.** Calculate the marginal distribution of day of week in two different ways using the results from the last cell.",
"_____no_output_____"
]
],
[
[
"# ENTER YOUR CODE HERE",
"_____no_output_____"
]
],
[
[
"**Exercise 3.** Make a visualization and display the DataFrame that displays the conditional distribution of party size, given the day of the week. That is, show $P(\\text{party size} | \\text{day of week})$.",
"_____no_output_____"
]
],
[
[
"# ENTER YOUR CODE HERE",
"_____no_output_____"
]
],
[
[
"**Exercise 4.** What proportion of Saturday parties had 2 people? Is this the same as the proportion of 2-person parties that dined on Saturday? Give the equation for both of these and explain the difference",
"_____no_output_____"
]
],
[
[
"# ENTER YOUR CODE HERE",
"_____no_output_____"
]
],
[
[
"**Math Answer Here.**",
"_____no_output_____"
],
[
"**Exercise 5.** Report a measure of the strength of the relationship between the size of the party and the day of the week. Display the count table and the conditional distribution table as well. ",
"_____no_output_____"
]
],
[
[
"# YOUR CODE HERE ",
"_____no_output_____"
]
],
[
[
"**Bonus Bonus 5 Point Exercise.** We discussed above that the conditional distributions of A given B and the conditional distributions of B given A are _not_ the same. \n\nCan you figure out a way to relate the two? \n\nCan you write code that will convert a table with the conditional distributions of A given B, into a table with the conditional distributions of B given A?\n\nTo get complete credit you must write code and write the mathmatical formula you use (in math mode offset by \\$ symbols) and name the formula correctly.\n\n",
"_____no_output_____"
]
],
[
[
"# ENTER YOUR CODE HERE",
"_____no_output_____"
]
],
[
[
"**Math Answer Here.**",
"_____no_output_____"
],
[
"### When you have filled out all the questions, submit via [Tulane Canvas](https://tulane.instructure.com/)",
"_____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"
] |
[
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"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",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
]
] |
cbb47353cef581c8af9a0b53a054e87439c43308
| 84,516 |
ipynb
|
Jupyter Notebook
|
SVM/TP4_SVM.ipynb
|
YanCHEN-fr/Machine_learning_for_Robot
|
7ba566247f1438b9b3de845427d956a0beb6520e
|
[
"Apache-2.0"
] | null | null | null |
SVM/TP4_SVM.ipynb
|
YanCHEN-fr/Machine_learning_for_Robot
|
7ba566247f1438b9b3de845427d956a0beb6520e
|
[
"Apache-2.0"
] | null | null | null |
SVM/TP4_SVM.ipynb
|
YanCHEN-fr/Machine_learning_for_Robot
|
7ba566247f1438b9b3de845427d956a0beb6520e
|
[
"Apache-2.0"
] | null | null | null | 165.717647 | 22,350 | 0.842468 |
[
[
[
"<a href=\"https://colab.research.google.com/github/PPatrickGU/ROB311/blob/master/TP4_SVM.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"_____no_output_____"
],
[
"# **ROB311 TP4** \n\n### **Implementation of the algorithm of SVM to identify the handwriting number** \n\n*Author: Yan CHEN & Dajing GU*",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport itertools\nimport operator\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.svm import SVC\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import classification_report, confusion_matrix\n%matplotlib inline",
"_____no_output_____"
]
],
[
[
"### **Useful function**",
"_____no_output_____"
]
],
[
[
"def data_loading(path):\n dataset = pd.read_csv(path)\n data = dataset.iloc[:, 1:]\n label = dataset.iloc[:, 0]\n return data, label\n\n# Reference : https://blog.csdn.net/u012193416/article/details/79469770\ndef plot_confusion_matrix(cm, classes, normalize=False, cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n title = 'Normalized confusion matrix'\n print(\"Normalized confusion matrix\")\n else:\n title = 'Confusion matrix without normalization'\n print('Confusion matrix without normalization')\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=0)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n verticalalignment='top',\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.show() \n\ndef getAccuracy(testSet, predictions):\n correct = 0\n for x in range(testSet.shape[0]):\n if testSet[x] == predictions[x]:\n correct += 1\n print(\"\\n Accuracy: %.2f%% \\n\" %float(correct/len(predictions)*100))\n\ndef getResult(prediction_label, test_label):\n cm = confusion_matrix(test_label, prediction_label)\n print(\"classification report : \", \"\\n\", classification_report(test_label, prediction_label))\n print(\"\\n\", \"confusion matrix:\", \"\\n\", cm, \"\\n\")\n getAccuracy(prediction_label, test_label)\n label_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n plot_confusion_matrix(cm, classes=label_names, normalize=True)\n\n",
"_____no_output_____"
]
],
[
[
"### **Data loading**",
"_____no_output_____"
]
],
[
[
"train_path = \"./mnist_train.csv\"\ntest_path = \"./mnist_test.csv\"\ntrain_data, train_target = data_loading(train_path)\ntest_data, test_target = data_loading(test_path)\n",
"_____no_output_____"
]
],
[
[
"### **I)A simple implementation of the algorithm**\n",
"_____no_output_____"
]
],
[
[
"pca = PCA(n_components=100)\nprint(\"data size before PCA:\", train_data.shape)\npca.fit(train_data)\ntrain_data_PCA = pca.transform(train_data)\ntest_data_PCA = pca.transform(test_data)\nprint('data size after PCA: ' ,train_data_PCA.shape)",
"data size before PCA: (60000, 784)\ndata size after PCA: (60000, 100)\n"
],
[
"clf = SVC()\nclf.fit(train_data_PCA, train_target)\nprediction = clf.predict(test_data_PCA)\ngetResult(prediction, test_target)",
"classification report : \n precision recall f1-score support\n\n 0 0.98 0.99 0.99 980\n 1 0.99 0.99 0.99 1135\n 2 0.98 0.98 0.98 1032\n 3 0.98 0.99 0.99 1010\n 4 0.99 0.98 0.98 982\n 5 0.99 0.99 0.99 892\n 6 0.99 0.99 0.99 958\n 7 0.98 0.98 0.98 1028\n 8 0.98 0.98 0.98 974\n 9 0.98 0.97 0.98 1009\n\n accuracy 0.98 10000\n macro avg 0.98 0.98 0.98 10000\nweighted avg 0.98 0.98 0.98 10000\n\n\n confusion matrix: \n [[ 974 0 1 0 0 2 0 1 2 0]\n [ 0 1128 3 1 0 1 1 0 1 0]\n [ 5 0 1014 0 1 0 1 7 4 0]\n [ 0 0 2 996 0 3 0 5 3 1]\n [ 0 0 3 0 964 0 4 0 1 10]\n [ 2 0 0 6 0 879 2 1 1 1]\n [ 5 2 0 0 2 3 945 0 1 0]\n [ 0 5 9 1 0 0 0 1007 1 5]\n [ 2 0 2 3 2 2 2 2 957 2]\n [ 2 3 1 5 8 2 1 5 3 979]] \n\n\n Accuracy: 98.43% \n\nNormalized confusion matrix\n"
]
],
[
[
"### **II) A better implementation using make_pipeline**",
"_____no_output_____"
]
],
[
[
"pca = PCA(n_components=100, whiten=True)\nsvc = SVC(kernel='rbf', class_weight='balanced')\nmodel = make_pipeline(pca, StandardScaler(), svc)\nmodel.fit(train_data, train_target)\nprediction = model.predict(test_data)\ngetResult(prediction, test_target)",
"classification report : \n precision recall f1-score support\n\n 0 0.98 0.99 0.99 980\n 1 0.99 0.99 0.99 1135\n 2 0.97 0.98 0.98 1032\n 3 0.98 0.98 0.98 1010\n 4 0.98 0.98 0.98 982\n 5 0.98 0.98 0.98 892\n 6 0.99 0.99 0.99 958\n 7 0.98 0.98 0.98 1028\n 8 0.98 0.98 0.98 974\n 9 0.98 0.96 0.97 1009\n\n accuracy 0.98 10000\n macro avg 0.98 0.98 0.98 10000\nweighted avg 0.98 0.98 0.98 10000\n\n\n confusion matrix: \n [[ 973 0 1 1 0 0 3 0 2 0]\n [ 0 1124 2 1 1 2 2 1 2 0]\n [ 1 2 1014 1 1 0 1 3 8 1]\n [ 0 0 7 986 0 6 0 5 5 1]\n [ 0 0 6 0 963 0 2 0 1 10]\n [ 2 0 0 6 0 878 3 0 3 0]\n [ 5 2 0 1 2 2 946 0 0 0]\n [ 0 4 12 2 0 1 0 1003 0 6]\n [ 3 0 1 3 2 3 1 4 955 2]\n [ 4 2 2 7 12 4 0 7 2 969]] \n\n\n Accuracy: 98.11% \n\nNormalized confusion matrix\n"
]
],
[
[
"### **III) A try with the grid_search**",
"_____no_output_____"
]
],
[
[
"def svm_test(test_path, clf):\n test_data, test_label = data_loading(test_path)\n prediction_label = clf.predict(test_data)\n return prediction_label, test_label\n\ndef svm_train_pca(train_path, svc_kernel = 'rbf', gridsearchcv = False):\n train_data, train_label = data_loading(train_path)\n pca = PCA(n_components=100, whiten=True)\n svc = SVC(kernel=svc_kernel, class_weight='balanced')\n clf = make_pipeline(pca, svc)\n if gridsearchcv == True:\n parameters = {'svc__kernel':('linear', 'rbf', 'poly', 'sigmoid'), 'svc__C':[1, 10]}\n clf = GridSearchCV(clf, parameters)\n clf.fit(train_data, train_label)\n print(\"The best parameters and best score: \\n\", clf.best_params_, clf.best_score_)\n else:\n clf.fit(train_data, train_label)\n return clf\n",
"_____no_output_____"
]
],
[
[
"**Train**",
"_____no_output_____"
]
],
[
[
"clf = svm_train_pca(train_path, gridsearchcv=True)",
"The best parameters and best score: \n {'svc__C': 10, 'svc__kernel': 'rbf'} 0.97955\n"
]
],
[
[
"**Test and Result**",
"_____no_output_____"
]
],
[
[
"prediction, test_label = svm_test(test_path, clf)\ngetResult(prediction, test_label)",
"classification report : \n precision recall f1-score support\n\n 0 0.98 0.99 0.99 980\n 1 0.99 0.99 0.99 1135\n 2 0.97 0.98 0.98 1032\n 3 0.98 0.98 0.98 1010\n 4 0.98 0.98 0.98 982\n 5 0.98 0.99 0.98 892\n 6 0.99 0.99 0.99 958\n 7 0.98 0.98 0.98 1028\n 8 0.98 0.98 0.98 974\n 9 0.98 0.96 0.97 1009\n\n accuracy 0.98 10000\n macro avg 0.98 0.98 0.98 10000\nweighted avg 0.98 0.98 0.98 10000\n\n\n confusion matrix: \n [[ 974 0 1 1 0 0 2 0 2 0]\n [ 0 1127 3 1 1 1 1 0 1 0]\n [ 2 1 1014 1 1 0 1 4 7 1]\n [ 0 0 7 987 0 5 0 5 5 1]\n [ 0 0 6 0 965 0 1 0 1 9]\n [ 1 0 1 7 0 879 3 0 1 0]\n [ 5 2 0 0 3 3 945 0 0 0]\n [ 0 5 11 2 2 1 0 1004 0 3]\n [ 3 0 1 2 1 3 1 3 958 2]\n [ 4 2 2 6 10 4 0 7 3 971]] \n\n\n Accuracy: 98.24% \n\nNormalized confusion matrix\n"
]
]
] |
[
"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"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
cbb4884b58ca1358d6f776bfec2a560fc17296a4
| 611,602 |
ipynb
|
Jupyter Notebook
|
ai-hackathon/medical-heart-prediction/medical heart failure prediction - notebook (feature).ipynb
|
rishuatgithub/MLPy
|
603fdc86a1d56c41e8199b94f96a19f35c719586
|
[
"Apache-2.0"
] | null | null | null |
ai-hackathon/medical-heart-prediction/medical heart failure prediction - notebook (feature).ipynb
|
rishuatgithub/MLPy
|
603fdc86a1d56c41e8199b94f96a19f35c719586
|
[
"Apache-2.0"
] | 1 |
2022-03-12T00:55:20.000Z
|
2022-03-12T00:55:20.000Z
|
ai-hackathon/medical-heart-prediction/medical heart failure prediction - notebook (feature).ipynb
|
rishuatgithub/MLPy
|
603fdc86a1d56c41e8199b94f96a19f35c719586
|
[
"Apache-2.0"
] | 3 |
2021-04-15T08:10:01.000Z
|
2021-11-04T17:57:51.000Z
| 308.111839 | 59,200 | 0.707226 |
[
[
[
"import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn import metrics\nfrom sklearn import preprocessing\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nfrom xgboost import XGBClassifier\nimport xgboost as xgb\n\nimport shap",
"_____no_output_____"
],
[
"#!conda install -c conda-forge shap -y",
"_____no_output_____"
],
[
"data = pd.read_csv('data/heart.csv')\n\ndata.head()",
"_____no_output_____"
],
[
"#data.columns = ['age','sex','chest_pain_type','resting_bp','cholestrol',\n# 'fasting_blood_sugar','rest_ecg','max_heart_rate_achieved','exercise_induced_agnia',\n# 'oldpeak','slope','major_vessels_ca','thal','target']",
"_____no_output_____"
]
],
[
[
"## Understanding the data",
"_____no_output_____"
]
],
[
[
"data.describe()",
"_____no_output_____"
],
[
"data.info()",
"<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 303 entries, 0 to 302\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 age 303 non-null int64 \n 1 sex 303 non-null int64 \n 2 cp 303 non-null int64 \n 3 trestbps 303 non-null int64 \n 4 chol 303 non-null int64 \n 5 fbs 303 non-null int64 \n 6 restecg 303 non-null int64 \n 7 thalach 303 non-null int64 \n 8 exang 303 non-null int64 \n 9 oldpeak 303 non-null float64\n 10 slope 303 non-null int64 \n 11 ca 303 non-null int64 \n 12 thal 303 non-null int64 \n 13 target 303 non-null int64 \ndtypes: float64(1), int64(13)\nmemory usage: 33.3 KB\n"
],
[
"## finding correlation\n#plt.figure(figsize=(14,7))\n\n#heatmap = sns.heatmap(data.corr(), annot=True, vmin=-1, vmax=1)\n#heatmap.set_title('Correlation Map (heart disease)', pad=2, fontdict={'fontsize':12})\n\n#plt.show()",
"_____no_output_____"
],
[
"plt.pie(data.groupby(\"target\").size(), labels=['target-0','target-1'], autopct='%1.1f%%')\nplt.show()",
"_____no_output_____"
],
[
"plt.hist([data[data.target==0].age, data[data.target==1].age], \n bins = 20, alpha = 0.5, \n label = [\"no heart disease\",\"with heart disease\"])\nplt.xlabel(\"age\")\nplt.ylabel(\"percentage\")\nplt.legend()\nplt.show()",
"_____no_output_____"
],
[
"# finding the outliers in the data\n\ncontinous_data = data[['age','trestbps','chol','thalach','oldpeak']]\n\nfor cols in continous_data.columns:\n plt.subplot(3,2,list(continous_data.columns).index(cols)+1)\n plt.boxplot(continous_data[cols], patch_artist=True, labels=[cols])\n plt.ylabel(\"value\")\nplt.tight_layout()\nplt.show()",
"_____no_output_____"
],
[
"continous_data.describe()",
"_____no_output_____"
],
[
"## removing the outliers\n\ndf1 = data[data['trestbps'] < (data['trestbps'].mean() + data['trestbps'].std()*3)]\ndf2 = df1[df1['chol'] < (df1['chol'].mean() + df1['chol'].std()*3)]\ndf3 = df2[df2['thalach'] < (df2['thalach'].mean() + df2['thalach'].std()*3)]\ndf4 = df3[df3['oldpeak'] < (df3['oldpeak'].mean() + df3['oldpeak'].std()*3)]\n\ndata = df4.copy()\n\ndata.describe()",
"_____no_output_____"
],
[
"## handling categorical data\n\ndata_catg = data.copy()\n\ndata_catg['cp'] = data['cp'].map({0:\"asymptomatic\",1:\"typical_angina\",2:\"atypical_angina\",3:\"non_anginal_pain\"})\ndata_catg['sex'] = data['sex'].map({0:\"female\", 1:\"male\"}) \ndata_catg['exang'] = data['exang'].map({0:\"exercise_not_induce_angina\", 1:\"exercise_induced_angina\"})\ndata_catg['slope'] = data['slope'].map({1:\"upsloping\", 2:\"flat\", 3:\"downsloping\"})\ndata_catg['thal'] = data['thal'].map({1:\"normal\",2:\"fixed_defect\", 3:\"reversable_defect\"})\n\ndf_new = pd.get_dummies(data_catg, drop_first = True)\n\ndf_new.head()",
"_____no_output_____"
],
[
"## trying to find the best features by running a dummy model\n\nX = df_new.drop(\"target\", 1).values\ny = df_new[\"target\"].astype(\"int\").values\n\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.10, random_state=32)",
"_____no_output_____"
],
[
"model = XGBClassifier(use_label_encoder =False, eval_metric='logloss')\n\nparam = {\n 'max_depth': [3,5,7,9], \n 'learning_rate':[0.001,0.01, 0.1, 0.3], \n 'n_estimators':[100,500]\n}\ncv = GridSearchCV(model, param_grid=param, cv=10, return_train_score=True)\ncv",
"_____no_output_____"
],
[
"cv.fit(X_train, y_train)\ntest_pred = cv.predict(X_test)\ncv.best_estimator_",
"_____no_output_____"
],
[
"max_depth_of_model = cv.best_estimator_.max_depth\nbest_learning_rate = cv.best_estimator_.learning_rate\nbest_estimator = cv.best_estimator_.n_estimators\nbest_reg_lambda = cv.best_estimator_.reg_lambda\n\nmodel = XGBClassifier(max_depth=max_depth_of_model, \n learning_rate=best_learning_rate, \n n_estimators= best_estimator,\n n_jobs=1)\nmodel.fit(X_train, y_train)\n\nyhat = model.predict(X_test)\ny_proba = model.predict_proba(X_test)[:, 1]\n\naccuracy_score(yhat,y_test)",
"[11:33:29] WARNING: /opt/concourse/worker/volumes/live/7a2b9f41-3287-451b-6691-43e9a6c0910f/volume/xgboost-split_1619728204606/work/src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.\n"
],
[
"importances = model.feature_importances_\nimportances",
"_____no_output_____"
],
[
"inducies = np.argsort(importances)[::-1]\n\nfeature_dict = dict()\nfor idx in inducies:\n feature_dict[list(df_new.drop(\"target\",1).columns)[idx]] = float(importances[idx])\nfeature_dict",
"_____no_output_____"
],
[
"y_pos = np.arange(len(feature_dict.keys()))\nplt.bar(y_pos, list(feature_dict.values()), align = \"center\")\nplt.xticks(y_pos, list(feature_dict.keys()), rotation = 90)\nplt.xlabel(\"feature\")\nplt.ylabel(\"ratio\")\nplt.title(\"feature importances\")\nplt.show()",
"_____no_output_____"
],
[
"tp,fn,fp,tn = confusion_matrix(y_test, yhat, labels=[1,0]).ravel()\ntp,tn,fp,fn",
"_____no_output_____"
],
[
"precision_rate = tp / (tp + fp)\nrecall_rate = tp / (tp + fn)\nprint(\"The precision rate is: \", precision_rate)\nprint(\"The recall rate is: \", recall_rate)",
"The precision rate is: 0.9\nThe recall rate is: 0.6923076923076923\n"
],
[
"feature_dict = dict(enumerate(df_new.drop(\"target\", 1).columns))\nfeature_dict",
"_____no_output_____"
],
[
"explainer = shap.TreeExplainer(model)\nshap_values = explainer.shap_values(X_test)\n\nshap.summary_plot(shap_values, \n X_test, \n feature_names = list(feature_dict.values()), \n plot_type = \"bar\", \n color = \"lightblue\")",
"_____no_output_____"
],
[
"shap.summary_plot(shap_values, X_test, feature_names = list(feature_dict.values()))",
"_____no_output_____"
],
[
"def shap_force_plot_of_data(model, dataset):\n explainer = shap.TreeExplainer(model)\n shap_value_for_sample = explainer.shap_values(dataset)\n shap.initjs()\n drivein_force = shap.force_plot(explainer.expected_value, shap_value_for_sample, dataset)\n return drivein_force\n\nperson_is_monitored = pd.DataFrame(X_test, columns = list(feature_dict.values()))\nshap_force_plot_of_data(model, person_is_monitored[person_is_monitored[\"sex_male\"]==1])",
"_____no_output_____"
],
[
"from sklearn.svm import SVC\nfrom sklearn.neural_network import MLPClassifier",
"_____no_output_____"
],
[
"svm_model = SVC()\nsvm_model.fit(X_train, y_train)\n\nprint(\"Support Vector Machine Accuracy {:.2f}%\".format(svm_model.score(X_test, y_test) * 100))",
"Support Vector Machine Accuracy 66.67%\n"
],
[
"nn_model = MLPClassifier()\nnn_model.fit(X_train, y_train)\n\nprint(\"Neural Network Accuracy {:.2f}%\".format(nn_model.score(X_test, y_test) * 100))",
"Neural Network Accuracy 86.67%\n"
],
[
"#!conda install -c conda-forge tensorflow -y\n#!conda install -c conda-forge keras -y",
"_____no_output_____"
],
[
"from tensorflow import keras\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom keras.layers import Dropout\n\n\nmodel = tf.keras.Sequential()\nmodel.add(layers.Dense(20, activation='relu', name='layer1'))\n#model.add(Dropout(0.2))\nmodel.add(layers.Dense(25, activation='relu', name='layer2'))\n#model.add(Dropout(0.5))\nmodel.add(layers.Dense(10, activation='relu', name='layer3'))\nmodel.add(layers.Dense(2, activation='sigmoid', name='f-layer'))",
"_____no_output_____"
],
[
"from tensorflow import keras \nmodel.compile(\n loss = keras.losses.SparseCategoricalCrossentropy(from_logits = True),\n optimizer = keras.optimizers.Adam(lr = 0.001),\n metrics = ['accuracy']\n)",
"_____no_output_____"
],
[
"model.fit(X_train, y_train, batch_size = 10, epochs = 100, verbose=2)",
"Epoch 1/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 2/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 3/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 4/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 5/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 6/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 7/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 8/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 9/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 10/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 11/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 12/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 13/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 14/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 15/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 16/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 17/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 18/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 19/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 20/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 21/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 22/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 23/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 24/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 25/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 26/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 27/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 28/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 29/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 30/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 31/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 32/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 33/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 34/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 35/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 36/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 37/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 38/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 39/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 40/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 41/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 42/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 43/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 44/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 45/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 46/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 47/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 48/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 49/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 50/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 51/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 52/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 53/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 54/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 55/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 56/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 57/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 58/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 59/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 60/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 61/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 62/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 63/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 64/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 65/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 66/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 67/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 68/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 69/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 70/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 71/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 72/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 73/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 74/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 75/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 76/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 77/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 78/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 79/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 80/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 81/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 82/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 83/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 84/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 85/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 86/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 87/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 88/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 89/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 90/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 91/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 92/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 93/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 94/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 95/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 96/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 97/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 98/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 99/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\nEpoch 100/100\n265/265 - 0s - loss: 0.6931 - acc: 0.4340\n"
],
[
"model.evaluate(X_test, y_test, batch_size=10, verbose=2)",
"30/30 - 0s - loss: 0.6931 - acc: 0.5667\n"
]
]
] |
[
"code",
"markdown",
"code"
] |
[
[
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code",
"code"
]
] |
cbb491120c66b70101261c79820c7ec1cdc6e127
| 75,648 |
ipynb
|
Jupyter Notebook
|
notebooks/2020_Notebook05_Training_Tuning.ipynb
|
PBenavides/House_pricing_Lima
|
1300794e6f43cf3411d873e43f3b1985bbc2b766
|
[
"MIT"
] | 12 |
2019-08-21T03:41:23.000Z
|
2021-07-10T08:12:58.000Z
|
notebooks/2020_Notebook05_Training_Tuning.ipynb
|
PBenavides/House_pricing_Lima
|
1300794e6f43cf3411d873e43f3b1985bbc2b766
|
[
"MIT"
] | 3 |
2020-11-03T04:26:51.000Z
|
2021-05-01T15:09:17.000Z
|
notebooks/2020_Notebook05_Training_Tuning.ipynb
|
PBenavides/House_pricing_Lima
|
1300794e6f43cf3411d873e43f3b1985bbc2b766
|
[
"MIT"
] | 7 |
2019-11-11T22:41:16.000Z
|
2021-01-05T04:53:51.000Z
| 91.583535 | 754 | 0.559949 |
[
[
[
"##### Training and Tuning\n\nLa principal razón del anterior notebook ha sido probar varios modelos de la forma más rápida posible, ver sus métricas y los impactos de diversos cambios. El principal problema (hasta ahora) con la versión de PyCaret es que al desplegar el modelo es un objeto de la misma librería, haciendo que se requiera instalar la PyCaret en producción lo cual es muy poco eficiente y complica mucho más las cosas. Por otro lado, PyCaret hace su hyperparameter tuning por RandomSearchCV, que no está mal pero sería más optimo hacerlo de manera Bayesiana. En ese sentido este notebook servirá para entrenar denuevo el(los) modelo(s) guardarlos y posteriormente desplegarlos de manera rápida y sencilla siendo prioridad el hacer el modelo lo más ligero posible.",
"_____no_output_____"
]
],
[
[
"import pandas as pd\nimport numpy as np\nimport warnings\nimport lightgbm as lgb\nimport xgboost as xgb\nfrom sklearn.ensemble import RandomForestRegressor\nfrom bayes_opt import BayesianOptimization\n\ncsv_path = (\n \"../data/train_encoded.csv\",\n \"../data/test_encoded.csv\"\n)\n\ntrain = pd.read_csv(csv_path[0]).drop([\"latitud\",\"longitud\"], axis=1)\ntest = pd.read_csv(csv_path[1]).drop([\"latitud\",\"longitud\"], axis=1)",
"_____no_output_____"
]
],
[
[
"##### Para LightGBM.\n\nComo ya lo hemos tuneado con Pycaret, los parámetros son:\n\n```\nSin Tunear:\nLGBMRegressor(boosting_type='gbdt', class_weight=None, colsample_bytree=1.0,\n importance_type='split', learning_rate=0.1, max_depth=-1,\n min_child_samples=20, min_child_weight=0.001, min_split_gain=0.0,\n n_estimators=100, n_jobs=-1, num_leaves=31, objective=None,\n random_state=104, reg_alpha=0.0, reg_lambda=0.0, silent=True,\n subsample=1.0, subsample_for_bin=200000, subsample_freq=0)\n\nTuneado:\nLGBMRegressor(bagging_fraction=1.0, bagging_freq=6, boosting_type='gbdt',\n class_weight=None, colsample_bytree=1.0, feature_fraction=0.9,\n importance_type='split', learning_rate=0.15, max_depth=-1,\n min_child_samples=46, min_child_weight=0.001, min_split_gain=0,\n n_estimators=150, n_jobs=-1, num_leaves=2, objective=None,\n random_state=104, reg_alpha=0.7, reg_lambda=5, silent=True,\n subsample=1.0, subsample_for_bin=200000, subsample_freq=0)\n```",
"_____no_output_____"
]
],
[
[
"import warnings\nwarnings.filterwarnings('ignore')\nrandom_state = 104 #Para benchmark. \n\ndef bayes_parameter_opt_lgb(X, y, init_points=15, opt_round=25, n_folds=5, random_seed=6, n_estimators=10000, learning_rate=0.05, output_process=False):\n \n \n def lgb_eval(num_leaves, bagging_fraction, lambda_l1, lambda_l2, min_split_gain):\n \"\"\"\n Defino los parametros que serán tuneados. Así como los parámetros fijos\n \"\"\"\n params = {'application':'regression','num_iterations':5000, 'learning_rate':0.05, 'early_stopping_round':100, 'metric':'rmse',\n 'feature_fraction':0.9,'n_estimators':200,'feature_fraction':0.9, 'max_depth':-1,'min_child_weight':0.001,'verbose':-1}\n \n \n params[\"num_leaves\"] = round(num_leaves)\n params['bagging_fraction'] = max(min(bagging_fraction, 1), 0)\n params['max_depth'] = -1\n params['lambda_l1'] = max(lambda_l1, 0)\n params['lambda_l2'] = max(lambda_l2, 0)\n params['min_split_gain'] = min_split_gain\n \n train_data = lgb.Dataset(data=X, label=y)\n \n cv_result = lgb.cv(params, train_data, nfold=5, seed=random_state, verbose_eval =200, metrics=['mae'], shuffle=False, \n stratified=False)\n return -max(cv_result['l1-mean'])\n \n #Configuro el rango de cada parametro\n lgbm_optimization = BayesianOptimization(lgb_eval, {'num_leaves': (2, 25),\n 'bagging_fraction':(0.8,1),\n 'lambda_l1':(0.5,3),\n 'lambda_l2':(3,20),\n 'min_split_gain': (0.001, 0.1)\n })\n \n lgbm_optimization.maximize(init_points=init_points, n_iter=opt_round) #CHECK\n \n if output_process == True:\n lgbm_optimization.points_to_csv('lgbm_bayers_opt_result.csv')\n \n return lgbm_optimization",
"_____no_output_____"
],
[
"X = train.select_dtypes(exclude='object').drop('Precio_m2_total',axis=1)\ny = train['Precio_m2_total']\n\nopt_params = bayes_parameter_opt_lgb(X=X,y=y, init_points= 30, opt_round=100)",
"| iter | target | baggin... | lambda_l1 | lambda_l2 | min_sp... | num_le... |\n-------------------------------------------------------------------------------------\n[200]\tcv_agg's l1: 1551.4 + 36.3896\n| \u001b[0m 1 \u001b[0m | \u001b[0m-2.35e+03\u001b[0m | \u001b[0m 0.8932 \u001b[0m | \u001b[0m 0.8695 \u001b[0m | \u001b[0m 3.635 \u001b[0m | \u001b[0m 0.09268 \u001b[0m | \u001b[0m 5.296 \u001b[0m |\n[200]\tcv_agg's l1: 1487.55 + 38.0394\n| \u001b[95m 2 \u001b[0m | \u001b[95m-2.335e+0\u001b[0m | \u001b[95m 0.8504 \u001b[0m | \u001b[95m 1.381 \u001b[0m | \u001b[95m 4.344 \u001b[0m | \u001b[95m 0.03386 \u001b[0m | \u001b[95m 16.2 \u001b[0m |\n[200]\tcv_agg's l1: 1495.1 + 42.8983\n| \u001b[0m 3 \u001b[0m | \u001b[0m-2.338e+0\u001b[0m | \u001b[0m 0.8858 \u001b[0m | \u001b[0m 0.8048 \u001b[0m | \u001b[0m 6.898 \u001b[0m | \u001b[0m 0.06496 \u001b[0m | \u001b[0m 12.67 \u001b[0m |\n[200]\tcv_agg's l1: 1494.99 + 42.1525\n| \u001b[0m 4 \u001b[0m | \u001b[0m-2.337e+0\u001b[0m | \u001b[0m 0.9934 \u001b[0m | \u001b[0m 2.994 \u001b[0m | \u001b[0m 4.707 \u001b[0m | \u001b[0m 0.08822 \u001b[0m | \u001b[0m 12.79 \u001b[0m |\n[200]\tcv_agg's l1: 1494.93 + 46.5012\n| \u001b[0m 5 \u001b[0m | \u001b[0m-2.339e+0\u001b[0m | \u001b[0m 0.9247 \u001b[0m | \u001b[0m 1.525 \u001b[0m | \u001b[0m 16.26 \u001b[0m | \u001b[0m 0.08735 \u001b[0m | \u001b[0m 13.89 \u001b[0m |\n[200]\tcv_agg's l1: 1557.22 + 38.5587\n| \u001b[0m 6 \u001b[0m | \u001b[0m-2.349e+0\u001b[0m | \u001b[0m 0.997 \u001b[0m | \u001b[0m 1.328 \u001b[0m | \u001b[0m 15.22 \u001b[0m | \u001b[0m 0.02098 \u001b[0m | \u001b[0m 4.919 \u001b[0m |\n[200]\tcv_agg's l1: 1559.28 + 36.5023\n| \u001b[0m 7 \u001b[0m | \u001b[0m-2.349e+0\u001b[0m | \u001b[0m 0.972 \u001b[0m | \u001b[0m 2.938 \u001b[0m | \u001b[0m 18.76 \u001b[0m | \u001b[0m 0.04317 \u001b[0m | \u001b[0m 4.799 \u001b[0m |\n[200]\tcv_agg's l1: 1480.97 + 40.4715\n| \u001b[95m 8 \u001b[0m | \u001b[95m-2.334e+0\u001b[0m | \u001b[95m 0.8309 \u001b[0m | \u001b[95m 1.684 \u001b[0m | \u001b[95m 5.312 \u001b[0m | \u001b[95m 0.03651 \u001b[0m | \u001b[95m 17.94 \u001b[0m |\n[200]\tcv_agg's l1: 1580 + 34.8253\n| \u001b[0m 9 \u001b[0m | \u001b[0m-2.353e+0\u001b[0m | \u001b[0m 0.8033 \u001b[0m | \u001b[0m 2.867 \u001b[0m | \u001b[0m 9.324 \u001b[0m | \u001b[0m 0.06356 \u001b[0m | \u001b[0m 4.258 \u001b[0m |\n[200]\tcv_agg's l1: 1493.11 + 43.0945\n| \u001b[0m 10 \u001b[0m | \u001b[0m-2.338e+0\u001b[0m | \u001b[0m 0.8294 \u001b[0m | \u001b[0m 1.934 \u001b[0m | \u001b[0m 8.921 \u001b[0m | \u001b[0m 0.05369 \u001b[0m | \u001b[0m 14.5 \u001b[0m |\n[200]\tcv_agg's l1: 1481.98 + 42.2089\n| \u001b[95m 11 \u001b[0m | \u001b[95m-2.334e+0\u001b[0m | \u001b[95m 0.868 \u001b[0m | \u001b[95m 1.826 \u001b[0m | \u001b[95m 10.72 \u001b[0m | \u001b[95m 0.06697 \u001b[0m | \u001b[95m 21.27 \u001b[0m |\n[200]\tcv_agg's l1: 1481.95 + 42.875\n| \u001b[95m 12 \u001b[0m | \u001b[95m-2.333e+0\u001b[0m | \u001b[95m 0.8971 \u001b[0m | \u001b[95m 1.518 \u001b[0m | \u001b[95m 5.173 \u001b[0m | \u001b[95m 0.01755 \u001b[0m | \u001b[95m 19.55 \u001b[0m |\n[200]\tcv_agg's l1: 1629.38 + 39.4417\n| \u001b[0m 13 \u001b[0m | \u001b[0m-2.359e+0\u001b[0m | \u001b[0m 0.9165 \u001b[0m | \u001b[0m 0.5005 \u001b[0m | \u001b[0m 6.603 \u001b[0m | \u001b[0m 0.07385 \u001b[0m | \u001b[0m 3.309 \u001b[0m |\n[200]\tcv_agg's l1: 1581.72 + 37.8067\n| \u001b[0m 14 \u001b[0m | \u001b[0m-2.353e+0\u001b[0m | \u001b[0m 0.9621 \u001b[0m | \u001b[0m 1.875 \u001b[0m | \u001b[0m 11.78 \u001b[0m | \u001b[0m 0.02499 \u001b[0m | \u001b[0m 4.256 \u001b[0m |\n[200]\tcv_agg's l1: 1500.43 + 40.6821\n| \u001b[0m 15 \u001b[0m | \u001b[0m-2.34e+03\u001b[0m | \u001b[0m 0.8824 \u001b[0m | \u001b[0m 1.765 \u001b[0m | \u001b[0m 12.88 \u001b[0m | \u001b[0m 0.03971 \u001b[0m | \u001b[0m 12.25 \u001b[0m |\n[200]\tcv_agg's l1: 1509.62 + 41.6103\n| \u001b[0m 16 \u001b[0m | \u001b[0m-2.341e+0\u001b[0m | \u001b[0m 0.8245 \u001b[0m | \u001b[0m 2.496 \u001b[0m | \u001b[0m 12.86 \u001b[0m | \u001b[0m 0.09231 \u001b[0m | \u001b[0m 9.912 \u001b[0m |\n[200]\tcv_agg's l1: 1480 + 47.428\n| \u001b[0m 17 \u001b[0m | \u001b[0m-2.336e+0\u001b[0m | \u001b[0m 0.9137 \u001b[0m | \u001b[0m 0.6126 \u001b[0m | \u001b[0m 17.45 \u001b[0m | \u001b[0m 0.0042 \u001b[0m | \u001b[0m 22.61 \u001b[0m |\n[200]\tcv_agg's l1: 1486.75 + 48.4568\n| \u001b[0m 18 \u001b[0m | \u001b[0m-2.337e+0\u001b[0m | \u001b[0m 0.9524 \u001b[0m | \u001b[0m 1.191 \u001b[0m | \u001b[0m 14.95 \u001b[0m | \u001b[0m 0.02127 \u001b[0m | \u001b[0m 17.78 \u001b[0m |\n[200]\tcv_agg's l1: 1580.4 + 36.5218\n| \u001b[0m 19 \u001b[0m | \u001b[0m-2.353e+0\u001b[0m | \u001b[0m 0.9718 \u001b[0m | \u001b[0m 1.867 \u001b[0m | \u001b[0m 9.091 \u001b[0m | \u001b[0m 0.05185 \u001b[0m | \u001b[0m 4.488 \u001b[0m |\n[200]\tcv_agg's l1: 1505.9 + 39.7418\n| \u001b[0m 20 \u001b[0m | \u001b[0m-2.341e+0\u001b[0m | \u001b[0m 0.8167 \u001b[0m | \u001b[0m 2.149 \u001b[0m | \u001b[0m 3.932 \u001b[0m | \u001b[0m 0.05685 \u001b[0m | \u001b[0m 9.722 \u001b[0m |\n[200]\tcv_agg's l1: 1530.28 + 38.0832\n| \u001b[0m 21 \u001b[0m | \u001b[0m-2.345e+0\u001b[0m | \u001b[0m 0.9444 \u001b[0m | \u001b[0m 1.443 \u001b[0m | \u001b[0m 15.38 \u001b[0m | \u001b[0m 0.02763 \u001b[0m | \u001b[0m 7.406 \u001b[0m |\n[200]\tcv_agg's l1: 1485.73 + 49.9874\n| \u001b[0m 22 \u001b[0m | \u001b[0m-2.336e+0\u001b[0m | \u001b[0m 0.8006 \u001b[0m | \u001b[0m 2.271 \u001b[0m | \u001b[0m 15.76 \u001b[0m | \u001b[0m 0.07055 \u001b[0m | \u001b[0m 19.24 \u001b[0m |\n[200]\tcv_agg's l1: 1486.22 + 45.6198\n| \u001b[0m 23 \u001b[0m | \u001b[0m-2.336e+0\u001b[0m | \u001b[0m 0.8379 \u001b[0m | \u001b[0m 1.252 \u001b[0m | \u001b[0m 18.08 \u001b[0m | \u001b[0m 0.02477 \u001b[0m | \u001b[0m 20.44 \u001b[0m |\n[200]\tcv_agg's l1: 1520.42 + 40.07\n| \u001b[0m 24 \u001b[0m | \u001b[0m-2.342e+0\u001b[0m | \u001b[0m 0.8444 \u001b[0m | \u001b[0m 0.7671 \u001b[0m | \u001b[0m 18.66 \u001b[0m | \u001b[0m 0.04331 \u001b[0m | \u001b[0m 8.814 \u001b[0m |\n[200]\tcv_agg's l1: 1476.13 + 44.3584\n| \u001b[0m 25 \u001b[0m | \u001b[0m-2.336e+0\u001b[0m | \u001b[0m 0.8571 \u001b[0m | \u001b[0m 1.653 \u001b[0m | \u001b[0m 16.77 \u001b[0m | \u001b[0m 0.006111\u001b[0m | \u001b[0m 23.75 \u001b[0m |\n[200]\tcv_agg's l1: 1492.63 + 47.875\n| \u001b[0m 26 \u001b[0m | \u001b[0m-2.338e+0\u001b[0m | \u001b[0m 0.8212 \u001b[0m | \u001b[0m 2.59 \u001b[0m | \u001b[0m 17.89 \u001b[0m | \u001b[0m 0.01367 \u001b[0m | \u001b[0m 16.17 \u001b[0m |\n[200]\tcv_agg's l1: 1480.66 + 45.3628\n| \u001b[0m 27 \u001b[0m | \u001b[0m-2.336e+0\u001b[0m | \u001b[0m 0.8272 \u001b[0m | \u001b[0m 2.406 \u001b[0m | \u001b[0m 19.32 \u001b[0m | \u001b[0m 0.03874 \u001b[0m | \u001b[0m 23.77 \u001b[0m |\n[200]\tcv_agg's l1: 1478.31 + 43.1954\n| \u001b[0m 28 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 0.9274 \u001b[0m | \u001b[0m 2.84 \u001b[0m | \u001b[0m 12.25 \u001b[0m | \u001b[0m 0.01835 \u001b[0m | \u001b[0m 23.8 \u001b[0m |\n[200]\tcv_agg's l1: 1584.02 + 35.1673\n| \u001b[0m 29 \u001b[0m | \u001b[0m-2.353e+0\u001b[0m | \u001b[0m 0.8517 \u001b[0m | \u001b[0m 1.644 \u001b[0m | \u001b[0m 16.91 \u001b[0m | \u001b[0m 0.004761\u001b[0m | \u001b[0m 3.584 \u001b[0m |\n[200]\tcv_agg's l1: 1507.29 + 38.3132\n| \u001b[0m 30 \u001b[0m | \u001b[0m-2.341e+0\u001b[0m | \u001b[0m 0.8876 \u001b[0m | \u001b[0m 0.6959 \u001b[0m | \u001b[0m 7.164 \u001b[0m | \u001b[0m 0.002954\u001b[0m | \u001b[0m 10.45 \u001b[0m |\n[200]\tcv_agg's l1: 1472.75 + 45.0813\n| \u001b[95m 31 \u001b[0m | \u001b[95m-2.332e+0\u001b[0m | \u001b[95m 0.8 \u001b[0m | \u001b[95m 3.0 \u001b[0m | \u001b[95m 3.0 \u001b[0m | \u001b[95m 0.1 \u001b[0m | \u001b[95m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1475.07 + 39.3161\n| \u001b[0m 32 \u001b[0m | \u001b[0m-2.333e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 6.397 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1474.21 + 44.3682\n| \u001b[95m 33 \u001b[0m | \u001b[95m-2.332e+0\u001b[0m | \u001b[95m 1.0 \u001b[0m | \u001b[95m 0.5 \u001b[0m | \u001b[95m 3.0 \u001b[0m | \u001b[95m 0.1 \u001b[0m | \u001b[95m 23.17 \u001b[0m |\n[200]\tcv_agg's l1: 1473.5 + 42.973\n| \u001b[0m 34 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 21.43 \u001b[0m |\n[200]\tcv_agg's l1: 1477.03 + 43.3563\n| \u001b[0m 35 \u001b[0m | \u001b[0m-2.333e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 5.866 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 23.14 \u001b[0m |\n[200]\tcv_agg's l1: 1472.44 + 44.7157\n| \u001b[0m 36 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1474.76 + 43.6024\n| \u001b[0m 37 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8775 \u001b[0m | \u001b[0m 0.812 \u001b[0m | \u001b[0m 3.029 \u001b[0m | \u001b[0m 0.00244 \u001b[0m | \u001b[0m 20.57 \u001b[0m |\n[200]\tcv_agg's l1: 1472.01 + 42.9039\n| \u001b[0m 38 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 1.977 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 22.86 \u001b[0m |\n[200]\tcv_agg's l1: 1476.75 + 45.0491\n| \u001b[0m 39 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 11.41 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1472.78 + 43.6905\n| \u001b[0m 40 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 23.36 \u001b[0m |\n[200]\tcv_agg's l1: 1474.26 + 45.4016\n| \u001b[0m 41 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 21.77 \u001b[0m |\n[200]\tcv_agg's l1: 1473.81 + 45.5622\n| \u001b[0m 42 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 1.519 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 21.8 \u001b[0m |\n[200]\tcv_agg's l1: 1477.1 + 43.9113\n| \u001b[0m 43 \u001b[0m | \u001b[0m-2.333e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 19.04 \u001b[0m |\n[200]\tcv_agg's l1: 1476.11 + 43.8637\n| \u001b[0m 44 \u001b[0m | \u001b[0m-2.333e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 19.13 \u001b[0m |\n[200]\tcv_agg's l1: 1472.98 + 42.4\n| \u001b[0m 45 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 4.385 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 23.05 \u001b[0m |\n[200]\tcv_agg's l1: 1472.78 + 43.69\n| \u001b[0m 46 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9894 \u001b[0m | \u001b[0m 1.626 \u001b[0m | \u001b[0m 3.071 \u001b[0m | \u001b[0m 0.0737 \u001b[0m | \u001b[0m 24.02 \u001b[0m |\n[200]\tcv_agg's l1: 1471.45 + 46.6164\n| \u001b[95m 47 \u001b[0m | \u001b[95m-2.332e+0\u001b[0m | \u001b[95m 0.8 \u001b[0m | \u001b[95m 0.6344 \u001b[0m | \u001b[95m 3.0 \u001b[0m | \u001b[95m 0.1 \u001b[0m | \u001b[95m 23.98 \u001b[0m |\n[200]\tcv_agg's l1: 1472.78 + 43.6905\n| \u001b[0m 48 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 22.93 \u001b[0m |\n[200]\tcv_agg's l1: 1475.38 + 43.8199\n| \u001b[0m 49 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 3.353 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 21.6 \u001b[0m |\n[200]\tcv_agg's l1: 1473.47 + 43.6269\n| \u001b[0m 50 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 2.311 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 20.86 \u001b[0m |\n[200]\tcv_agg's l1: 1474.32 + 45.9077\n| \u001b[0m 51 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 22.09 \u001b[0m |\n[200]\tcv_agg's l1: 1475.38 + 40.8016\n| \u001b[0m 52 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 4.151 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 20.77 \u001b[0m |\n[200]\tcv_agg's l1: 1467.24 + 38.5439\n| \u001b[0m 53 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9658 \u001b[0m | \u001b[0m 2.941 \u001b[0m | \u001b[0m 4.685 \u001b[0m | \u001b[0m 0.03266 \u001b[0m | \u001b[0m 24.9 \u001b[0m |\n[200]\tcv_agg's l1: 1475.78 + 41.5738\n| \u001b[0m 54 \u001b[0m | \u001b[0m-2.333e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 8.869 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1473.75 + 44.7056\n| \u001b[95m 55 \u001b[0m | \u001b[95m-2.332e+0\u001b[0m | \u001b[95m 0.9919 \u001b[0m | \u001b[95m 2.966 \u001b[0m | \u001b[95m 3.748 \u001b[0m | \u001b[95m 0.08387 \u001b[0m | \u001b[95m 23.42 \u001b[0m |\n[200]\tcv_agg's l1: 1469.77 + 46.3281\n| \u001b[95m 56 \u001b[0m | \u001b[95m-2.332e+0\u001b[0m | \u001b[95m 0.8129 \u001b[0m | \u001b[95m 2.926 \u001b[0m | \u001b[95m 3.293 \u001b[0m | \u001b[95m 0.004205\u001b[0m | \u001b[95m 23.8 \u001b[0m |\n[200]\tcv_agg's l1: 1473.57 + 41.218\n| \u001b[0m 57 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8015 \u001b[0m | \u001b[0m 2.108 \u001b[0m | \u001b[0m 3.456 \u001b[0m | \u001b[0m 0.0931 \u001b[0m | \u001b[0m 23.54 \u001b[0m |\n[200]\tcv_agg's l1: 1473.31 + 45.271\n| \u001b[0m 58 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9282 \u001b[0m | \u001b[0m 2.238 \u001b[0m | \u001b[0m 3.055 \u001b[0m | \u001b[0m 0.07924 \u001b[0m | \u001b[0m 23.46 \u001b[0m |\n[200]\tcv_agg's l1: 1473.21 + 41.8987\n| \u001b[0m 59 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9623 \u001b[0m | \u001b[0m 1.025 \u001b[0m | \u001b[0m 3.108 \u001b[0m | \u001b[0m 0.02016 \u001b[0m | \u001b[0m 23.32 \u001b[0m |\n[200]\tcv_agg's l1: 1474.83 + 40.8131\n| \u001b[0m 60 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8273 \u001b[0m | \u001b[0m 1.36 \u001b[0m | \u001b[0m 3.648 \u001b[0m | \u001b[0m 0.07296 \u001b[0m | \u001b[0m 20.58 \u001b[0m |\n[200]\tcv_agg's l1: 1474.09 + 43.7727\n| \u001b[95m 61 \u001b[0m | \u001b[95m-2.331e+0\u001b[0m | \u001b[95m 0.8124 \u001b[0m | \u001b[95m 2.828 \u001b[0m | \u001b[95m 3.555 \u001b[0m | \u001b[95m 0.06011 \u001b[0m | \u001b[95m 23.19 \u001b[0m |\n[200]\tcv_agg's l1: 1480.57 + 44.8592\n| \u001b[0m 62 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 8.431 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 19.61 \u001b[0m |\n[200]\tcv_agg's l1: 1475.6 + 40.849\n| \u001b[0m 63 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 2.999 \u001b[0m | \u001b[0m 3.421 \u001b[0m | \u001b[0m 0.001018\u001b[0m | \u001b[0m 23.29 \u001b[0m |\n[200]\tcv_agg's l1: 1472.9 + 45.2549\n| \u001b[0m 64 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 1.793 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1473.75 + 44.7056\n| \u001b[0m 65 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9709 \u001b[0m | \u001b[0m 2.971 \u001b[0m | \u001b[0m 3.747 \u001b[0m | \u001b[0m 0.09487 \u001b[0m | \u001b[0m 22.78 \u001b[0m |\n[200]\tcv_agg's l1: 1472.46 + 43.3006\n| \u001b[0m 66 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.866 \u001b[0m | \u001b[0m 2.337 \u001b[0m | \u001b[0m 3.81 \u001b[0m | \u001b[0m 0.08356 \u001b[0m | \u001b[0m 22.81 \u001b[0m |\n[200]\tcv_agg's l1: 1473.75 + 43.1004\n| \u001b[0m 67 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8075 \u001b[0m | \u001b[0m 2.98 \u001b[0m | \u001b[0m 3.89 \u001b[0m | \u001b[0m 0.004706\u001b[0m | \u001b[0m 22.71 \u001b[0m |\n[200]\tcv_agg's l1: 1471.45 + 46.6163\n| \u001b[0m 68 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 23.89 \u001b[0m |\n[200]\tcv_agg's l1: 1477.29 + 40.5679\n| \u001b[0m 69 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8196 \u001b[0m | \u001b[0m 2.85 \u001b[0m | \u001b[0m 3.425 \u001b[0m | \u001b[0m 0.002186\u001b[0m | \u001b[0m 22.86 \u001b[0m |\n[200]\tcv_agg's l1: 1469.66 + 45.7064\n| \u001b[0m 70 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.9094 \u001b[0m | \u001b[0m 2.821 \u001b[0m | \u001b[0m 3.479 \u001b[0m | \u001b[0m 0.05122 \u001b[0m | \u001b[0m 23.29 \u001b[0m |\n[200]\tcv_agg's l1: 1472.93 + 46.9749\n| \u001b[0m 71 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8565 \u001b[0m | \u001b[0m 2.339 \u001b[0m | \u001b[0m 3.331 \u001b[0m | \u001b[0m 0.09795 \u001b[0m | \u001b[0m 22.78 \u001b[0m |\n[200]\tcv_agg's l1: 1472.12 + 41.6903\n| \u001b[0m 72 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8557 \u001b[0m | \u001b[0m 2.972 \u001b[0m | \u001b[0m 3.544 \u001b[0m | \u001b[0m 0.07828 \u001b[0m | \u001b[0m 23.54 \u001b[0m |\n[200]\tcv_agg's l1: 1480.15 + 45.7324\n| \u001b[0m 73 \u001b[0m | \u001b[0m-2.335e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 13.05 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 21.55 \u001b[0m |\n[200]\tcv_agg's l1: 1479.57 + 41.1118\n| \u001b[0m 74 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 9.244 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 23.11 \u001b[0m |\n[200]\tcv_agg's l1: 1471.78 + 42.6872\n| \u001b[0m 75 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9465 \u001b[0m | \u001b[0m 0.5499 \u001b[0m | \u001b[0m 3.485 \u001b[0m | \u001b[0m 0.0897 \u001b[0m | \u001b[0m 23.97 \u001b[0m |\n[200]\tcv_agg's l1: 1474.38 + 43.3935\n| \u001b[0m 76 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9939 \u001b[0m | \u001b[0m 1.223 \u001b[0m | \u001b[0m 4.067 \u001b[0m | \u001b[0m 0.0313 \u001b[0m | \u001b[0m 24.61 \u001b[0m |\n[200]\tcv_agg's l1: 1474.08 + 42.645\n| \u001b[95m 77 \u001b[0m | \u001b[95m-2.331e+0\u001b[0m | \u001b[95m 0.9497 \u001b[0m | \u001b[95m 2.919 \u001b[0m | \u001b[95m 3.52 \u001b[0m | \u001b[95m 0.00569 \u001b[0m | \u001b[95m 22.93 \u001b[0m |\n[200]\tcv_agg's l1: 1473.79 + 44.867\n| \u001b[0m 78 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.9367 \u001b[0m | \u001b[0m 2.554 \u001b[0m | \u001b[0m 3.316 \u001b[0m | \u001b[0m 0.04195 \u001b[0m | \u001b[0m 22.93 \u001b[0m |\n[200]\tcv_agg's l1: 1475.99 + 40.585\n| \u001b[0m 79 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.959 \u001b[0m | \u001b[0m 2.233 \u001b[0m | \u001b[0m 3.688 \u001b[0m | \u001b[0m 0.02267 \u001b[0m | \u001b[0m 23.01 \u001b[0m |\n[200]\tcv_agg's l1: 1473.19 + 43.3399\n| \u001b[0m 80 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8556 \u001b[0m | \u001b[0m 2.318 \u001b[0m | \u001b[0m 3.765 \u001b[0m | \u001b[0m 0.008417\u001b[0m | \u001b[0m 23.5 \u001b[0m |\n[200]\tcv_agg's l1: 1473.92 + 44.5731\n| \u001b[0m 81 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.852 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 20.78 \u001b[0m |\n[200]\tcv_agg's l1: 1472.21 + 43.1523\n| \u001b[0m 82 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8702 \u001b[0m | \u001b[0m 2.868 \u001b[0m | \u001b[0m 3.469 \u001b[0m | \u001b[0m 0.04576 \u001b[0m | \u001b[0m 23.1 \u001b[0m |\n[200]\tcv_agg's l1: 1478.62 + 44.5294\n| \u001b[0m 83 \u001b[0m | \u001b[0m-2.336e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 20.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1473.71 + 44.2252\n| \u001b[95m 84 \u001b[0m | \u001b[95m-2.331e+0\u001b[0m | \u001b[95m 0.8539 \u001b[0m | \u001b[95m 2.362 \u001b[0m | \u001b[95m 3.514 \u001b[0m | \u001b[95m 0.005887\u001b[0m | \u001b[95m 22.9 \u001b[0m |\n[200]\tcv_agg's l1: 1483.84 + 40.3961\n| \u001b[0m 85 \u001b[0m | \u001b[0m-2.335e+0\u001b[0m | \u001b[0m 0.9159 \u001b[0m | \u001b[0m 2.946 \u001b[0m | \u001b[0m 11.77 \u001b[0m | \u001b[0m 0.0572 \u001b[0m | \u001b[0m 18.72 \u001b[0m |\n[200]\tcv_agg's l1: 1480.3 + 44.3228\n| \u001b[0m 86 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 0.9106 \u001b[0m | \u001b[0m 2.998 \u001b[0m | \u001b[0m 8.241 \u001b[0m | \u001b[0m 0.02816 \u001b[0m | \u001b[0m 19.37 \u001b[0m |\n[200]\tcv_agg's l1: 1472.28 + 41.9972\n| \u001b[0m 87 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8185 \u001b[0m | \u001b[0m 1.32 \u001b[0m | \u001b[0m 3.405 \u001b[0m | \u001b[0m 0.009532\u001b[0m | \u001b[0m 24.23 \u001b[0m |\n[200]\tcv_agg's l1: 1476.52 + 44.6592\n| \u001b[0m 88 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9997 \u001b[0m | \u001b[0m 2.357 \u001b[0m | \u001b[0m 3.58 \u001b[0m | \u001b[0m 0.04174 \u001b[0m | \u001b[0m 21.42 \u001b[0m |\n[200]\tcv_agg's l1: 1494.66 + 41.0433\n| \u001b[0m 89 \u001b[0m | \u001b[0m-2.337e+0\u001b[0m | \u001b[0m 0.9398 \u001b[0m | \u001b[0m 0.6147 \u001b[0m | \u001b[0m 3.019 \u001b[0m | \u001b[0m 0.06548 \u001b[0m | \u001b[0m 13.22 \u001b[0m |\n[200]\tcv_agg's l1: 1494.08 + 48.0881\n| \u001b[0m 90 \u001b[0m | \u001b[0m-2.339e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 20.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 14.69 \u001b[0m |\n[200]\tcv_agg's l1: 1471.71 + 45.4319\n| \u001b[0m 91 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9633 \u001b[0m | \u001b[0m 1.07 \u001b[0m | \u001b[0m 3.109 \u001b[0m | \u001b[0m 0.07255 \u001b[0m | \u001b[0m 24.23 \u001b[0m |\n[200]\tcv_agg's l1: 1472.53 + 42.5606\n| \u001b[0m 92 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.655 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1474.16 + 42.0263\n| \u001b[0m 93 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8505 \u001b[0m | \u001b[0m 0.5857 \u001b[0m | \u001b[0m 3.483 \u001b[0m | \u001b[0m 0.05546 \u001b[0m | \u001b[0m 24.14 \u001b[0m |\n[200]\tcv_agg's l1: 1474.47 + 42.8161\n| \u001b[0m 94 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8318 \u001b[0m | \u001b[0m 2.663 \u001b[0m | \u001b[0m 3.522 \u001b[0m | \u001b[0m 0.007332\u001b[0m | \u001b[0m 22.76 \u001b[0m |\n[200]\tcv_agg's l1: 1477.26 + 44.6227\n| \u001b[0m 95 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9638 \u001b[0m | \u001b[0m 2.94 \u001b[0m | \u001b[0m 3.118 \u001b[0m | \u001b[0m 0.005574\u001b[0m | \u001b[0m 20.63 \u001b[0m |\n[200]\tcv_agg's l1: 1473.98 + 39.8001\n| \u001b[0m 96 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8782 \u001b[0m | \u001b[0m 2.718 \u001b[0m | \u001b[0m 3.824 \u001b[0m | \u001b[0m 0.01317 \u001b[0m | \u001b[0m 23.32 \u001b[0m |\n[200]\tcv_agg's l1: 1475.73 + 42.8267\n| \u001b[0m 97 \u001b[0m | \u001b[0m-2.335e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 14.6 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1476.62 + 43.2768\n| \u001b[0m 98 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 9.046 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 22.62 \u001b[0m |\n[200]\tcv_agg's l1: 1470.08 + 43.4666\n| \u001b[0m 99 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9998 \u001b[0m | \u001b[0m 2.569 \u001b[0m | \u001b[0m 3.344 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 24.37 \u001b[0m |\n[200]\tcv_agg's l1: 1475.9 + 43.9979\n| \u001b[0m 100 \u001b[0m | \u001b[0m-2.335e+0\u001b[0m | \u001b[0m 0.9321 \u001b[0m | \u001b[0m 0.5126 \u001b[0m | \u001b[0m 14.57 \u001b[0m | \u001b[0m 0.008573\u001b[0m | \u001b[0m 24.99 \u001b[0m |\n[200]\tcv_agg's l1: 1476.01 + 45.6624\n| \u001b[0m 101 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.9225 \u001b[0m | \u001b[0m 2.199 \u001b[0m | \u001b[0m 3.385 \u001b[0m | \u001b[0m 0.005016\u001b[0m | \u001b[0m 23.04 \u001b[0m |\n[200]\tcv_agg's l1: 1486.95 + 46.341\n| \u001b[0m 102 \u001b[0m | \u001b[0m-2.337e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 20.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 19.76 \u001b[0m |\n[200]\tcv_agg's l1: 1472.15 + 40.2528\n| \u001b[0m 103 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.9436 \u001b[0m | \u001b[0m 2.579 \u001b[0m | \u001b[0m 3.52 \u001b[0m | \u001b[0m 0.004962\u001b[0m | \u001b[0m 23.36 \u001b[0m |\n[200]\tcv_agg's l1: 1489.73 + 44.8313\n| \u001b[0m 104 \u001b[0m | \u001b[0m-2.336e+0\u001b[0m | \u001b[0m 0.9081 \u001b[0m | \u001b[0m 0.5054 \u001b[0m | \u001b[0m 11.0 \u001b[0m | \u001b[0m 0.05701 \u001b[0m | \u001b[0m 17.33 \u001b[0m |\n[200]\tcv_agg's l1: 1480.09 + 49.2454\n| \u001b[0m 105 \u001b[0m | \u001b[0m-2.335e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 14.03 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 21.54 \u001b[0m |\n[200]\tcv_agg's l1: 1474.18 + 41.1525\n| \u001b[0m 106 \u001b[0m | \u001b[0m-2.333e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 8.838 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n[200]\tcv_agg's l1: 1475.2 + 44.0023\n| \u001b[0m 107 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8108 \u001b[0m | \u001b[0m 1.616 \u001b[0m | \u001b[0m 3.297 \u001b[0m | \u001b[0m 0.07958 \u001b[0m | \u001b[0m 22.4 \u001b[0m |\n[200]\tcv_agg's l1: 1473.85 + 41.8913\n| \u001b[0m 108 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8079 \u001b[0m | \u001b[0m 1.359 \u001b[0m | \u001b[0m 3.025 \u001b[0m | \u001b[0m 0.09241 \u001b[0m | \u001b[0m 21.03 \u001b[0m |\n[200]\tcv_agg's l1: 1473.96 + 42.6472\n| \u001b[0m 109 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8243 \u001b[0m | \u001b[0m 0.5056 \u001b[0m | \u001b[0m 3.264 \u001b[0m | \u001b[0m 0.01655 \u001b[0m | \u001b[0m 23.64 \u001b[0m |\n[200]\tcv_agg's l1: 1473.94 + 43.8788\n| \u001b[0m 110 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.9836 \u001b[0m | \u001b[0m 2.315 \u001b[0m | \u001b[0m 3.438 \u001b[0m | \u001b[0m 0.0107 \u001b[0m | \u001b[0m 23.04 \u001b[0m |\n[200]\tcv_agg's l1: 1474.66 + 43.7524\n| \u001b[0m 111 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8032 \u001b[0m | \u001b[0m 1.587 \u001b[0m | \u001b[0m 3.417 \u001b[0m | \u001b[0m 0.003666\u001b[0m | \u001b[0m 23.6 \u001b[0m |\n[200]\tcv_agg's l1: 1472.32 + 47.994\n| \u001b[0m 112 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8538 \u001b[0m | \u001b[0m 2.165 \u001b[0m | \u001b[0m 3.324 \u001b[0m | \u001b[0m 0.00919 \u001b[0m | \u001b[0m 23.06 \u001b[0m |\n[200]\tcv_agg's l1: 1474.04 + 45.941\n| \u001b[0m 113 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9005 \u001b[0m | \u001b[0m 1.908 \u001b[0m | \u001b[0m 3.31 \u001b[0m | \u001b[0m 0.006905\u001b[0m | \u001b[0m 24.23 \u001b[0m |\n[200]\tcv_agg's l1: 1472.37 + 42.2504\n| \u001b[0m 114 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8914 \u001b[0m | \u001b[0m 2.506 \u001b[0m | \u001b[0m 3.397 \u001b[0m | \u001b[0m 0.009921\u001b[0m | \u001b[0m 23.52 \u001b[0m |\n[200]\tcv_agg's l1: 1476.63 + 44.8284\n| \u001b[0m 115 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9925 \u001b[0m | \u001b[0m 2.993 \u001b[0m | \u001b[0m 3.595 \u001b[0m | \u001b[0m 0.02441 \u001b[0m | \u001b[0m 24.46 \u001b[0m |\n[200]\tcv_agg's l1: 1475.48 + 44.1627\n| \u001b[0m 116 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 0.8139 \u001b[0m | \u001b[0m 0.5468 \u001b[0m | \u001b[0m 6.956 \u001b[0m | \u001b[0m 0.03993 \u001b[0m | \u001b[0m 21.43 \u001b[0m |\n[200]\tcv_agg's l1: 1502.63 + 42.1846\n| \u001b[0m 117 \u001b[0m | \u001b[0m-2.341e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 20.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 11.87 \u001b[0m |\n[200]\tcv_agg's l1: 1474.21 + 47.1372\n| \u001b[0m 118 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.8294 \u001b[0m | \u001b[0m 2.668 \u001b[0m | \u001b[0m 3.564 \u001b[0m | \u001b[0m 0.05457 \u001b[0m | \u001b[0m 22.81 \u001b[0m |\n[200]\tcv_agg's l1: 1487.06 + 43.1364\n| \u001b[0m 119 \u001b[0m | \u001b[0m-2.335e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 15.74 \u001b[0m |\n[200]\tcv_agg's l1: 1469.76 + 43.6219\n| \u001b[0m 120 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 0.8227 \u001b[0m | \u001b[0m 2.965 \u001b[0m | \u001b[0m 6.97 \u001b[0m | \u001b[0m 0.01014 \u001b[0m | \u001b[0m 24.85 \u001b[0m |\n[200]\tcv_agg's l1: 1470.66 + 43.613\n| \u001b[0m 121 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.9938 \u001b[0m | \u001b[0m 2.044 \u001b[0m | \u001b[0m 3.39 \u001b[0m | \u001b[0m 0.001024\u001b[0m | \u001b[0m 23.88 \u001b[0m |\n[200]\tcv_agg's l1: 1474.21 + 44.3682\n| \u001b[0m 122 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.001 \u001b[0m | \u001b[0m 22.66 \u001b[0m |\n[200]\tcv_agg's l1: 1471.28 + 42.5352\n| \u001b[0m 123 \u001b[0m | \u001b[0m-2.331e+0\u001b[0m | \u001b[0m 0.927 \u001b[0m | \u001b[0m 2.37 \u001b[0m | \u001b[0m 3.578 \u001b[0m | \u001b[0m 0.01809 \u001b[0m | \u001b[0m 22.76 \u001b[0m |\n[200]\tcv_agg's l1: 1473.13 + 44.2118\n| \u001b[0m 124 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9468 \u001b[0m | \u001b[0m 2.967 \u001b[0m | \u001b[0m 3.709 \u001b[0m | \u001b[0m 0.01083 \u001b[0m | \u001b[0m 23.08 \u001b[0m |\n[200]\tcv_agg's l1: 1486.02 + 42.4633\n| \u001b[0m 125 \u001b[0m | \u001b[0m-2.335e+0\u001b[0m | \u001b[0m 0.8 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 7.35 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 17.1 \u001b[0m |\n[200]\tcv_agg's l1: 1478.47 + 40.6712\n| \u001b[0m 126 \u001b[0m | \u001b[0m-2.334e+0\u001b[0m | \u001b[0m 0.8062 \u001b[0m | \u001b[0m 2.897 \u001b[0m | \u001b[0m 7.053 \u001b[0m | \u001b[0m 0.03652 \u001b[0m | \u001b[0m 20.74 \u001b[0m |\n[200]\tcv_agg's l1: 1474.05 + 43.2385\n| \u001b[0m 127 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 0.5 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 21.02 \u001b[0m |\n[200]\tcv_agg's l1: 1475.03 + 44.4183\n| \u001b[0m 128 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9319 \u001b[0m | \u001b[0m 1.988 \u001b[0m | \u001b[0m 3.091 \u001b[0m | \u001b[0m 0.03745 \u001b[0m | \u001b[0m 19.69 \u001b[0m |\n[200]\tcv_agg's l1: 1472.37 + 41.9752\n| \u001b[0m 129 \u001b[0m | \u001b[0m-2.332e+0\u001b[0m | \u001b[0m 0.9403 \u001b[0m | \u001b[0m 2.994 \u001b[0m | \u001b[0m 3.599 \u001b[0m | \u001b[0m 0.05243 \u001b[0m | \u001b[0m 22.22 \u001b[0m |\n[200]\tcv_agg's l1: 1488.67 + 48.3033\n| \u001b[0m 130 \u001b[0m | \u001b[0m-2.337e+0\u001b[0m | \u001b[0m 1.0 \u001b[0m | \u001b[0m 3.0 \u001b[0m | \u001b[0m 12.92 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 15.94 \u001b[0m |\n=====================================================================================\n"
],
[
"min_ = min([res['target'] for res in opt_params.res])\n[res['params'] for res in opt_params.res if res['target'] == min_]",
"_____no_output_____"
],
[
"#Fit model\n\ntrain_data = lgb.Dataset(X,y)\n\nparams = {'application':'regression','num_iterations':5000, 'learning_rate':0.05, 'metric':'rmse',\n 'feature_fraction':0.9,'n_estimators':200,'feature_fraction':0.9, 'max_depth':-1,'min_child_weight':0.001,'verbose':-1,\n 'bagging_fraction': 0.9164810602504456,'lambda_l1': 0.5005454948781294,'lambda_l2': 6.60276585681876,\n 'min_split_gain': 0.07385271072078259,'num_leaves': 3}\n\nmodel = lgb.cv(params, train_data, nfold=5, seed=random_state, verbose_eval =200, metrics=['mae'], shuffle=False, \n stratified=False)\n#l1_error = Mae",
"[200]\tcv_agg's l1: 1629.38 + 39.4417\n"
],
[
"X_test = test.select_dtypes(exclude='object').drop('Precio_m2_total',axis=1)\ny_test = test['Precio_m2_total']\nmodel = lgb.train(params, train_data)\npreds = model.predict(X_test)",
"_____no_output_____"
],
[
"from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n\nr2 = r2_score(y_test, preds)\nmae = mean_absolute_error(y_test, preds)\nmse = mean_squared_error(y_test, preds)\nprint('r2:{}\\nmae:{}\\nmse:{}'.format(r2, mae, mse))",
"r2:0.3195114290174482\nmae:1833.7454405484887\nmse:13746071.920770092\n"
]
],
[
[
"Entrenando modelo final:",
"_____no_output_____"
]
],
[
[
"data_x = pd.concat([X,X_test])\ndata_y = pd.concat([y,y_test])\ndata = lgb.Dataset(data_x,data_y)\n\nmodel_final = lgb.train(params, data)",
"_____no_output_____"
],
[
"import pickle\n\nwith open('../webapp/artifacts/models/lgbm_base.pkl','wb') as handle:\n pickle.dump(model_final, handle, protocol=pickle.HIGHEST_PROTOCOL)",
"_____no_output_____"
]
],
[
[
"#### Random Forest:",
"_____no_output_____"
]
],
[
[
"from sklearn.model_selection import cross_val_score\n\ndef rf_cv(min_impurity_decrease, min_samples_split, max_features,max_depth, data, target):\n \"\"\"Random Forest Cross Validation\n \n Esta funcion instanciará un regressor de Random Forest con los parámetros a optimizar:\n min_samples_split, max_features, min_impurity_decrease.\n \n \"\"\"\n model = RandomForestRegressor(\n n_estimators = 150,\n min_impurity_decrease=min_impurity_decrease,\n min_samples_split = min_samples_split,\n max_features = max_features,\n max_depth = max_depth, #No olvidar tenerlo en integer.\n random_state = 123,\n n_jobs=-1\n )\n \n cross_val = cross_val_score(model, data, target,\n scoring='neg_mean_absolute_error', cv=4)\n \n return cross_val.mean()\n\ndef optimize_rf(data, target):\n \"\"\"Aplicamos Optimización Bayesiana a los parámetros del Random Forest Regressor\"\"\"\n \n def inside_rf_cv(min_impurity_decrease, min_samples_split, max_features, max_depth):\n \"\"\"Wrapper of RandomForest cross validation.\n \n Tenemos que evitar que los parametros que toman valores enteros no se repitan, además de tener que\n restringir aquellos parámetros que van de 0 a 1.\n \"\"\"\n \n return rf_cv(\n min_samples_split = int(min_samples_split),\n min_impurity_decrease = max(min(min_impurity_decrease, 0.999), 1e-3),\n max_features = max(min(max_features, 0.999), 1e-3),\n max_depth = int(max_depth),\n data = data,\n target = target,\n )\n \n optimizer = BayesianOptimization(\n f = inside_rf_cv,\n pbounds={\n \"min_samples_split\":(2,25),\n \"min_impurity_decrease\":(0.1,0.999),\n \"max_features\":(0.1, 0.999),\n \"max_depth\":(5, 25),\n },\n random_state=123,\n verbose=2\n )\n optimizer.maximize(init_points = 30, n_iter=100)\n \n print(\"Resultado Final\", optimizer.max)\n \n return optimizer",
"_____no_output_____"
],
[
"X_train = train.select_dtypes(exclude='object').drop('Precio_m2_total',axis=1)\ny_train = train['Precio_m2_total']\n\nfrom bayes_opt.util import Colours\n\nprint(Colours.yellow(\"----Random Forest Regressor Optimizer----\"))\noptimize_rf(X_train, y_train)",
"\u001b[93m----Random Forest Regressor Optimizer----\u001b[0m\n| iter | target | max_depth | max_fe... | min_im... | min_sa... |\n-------------------------------------------------------------------------\n| \u001b[0m 1 \u001b[0m | \u001b[0m-1.479e+0\u001b[0m | \u001b[0m 18.93 \u001b[0m | \u001b[0m 0.3572 \u001b[0m | \u001b[0m 0.3039 \u001b[0m | \u001b[0m 14.68 \u001b[0m |\n| \u001b[0m 2 \u001b[0m | \u001b[0m-1.48e+03\u001b[0m | \u001b[0m 19.39 \u001b[0m | \u001b[0m 0.4804 \u001b[0m | \u001b[0m 0.9817 \u001b[0m | \u001b[0m 17.75 \u001b[0m |\n| \u001b[0m 3 \u001b[0m | \u001b[0m-1.484e+0\u001b[0m | \u001b[0m 14.62 \u001b[0m | \u001b[0m 0.4525 \u001b[0m | \u001b[0m 0.4085 \u001b[0m | \u001b[0m 18.77 \u001b[0m |\n| \u001b[0m 4 \u001b[0m | \u001b[0m-1.549e+0\u001b[0m | \u001b[0m 13.77 \u001b[0m | \u001b[0m 0.1537 \u001b[0m | \u001b[0m 0.4578 \u001b[0m | \u001b[0m 18.97 \u001b[0m |\n| \u001b[0m 5 \u001b[0m | \u001b[0m-1.585e+0\u001b[0m | \u001b[0m 8.65 \u001b[0m | \u001b[0m 0.2577 \u001b[0m | \u001b[0m 0.5779 \u001b[0m | \u001b[0m 14.23 \u001b[0m |\n| \u001b[0m 6 \u001b[0m | \u001b[0m-1.481e+0\u001b[0m | \u001b[0m 17.69 \u001b[0m | \u001b[0m 0.8636 \u001b[0m | \u001b[0m 0.7513 \u001b[0m | \u001b[0m 16.05 \u001b[0m |\n| \u001b[95m 7 \u001b[0m | \u001b[95m-1.46e+03\u001b[0m | \u001b[95m 19.45 \u001b[0m | \u001b[95m 0.3903 \u001b[0m | \u001b[95m 0.4252 \u001b[0m | \u001b[95m 7.25 \u001b[0m |\n| \u001b[0m 8 \u001b[0m | \u001b[0m-1.484e+0\u001b[0m | \u001b[0m 10.87 \u001b[0m | \u001b[0m 0.6672 \u001b[0m | \u001b[0m 0.1828 \u001b[0m | \u001b[0m 11.98 \u001b[0m |\n| \u001b[0m 9 \u001b[0m | \u001b[0m-1.465e+0\u001b[0m | \u001b[0m 13.62 \u001b[0m | \u001b[0m 0.5438 \u001b[0m | \u001b[0m 0.4828 \u001b[0m | \u001b[0m 9.182 \u001b[0m |\n| \u001b[0m 10 \u001b[0m | \u001b[0m-1.477e+0\u001b[0m | \u001b[0m 13.53 \u001b[0m | \u001b[0m 0.9032 \u001b[0m | \u001b[0m 0.9488 \u001b[0m | \u001b[0m 13.54 \u001b[0m |\n| \u001b[0m 11 \u001b[0m | \u001b[0m-1.483e+0\u001b[0m | \u001b[0m 17.48 \u001b[0m | \u001b[0m 0.2039 \u001b[0m | \u001b[0m 0.3852 \u001b[0m | \u001b[0m 11.54 \u001b[0m |\n| \u001b[0m 12 \u001b[0m | \u001b[0m-1.499e+0\u001b[0m | \u001b[0m 22.33 \u001b[0m | \u001b[0m 0.3252 \u001b[0m | \u001b[0m 0.5342 \u001b[0m | \u001b[0m 24.67 \u001b[0m |\n| \u001b[0m 13 \u001b[0m | \u001b[0m-1.488e+0\u001b[0m | \u001b[0m 15.39 \u001b[0m | \u001b[0m 0.651 \u001b[0m | \u001b[0m 0.2084 \u001b[0m | \u001b[0m 21.01 \u001b[0m |\n| \u001b[95m 14 \u001b[0m | \u001b[95m-1.46e+03\u001b[0m | \u001b[95m 17.06 \u001b[0m | \u001b[95m 0.59 \u001b[0m | \u001b[95m 0.4081 \u001b[0m | \u001b[95m 8.995 \u001b[0m |\n| \u001b[0m 15 \u001b[0m | \u001b[0m-1.474e+0\u001b[0m | \u001b[0m 13.34 \u001b[0m | \u001b[0m 0.7125 \u001b[0m | \u001b[0m 0.887 \u001b[0m | \u001b[0m 13.74 \u001b[0m |\n| \u001b[0m 16 \u001b[0m | \u001b[0m-1.481e+0\u001b[0m | \u001b[0m 18.39 \u001b[0m | \u001b[0m 0.6268 \u001b[0m | \u001b[0m 0.6618 \u001b[0m | \u001b[0m 17.52 \u001b[0m |\n| \u001b[0m 17 \u001b[0m | \u001b[0m-1.5e+03 \u001b[0m | \u001b[0m 21.85 \u001b[0m | \u001b[0m 0.1748 \u001b[0m | \u001b[0m 0.7866 \u001b[0m | \u001b[0m 7.604 \u001b[0m |\n| \u001b[0m 18 \u001b[0m | \u001b[0m-1.534e+0\u001b[0m | \u001b[0m 8.884 \u001b[0m | \u001b[0m 0.6146 \u001b[0m | \u001b[0m 0.186 \u001b[0m | \u001b[0m 22.36 \u001b[0m |\n| \u001b[0m 19 \u001b[0m | \u001b[0m-1.477e+0\u001b[0m | \u001b[0m 17.54 \u001b[0m | \u001b[0m 0.7504 \u001b[0m | \u001b[0m 0.1145 \u001b[0m | \u001b[0m 15.67 \u001b[0m |\n| \u001b[0m 20 \u001b[0m | \u001b[0m-1.498e+0\u001b[0m | \u001b[0m 16.14 \u001b[0m | \u001b[0m 0.2429 \u001b[0m | \u001b[0m 0.2376 \u001b[0m | \u001b[0m 18.0 \u001b[0m |\n| \u001b[0m 21 \u001b[0m | \u001b[0m-1.475e+0\u001b[0m | \u001b[0m 11.38 \u001b[0m | \u001b[0m 0.7221 \u001b[0m | \u001b[0m 0.5984 \u001b[0m | \u001b[0m 10.95 \u001b[0m |\n| \u001b[0m 22 \u001b[0m | \u001b[0m-1.47e+03\u001b[0m | \u001b[0m 23.5 \u001b[0m | \u001b[0m 0.8567 \u001b[0m | \u001b[0m 0.4213 \u001b[0m | \u001b[0m 3.003 \u001b[0m |\n| \u001b[0m 23 \u001b[0m | \u001b[0m-1.501e+0\u001b[0m | \u001b[0m 11.1 \u001b[0m | \u001b[0m 0.458 \u001b[0m | \u001b[0m 0.7338 \u001b[0m | \u001b[0m 24.89 \u001b[0m |\n| \u001b[0m 24 \u001b[0m | \u001b[0m-1.486e+0\u001b[0m | \u001b[0m 12.12 \u001b[0m | \u001b[0m 0.7855 \u001b[0m | \u001b[0m 0.6333 \u001b[0m | \u001b[0m 17.91 \u001b[0m |\n| \u001b[0m 25 \u001b[0m | \u001b[0m-1.52e+03\u001b[0m | \u001b[0m 8.023 \u001b[0m | \u001b[0m 0.4586 \u001b[0m | \u001b[0m 0.3165 \u001b[0m | \u001b[0m 9.899 \u001b[0m |\n| \u001b[95m 26 \u001b[0m | \u001b[95m-1.455e+0\u001b[0m | \u001b[95m 15.26 \u001b[0m | \u001b[95m 0.6993 \u001b[0m | \u001b[95m 0.1952 \u001b[0m | \u001b[95m 5.011 \u001b[0m |\n| \u001b[0m 27 \u001b[0m | \u001b[0m-1.485e+0\u001b[0m | \u001b[0m 11.44 \u001b[0m | \u001b[0m 0.6947 \u001b[0m | \u001b[0m 0.861 \u001b[0m | \u001b[0m 14.72 \u001b[0m |\n| \u001b[0m 28 \u001b[0m | \u001b[0m-1.47e+03\u001b[0m | \u001b[0m 22.09 \u001b[0m | \u001b[0m 0.446 \u001b[0m | \u001b[0m 0.3848 \u001b[0m | \u001b[0m 10.15 \u001b[0m |\n| \u001b[0m 29 \u001b[0m | \u001b[0m-1.519e+0\u001b[0m | \u001b[0m 8.422 \u001b[0m | \u001b[0m 0.8454 \u001b[0m | \u001b[0m 0.4045 \u001b[0m | \u001b[0m 14.7 \u001b[0m |\n| \u001b[0m 30 \u001b[0m | \u001b[0m-1.491e+0\u001b[0m | \u001b[0m 16.57 \u001b[0m | \u001b[0m 0.5689 \u001b[0m | \u001b[0m 0.1024 \u001b[0m | \u001b[0m 24.73 \u001b[0m |\n| \u001b[0m 31 \u001b[0m | \u001b[0m-1.555e+0\u001b[0m | \u001b[0m 7.9 \u001b[0m | \u001b[0m 0.4825 \u001b[0m | \u001b[0m 0.1283 \u001b[0m | \u001b[0m 11.87 \u001b[0m |\n| \u001b[0m 32 \u001b[0m | \u001b[0m-1.456e+0\u001b[0m | \u001b[0m 15.68 \u001b[0m | \u001b[0m 0.679 \u001b[0m | \u001b[0m 0.7953 \u001b[0m | \u001b[0m 5.404 \u001b[0m |\n| \u001b[95m 33 \u001b[0m | \u001b[95m-1.453e+0\u001b[0m | \u001b[95m 15.28 \u001b[0m | \u001b[95m 0.67 \u001b[0m | \u001b[95m 0.1 \u001b[0m | \u001b[95m 6.029 \u001b[0m |\n| \u001b[0m 34 \u001b[0m | \u001b[0m-1.457e+0\u001b[0m | \u001b[0m 14.57 \u001b[0m | \u001b[0m 0.8538 \u001b[0m | \u001b[0m 0.796 \u001b[0m | \u001b[0m 5.604 \u001b[0m |\n| \u001b[0m 35 \u001b[0m | \u001b[0m-1.459e+0\u001b[0m | \u001b[0m 18.02 \u001b[0m | \u001b[0m 0.5018 \u001b[0m | \u001b[0m 0.405 \u001b[0m | \u001b[0m 7.811 \u001b[0m |\n| \u001b[0m 36 \u001b[0m | \u001b[0m-1.459e+0\u001b[0m | \u001b[0m 16.5 \u001b[0m | \u001b[0m 0.6208 \u001b[0m | \u001b[0m 0.754 \u001b[0m | \u001b[0m 7.238 \u001b[0m |\n| \u001b[0m 37 \u001b[0m | \u001b[0m-1.454e+0\u001b[0m | \u001b[0m 14.84 \u001b[0m | \u001b[0m 0.6482 \u001b[0m | \u001b[0m 0.6014 \u001b[0m | \u001b[0m 7.68 \u001b[0m |\n| \u001b[0m 38 \u001b[0m | \u001b[0m-1.464e+0\u001b[0m | \u001b[0m 15.44 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 8.97 \u001b[0m |\n| \u001b[0m 39 \u001b[0m | \u001b[0m-1.456e+0\u001b[0m | \u001b[0m 17.97 \u001b[0m | \u001b[0m 0.5981 \u001b[0m | \u001b[0m 0.2881 \u001b[0m | \u001b[0m 6.062 \u001b[0m |\n| \u001b[0m 40 \u001b[0m | \u001b[0m-1.516e+0\u001b[0m | \u001b[0m 13.51 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 6.897 \u001b[0m |\n| \u001b[0m 41 \u001b[0m | \u001b[0m-1.46e+03\u001b[0m | \u001b[0m 16.98 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 4.881 \u001b[0m |\n| \u001b[0m 42 \u001b[0m | \u001b[0m-1.509e+0\u001b[0m | \u001b[0m 15.64 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 8.572 \u001b[0m |\n| \u001b[0m 43 \u001b[0m | \u001b[0m-1.457e+0\u001b[0m | \u001b[0m 16.7 \u001b[0m | \u001b[0m 0.4294 \u001b[0m | \u001b[0m 0.1791 \u001b[0m | \u001b[0m 6.274 \u001b[0m |\n| \u001b[0m 44 \u001b[0m | \u001b[0m-1.469e+0\u001b[0m | \u001b[0m 18.6 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 9.186 \u001b[0m |\n| \u001b[0m 45 \u001b[0m | \u001b[0m-1.466e+0\u001b[0m | \u001b[0m 19.25 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 5.791 \u001b[0m |\n| \u001b[0m 46 \u001b[0m | \u001b[0m-1.461e+0\u001b[0m | \u001b[0m 15.54 \u001b[0m | \u001b[0m 0.8501 \u001b[0m | \u001b[0m 0.15 \u001b[0m | \u001b[0m 7.15 \u001b[0m |\n| \u001b[0m 47 \u001b[0m | \u001b[0m-1.493e+0\u001b[0m | \u001b[0m 18.51 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 4.553 \u001b[0m |\n| \u001b[0m 48 \u001b[0m | \u001b[0m-1.464e+0\u001b[0m | \u001b[0m 17.63 \u001b[0m | \u001b[0m 0.9572 \u001b[0m | \u001b[0m 0.9114 \u001b[0m | \u001b[0m 6.7 \u001b[0m |\n| \u001b[0m 49 \u001b[0m | \u001b[0m-1.459e+0\u001b[0m | \u001b[0m 15.67 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 3.588 \u001b[0m |\n| \u001b[0m 50 \u001b[0m | \u001b[0m-1.458e+0\u001b[0m | \u001b[0m 14.06 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 3.819 \u001b[0m |\n| \u001b[0m 51 \u001b[0m | \u001b[0m-1.499e+0\u001b[0m | \u001b[0m 14.77 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 3.056 \u001b[0m |\n| \u001b[0m 52 \u001b[0m | \u001b[0m-1.47e+03\u001b[0m | \u001b[0m 13.77 \u001b[0m | \u001b[0m 0.7691 \u001b[0m | \u001b[0m 0.3868 \u001b[0m | \u001b[0m 10.85 \u001b[0m |\n| \u001b[0m 53 \u001b[0m | \u001b[0m-1.461e+0\u001b[0m | \u001b[0m 11.96 \u001b[0m | \u001b[0m 0.8822 \u001b[0m | \u001b[0m 0.7063 \u001b[0m | \u001b[0m 3.499 \u001b[0m |\n| \u001b[0m 54 \u001b[0m | \u001b[0m-1.463e+0\u001b[0m | \u001b[0m 11.24 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 2.0 \u001b[0m |\n| \u001b[0m 55 \u001b[0m | \u001b[0m-1.47e+03\u001b[0m | \u001b[0m 10.19 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 3.478 \u001b[0m |\n| \u001b[0m 56 \u001b[0m | \u001b[0m-1.569e+0\u001b[0m | \u001b[0m 10.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 2.0 \u001b[0m |\n| \u001b[0m 57 \u001b[0m | \u001b[0m-1.457e+0\u001b[0m | \u001b[0m 12.44 \u001b[0m | \u001b[0m 0.5928 \u001b[0m | \u001b[0m 0.9908 \u001b[0m | \u001b[0m 2.173 \u001b[0m |\n| \u001b[0m 58 \u001b[0m | \u001b[0m-1.471e+0\u001b[0m | \u001b[0m 10.77 \u001b[0m | \u001b[0m 0.8853 \u001b[0m | \u001b[0m 0.9713 \u001b[0m | \u001b[0m 5.209 \u001b[0m |\n| \u001b[0m 59 \u001b[0m | \u001b[0m-1.477e+0\u001b[0m | \u001b[0m 20.5 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 11.32 \u001b[0m |\n| \u001b[0m 60 \u001b[0m | \u001b[0m-1.507e+0\u001b[0m | \u001b[0m 19.49 \u001b[0m | \u001b[0m 0.1623 \u001b[0m | \u001b[0m 0.9902 \u001b[0m | \u001b[0m 8.762 \u001b[0m |\n| \u001b[0m 61 \u001b[0m | \u001b[0m-1.458e+0\u001b[0m | \u001b[0m 12.96 \u001b[0m | \u001b[0m 0.921 \u001b[0m | \u001b[0m 0.4415 \u001b[0m | \u001b[0m 4.644 \u001b[0m |\n| \u001b[0m 62 \u001b[0m | \u001b[0m-1.459e+0\u001b[0m | \u001b[0m 15.17 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 6.707 \u001b[0m |\n| \u001b[0m 63 \u001b[0m | \u001b[0m-1.478e+0\u001b[0m | \u001b[0m 22.9 \u001b[0m | \u001b[0m 0.9587 \u001b[0m | \u001b[0m 0.689 \u001b[0m | \u001b[0m 11.97 \u001b[0m |\n| \u001b[0m 64 \u001b[0m | \u001b[0m-1.466e+0\u001b[0m | \u001b[0m 17.15 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 2.777 \u001b[0m |\n| \u001b[0m 65 \u001b[0m | \u001b[0m-1.463e+0\u001b[0m | \u001b[0m 24.91 \u001b[0m | \u001b[0m 0.6256 \u001b[0m | \u001b[0m 0.1515 \u001b[0m | \u001b[0m 4.566 \u001b[0m |\n| \u001b[0m 66 \u001b[0m | \u001b[0m-1.462e+0\u001b[0m | \u001b[0m 23.53 \u001b[0m | \u001b[0m 0.6522 \u001b[0m | \u001b[0m 0.9963 \u001b[0m | \u001b[0m 4.986 \u001b[0m |\n| \u001b[0m 67 \u001b[0m | \u001b[0m-1.467e+0\u001b[0m | \u001b[0m 24.78 \u001b[0m | \u001b[0m 0.9041 \u001b[0m | \u001b[0m 0.7646 \u001b[0m | \u001b[0m 6.218 \u001b[0m |\n| \u001b[0m 68 \u001b[0m | \u001b[0m-1.502e+0\u001b[0m | \u001b[0m 25.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 3.173 \u001b[0m |\n| \u001b[0m 69 \u001b[0m | \u001b[0m-1.469e+0\u001b[0m | \u001b[0m 22.24 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 4.379 \u001b[0m |\n| \u001b[0m 70 \u001b[0m | \u001b[0m-1.5e+03 \u001b[0m | \u001b[0m 21.67 \u001b[0m | \u001b[0m 0.1723 \u001b[0m | \u001b[0m 0.9832 \u001b[0m | \u001b[0m 2.467 \u001b[0m |\n| \u001b[0m 71 \u001b[0m | \u001b[0m-1.469e+0\u001b[0m | \u001b[0m 24.54 \u001b[0m | \u001b[0m 0.6028 \u001b[0m | \u001b[0m 0.2041 \u001b[0m | \u001b[0m 9.882 \u001b[0m |\n| \u001b[0m 72 \u001b[0m | \u001b[0m-1.502e+0\u001b[0m | \u001b[0m 24.06 \u001b[0m | \u001b[0m 0.1354 \u001b[0m | \u001b[0m 0.119 \u001b[0m | \u001b[0m 5.809 \u001b[0m |\n| \u001b[0m 73 \u001b[0m | \u001b[0m-1.525e+0\u001b[0m | \u001b[0m 12.93 \u001b[0m | \u001b[0m 0.1598 \u001b[0m | \u001b[0m 0.9476 \u001b[0m | \u001b[0m 4.084 \u001b[0m |\n| \u001b[0m 74 \u001b[0m | \u001b[0m-1.494e+0\u001b[0m | \u001b[0m 18.49 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 6.83 \u001b[0m |\n| \u001b[0m 75 \u001b[0m | \u001b[0m-1.458e+0\u001b[0m | \u001b[0m 17.35 \u001b[0m | \u001b[0m 0.4395 \u001b[0m | \u001b[0m 0.7619 \u001b[0m | \u001b[0m 5.624 \u001b[0m |\n| \u001b[0m 76 \u001b[0m | \u001b[0m-1.464e+0\u001b[0m | \u001b[0m 16.39 \u001b[0m | \u001b[0m 0.2238 \u001b[0m | \u001b[0m 0.8484 \u001b[0m | \u001b[0m 4.312 \u001b[0m |\n| \u001b[0m 77 \u001b[0m | \u001b[0m-1.455e+0\u001b[0m | \u001b[0m 14.05 \u001b[0m | \u001b[0m 0.9677 \u001b[0m | \u001b[0m 0.2225 \u001b[0m | \u001b[0m 5.123 \u001b[0m |\n| \u001b[0m 78 \u001b[0m | \u001b[0m-1.455e+0\u001b[0m | \u001b[0m 14.81 \u001b[0m | \u001b[0m 0.8189 \u001b[0m | \u001b[0m 0.8773 \u001b[0m | \u001b[0m 4.587 \u001b[0m |\n| \u001b[0m 79 \u001b[0m | \u001b[0m-1.461e+0\u001b[0m | \u001b[0m 12.29 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 2.494 \u001b[0m |\n| \u001b[0m 80 \u001b[0m | \u001b[0m-1.462e+0\u001b[0m | \u001b[0m 11.75 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 4.662 \u001b[0m |\n| \u001b[0m 81 \u001b[0m | \u001b[0m-1.464e+0\u001b[0m | \u001b[0m 17.2 \u001b[0m | \u001b[0m 0.9693 \u001b[0m | \u001b[0m 0.2123 \u001b[0m | \u001b[0m 7.917 \u001b[0m |\n| \u001b[0m 82 \u001b[0m | \u001b[0m-1.467e+0\u001b[0m | \u001b[0m 20.05 \u001b[0m | \u001b[0m 0.9362 \u001b[0m | \u001b[0m 0.3627 \u001b[0m | \u001b[0m 6.62 \u001b[0m |\n| \u001b[0m 83 \u001b[0m | \u001b[0m-1.471e+0\u001b[0m | \u001b[0m 24.81 \u001b[0m | \u001b[0m 0.8913 \u001b[0m | \u001b[0m 0.8577 \u001b[0m | \u001b[0m 8.258 \u001b[0m |\n| \u001b[0m 84 \u001b[0m | \u001b[0m-1.468e+0\u001b[0m | \u001b[0m 12.1 \u001b[0m | \u001b[0m 0.8731 \u001b[0m | \u001b[0m 0.9686 \u001b[0m | \u001b[0m 9.018 \u001b[0m |\n| \u001b[0m 85 \u001b[0m | \u001b[0m-1.488e+0\u001b[0m | \u001b[0m 24.89 \u001b[0m | \u001b[0m 0.2231 \u001b[0m | \u001b[0m 0.5043 \u001b[0m | \u001b[0m 11.51 \u001b[0m |\n| \u001b[0m 86 \u001b[0m | \u001b[0m-1.469e+0\u001b[0m | \u001b[0m 16.47 \u001b[0m | \u001b[0m 0.9657 \u001b[0m | \u001b[0m 0.1852 \u001b[0m | \u001b[0m 10.21 \u001b[0m |\n| \u001b[0m 87 \u001b[0m | \u001b[0m-1.501e+0\u001b[0m | \u001b[0m 15.5 \u001b[0m | \u001b[0m 0.1027 \u001b[0m | \u001b[0m 0.7598 \u001b[0m | \u001b[0m 6.511 \u001b[0m |\n| \u001b[0m 88 \u001b[0m | \u001b[0m-1.458e+0\u001b[0m | \u001b[0m 16.12 \u001b[0m | \u001b[0m 0.8986 \u001b[0m | \u001b[0m 0.1476 \u001b[0m | \u001b[0m 5.557 \u001b[0m |\n| \u001b[0m 89 \u001b[0m | \u001b[0m-1.466e+0\u001b[0m | \u001b[0m 14.12 \u001b[0m | \u001b[0m 0.9847 \u001b[0m | \u001b[0m 0.5234 \u001b[0m | \u001b[0m 8.363 \u001b[0m |\n| \u001b[0m 90 \u001b[0m | \u001b[0m-1.539e+0\u001b[0m | \u001b[0m 12.48 \u001b[0m | \u001b[0m 0.1189 \u001b[0m | \u001b[0m 0.1573 \u001b[0m | \u001b[0m 9.695 \u001b[0m |\n| \u001b[0m 91 \u001b[0m | \u001b[0m-1.465e+0\u001b[0m | \u001b[0m 17.78 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 8.534 \u001b[0m |\n| \u001b[0m 92 \u001b[0m | \u001b[0m-1.464e+0\u001b[0m | \u001b[0m 14.4 \u001b[0m | \u001b[0m 0.9241 \u001b[0m | \u001b[0m 0.8977 \u001b[0m | \u001b[0m 9.907 \u001b[0m |\n| \u001b[0m 93 \u001b[0m | \u001b[0m-1.459e+0\u001b[0m | \u001b[0m 12.62 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 5.505 \u001b[0m |\n| \u001b[0m 94 \u001b[0m | \u001b[0m-1.471e+0\u001b[0m | \u001b[0m 15.14 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 11.06 \u001b[0m |\n| \u001b[0m 95 \u001b[0m | \u001b[0m-1.478e+0\u001b[0m | \u001b[0m 10.87 \u001b[0m | \u001b[0m 0.9962 \u001b[0m | \u001b[0m 0.8543 \u001b[0m | \u001b[0m 7.53 \u001b[0m |\n| \u001b[0m 96 \u001b[0m | \u001b[0m-1.464e+0\u001b[0m | \u001b[0m 16.46 \u001b[0m | \u001b[0m 0.9896 \u001b[0m | \u001b[0m 0.1711 \u001b[0m | \u001b[0m 3.759 \u001b[0m |\n| \u001b[0m 97 \u001b[0m | \u001b[0m-1.458e+0\u001b[0m | \u001b[0m 13.43 \u001b[0m | \u001b[0m 0.9719 \u001b[0m | \u001b[0m 0.7068 \u001b[0m | \u001b[0m 2.125 \u001b[0m |\n| \u001b[0m 98 \u001b[0m | \u001b[0m-1.506e+0\u001b[0m | \u001b[0m 8.715 \u001b[0m | \u001b[0m 0.7211 \u001b[0m | \u001b[0m 0.9467 \u001b[0m | \u001b[0m 5.015 \u001b[0m |\n| \u001b[0m 99 \u001b[0m | \u001b[0m-1.467e+0\u001b[0m | \u001b[0m 21.03 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 5.182 \u001b[0m |\n| \u001b[0m 100 \u001b[0m | \u001b[0m-1.473e+0\u001b[0m | \u001b[0m 22.22 \u001b[0m | \u001b[0m 0.1853 \u001b[0m | \u001b[0m 0.9574 \u001b[0m | \u001b[0m 5.157 \u001b[0m |\n| \u001b[0m 101 \u001b[0m | \u001b[0m-1.461e+0\u001b[0m | \u001b[0m 16.43 \u001b[0m | \u001b[0m 0.9598 \u001b[0m | \u001b[0m 0.9947 \u001b[0m | \u001b[0m 4.727 \u001b[0m |\n| \u001b[0m 102 \u001b[0m | \u001b[0m-1.472e+0\u001b[0m | \u001b[0m 23.4 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 9.5 \u001b[0m |\n| \u001b[0m 103 \u001b[0m | \u001b[0m-1.495e+0\u001b[0m | \u001b[0m 14.95 \u001b[0m | \u001b[0m 0.272 \u001b[0m | \u001b[0m 0.2352 \u001b[0m | \u001b[0m 14.71 \u001b[0m |\n| \u001b[0m 104 \u001b[0m | \u001b[0m-1.466e+0\u001b[0m | \u001b[0m 16.01 \u001b[0m | \u001b[0m 0.9633 \u001b[0m | \u001b[0m 0.9599 \u001b[0m | \u001b[0m 2.249 \u001b[0m |\n| \u001b[0m 105 \u001b[0m | \u001b[0m-1.49e+03\u001b[0m | \u001b[0m 25.0 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 18.19 \u001b[0m |\n| \u001b[0m 106 \u001b[0m | \u001b[0m-1.652e+0\u001b[0m | \u001b[0m 5.0 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 17.96 \u001b[0m |\n| \u001b[0m 107 \u001b[0m | \u001b[0m-1.526e+0\u001b[0m | \u001b[0m 22.07 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 15.17 \u001b[0m |\n| \u001b[0m 108 \u001b[0m | \u001b[0m-1.492e+0\u001b[0m | \u001b[0m 20.65 \u001b[0m | \u001b[0m 0.9979 \u001b[0m | \u001b[0m 0.3717 \u001b[0m | \u001b[0m 20.6 \u001b[0m |\n| \u001b[0m 109 \u001b[0m | \u001b[0m-1.831e+0\u001b[0m | \u001b[0m 5.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n| \u001b[0m 110 \u001b[0m | \u001b[0m-1.543e+0\u001b[0m | \u001b[0m 25.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 21.92 \u001b[0m |\n| \u001b[0m 111 \u001b[0m | \u001b[0m-1.644e+0\u001b[0m | \u001b[0m 5.0 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 2.0 \u001b[0m |\n| \u001b[0m 112 \u001b[0m | \u001b[0m-1.507e+0\u001b[0m | \u001b[0m 9.786 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 17.26 \u001b[0m |\n| \u001b[0m 113 \u001b[0m | \u001b[0m-1.646e+0\u001b[0m | \u001b[0m 5.0 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 8.125 \u001b[0m |\n| \u001b[0m 114 \u001b[0m | \u001b[0m-1.508e+0\u001b[0m | \u001b[0m 18.25 \u001b[0m | \u001b[0m 0.2713 \u001b[0m | \u001b[0m 0.8428 \u001b[0m | \u001b[0m 21.87 \u001b[0m |\n| \u001b[0m 115 \u001b[0m | \u001b[0m-1.496e+0\u001b[0m | \u001b[0m 14.15 \u001b[0m | \u001b[0m 0.9491 \u001b[0m | \u001b[0m 0.9654 \u001b[0m | \u001b[0m 24.49 \u001b[0m |\n| \u001b[0m 116 \u001b[0m | \u001b[0m-1.483e+0\u001b[0m | \u001b[0m 13.44 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 16.28 \u001b[0m |\n| \u001b[0m 117 \u001b[0m | \u001b[0m-1.515e+0\u001b[0m | \u001b[0m 19.2 \u001b[0m | \u001b[0m 0.2181 \u001b[0m | \u001b[0m 0.9116 \u001b[0m | \u001b[0m 24.83 \u001b[0m |\n| \u001b[0m 118 \u001b[0m | \u001b[0m-1.527e+0\u001b[0m | \u001b[0m 25.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 15.09 \u001b[0m |\n| \u001b[0m 119 \u001b[0m | \u001b[0m-1.55e+03\u001b[0m | \u001b[0m 25.0 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 25.0 \u001b[0m |\n| \u001b[0m 120 \u001b[0m | \u001b[0m-1.532e+0\u001b[0m | \u001b[0m 22.28 \u001b[0m | \u001b[0m 0.1593 \u001b[0m | \u001b[0m 0.1656 \u001b[0m | \u001b[0m 18.73 \u001b[0m |\n| \u001b[0m 121 \u001b[0m | \u001b[0m-1.486e+0\u001b[0m | \u001b[0m 16.36 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 19.57 \u001b[0m |\n| \u001b[0m 122 \u001b[0m | \u001b[0m-1.483e+0\u001b[0m | \u001b[0m 10.1 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 9.664 \u001b[0m |\n| \u001b[0m 123 \u001b[0m | \u001b[0m-1.478e+0\u001b[0m | \u001b[0m 17.27 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 13.53 \u001b[0m |\n| \u001b[0m 124 \u001b[0m | \u001b[0m-1.461e+0\u001b[0m | \u001b[0m 18.41 \u001b[0m | \u001b[0m 0.6071 \u001b[0m | \u001b[0m 0.3126 \u001b[0m | \u001b[0m 2.0 \u001b[0m |\n| \u001b[0m 125 \u001b[0m | \u001b[0m-1.496e+0\u001b[0m | \u001b[0m 12.44 \u001b[0m | \u001b[0m 0.9844 \u001b[0m | \u001b[0m 0.4886 \u001b[0m | \u001b[0m 22.59 \u001b[0m |\n| \u001b[0m 126 \u001b[0m | \u001b[0m-1.478e+0\u001b[0m | \u001b[0m 19.84 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 13.02 \u001b[0m |\n| \u001b[0m 127 \u001b[0m | \u001b[0m-1.477e+0\u001b[0m | \u001b[0m 12.16 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 12.26 \u001b[0m |\n| \u001b[0m 128 \u001b[0m | \u001b[0m-1.48e+03\u001b[0m | \u001b[0m 25.0 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 2.0 \u001b[0m |\n| \u001b[0m 129 \u001b[0m | \u001b[0m-1.472e+0\u001b[0m | \u001b[0m 20.08 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.1 \u001b[0m | \u001b[0m 2.0 \u001b[0m |\n| \u001b[0m 130 \u001b[0m | \u001b[0m-1.494e+0\u001b[0m | \u001b[0m 21.39 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 0.999 \u001b[0m | \u001b[0m 22.67 \u001b[0m |\n=========================================================================\nResultado Final {'target': -1452.6107276303255, 'params': {'max_depth': 15.275973296691198, 'max_features': 0.670029541753297, 'min_impurity_decrease': 0.1, 'min_samples_split': 6.0286439514233185}}\n"
],
[
"from sklearn.metrics import r2_score, mean_absolute_error\nrf_reg = RandomForestRegressor(n_estimators = 300, n_jobs = -1, max_depth = 15, max_features = 0.67, min_impurity_decrease=0.1, min_samples_split=6)\nrf_reg.fit(X_train, y_train)\npreds = rf_reg.predict(X_test)\n\nr2_score(y_test, preds) #0.38?",
"_____no_output_____"
],
[
"final_model_rf = rf_reg.fit(pd.concat([X_train,X_test]), pd.concat([y_train, y_test]))",
"_____no_output_____"
],
[
"import pickle\n\nwith open('../webapp/artifacts/models/rf_base.pkl','wb') as handle:\n pickle.dump(final_model_rf, handle, protocol=pickle.HIGHEST_PROTOCOL)",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code",
"code"
],
[
"markdown"
],
[
"code",
"code"
],
[
"markdown"
],
[
"code",
"code",
"code",
"code",
"code"
]
] |
cbb49a857590593248d5ce6fc4b46007fd52bcda
| 77,799 |
ipynb
|
Jupyter Notebook
|
assignments/05/10219101/work_of_friction_10219101.ipynb
|
ErvandyR/fi3201-01-2021-2
|
849a7534114250731f6d5f4ccc23d56ff891c11f
|
[
"MIT"
] | 7 |
2022-01-18T14:11:54.000Z
|
2022-03-29T02:26:29.000Z
|
assignments/05/10219101/work_of_friction_10219101.ipynb
|
ErvandyR/fi3201-01-2021-2
|
849a7534114250731f6d5f4ccc23d56ff891c11f
|
[
"MIT"
] | 1 |
2022-01-18T16:04:13.000Z
|
2022-01-18T16:04:13.000Z
|
assignments/05/10219101/work_of_friction_10219101.ipynb
|
ErvandyR/fi3201-01-2021-2
|
849a7534114250731f6d5f4ccc23d56ff891c11f
|
[
"MIT"
] | 52 |
2022-01-18T14:15:23.000Z
|
2022-01-27T08:35:03.000Z
| 47.467358 | 5,656 | 0.530984 |
[
[
[
"# Kerja Gaya Gesek\n\nSparisoma Viridi<sup>1</sup>, Muhammad Ervandy Rachmat<sup>2</sup> <br>\nProgram Studi Sarjana Fisika, Institut Teknologi Bandung <br>\nJalan Gensha 10, Bandung 40132, Indonesia <br>\n<sup>1</sup>[email protected], https://github.com/dudung <br>\n<sup>2</sup>[email protected], https://github.com/ErvandyR\n\nKerja yang dilakukan oleh gaya gesek merupakan bentuk kerja yang tidak diharapkan karena energi yang dikeluarkan, biasanya dalam bentuk panas atau bunyi yang dilepas ke lingkungan, tidak dapat dimanfaatkan lagi oleh sistem sehingga energi sistem berkurang.",
"_____no_output_____"
],
[
"## Gerak benda di atas lantai mendatar kasar\nSistem yang ditinjau adalah suatu benda yang bergerak di atas lantai mendatar kasar. Benda diberi kecepatan awal tertentu dan bergerak melambat sampai berhenti karena adanya gaya gesek kinetis antara benda dan lantai kasar.",
"_____no_output_____"
],
[
"## Parameter\nBeberapa parameter yang digunakan adalah seperti pada tabel berikut ini.\n\nTabel <a name='tab1'>1</a>. Simbol beserta satuan dan artinya.\n\nSimbol | Satuan | Arti\n:- | :- | :-\n$t$ | s | waktu\n$v_0$ | m/s | kecepatan awal\n$x_0$ | m | posisi awal\n$v$ | m/s | kecepatan saat $t$\n$x$ | m | waktu saat $t$\n$a$ | m/s<sup>2</sup> | percepatan\n$\\mu_k$ | - | koefisien gesek kinetis\n$f_k$ | N | gaya gesek kinetis\n$m$ | kg | massa benda\n$F$ | N | total gaya yang bekerja\n$N$ | N | gaya normal\n$w$ | N | gaya gravitasi\n\nSimbol-simbol pada Tabel [1](#tab1) akan diberi nilai kemudian saat diimplementasikan dalam program.",
"_____no_output_____"
],
[
"## Persamaan\nPersamaan-persamaan yang akan digunakan adalah seperti dicantumkan pada bagian ini.",
"_____no_output_____"
],
[
"### Kinematika\nHubungan antara antara kecepatan $v$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ diberikan oleh\n\n<a name='eqn1'></a>\n\\begin{equation}\\label{eqn:kinematics-v-a-t}\\tag{1}\nv = v_0 + at.\n\\end{equation}",
"_____no_output_____"
],
[
"Posisi benda $x$ bergantung pada posisi awal $x_0$, kecepatan awal $v_0$, percepatan $a$, dan waktu $t$ melalui hubungan\n\n<a name='eqn2'></a>\n\\begin{equation}\\label{eqn:kinematics-x-v-a-t}\\tag{2}\nx = x_0 + v_0 t + \\tfrac12 at^2.\n\\end{equation}\n",
"_____no_output_____"
],
[
"Selain kedua persamaan sebelumnya, terdapat pula persamaan berikut\n\n<a name='eqn3'></a>\n\\begin{equation}\\label{eqn:kinematics-v-x-a}\\tag{3}\nv^2 = v_0^2 + 2a(x - x_0),\n\\end{equation}\n\nyang menghubungkan kecepatan $v$ dengan kecepatan awal $v_0$, percepatan $a$, dan jarak yang ditempuh $x - x_0$.",
"_____no_output_____"
],
[
"### Dinamika\nHukum Newton I menyatakan bahwa benda yang semula diam akan tetap diam dan yang semula bergerak dengan kecepatan tetap akan tetap bergerak dengan kecepatan tetap bila tidak ada gaya yang bekerja pada benda atau jumlah gaya-gaya yang bekerja sama dengan nol\n\n<a name='eqn4'></a>\n\\begin{equation}\\label{eqn:newtons-law-1}\\tag{4}\n\\sum F = 0.\n\\end{equation}",
"_____no_output_____"
],
[
"Bila ada gaya yang bekerj pada benda bermassa $m$ atau jumlah gaya-gaya tidak nol\n\n<a name='eqn5'></a>\n\\begin{equation}\\label{eqn:newtons-law-2}\\tag{5}\n\\sum F = ma,\n\\end{equation}\n\nmaka keadaan gerak benda akan berubah melalui percepatan $a$, dengan $m > 0$ dan $a \\ne 0$.",
"_____no_output_____"
],
[
"### Usaha\nUsaha oleh suatu gaya $F$ dengan posisi awal $x_0$ dan posisi akhir $x_0$ dapat diperoleh melalui\n\n<a name='eqn6'></a>\n\\begin{equation}\\label{eqn:work-1}\\tag{6}\nW = \\int_{x_0}^x F dx\n\\end{equation}\n\natau dengan\n\n<a name='eqn7'></a>\n\\begin{equation}\\label{eqn:work-2}\\tag{7}\nW = \\Delta K\n\\end{equation}\n\ndengan $K$ adalah energi kinetik. Persamaan ([7](#eqn7)) akan memberikan gaya oleh semua gaya. Dengan demikian bila $F$ adalah satu-satunya gaya yang bekerja pada benda, maka persamaan ini akan menjadi Persamaan ([6](#eqn6)).",
"_____no_output_____"
],
[
"## Sistem\nIlustrasi sistem perlu diberikan agar dapat terbayangan dan memudahkan penyelesaian masalah. Selain itu juga perlu disajikan diagram gaya-gaya yang bekerja pada benda.",
"_____no_output_____"
],
[
"### Ilustrasi\nSistem yang benda bermassa $m$ bergerak di atas lantai kasar dapat digambarkan\nseperti berikut ini.",
"_____no_output_____"
]
],
[
[
"%%html\n\n<svg\n width=\"320\"\n height=\"140\"\n viewBox=\"0 0 320 140.00001\"\n id=\"svg2\"\n version=\"1.1\"\n inkscape:version=\"1.1.2 (b8e25be833, 2022-02-05)\"\n sodipodi:docname=\"mass-horizontal-rough-surface.svg\"\n xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\n xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:svg=\"http://www.w3.org/2000/svg\"\n xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n xmlns:cc=\"http://creativecommons.org/ns#\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <defs\n id=\"defs4\">\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"marker11604\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"Arrow2Mend\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(-0.6)\"\n d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round\"\n id=\"path11602\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"Arrow2Mend\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"Arrow2Mend\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(-0.6)\"\n d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round\"\n id=\"path11361\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-3\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-1\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-35\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-0\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-0\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-4\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-37\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-9\" />\n </marker>\n </defs>\n <sodipodi:namedview\n id=\"base\"\n pagecolor=\"#ffffff\"\n bordercolor=\"#666666\"\n borderopacity=\"1.0\"\n inkscape:pageopacity=\"0.0\"\n inkscape:pageshadow=\"2\"\n inkscape:zoom=\"1.5\"\n inkscape:cx=\"173\"\n inkscape:cy=\"97.333333\"\n inkscape:document-units=\"px\"\n inkscape:current-layer=\"layer1\"\n showgrid=\"false\"\n inkscape:snap-bbox=\"false\"\n inkscape:snap-global=\"false\"\n units=\"px\"\n showborder=\"true\"\n inkscape:showpageshadow=\"true\"\n borderlayer=\"false\"\n inkscape:window-width=\"1366\"\n inkscape:window-height=\"705\"\n inkscape:window-x=\"-8\"\n inkscape:window-y=\"-8\"\n inkscape:window-maximized=\"1\"\n inkscape:pagecheckerboard=\"0\">\n <inkscape:grid\n type=\"xygrid\"\n id=\"grid970\" />\n </sodipodi:namedview>\n <metadata\n id=\"metadata7\">\n <rdf:RDF>\n <cc:Work\n rdf:about=\"\">\n <dc:format>image/svg+xml</dc:format>\n <dc:type\n rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" />\n </cc:Work>\n </rdf:RDF>\n </metadata>\n <g\n inkscape:label=\"Layer 1\"\n inkscape:groupmode=\"layer\"\n id=\"layer1\"\n transform=\"translate(0,-732.36216)\">\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"120.0725\"\n y=\"759.6109\"\n id=\"text2711-6-2-9\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2\"\n x=\"120.0725\"\n y=\"759.6109\"\n style=\"font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\"><tspan\n style=\"font-style:italic\"\n id=\"tspan9923\">v</tspan><tspan\n style=\"font-size:65%;baseline-shift:sub\"\n id=\"tspan1668\">0</tspan></tspan></text>\n <path\n style=\"fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM)\"\n d=\"m 84.656156,757.55169 25.738704,1.3e-4\"\n id=\"path11252\" />\n <rect\n style=\"fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-opacity:1\"\n id=\"rect1007\"\n width=\"59\"\n height=\"59\"\n x=\"56.5\"\n y=\"772.86218\"\n rx=\"0\"\n ry=\"0\" />\n <path\n style=\"fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\"\n d=\"m 20,832.86218 280,-2e-5\"\n id=\"path1386\" />\n <rect\n style=\"fill:#ffffff;fill-opacity:1;stroke:#c8c8c8;stroke-width:0.5;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:2, 2;stroke-dashoffset:0;stroke-opacity:1\"\n id=\"rect1007-2\"\n width=\"59\"\n height=\"59\"\n x=\"225.16667\"\n y=\"772.86218\"\n rx=\"0\"\n ry=\"0\" />\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#c8c8c8;fill-opacity:1;stroke:none\"\n x=\"236.05922\"\n y=\"759.6109\"\n id=\"text2711-6-2-9-9\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-8\"\n x=\"236.05922\"\n y=\"759.6109\"\n style=\"font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, ';fill:#c8c8c8;fill-opacity:1\"><tspan\n style=\"font-style:italic;fill:#c8c8c8;fill-opacity:1\"\n id=\"tspan9923-8\">v</tspan> = 0</tspan></text>\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"149.18359\"\n y=\"824.54877\"\n id=\"text2711-6-2-9-96\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-6\"\n x=\"149.18359\"\n y=\"824.54877\"\n style=\"font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\"><tspan\n style=\"font-style:italic\"\n id=\"tspan3028\">μ<tspan\n style=\"font-size:65%;baseline-shift:sub\"\n id=\"tspan3074\">k</tspan></tspan> > 0</tspan></text>\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"79.505844\"\n y=\"806.37714\"\n id=\"text2711-6-2-9-2\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-84\"\n x=\"79.505844\"\n y=\"806.37714\"\n style=\"font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\">m</tspan></text>\n <path\n style=\"fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-37)\"\n d=\"m 33.785239,770.82609 -1.3e-4,25.7387\"\n id=\"path11252-5\" />\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"29.173132\"\n y=\"759.45776\"\n id=\"text2711-6-2-9-8\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-2\"\n x=\"29.173132\"\n y=\"759.45776\"\n style=\"font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\">g</tspan></text>\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"79.368446\"\n y=\"849.21539\"\n id=\"text2711-6-2-9-23\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-3\"\n x=\"79.368446\"\n y=\"849.21539\"\n style=\"font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\"><tspan\n style=\"font-style:italic\"\n id=\"tspan9923-0\">x</tspan><tspan\n style=\"font-size:65%;baseline-shift:sub\"\n id=\"tspan1668-9\">0</tspan></tspan></text>\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"250.91145\"\n y=\"849.21539\"\n id=\"text2711-6-2-9-23-0\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-3-0\"\n x=\"250.91145\"\n y=\"849.21539\"\n style=\"font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\"><tspan\n style=\"font-style:italic\"\n id=\"tspan9923-0-3\">x</tspan><tspan\n style=\"font-size:65%;baseline-shift:sub\"\n id=\"tspan1668-9-3\" /></tspan></text>\n </g>\n</svg>\n\n<br/>\n\nGambar <a name='fig1'>1</a>. Sistem benda bermassa $m$ begerak di atas lantai\nmendatar kasar dengan koefisien gesek kinetis $\\mu_k$.",
"_____no_output_____"
]
],
[
[
"Keadaan akhir benda, yaitu saat kecepatan $v = 0$ diberikan pada bagian kanan Gambar [1](#fig1) dengan warna abu-abu.",
"_____no_output_____"
],
[
"### Diagram gaya\nDiagram gaya-gaya yang berja pada benda perlu dibuat berdasarkan informasi dari Gambar [1](#fig1) dan Tabel [1](#tab1), yang diberikan berikut ini.",
"_____no_output_____"
]
],
[
[
"%%html\n\n<svg\n width=\"320\"\n height=\"200\"\n viewBox=\"0 0 320 200.00001\"\n id=\"svg2\"\n version=\"1.1\"\n inkscape:version=\"1.1.2 (b8e25be833, 2022-02-05)\"\n sodipodi:docname=\"mass-horizontal-rough-surface-fbd.svg\"\n xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\n xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:svg=\"http://www.w3.org/2000/svg\"\n xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n xmlns:cc=\"http://creativecommons.org/ns#\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <defs\n id=\"defs4\">\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"marker11604\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"Arrow2Mend\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(-0.6)\"\n d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round\"\n id=\"path11602\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"Arrow2Mend\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"Arrow2Mend\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(-0.6)\"\n d=\"M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:0.625;stroke-linejoin:round\"\n id=\"path11361\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-3\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-1\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-35\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-0\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-0\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-4\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-37\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-9\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-9\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-8\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-9-3\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-8-3\" />\n </marker>\n <marker\n style=\"overflow:visible\"\n id=\"TriangleOutM-37-5\"\n refX=\"0\"\n refY=\"0\"\n orient=\"auto\"\n inkscape:stockid=\"TriangleOutM\"\n inkscape:isstock=\"true\">\n <path\n transform=\"scale(0.4)\"\n style=\"fill:context-stroke;fill-rule:evenodd;stroke:context-stroke;stroke-width:1pt\"\n d=\"M 5.77,0 -2.88,5 V -5 Z\"\n id=\"path11479-9-9\" />\n </marker>\n </defs>\n <sodipodi:namedview\n id=\"base\"\n pagecolor=\"#ffffff\"\n bordercolor=\"#666666\"\n borderopacity=\"1.0\"\n inkscape:pageopacity=\"0.0\"\n inkscape:pageshadow=\"2\"\n inkscape:zoom=\"1.2079428\"\n inkscape:cx=\"159.36185\"\n inkscape:cy=\"35.597712\"\n inkscape:document-units=\"px\"\n inkscape:current-layer=\"layer1\"\n showgrid=\"false\"\n inkscape:snap-bbox=\"false\"\n inkscape:snap-global=\"false\"\n units=\"px\"\n showborder=\"true\"\n inkscape:showpageshadow=\"true\"\n borderlayer=\"false\"\n inkscape:window-width=\"1366\"\n inkscape:window-height=\"705\"\n inkscape:window-x=\"-8\"\n inkscape:window-y=\"-8\"\n inkscape:window-maximized=\"1\"\n inkscape:pagecheckerboard=\"0\">\n <inkscape:grid\n type=\"xygrid\"\n id=\"grid970\" />\n </sodipodi:namedview>\n <metadata\n id=\"metadata7\">\n <rdf:RDF>\n <cc:Work\n rdf:about=\"\">\n <dc:format>image/svg+xml</dc:format>\n <dc:type\n rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" />\n </cc:Work>\n </rdf:RDF>\n </metadata>\n <g\n inkscape:label=\"Layer 1\"\n inkscape:groupmode=\"layer\"\n id=\"layer1\"\n transform=\"translate(0,-732.36216)\">\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"148.01953\"\n y=\"766.72156\"\n id=\"text2711-6-2-9-23\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-3\"\n x=\"148.01953\"\n y=\"766.72156\"\n style=\"font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\">N</tspan></text>\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"251.40584\"\n y=\"806.94421\"\n id=\"text2711-6-2-9\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2\"\n x=\"251.40584\"\n y=\"806.94421\"\n style=\"font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\"><tspan\n style=\"font-style:italic\"\n id=\"tspan9923\">v</tspan><tspan\n style=\"font-size:65%;baseline-shift:sub\"\n id=\"tspan1668\" /></tspan></text>\n <path\n style=\"fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM)\"\n d=\"m 215.98949,804.88502 25.7387,1.3e-4\"\n id=\"path11252\" />\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"153.68098\"\n y=\"915.71051\"\n id=\"text2711-6-2-9-2\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-84\"\n x=\"153.68098\"\n y=\"915.71051\"\n style=\"font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\">w</tspan></text>\n <path\n style=\"fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-37)\"\n d=\"m 31.113403,791.97918 -1.3e-4,25.7387\"\n id=\"path11252-5\" />\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"26.501303\"\n y=\"780.6109\"\n id=\"text2711-6-2-9-8\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-2\"\n x=\"26.501303\"\n y=\"780.6109\"\n style=\"font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\">g</tspan></text>\n <rect\n style=\"fill:#ffffff;fill-opacity:1;stroke:#000000;stroke-width:1;stroke-linecap:round;stroke-opacity:1\"\n id=\"rect1007\"\n width=\"59\"\n height=\"59\"\n x=\"130.5\"\n y=\"792.86218\"\n rx=\"0\"\n ry=\"0\" />\n <g\n id=\"g1363\"\n transform=\"translate(-6,20)\">\n <path\n style=\"fill:none;stroke:#ff0000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-9)\"\n d=\"m 161.00001,831.69534 -45.73871,1.3e-4\"\n id=\"path11252-4\" />\n <path\n style=\"fill:none;stroke:#0000ff;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-9-3)\"\n d=\"m 160.79738,832.36215 -1.3e-4,-75.7387\"\n id=\"path11252-4-6\" />\n </g>\n <path\n style=\"fill:none;stroke:#000000;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;marker-end:url(#TriangleOutM-37-5)\"\n d=\"m 159.99967,822.02879 3.4e-4,75.73871\"\n id=\"path11252-5-0\" />\n <text\n xml:space=\"preserve\"\n style=\"font-style:normal;font-weight:normal;font-size:18.6667px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none\"\n x=\"85.624084\"\n y=\"854.51099\"\n id=\"text2711-6-2-9-8-4\"><tspan\n sodipodi:role=\"line\"\n id=\"tspan2709-5-9-2-2-1\"\n x=\"85.624084\"\n y=\"854.51099\"\n style=\"font-style:italic;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:18.6667px;font-family:'Times New Roman';-inkscape-font-specification:'Times New Roman, '\">f<tspan\n style=\"font-size:65%;baseline-shift:sub\"\n id=\"tspan2197\">k</tspan></tspan></text>\n </g>\n</svg>\n\n<br>\n\nGambar <a name='fig2'>2</a>. Diagram gaya-gaya yang bekerja pada benda\nbermassa $m$.",
"_____no_output_____"
]
],
[
[
"Terlihat bahwa pada arah $y$ terdapat gaya normal $N$ dan gaya gravitasi $w$, sedangkan pada arah $x$ hanya terdapat gaya gesek kinetis $f_k$ yang melawan arah gerak benda. Arah gerak benda diberikan oleh arah kecepatan $v$.",
"_____no_output_____"
],
[
"## Metode numerik\nInterasi suatu fungsi $f(x)$ berbentuk\n\n<a name='eqn8'></a>\n\\begin{equation}\\label{eqn:integral-1}\\tag{8}\nA = \\int_a^b f(x) dx\n\\end{equation}\n\ndapat didekati dengan\n\n<a name='eqn9'></a>\n\\begin{equation}\\label{eqn:integral-2}\\tag{9}\nA \\approx \\sum_{i = 0}^N f\\left[ \\tfrac12(x_i + x_{i+1}) \\right] \\Delta x\n\\end{equation}\n\nyang dikenal sebagai metode persegi titik tengah, di mana\n\n<a name='eqn10'></a>\n\\begin{equation}\\label{eqn:integral-3}\\tag{10}\n\\Delta x = \\frac{b - a}{N}\n\\end{equation}\n\ndengan $N$ adalah jumlah partisi. Variabel $x_i$ pada Persamaan ([9](#eqn9)) diberikan oleh\n\n<a name='eqn11'></a>\n\\begin{equation}\\label{eqn:integral-4}\\tag{11}\nx_i = a + i\\Delta x\n\\end{equation}\n\ndengan $i = 0, \\dots, N$.",
"_____no_output_____"
],
[
"## Penyelesaian\nPenerapan Persamaan ([1](#eqn1)), ([2](#eqn2)), ([3](#eqn3)), ([4](#eqn4)), dan ([5](#eqn5)) pada Gambar [2](#fig2) akan menghasilkan\n\n<a name='eqn10'></a>\n\\begin{equation}\\label{eqn:friction}\\tag{10}\nf_k = \\mu_k mg\n\\end{equation}\n\ndan usahanya adalah\n\n<a name='eqn11'></a>\n\\begin{equation}\\label{eqn:friction-work}\\tag{11}\n\\begin{array}{rcl}\nW & = & \\displaystyle \\int_{x_0}^x f_k dx \\newline\n& = & \\displaystyle \\int_{x_0}^x \\mu_k m g dx \\newline\n& = & \\displaystyle m g \\int_{x_0}^x \\mu_k dx\n\\end{array}\n\\end{equation}\n\ndengan koefisien gesek statisnya dapat merupakan fungsi dari posisi $\\mu_k = \\mu_k(x)$.",
"_____no_output_____"
]
],
[
[
"import numpy as np\nimport matplotlib.pyplot as plt\nplt.ion()\n\n# set integral lower and upper bounds\na = 0\nb = 1\n\n# generate x\nx = [1, 2, 3, 4, 5]\n\n# generate y from numerical integration\ny = [1, 2, 3, 5, 6]\n\n## plot results\nfig, ax = plt.subplots()\nax.scatter(x, y)\nax.set_xlabel(\"$x - x^0$\")\nax.set_ylabel(\"y\")\n\nfrom IPython import display\nfrom IPython.core.display import HTML\nHTML('''\n<div>\nGambar <a name='fig3'>3</a>. Kurva antara usaha $W$ dan jarak tempuh $x - x_0$.\n</div>\n''')",
"_____no_output_____"
]
],
[
[
"## Diskusi\nBerdasarkan Gambar [3](#fig3) dapat dijelaskan bahwa dengan $\\mu_k = \\mu_k(x)$ maka kurva $W(x)$ tidak lagi linier karena dipengaruhi oleh sejauh mana perhitungan kerja dilakukan.",
"_____no_output_____"
],
[
"## Kesimpulan\nPerhitungan kerja dengan $\\mu_k = \\mu_k(x)$ telah dapat dilakukan.",
"_____no_output_____"
],
[
"## Referensi\n1. J. A. C. Martins, J. T. Oden, F. M. F. Simões, \"A study of static and kinetic friction\", International Journal of Engineerting Science, vol 28, no 1, p 29-92, 1990, url <https://doi.org/10.1016/0020-7225(90)90014-A>. \n1. Carl Rod Nave, \"Friction\", HyperPhysics, 2017, url <http://hyperphysics.phy-astr.gsu.edu/hbase/frict.html#fri> [20220419].\n2. Wikipedia contributors, \"Friction\", Wikipedia, The Free Encyclopedia, 12 April 2022, 00:33 UTC, url <https://en.wikipedia.org/w/index.php?oldid=1082223658> [20220419].\n3. Tia Ghose, Ailsa Harvey, \"What is friction?\", Live Science, 8 Feb 2022, url <https://www.livescience.com/37161-what-is-friction.html> [20220419].",
"_____no_output_____"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown",
"markdown",
"markdown"
]
] |
cbb49f8e72f940a7b1da388fd53168d417cd24cd
| 17,096 |
ipynb
|
Jupyter Notebook
|
Tutorial-Template_Style_Guide.ipynb
|
rhaas80/nrpytutorial
|
4398cd6b5a071c8fb8b2b584a01f07a4591dd5f4
|
[
"BSD-2-Clause"
] | null | null | null |
Tutorial-Template_Style_Guide.ipynb
|
rhaas80/nrpytutorial
|
4398cd6b5a071c8fb8b2b584a01f07a4591dd5f4
|
[
"BSD-2-Clause"
] | null | null | null |
Tutorial-Template_Style_Guide.ipynb
|
rhaas80/nrpytutorial
|
4398cd6b5a071c8fb8b2b584a01f07a4591dd5f4
|
[
"BSD-2-Clause"
] | null | null | null | 55.326861 | 764 | 0.671327 |
[
[
[
"<script async src=\"https://www.googletagmanager.com/gtag/js?id=UA-59152712-8\"></script>\n<script>\n window.dataLayer = window.dataLayer || [];\n function gtag(){dataLayer.push(arguments);}\n gtag('js', new Date());\n\n gtag('config', 'UA-59152712-8');\n</script>\n\n# The NRPy+ Jupyter Tutorial Style Guide / Template\n## Authors: Brandon Clark, Zach Etienne, & First Last\n### Formatting improvements courtesy Brandon Clark\n\n<font color='red'>**This is a warning message, in red text and bolded, to warn anyone using the module that it is, for example, actively in development, not yet validated, etc. Warning messages are optional.**</font>\n\n## This module implements a template designed by Brandon Clark to be used as a style guide for all tutorial notebooks within NRPy+.\n\n### Items in Markdown code contained within \"</>\" are not included within the output (double click this box to see what I mean). To the run Markdown code simply hit \"Shift + Enter\" or the \"Run\" button above. \n\n<font color='green'>**This text discusses how a module has been validated against other existing code or modules. This text is given a green font color and bolded. See how to bold and make text different colors in the Markdown code.**</font>\n\n### </list_source_code> NRPy+ Source Code for this module:\n1. [Template_Style_Guide.py](../edit/Template_Style_Guide.py); [\\[**tutorial**\\]](Tutorial-Template_Style_Guide.ipynb) </description_here> This is where you would describe what purpose this source code serves in this module. Read how to correctly link to these source code files/tutorial notebooks later in []. \n1. </additional_source_code_links__here>\n\n## Introduction:\nHere you write an introduction that discusses in slight detail the framework of this tutorial notebook. Here you may reference external works or websites on which pieces of your module rely. It is often helpful to include an enumerated algorihtm to highlight this modules processes. Within the algortihm you may refer to where source code is implemeted as a part of this module. </optional>\n\nThe entire </made_up>algorithm is outlined below, with NRPy+-based components highlighted in <font color='green'>green</font>.\n\n1. Constructing a Table of Contents\n1. 1. Discussing [Markdown Linking Protocol](https://medium.com/@sambozek/ipython-er-jupyter-table-of-contents-69bb72cf39d3)\n 1. Linking to sections internally within the module \n 1. Linking to external sources\n1. No parts of this template tutorial notebook rely on <font color='green'>NRPy+-based components</font>\n1. Converting Jupyter notebook to output LaTex PDF\n\n</optional>\nYou could also write your introduction to include subsections preceded by ###. \n\n### introduction subsection:\nInclude information relevant to this subsection here.\n\n## </other> Other (Optional): \nYou may include any number of items here within the first box of the tutorial notebook, but I suggest being minimalistic when you can. Other sections that have been included in other tutorial moudles are as follows\n\n### Note on Notation:\nWhen using a new type of notation for the first time within the NRPy+ tutorial, you may want to include some notes on that here.\n\n### Citations:\nThis is a great place to list out the references you link to within the module with actual citations. ",
"_____no_output_____"
],
[
"<a id='toc'></a>\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis notebook is organized as follows\n\n0. [Preliminaries](#prelim): This is an optional section\n1. [Step 1](#linking): The Markdown Linking Protocol </header_section>\n 1. [Step 1.a](#internal_links) Internal linking with the Jupyter notebook, Table of Contents </subsection>\n 1. [Step 1.b](#external_links): External linking outside of Jupyter notebook </subsection>\n 1. [Step 1.b.i](#nrpy_links): Linking to other files/modules within NRPy+ </subsubsection>\n1. [Step 2](#latex_pdf_output): Output this notebook to $\\LaTeX$-formatted PDF file\n\n\nThe Table of Contents (ToC) plays a significant role in the formatting of your module. The above ToC is for this module, but I have constructed it in a way such that you should see all of the important details for any module you need to write. If you choose to include a preliminaries section, enumerate it with the \"0.\" All other sections, subsections, and sub-subsections can be enumerated with the 1. Jupyter/LaTex will handle there own numerbing/lettering scheme. It is important when creating subsections and sub-subsections that you indent seen in the Markdown code. The text colors vary for the level section you're assigning within the Markdown code. When writing within the brackets to specify a step number, the following scheme is to be used:\n\n* Header Sections: Step 1, Step 2, Step 3\n* Subsections: Step 1.a, Step 1.b, Step 1.c\n* Sub-subsections: Step 1.a.i, 1.a.ii, 1.a.iii </roman_numerals>\n\nIf for some reason you go more then three levels deep in your sectioning, I would suggest finding a way to reorganize your sectioning to prevent that, or ask Zach Etienne what the next level of labelling for Steps should be. We will talk about the other components within the Markdown Code for the ToC in [Step 1.a](#internal_links). The only text within the ToC section of this module should be the ToC code itself and what precedes it.\n\nI also suggest that the titles for the Steps you include here following the \":\" match the titles you use throughout your module.",
"_____no_output_____"
],
[
"<a id='prelim'></a>\n\n# Preliminaries: This is an optional section \\[Back to [top](#toc)\\]\n$$\\label{prelim}$$ \n\nThis section is a great chance to include textual verbage that might have been too specific for the introduction section, but serves as a beneficial setup to the remainder of the module. For instance, you may want to define quantities here, express important equations, and so on. I suggest that the Preliminaries section is not followed by any Python code blocks, and remains simply a block of information for users to refer back to.\n",
"_____no_output_____"
],
[
"<a id='linking'></a>\n\n# Step 1: The Markdown Linking Protocol \\[Back to [top](#toc)\\]\n$$\\label{linking}$$\n\nWe have already within this template had to link to sources both internally within this module, exteranlly to other components of the NRPy+ tutorial, as well as externally to additional web sources. The next few sections discuss how this is done. It is important to know that any linking is down by combining brackets and parentheses \"\\[ \\]()\" with the desired input in each. \n\nOn another note, main sections like this have their titles preoceed by a single #. As you will see, for every deeper layer of sectioning, an addiotnal # is appended on, reducing the size of the text.",
"_____no_output_____"
],
[
"<a id='internal_links'></a>\n\n## Step 1.a: Internal linking with the Jupyter notebook, Table of Contents \\[Back to [top](#toc)\\]\n$$\\label{internal_links}$$\n\nA great resource for how to construct a Table of Contents is:\nhttps://medium.com/@sambozek/ipython-er-jupyter-table-of-contents-69bb72cf39d3\n\nThe Table of Contents is a family of internal links. To link internally we first have to specify an ***anchor tag*** which is the text within the parenthese of preceded by a # (See ToC Markdown code). For instance, the anchor tag for this subsection is \"internal_links\". So, for a particular Step within the Table of Contents you specify the Step title in brackets (e.g., <font color='blue'>[Step 1.a]</font>), appended by the anchor tag in parentheses preced by a # (e.g., <font color='red'>(#internal_links)</font>), followed by a \":\" and the Step description (e.g., : Internal linking with the Jupyter notebook, Table of Contents). Look at the Markdown code for the Table of Contents for a few examples. \n\n**Important Note**: The anchor tags cannot be anything that you want. Anchor tags must be entirely lowercase and contain no spaces. Numbers are fine as well as underscores, but not capitalization. I suggest making the anchor tags have siginificant meaning to the section there tied to, instead of making one that reads \"step1a\". The reason I say this, is because if you ever need to resection your module, the tags won't all need to be chnaged as well if you give each one a unqiue name. \n\nAll we have done so far is establish anchor tags and clickable links within the Table of Contents, but how do we establish the link to the specific section within the module. Opening up the Markdown code for this section you will see a line of code above the title, and a line of code directly below the title. These are the answers to the question. Each section requires these components to be included for both the Jupyter notebook and LaTex internal linking. Make sure the top line of the Markdown code has a space between it and the title. Similarly, the code directly beneath the title needs space below it as well, separated from the main body of text (see above in Markdown code).\n\n**Important Note**: Links do not work unless the two sections which are linked have been run.\n\nThe Table of Contents is now linked to this section and you may have already noticed but this section, and all others, are linked back to the Table of Contents using the Markdown code in line at the end of the section title. This is exceedingly convenient for modules of great length. It may also be convenient when you're in a particular subsection and you wish to just return to the header section. This is accomplished using a bracket parentheses \\[\\]() pairing like so (see this in Markdown code). Go back to [Step 1](#linking)\n\nLastly, you would more often than not write a code block below implementing what was discussed in this section. This isn't always necessary, some header sections plainly serve as a set up for subsections that will contain all of the necessary coding components. ",
"_____no_output_____"
]
],
[
[
"# This is the code block corresponding to Step 1.a: Internal linking within the Jupyter notebook, Table of Contents\nprint(\"We have successfully learned how to code internal links using Markdown Linking Protocol!!!\")",
"We have successfully learned how to code internal links using Markdown Linking Protocol!!!\n"
]
],
[
[
"<a id='external_links'></a>\n\n## Step 1.b: External linking outside of this module \\[Back to [top](#toc)\\]\n$$\\label{external_links}$$\n\nTo link outside of this particular module we still use bracket parentheses \\[ \\]() pairings. Since the links are not internal, we no longer need the # symbol and anchor tags. Instead, you need an actual link. For instance, look at your Markdown code to see how we link this [website](https://medium.com/@sambozek/ipython-er-jupyter-table-of-contents-69bb72cf39d3) to a line of text. Of course, web links will simply work on there own as a hyperlink, but often you may need to link to multiple external sources and do not want all of the individual addresses clogging up the body of your text. ",
"_____no_output_____"
]
],
[
[
"# This is the code block for Step 1.b: External linking outside of Jupyter notebook\nprint(\"Be efficient in how you link external sources, utilize []() pairs!!!\")",
"Be efficient in how you link external sources, utilize []() pairs!!!\n"
]
],
[
[
"<a id='nrpy_links'></a>\n\n### Step 1.b.i: Linking to other files/modules within NRPy+ \\[Back to [top](#toc)\\]\n$$\\label{nrpy_links}$$\n\nOther useful extranal sources we would like to link to are the existing files/moudles within NRPy+. To do this we again resort to the \\[ \\]() pair. By simply typing the file name into the parentheses, you can connect to another [Tutorial module](Tutorial-Template_Style_Guide.ipynb) (see Markdown). To access a .py file, you want to type the command ../edit/\nfollowed by the file location. For instance, here is the [.py file](../edit/Template_Style_Guide.py) for this notebook (see Markdown). \n",
"_____no_output_____"
]
],
[
[
"# This is the code block for Step 1.b.i: Linking to other files/modules within NRPy+\nprint(\"Template_Style_Guide.py is an empty file...\")",
"Template_Style_Guide.py is an empty file...\n"
]
],
[
[
"<a id='latex_pdf_output'></a>\n\n# Step 2: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-Template_Style_Guide.pdf](Tutorial-Template_Style_Guide.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)\n\n**Important Note**: Make sure that the file name is right in all six locations, two here in the Markdown, four in the code below. \n\n* Tutorial-Template_Style_Guide.pdf\n* Tutorial-Template_Style_Guide.ipynb\n* Tutorial-Template_Style_Guide.tex",
"_____no_output_____"
]
],
[
[
"import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface\ncmd.output_Jupyter_notebook_to_LaTeXed_PDF(\"Tutorial-Template_Style_Guide\")",
"Created Tutorial-Template_Style_Guide.tex, and compiled LaTeX file to PDF\n file Tutorial-Template_Style_Guide.pdf\n"
]
]
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
[
[
"markdown",
"markdown",
"markdown",
"markdown",
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
],
[
"markdown"
],
[
"code"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.