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
4af88a36713307883ae44bb88fbc396e22531fc9
7,944
ipynb
Jupyter Notebook
nbs_ref/7 - Clean Real Data.ipynb
cmg777/Try-Pandas
358a69e7c0c04e4e2e7cd7779a85edf95ab7d7b2
[ "MIT" ]
11
2021-10-19T07:01:09.000Z
2022-03-26T12:38:29.000Z
nbs_ref/7 - Clean Real Data.ipynb
Dennis5010/Try-Pandas
ea7407e4e88e6bd05c3cac8e0cf1bae96777b56a
[ "MIT" ]
null
null
null
nbs_ref/7 - Clean Real Data.ipynb
Dennis5010/Try-Pandas
ea7407e4e88e6bd05c3cac8e0cf1bae96777b56a
[ "MIT" ]
5
2021-11-07T22:19:03.000Z
2022-02-20T07:56:47.000Z
35.306667
2,175
0.704179
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af8903a8add4ab32c2f44e1192509cb6ba54954
8,101
ipynb
Jupyter Notebook
Clase11-Clustering&GA/NQueen_GeneticAlgorithm.ipynb
diegostaPy/cursoIA
c18b68452f65e301a310c2e7d392558c8e266986
[ "Apache-2.0" ]
3
2021-02-09T18:04:58.000Z
2021-03-19T01:56:56.000Z
Clase11-Clustering&GA/NQueen_GeneticAlgorithm.ipynb
diegostaPy/cursoIA
c18b68452f65e301a310c2e7d392558c8e266986
[ "Apache-2.0" ]
null
null
null
Clase11-Clustering&GA/NQueen_GeneticAlgorithm.ipynb
diegostaPy/cursoIA
c18b68452f65e301a310c2e7d392558c8e266986
[ "Apache-2.0" ]
null
null
null
30.685606
422
0.548574
[ [ [ " Cognizant Data Science Summit 2020 : July 1, 2020\n \n Yogesh Deshpande [157456]\n", "_____no_output_____" ], [ "# Week 1 challenge - Python\n\nDescription\n\nThe eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general n queens problem of placing n non-attacking queens on an n×n chessboard. (Source : https://en.wikipedia.org/wiki/Eight_queens_puzzle )\t\nChallenge\nThe challenge is to generate one right sequence through Genetic Programming. The sequence has to be 8 numbers between 0 to 7. Each number represents the positions the Queens can be placed. Each number refers to the row number in the specific column\n0\t3\t4\t5\t6\t1\t2\t4\n\n•\t0 is the row number in the column 0 where the Queen can be placed\n\n•\t3 is the row number in the column 1 where the Queen can be placed", "_____no_output_____" ], [ "# Initiaze variables, functions' definitions", "_____no_output_____" ] ], [ [ "import random\n\n# Set the variables as per the problem statement\nNumberofQueens = 8\nInitialPopulation = 1000000 # Initial population has number of chromozones out of which one or more are possible solutions\nNumberofIterations = 1000 # Number of generations to check for possible solution", "_____no_output_____" ], [ "def create_chromozone(NumberofQueens):\n chromozone = []\n for gene in range(NumberofQueens):\n chromozone.append(random.randint(0, NumberofQueens-1))\n return chromozone\n #print(chromozone)\n\n# Unit testing\n# create_chromozone(NumberofQueens)", "_____no_output_____" ], [ "def create_population(NumberofQueens, InitialPopulation):\n Population = []\n for chromozone in range(InitialPopulation):\n Population.append(create_chromozone(NumberofQueens))\n #print(Population)\n return Population\n\n# Unit testing\n#create_population(NumberofQueens, InitialPopulation)", "_____no_output_____" ], [ "def fitness_calculation(chromosome, maxFitness):\n horizontal_collisions = sum([chromosome.count(i) - 1 for i in chromosome])/2\n diagonal_collisions = 0\n for record in range(1,len(chromosome)+1):\n column1 = record-1\n row1 = chromosome[column1]\n for i in range (column1+1, len(chromosome)):\n column2 = i\n row2 = chromosome[i]\n deltaRow = abs(row1 - row2)\n deltaCol = abs(column1 - column2)\n if (deltaRow == deltaCol):\n #print(\"######## Collision detected ##############\")\n diagonal_collisions = diagonal_collisions + 1\n #print(\"Horizontal Collisions are {} and Diagonal are {} \".format(horizontal_collisions, diagonal_collisions))\n fitness_score = maxFitness - (horizontal_collisions + diagonal_collisions)\n #print(\"The fitness score is {}\".format(fitness_score))\n return fitness_score\n\n#Unit Test\n#itness_calculation([4, 1, 5, 8, 2, 7, 3, 6], 28)", "_____no_output_____" ], [ "def strength_of_chromosome(chromosome, maxFitness):\n return fitness_calculation(chromosome, maxFitness) / maxFitness\n\n#Unit Test\n#strength_of_chromosome([1, 1, 1, 1, 1, 1, 1, 1], 28)\n#strength_of_chromosome([4, 1, 5, 8, 2, 7, 3, 6], 28)", "_____no_output_____" ] ], [ [ "# Main Program for solution to get a 8-Queen sequence", "_____no_output_____" ] ], [ [ "# Main Program\n\nif __name__ == \"__main__\":\n # Calulate the target Fitness\n TargetFitness = (NumberofQueens * (NumberofQueens - 1)) /2\n print(\"Maximum score to achive is = {}\".format(TargetFitness))\n \n # Inital population\n Population = create_population(NumberofQueens, InitialPopulation)\n \n generation_counter = 0\n for iteration in range(NumberofIterations):\n MaxPopulationScore = max([fitness_calculation(chromozone, TargetFitness) for chromozone in Population])\n print(\"generation counter = {}, MaxPopulationScore = {}\".format(generation_counter, MaxPopulationScore))\n \n if (MaxPopulationScore != TargetFitness):\n # If the current population has no score matching target score, continue with next generation\n generation_counter = generation_counter + 1\n else:\n # Target score is achieved at this stage\n break\n \n print(\"Solved in generation {}\".format(generation_counter+1))\n for chromosome in Population:\n if (fitness_calculation(chromosome, TargetFitness) == TargetFitness):\n print(\"Solution =======> {}\".format(chromosome))", "Maximum score to achive is = 28.0\ngeneration counter = 0, MaxPopulationScore = 28.0\nSolved in generation 1\nSolution =======> [5, 2, 0, 7, 4, 1, 3, 6]\nSolution =======> [0, 5, 7, 2, 6, 3, 1, 4]\nSolution =======> [5, 2, 0, 6, 4, 7, 1, 3]\nSolution =======> [2, 4, 7, 3, 0, 6, 1, 5]\nSolution =======> [3, 1, 7, 5, 0, 2, 4, 6]\nSolution =======> [5, 2, 4, 7, 0, 3, 1, 6]\nSolution =======> [6, 1, 5, 2, 0, 3, 7, 4]\nSolution =======> [6, 3, 1, 7, 5, 0, 2, 4]\n" ], [ "create_chromozone(8)", "_____no_output_____" ], [ "create_chromozone(8)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4af8ab4095468193ed09db1dd861dc66a9c5ec09
93,238
ipynb
Jupyter Notebook
language_translation_through_RNN.ipynb
ZhangShiqiu1993/Language-Translation-through-RNN
c2ae3cba18162c5173e3cdc9040a841f90e69416
[ "MIT" ]
1
2017-08-31T06:40:13.000Z
2017-08-31T06:40:13.000Z
language_translation_through_RNN.ipynb
ZhangShiqiu1993/Language-Translation-through-RNN
c2ae3cba18162c5173e3cdc9040a841f90e69416
[ "MIT" ]
null
null
null
language_translation_through_RNN.ipynb
ZhangShiqiu1993/Language-Translation-through-RNN
c2ae3cba18162c5173e3cdc9040a841f90e69416
[ "MIT" ]
null
null
null
58.019913
405
0.610845
[ [ [ "# Language Translation\nIn this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French.\n## Get the Data\nSince translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport problem_unittests as tests\n\nsource_path = 'data/small_vocab_en'\ntarget_path = 'data/small_vocab_fr'\nsource_text = helper.load_data(source_path)\ntarget_text = helper.load_data(target_path)", "_____no_output_____" ] ], [ [ "## Explore the Data\nPlay around with view_sentence_range to view different parts of the data.", "_____no_output_____" ] ], [ [ "view_sentence_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()})))\n\nsentences = source_text.split('\\n')\nword_counts = [len(sentence.split()) for sentence in sentences]\nprint('Number of sentences: {}'.format(len(sentences)))\nprint('Average number of words in a sentence: {}'.format(np.average(word_counts)))\n\nprint()\nprint('English sentences {} to {}:'.format(*view_sentence_range))\nprint('\\n'.join(source_text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))\nprint()\nprint('French sentences {} to {}:'.format(*view_sentence_range))\nprint('\\n'.join(target_text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))", "Dataset Stats\nRoughly the number of unique words: 227\nNumber of sentences: 137861\nAverage number of words in a sentence: 13.225277634719028\n\nEnglish sentences 0 to 10:\nnew jersey is sometimes quiet during autumn , and it is snowy in april .\nthe united states is usually chilly during july , and it is usually freezing in november .\ncalifornia is usually quiet during march , and it is usually hot in june .\nthe united states is sometimes mild during june , and it is cold in september .\nyour least liked fruit is the grape , but my least liked is the apple .\nhis favorite fruit is the orange , but my favorite is the grape .\nparis is relaxing during december , but it is usually chilly in july .\nnew jersey is busy during spring , and it is never hot in march .\nour least liked fruit is the lemon , but my least liked is the grape .\nthe united states is sometimes busy during january , and it is sometimes warm in november .\n\nFrench sentences 0 to 10:\nnew jersey est parfois calme pendant l' automne , et il est neigeux en avril .\nles états-unis est généralement froid en juillet , et il gèle habituellement en novembre .\ncalifornia est généralement calme en mars , et il est généralement chaud en juin .\nles états-unis est parfois légère en juin , et il fait froid en septembre .\nvotre moins aimé fruit est le raisin , mais mon moins aimé est la pomme .\nson fruit préféré est l'orange , mais mon préféré est le raisin .\nparis est relaxant en décembre , mais il est généralement froid en juillet .\nnew jersey est occupé au printemps , et il est jamais chaude en mars .\nnotre fruit est moins aimé le citron , mais mon moins aimé est le raisin .\nles états-unis est parfois occupé en janvier , et il est parfois chaud en novembre .\n" ] ], [ [ "## Implement Preprocessing Function\n### Text to Word Ids\nAs you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function `text_to_ids()`, you'll turn `source_text` and `target_text` from words to ids. However, you need to add the `<EOS>` word id at the end of `target_text`. This will help the neural network predict when the sentence should end.\n\nYou can get the `<EOS>` word id by doing:\n```python\ntarget_vocab_to_int['<EOS>']\n```\nYou can get other word ids using `source_vocab_to_int` and `target_vocab_to_int`.", "_____no_output_____" ] ], [ [ "def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):\n \"\"\"\n Convert source and target text to proper word ids\n :param source_text: String that contains all the source text.\n :param target_text: String that contains all the target text.\n :param source_vocab_to_int: Dictionary to go from the source words to an id\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :return: A tuple of lists (source_id_text, target_id_text)\n \"\"\"\n source_id_text = []\n target_id_text = []\n \n for line in source_text.splitlines():\n source_id_text.append([source_vocab_to_int[word] for word in line.split()])\n \n EOS = target_vocab_to_int['<EOS>']\n for line in target_text.splitlines():\n target_id_text.append([target_vocab_to_int[word] for word in line.split()] + [EOS])\n \n return source_id_text, target_id_text\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_text_to_ids(text_to_ids)", "Tests Passed\n" ] ], [ [ "### Preprocess all the data and save it\nRunning the code cell below will preprocess all the data and save it to file.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nhelper.preprocess_and_save_data(source_path, target_path, text_to_ids)", "_____no_output_____" ] ], [ [ "# Check Point\nThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\nimport helper\n\n(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()", "_____no_output_____" ] ], [ [ "### Check the Version of TensorFlow and Access to GPU\nThis will check to make sure you have the correct version of TensorFlow and access to a GPU", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom distutils.version import LooseVersion\nimport warnings\nimport tensorflow as tf\nfrom tensorflow.python.layers.core import Dense\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.1'), 'Please use TensorFlow version 1.1 or newer'\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))", "TensorFlow Version: 1.1.0\nDefault GPU Device: /gpu:0\n" ] ], [ [ "## Build the Neural Network\nYou'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:\n- `model_inputs`\n- `process_decoder_input`\n- `encoding_layer`\n- `decoding_layer_train`\n- `decoding_layer_infer`\n- `decoding_layer`\n- `seq2seq_model`\n\n### Input\nImplement the `model_inputs()` function to create TF Placeholders for the Neural Network. It should create the following placeholders:\n\n- Input text placeholder named \"input\" using the TF Placeholder name parameter with rank 2.\n- Targets placeholder with rank 2.\n- Learning rate placeholder with rank 0.\n- Keep probability placeholder named \"keep_prob\" using the TF Placeholder name parameter with rank 0.\n- Target sequence length placeholder named \"target_sequence_length\" with rank 1\n- Max target sequence length tensor named \"max_target_len\" getting its value from applying tf.reduce_max on the target_sequence_length placeholder. Rank 0.\n- Source sequence length placeholder named \"source_sequence_length\" with rank 1\n\nReturn the placeholders in the following the tuple (input, targets, learning rate, keep probability, target sequence length, max target sequence length, source sequence length)", "_____no_output_____" ] ], [ [ "def model_inputs():\n \"\"\"\n Create TF Placeholders for input, targets, learning rate, and lengths of source and target sequences.\n :return: Tuple (input, targets, learning rate, keep probability, target sequence length,\n max target sequence length, source sequence length)\n \"\"\"\n input_ = tf.placeholder(tf.int32, shape=[None, None], name=\"input\")\n targets = tf.placeholder(tf.int32, shape=[None, None], name=\"targets\")\n learning_rate = tf.placeholder(tf.float32, shape=None)\n keep_prob = tf.placeholder(tf.float32, shape=None, name=\"keep_prob\")\n target_sequence_length = tf.placeholder(tf.int32, shape=[None], name=\"target_sequence_length\")\n max_target_len = tf.reduce_max(target_sequence_length, name=\"max_target_len\")\n source_sequence_length = tf.placeholder(tf.int32, shape=[None], name=\"source_sequence_length\")\n return input_, targets, learning_rate, keep_prob, target_sequence_length, max_target_len, source_sequence_length\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_model_inputs(model_inputs)", "Tests Passed\n" ] ], [ [ "### Process Decoder Input\nImplement `process_decoder_input` by removing the last word id from each batch in `target_data` and concat the GO ID to the begining of each batch.", "_____no_output_____" ] ], [ [ "def process_decoder_input(target_data, target_vocab_to_int, batch_size):\n \"\"\"\n Preprocess target data for encoding\n :param target_data: Target Placehoder\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :param batch_size: Batch Size\n :return: Preprocessed target data\n \"\"\"\n \n batches = tf.strided_slice(target_data, [0,0], [batch_size, -1], [1, 1])\n padding = tf.fill(dims=[batch_size, 1], value=target_vocab_to_int['<GO>'])\n preprocessed_target_data = tf.concat(values=[padding, batches], axis=1)\n return preprocessed_target_data\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_process_encoding_input(process_decoder_input)", "Tests Passed\n" ] ], [ [ "### Encoding\nImplement `encoding_layer()` to create a Encoder RNN layer:\n * Embed the encoder input using [`tf.contrib.layers.embed_sequence`](https://www.tensorflow.org/api_docs/python/tf/contrib/layers/embed_sequence)\n * Construct a [stacked](https://github.com/tensorflow/tensorflow/blob/6947f65a374ebf29e74bb71e36fd82760056d82c/tensorflow/docs_src/tutorials/recurrent.md#stacking-multiple-lstms) [`tf.contrib.rnn.LSTMCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/LSTMCell) wrapped in a [`tf.contrib.rnn.DropoutWrapper`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/DropoutWrapper)\n * Pass cell and embedded input to [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn)", "_____no_output_____" ] ], [ [ "from imp import reload\nreload(tests)\n\ndef encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, \n source_sequence_length, source_vocab_size, \n encoding_embedding_size):\n \"\"\"\n Create encoding layer\n :param rnn_inputs: Inputs for the RNN\n :param rnn_size: RNN Size\n :param num_layers: Number of layers\n :param keep_prob: Dropout keep probability\n :param source_sequence_length: a list of the lengths of each sequence in the batch\n :param source_vocab_size: vocabulary size of source data\n :param encoding_embedding_size: embedding size of source data\n :return: tuple (RNN output, RNN state)\n \"\"\"\n \n def build_cell():\n lstm = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))\n drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n return drop\n \n embed_input = tf.contrib.layers.embed_sequence(rnn_inputs, source_vocab_size, encoding_embedding_size)\n cell = tf.contrib.rnn.MultiRNNCell([build_cell() for _ in range(num_layers)]) \n output, state = tf.nn.dynamic_rnn(cell, embed_input, source_sequence_length, dtype=tf.float32)\n return output, state\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_encoding_layer(encoding_layer)", "Tests Passed\n" ] ], [ [ "### Decoding - Training\nCreate a training decoding layer:\n* Create a [`tf.contrib.seq2seq.TrainingHelper`](https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/TrainingHelper) \n* Create a [`tf.contrib.seq2seq.BasicDecoder`](https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/BasicDecoder)\n* Obtain the decoder outputs from [`tf.contrib.seq2seq.dynamic_decode`](https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/dynamic_decode)", "_____no_output_____" ] ], [ [ "def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, \n target_sequence_length, max_summary_length, \n output_layer, keep_prob):\n \"\"\"\n Create a decoding layer for training\n :param encoder_state: Encoder State\n :param dec_cell: Decoder RNN Cell\n :param dec_embed_input: Decoder embedded input\n :param target_sequence_length: The lengths of each sequence in the target batch\n :param max_summary_length: The length of the longest sequence in the batch\n :param output_layer: Function to apply the output layer\n :param keep_prob: Dropout keep probability\n :return: BasicDecoderOutput containing training logits and sample_id\n \"\"\"\n training_helper = tf.contrib.seq2seq.TrainingHelper(inputs=dec_embed_input,\n sequence_length=target_sequence_length,\n time_major=False)\n training_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell,\n training_helper,\n encoder_state,\n output_layer)\n training_decoder_output, _ = tf.contrib.seq2seq.dynamic_decode(training_decoder,\n impute_finished=True,\n maximum_iterations=max_summary_length)\n return training_decoder_output\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_decoding_layer_train(decoding_layer_train)", "Tests Passed\n" ] ], [ [ "### Decoding - Inference\nCreate inference decoder:\n* Create a [`tf.contrib.seq2seq.GreedyEmbeddingHelper`](https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/GreedyEmbeddingHelper)\n* Create a [`tf.contrib.seq2seq.BasicDecoder`](https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/BasicDecoder)\n* Obtain the decoder outputs from [`tf.contrib.seq2seq.dynamic_decode`](https://www.tensorflow.org/api_docs/python/tf/contrib/seq2seq/dynamic_decode)", "_____no_output_____" ] ], [ [ "def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,\n end_of_sequence_id, max_target_sequence_length,\n vocab_size, output_layer, batch_size, keep_prob):\n \"\"\"\n Create a decoding layer for inference\n :param encoder_state: Encoder state\n :param dec_cell: Decoder RNN Cell\n :param dec_embeddings: Decoder embeddings\n :param start_of_sequence_id: GO ID\n :param end_of_sequence_id: EOS Id\n :param max_target_sequence_length: Maximum length of target sequences\n :param vocab_size: Size of decoder/target vocabulary\n :param output_layer: Function to apply the output layer\n :param batch_size: Batch size\n :param keep_prob: Dropout keep probability\n :return: BasicDecoderOutput containing inference logits and sample_id\n \"\"\"\n start_tokens = tf.tile(tf.constant([start_of_sequence_id], dtype=tf.int32), [batch_size], name='start_tokens')\n \n inference_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(dec_embeddings,\n start_tokens,\n end_of_sequence_id)\n inference_decoder = tf.contrib.seq2seq.BasicDecoder(dec_cell,\n inference_helper,\n encoder_state,\n output_layer)\n inference_decoder_output, _ = tf.contrib.seq2seq.dynamic_decode(inference_decoder,\n impute_finished=True,\n maximum_iterations=max_target_sequence_length)\n return inference_decoder_output\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_decoding_layer_infer(decoding_layer_infer)", "Tests Passed\n" ] ], [ [ "### Build the Decoding Layer\nImplement `decoding_layer()` to create a Decoder RNN layer.\n\n* Embed the target sequences\n* Construct the decoder LSTM cell (just like you constructed the encoder cell above)\n* Create an output layer to map the outputs of the decoder to the elements of our vocabulary\n* Use the your `decoding_layer_train(encoder_state, dec_cell, dec_embed_input, target_sequence_length, max_target_sequence_length, output_layer, keep_prob)` function to get the training logits.\n* Use your `decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, max_target_sequence_length, vocab_size, output_layer, batch_size, keep_prob)` function to get the inference logits.\n\nNote: You'll need to use [tf.variable_scope](https://www.tensorflow.org/api_docs/python/tf/variable_scope) to share variables between training and inference.", "_____no_output_____" ] ], [ [ "def decoding_layer(dec_input, encoder_state,\n target_sequence_length, max_target_sequence_length,\n rnn_size,\n num_layers, target_vocab_to_int, target_vocab_size,\n batch_size, keep_prob, decoding_embedding_size):\n \"\"\"\n Create decoding layer\n :param dec_input: Decoder input\n :param encoder_state: Encoder state\n :param target_sequence_length: The lengths of each sequence in the target batch\n :param max_target_sequence_length: Maximum length of target sequences\n :param rnn_size: RNN Size\n :param num_layers: Number of layers\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :param target_vocab_size: Size of target vocabulary\n :param batch_size: The size of the batch\n :param keep_prob: Dropout keep probability\n :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)\n \"\"\"\n\n def build_cell():\n lstm = tf.contrib.rnn.LSTMCell(rnn_size, initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))\n drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)\n return drop\n \n dec_cell = tf.contrib.rnn.MultiRNNCell([build_cell() for _ in range(num_layers)]) \n \n start_of_sequence_id = target_vocab_to_int[\"<GO>\"]\n end_of_sequence_id = target_vocab_to_int['<EOS>']\n vocab_size = len(target_vocab_to_int)\n dec_embeddings = tf.Variable(tf.random_uniform([vocab_size, decoding_embedding_size]))\n dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input)\n output_layer = Dense(target_vocab_size, \n kernel_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1))\n \n\n with tf.variable_scope(\"decode\"):# as decoding_scope:\n training_decoder_output = decoding_layer_train(encoder_state, dec_cell, dec_embed_input, \n target_sequence_length, max_target_sequence_length, \n output_layer, keep_prob)\n\n# decoding_scope.reuse_variables\n with tf.variable_scope(\"decode\", reuse=True):\n inference_decoder_output = decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id,\n end_of_sequence_id, max_target_sequence_length,\n vocab_size, output_layer, batch_size, keep_prob)\n return training_decoder_output, inference_decoder_output\n\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_decoding_layer(decoding_layer)", "Tests Passed\n" ] ], [ [ "### Build the Neural Network\nApply the functions you implemented above to:\n\n- Apply embedding to the input data for the encoder.\n- Encode the input using your `encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size)`.\n- Process target data using your `process_decoder_input(target_data, target_vocab_to_int, batch_size)` function.\n- Apply embedding to the target data for the decoder.\n- Decode the encoded input using your `decoding_layer(dec_input, enc_state, target_sequence_length, max_target_sentence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, dec_embedding_size)` function.", "_____no_output_____" ] ], [ [ "def seq2seq_model(input_data, target_data, keep_prob, batch_size,\n source_sequence_length, target_sequence_length,\n max_target_sentence_length,\n source_vocab_size, target_vocab_size,\n enc_embedding_size, dec_embedding_size,\n rnn_size, num_layers, target_vocab_to_int):\n \"\"\"\n Build the Sequence-to-Sequence part of the neural network\n :param input_data: Input placeholder\n :param target_data: Target placeholder\n :param keep_prob: Dropout keep probability placeholder\n :param batch_size: Batch Size\n :param source_sequence_length: Sequence Lengths of source sequences in the batch\n :param target_sequence_length: Sequence Lengths of target sequences in the batch\n :param source_vocab_size: Source vocabulary size\n :param target_vocab_size: Target vocabulary size\n :param enc_embedding_size: Decoder embedding size\n :param dec_embedding_size: Encoder embedding size\n :param rnn_size: RNN Size\n :param num_layers: Number of layers\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :return: Tuple of (Training BasicDecoderOutput, Inference BasicDecoderOutput)\n \"\"\"\n _, encoder_state = encoding_layer(input_data, rnn_size, num_layers, keep_prob, \n source_sequence_length, source_vocab_size, enc_embedding_size)\n dec_input = process_decoder_input(target_data, target_vocab_to_int, batch_size)\n \n training_decoder_output, inference_decoder_output = decoding_layer(dec_input, \n encoder_state,\n target_sequence_length,\n max_target_sentence_length,\n rnn_size,\n num_layers, \n target_vocab_to_int, \n target_vocab_size,\n batch_size, \n keep_prob, \n dec_embedding_size)\n\n \n return training_decoder_output, inference_decoder_output\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_seq2seq_model(seq2seq_model)", "Tests Passed\n" ] ], [ [ "## Neural Network Training\n### Hyperparameters\nTune the following parameters:\n\n- Set `epochs` to the number of epochs.\n- Set `batch_size` to the batch size.\n- Set `rnn_size` to the size of the RNNs.\n- Set `num_layers` to the number of layers.\n- Set `encoding_embedding_size` to the size of the embedding for the encoder.\n- Set `decoding_embedding_size` to the size of the embedding for the decoder.\n- Set `learning_rate` to the learning rate.\n- Set `keep_probability` to the Dropout keep probability\n- Set `display_step` to state how many steps between each debug output statement", "_____no_output_____" ] ], [ [ "# Number of Epochs\nepochs = 8\n# Batch Size\nbatch_size = 128\n# RNN Size\nrnn_size = 256\n# Number of Layers\nnum_layers = 2\n# Embedding Size\nencoding_embedding_size = 200\ndecoding_embedding_size = 200\n# Learning Rate\nlearning_rate = 0.0005\n# Dropout Keep Probability\nkeep_probability = 0.75\ndisplay_step = 20", "_____no_output_____" ] ], [ [ "### Build the Graph\nBuild the graph using the neural network you implemented.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nsave_path = 'checkpoints/dev'\n(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()\nmax_target_sentence_length = max([len(sentence) for sentence in source_int_text])\n\ntrain_graph = tf.Graph()\nwith train_graph.as_default():\n input_data, targets, lr, keep_prob, target_sequence_length, max_target_sequence_length, source_sequence_length = model_inputs()\n\n #sequence_length = tf.placeholder_with_default(max_target_sentence_length, None, name='sequence_length')\n input_shape = tf.shape(input_data)\n\n train_logits, inference_logits = seq2seq_model(tf.reverse(input_data, [-1]),\n targets,\n keep_prob,\n batch_size,\n source_sequence_length,\n target_sequence_length,\n max_target_sequence_length,\n len(source_vocab_to_int),\n len(target_vocab_to_int),\n encoding_embedding_size,\n decoding_embedding_size,\n rnn_size,\n num_layers,\n target_vocab_to_int)\n\n\n training_logits = tf.identity(train_logits.rnn_output, name='logits')\n inference_logits = tf.identity(inference_logits.sample_id, name='predictions')\n\n masks = tf.sequence_mask(target_sequence_length, max_target_sequence_length, dtype=tf.float32, name='masks')\n\n with tf.name_scope(\"optimization\"):\n # Loss function\n cost = tf.contrib.seq2seq.sequence_loss(\n training_logits,\n targets,\n masks)\n\n # Optimizer\n optimizer = tf.train.AdamOptimizer(lr)\n\n # Gradient Clipping\n gradients = optimizer.compute_gradients(cost)\n capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]\n train_op = optimizer.apply_gradients(capped_gradients)\n", "_____no_output_____" ] ], [ [ "Batch and pad the source and target sequences", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\ndef pad_sentence_batch(sentence_batch, pad_int):\n \"\"\"Pad sentences with <PAD> so that each sentence of a batch has the same length\"\"\"\n max_sentence = max([len(sentence) for sentence in sentence_batch])\n return [sentence + [pad_int] * (max_sentence - len(sentence)) for sentence in sentence_batch]\n\n\ndef get_batches(sources, targets, batch_size, source_pad_int, target_pad_int):\n \"\"\"Batch targets, sources, and the lengths of their sentences together\"\"\"\n for batch_i in range(0, len(sources)//batch_size):\n start_i = batch_i * batch_size\n\n # Slice the right amount for the batch\n sources_batch = sources[start_i:start_i + batch_size]\n targets_batch = targets[start_i:start_i + batch_size]\n\n # Pad\n pad_sources_batch = np.array(pad_sentence_batch(sources_batch, source_pad_int))\n pad_targets_batch = np.array(pad_sentence_batch(targets_batch, target_pad_int))\n\n # Need the lengths for the _lengths parameters\n pad_targets_lengths = []\n for target in pad_targets_batch:\n pad_targets_lengths.append(len(target))\n\n pad_source_lengths = []\n for source in pad_sources_batch:\n pad_source_lengths.append(len(source))\n\n yield pad_sources_batch, pad_targets_batch, pad_source_lengths, pad_targets_lengths\n", "_____no_output_____" ] ], [ [ "### Train\nTrain the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\ndef get_accuracy(target, logits):\n \"\"\"\n Calculate accuracy\n \"\"\"\n max_seq = max(target.shape[1], logits.shape[1])\n if max_seq - target.shape[1]:\n target = np.pad(\n target,\n [(0,0),(0,max_seq - target.shape[1])],\n 'constant')\n if max_seq - logits.shape[1]:\n logits = np.pad(\n logits,\n [(0,0),(0,max_seq - logits.shape[1])],\n 'constant')\n\n return np.mean(np.equal(target, logits))\n\n# Split data to training and validation sets\ntrain_source = source_int_text[batch_size:]\ntrain_target = target_int_text[batch_size:]\nvalid_source = source_int_text[:batch_size]\nvalid_target = target_int_text[:batch_size]\n(valid_sources_batch, valid_targets_batch, valid_sources_lengths, valid_targets_lengths ) = next(get_batches(valid_source,\n valid_target,\n batch_size,\n source_vocab_to_int['<PAD>'],\n target_vocab_to_int['<PAD>'])) \nwith tf.Session(graph=train_graph) as sess:\n sess.run(tf.global_variables_initializer())\n\n for epoch_i in range(epochs):\n for batch_i, (source_batch, target_batch, sources_lengths, targets_lengths) in enumerate(\n get_batches(train_source, train_target, batch_size,\n source_vocab_to_int['<PAD>'],\n target_vocab_to_int['<PAD>'])):\n\n _, loss = sess.run(\n [train_op, cost],\n {input_data: source_batch,\n targets: target_batch,\n lr: learning_rate,\n target_sequence_length: targets_lengths,\n source_sequence_length: sources_lengths,\n keep_prob: keep_probability})\n\n\n if batch_i % display_step == 0 and batch_i > 0:\n\n\n batch_train_logits = sess.run(\n inference_logits,\n {input_data: source_batch,\n source_sequence_length: sources_lengths,\n target_sequence_length: targets_lengths,\n keep_prob: 1.0})\n\n\n batch_valid_logits = sess.run(\n inference_logits,\n {input_data: valid_sources_batch,\n source_sequence_length: valid_sources_lengths,\n target_sequence_length: valid_targets_lengths,\n keep_prob: 1.0})\n\n train_acc = get_accuracy(target_batch, batch_train_logits)\n\n valid_acc = get_accuracy(valid_targets_batch, batch_valid_logits)\n\n print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.4f}, Validation Accuracy: {:>6.4f}, Loss: {:>6.4f}'\n .format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss))\n\n # Save Model\n saver = tf.train.Saver()\n saver.save(sess, save_path)\n print('Model Trained and Saved')", "Epoch 0 Batch 20/1077 - Train Accuracy: 0.3414, Validation Accuracy: 0.3960, Loss: 3.3371\nEpoch 0 Batch 40/1077 - Train Accuracy: 0.4047, Validation Accuracy: 0.4652, Loss: 2.8415\nEpoch 0 Batch 60/1077 - Train Accuracy: 0.4572, Validation Accuracy: 0.5000, Loss: 2.4231\nEpoch 0 Batch 80/1077 - Train Accuracy: 0.4410, Validation Accuracy: 0.5032, Loss: 2.2779\nEpoch 0 Batch 100/1077 - Train Accuracy: 0.4719, Validation Accuracy: 0.5160, Loss: 2.0464\nEpoch 0 Batch 120/1077 - Train Accuracy: 0.4430, Validation Accuracy: 0.4982, Loss: 1.8774\nEpoch 0 Batch 140/1077 - Train Accuracy: 0.4165, Validation Accuracy: 0.5014, Loss: 1.8498\nEpoch 0 Batch 160/1077 - Train Accuracy: 0.4199, Validation Accuracy: 0.4581, Loss: 1.6562\nEpoch 0 Batch 180/1077 - Train Accuracy: 0.4152, Validation Accuracy: 0.4737, Loss: 1.5528\nEpoch 0 Batch 200/1077 - Train Accuracy: 0.4605, Validation Accuracy: 0.5050, Loss: 1.4777\nEpoch 0 Batch 220/1077 - Train Accuracy: 0.4827, Validation Accuracy: 0.5288, Loss: 1.4401\nEpoch 0 Batch 240/1077 - Train Accuracy: 0.4816, Validation Accuracy: 0.5334, Loss: 1.3446\nEpoch 0 Batch 260/1077 - Train Accuracy: 0.5134, Validation Accuracy: 0.5252, Loss: 1.2222\nEpoch 0 Batch 280/1077 - Train Accuracy: 0.5020, Validation Accuracy: 0.5323, Loss: 1.2762\nEpoch 0 Batch 300/1077 - Train Accuracy: 0.4638, Validation Accuracy: 0.5312, Loss: 1.2391\nEpoch 0 Batch 320/1077 - Train Accuracy: 0.4785, Validation Accuracy: 0.5273, Loss: 1.1420\nEpoch 0 Batch 340/1077 - Train Accuracy: 0.4778, Validation Accuracy: 0.5415, Loss: 1.1009\nEpoch 0 Batch 360/1077 - Train Accuracy: 0.4980, Validation Accuracy: 0.5490, Loss: 1.0411\nEpoch 0 Batch 380/1077 - Train Accuracy: 0.5148, Validation Accuracy: 0.5629, Loss: 0.9668\nEpoch 0 Batch 400/1077 - Train Accuracy: 0.5645, Validation Accuracy: 0.5778, Loss: 0.9761\nEpoch 0 Batch 420/1077 - Train Accuracy: 0.5703, Validation Accuracy: 0.6019, Loss: 0.9137\nEpoch 0 Batch 440/1077 - Train Accuracy: 0.5668, Validation Accuracy: 0.5969, Loss: 0.9314\nEpoch 0 Batch 460/1077 - Train Accuracy: 0.5586, Validation Accuracy: 0.6080, Loss: 0.8865\nEpoch 0 Batch 480/1077 - Train Accuracy: 0.5859, Validation Accuracy: 0.6037, Loss: 0.8712\nEpoch 0 Batch 500/1077 - Train Accuracy: 0.5934, Validation Accuracy: 0.6112, Loss: 0.8199\nEpoch 0 Batch 520/1077 - Train Accuracy: 0.6202, Validation Accuracy: 0.6094, Loss: 0.7458\nEpoch 0 Batch 540/1077 - Train Accuracy: 0.5848, Validation Accuracy: 0.6183, Loss: 0.7342\nEpoch 0 Batch 560/1077 - Train Accuracy: 0.5977, Validation Accuracy: 0.6325, Loss: 0.7264\nEpoch 0 Batch 580/1077 - Train Accuracy: 0.6503, Validation Accuracy: 0.6374, Loss: 0.6704\nEpoch 0 Batch 600/1077 - Train Accuracy: 0.6254, Validation Accuracy: 0.6364, Loss: 0.6741\nEpoch 0 Batch 620/1077 - Train Accuracy: 0.6125, Validation Accuracy: 0.6385, Loss: 0.6800\nEpoch 0 Batch 640/1077 - Train Accuracy: 0.6138, Validation Accuracy: 0.6584, Loss: 0.6566\nEpoch 0 Batch 660/1077 - Train Accuracy: 0.6172, Validation Accuracy: 0.6509, Loss: 0.6650\nEpoch 0 Batch 680/1077 - Train Accuracy: 0.6540, Validation Accuracy: 0.6783, Loss: 0.6327\nEpoch 0 Batch 700/1077 - Train Accuracy: 0.6535, Validation Accuracy: 0.6541, Loss: 0.6269\nEpoch 0 Batch 720/1077 - Train Accuracy: 0.6213, Validation Accuracy: 0.6381, Loss: 0.6823\nEpoch 0 Batch 740/1077 - Train Accuracy: 0.6520, Validation Accuracy: 0.6907, Loss: 0.5953\nEpoch 0 Batch 760/1077 - Train Accuracy: 0.6441, Validation Accuracy: 0.6722, Loss: 0.6204\nEpoch 0 Batch 780/1077 - Train Accuracy: 0.6309, Validation Accuracy: 0.6768, Loss: 0.6155\nEpoch 0 Batch 800/1077 - Train Accuracy: 0.6488, Validation Accuracy: 0.6797, Loss: 0.5799\nEpoch 0 Batch 820/1077 - Train Accuracy: 0.6770, Validation Accuracy: 0.6641, Loss: 0.5704\nEpoch 0 Batch 840/1077 - Train Accuracy: 0.6793, Validation Accuracy: 0.6797, Loss: 0.5245\nEpoch 0 Batch 860/1077 - Train Accuracy: 0.6927, Validation Accuracy: 0.6982, Loss: 0.5350\nEpoch 0 Batch 880/1077 - Train Accuracy: 0.7102, Validation Accuracy: 0.6776, Loss: 0.5119\nEpoch 0 Batch 900/1077 - Train Accuracy: 0.6973, Validation Accuracy: 0.6903, Loss: 0.5477\nEpoch 0 Batch 920/1077 - Train Accuracy: 0.6703, Validation Accuracy: 0.6950, Loss: 0.5066\nEpoch 0 Batch 940/1077 - Train Accuracy: 0.6949, Validation Accuracy: 0.7021, Loss: 0.4763\nEpoch 0 Batch 960/1077 - Train Accuracy: 0.6961, Validation Accuracy: 0.7042, Loss: 0.4580\nEpoch 0 Batch 980/1077 - Train Accuracy: 0.7406, Validation Accuracy: 0.6925, Loss: 0.4650\nEpoch 0 Batch 1000/1077 - Train Accuracy: 0.7619, Validation Accuracy: 0.7255, Loss: 0.4126\nEpoch 0 Batch 1020/1077 - Train Accuracy: 0.7629, Validation Accuracy: 0.7177, Loss: 0.4163\nEpoch 0 Batch 1040/1077 - Train Accuracy: 0.7175, Validation Accuracy: 0.7262, Loss: 0.4565\nEpoch 0 Batch 1060/1077 - Train Accuracy: 0.7508, Validation Accuracy: 0.7362, Loss: 0.3872\nEpoch 1 Batch 20/1077 - Train Accuracy: 0.7695, Validation Accuracy: 0.7546, Loss: 0.3656\nEpoch 1 Batch 40/1077 - Train Accuracy: 0.7777, Validation Accuracy: 0.7617, Loss: 0.3687\nEpoch 1 Batch 60/1077 - Train Accuracy: 0.7582, Validation Accuracy: 0.7518, Loss: 0.3449\nEpoch 1 Batch 80/1077 - Train Accuracy: 0.7934, Validation Accuracy: 0.7624, Loss: 0.3342\nEpoch 1 Batch 100/1077 - Train Accuracy: 0.8113, Validation Accuracy: 0.7951, Loss: 0.3455\nEpoch 1 Batch 120/1077 - Train Accuracy: 0.8008, Validation Accuracy: 0.7731, Loss: 0.3529\nEpoch 1 Batch 140/1077 - Train Accuracy: 0.7878, Validation Accuracy: 0.8136, Loss: 0.3338\nEpoch 1 Batch 160/1077 - Train Accuracy: 0.8367, Validation Accuracy: 0.7720, Loss: 0.2980\nEpoch 1 Batch 180/1077 - Train Accuracy: 0.7926, Validation Accuracy: 0.7816, Loss: 0.2871\nEpoch 1 Batch 200/1077 - Train Accuracy: 0.7918, Validation Accuracy: 0.7955, Loss: 0.3128\nEpoch 1 Batch 220/1077 - Train Accuracy: 0.8150, Validation Accuracy: 0.8029, Loss: 0.2959\nEpoch 1 Batch 240/1077 - Train Accuracy: 0.8703, Validation Accuracy: 0.8139, Loss: 0.2624\nEpoch 1 Batch 260/1077 - Train Accuracy: 0.8192, Validation Accuracy: 0.8086, Loss: 0.2437\nEpoch 1 Batch 280/1077 - Train Accuracy: 0.8148, Validation Accuracy: 0.8089, Loss: 0.2650\nEpoch 1 Batch 300/1077 - Train Accuracy: 0.8627, Validation Accuracy: 0.8153, Loss: 0.2420\nEpoch 1 Batch 320/1077 - Train Accuracy: 0.8582, Validation Accuracy: 0.8395, Loss: 0.2514\nEpoch 1 Batch 340/1077 - Train Accuracy: 0.8376, Validation Accuracy: 0.7983, Loss: 0.2427\nEpoch 1 Batch 360/1077 - Train Accuracy: 0.8313, Validation Accuracy: 0.8111, Loss: 0.2338\nEpoch 1 Batch 380/1077 - Train Accuracy: 0.8734, Validation Accuracy: 0.8413, Loss: 0.2155\nEpoch 1 Batch 400/1077 - Train Accuracy: 0.8562, Validation Accuracy: 0.8459, Loss: 0.2203\nEpoch 1 Batch 420/1077 - Train Accuracy: 0.8762, Validation Accuracy: 0.8459, Loss: 0.2085\nEpoch 1 Batch 440/1077 - Train Accuracy: 0.8453, Validation Accuracy: 0.8551, Loss: 0.2192\nEpoch 1 Batch 460/1077 - Train Accuracy: 0.8879, Validation Accuracy: 0.8366, Loss: 0.2087\nEpoch 1 Batch 480/1077 - Train Accuracy: 0.8886, Validation Accuracy: 0.8423, Loss: 0.1912\nEpoch 1 Batch 500/1077 - Train Accuracy: 0.8773, Validation Accuracy: 0.8406, Loss: 0.1748\nEpoch 1 Batch 520/1077 - Train Accuracy: 0.9051, Validation Accuracy: 0.8626, Loss: 0.1662\nEpoch 1 Batch 540/1077 - Train Accuracy: 0.8777, Validation Accuracy: 0.8580, Loss: 0.1606\nEpoch 1 Batch 560/1077 - Train Accuracy: 0.8723, Validation Accuracy: 0.8548, Loss: 0.1527\nEpoch 1 Batch 580/1077 - Train Accuracy: 0.8616, Validation Accuracy: 0.8583, Loss: 0.1494\nEpoch 1 Batch 600/1077 - Train Accuracy: 0.8906, Validation Accuracy: 0.8544, Loss: 0.1654\nEpoch 1 Batch 620/1077 - Train Accuracy: 0.9066, Validation Accuracy: 0.8857, Loss: 0.1624\nEpoch 1 Batch 640/1077 - Train Accuracy: 0.8813, Validation Accuracy: 0.8796, Loss: 0.1553\nEpoch 1 Batch 660/1077 - Train Accuracy: 0.8637, Validation Accuracy: 0.8477, Loss: 0.1488\nEpoch 1 Batch 680/1077 - Train Accuracy: 0.8586, Validation Accuracy: 0.8725, Loss: 0.1357\nEpoch 1 Batch 700/1077 - Train Accuracy: 0.9129, Validation Accuracy: 0.8679, Loss: 0.1227\n" ] ], [ [ "### Save Parameters\nSave the `batch_size` and `save_path` parameters for inference.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Save parameters for checkpoint\nhelper.save_params(save_path)", "_____no_output_____" ] ], [ [ "# Checkpoint", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport helper\nimport problem_unittests as tests\n\n_, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess()\nload_path = helper.load_params()", "_____no_output_____" ] ], [ [ "## Sentence to Sequence\nTo feed a sentence into the model for translation, you first need to preprocess it. Implement the function `sentence_to_seq()` to preprocess new sentences.\n\n- Convert the sentence to lowercase\n- Convert words into ids using `vocab_to_int`\n - Convert words not in the vocabulary, to the `<UNK>` word id.", "_____no_output_____" ] ], [ [ "def sentence_to_seq(sentence, vocab_to_int):\n \"\"\"\n Convert a sentence to a sequence of ids\n :param sentence: String\n :param vocab_to_int: Dictionary to go from the words to an id\n :return: List of word ids\n \"\"\"\n index = [vocab_to_int.get(word.lower(), vocab_to_int[\"<UNK>\"]) for word in sentence.split()]\n return index\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_sentence_to_seq(sentence_to_seq)", "Tests Passed\n" ] ], [ [ "## Translate\nThis will translate `translate_sentence` from English to French.", "_____no_output_____" ] ], [ [ "translate_sentence = 'he saw a old yellow truck .'\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\ntranslate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int)\n\nloaded_graph = tf.Graph()\nwith tf.Session(graph=loaded_graph) as sess:\n # Load saved model\n loader = tf.train.import_meta_graph(load_path + '.meta')\n loader.restore(sess, load_path)\n\n input_data = loaded_graph.get_tensor_by_name('input:0')\n logits = loaded_graph.get_tensor_by_name('predictions:0')\n target_sequence_length = loaded_graph.get_tensor_by_name('target_sequence_length:0')\n source_sequence_length = loaded_graph.get_tensor_by_name('source_sequence_length:0')\n keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n\n translate_logits = sess.run(logits, {input_data: [translate_sentence]*batch_size,\n target_sequence_length: [len(translate_sentence)*2]*batch_size,\n source_sequence_length: [len(translate_sentence)]*batch_size,\n keep_prob: 1.0})[0]\n\nprint('Input')\nprint(' Word Ids: {}'.format([i for i in translate_sentence]))\nprint(' English Words: {}'.format([source_int_to_vocab[i] for i in translate_sentence]))\n\nprint('\\nPrediction')\nprint(' Word Ids: {}'.format([i for i in translate_logits]))\nprint(' French Words: {}'.format(\" \".join([target_int_to_vocab[i] for i in translate_logits])))\n", "INFO:tensorflow:Restoring parameters from checkpoints/dev\nInput\n Word Ids: [29, 18, 40, 125, 121, 79, 110]\n English Words: ['he', 'saw', 'a', 'old', 'yellow', 'truck', '.']\n\nPrediction\n Word Ids: [18, 116, 77, 177, 224, 351, 189, 47, 1]\n French Words: il a vu un vieux camion jaune . <EOS>\n" ] ], [ [ "## Imperfect Translation\nYou might notice that some sentences translate better than others. Since the dataset you're using only has a vocabulary of 227 English words of the thousands that you use, you're only going to see good results using these words. For this project, you don't need a perfect translation. However, if you want to create a better translation model, you'll need better data.\n\nYou can train on the [WMT10 French-English corpus](http://www.statmt.org/wmt10/training-giga-fren.tar). This dataset has more vocabulary and richer in topics discussed. However, this will take you days to train, so make sure you've a GPU and the neural network is performing well on dataset we provided. Just make sure you play with the WMT10 corpus after you've submitted this project.\n## Submitting This Project\nWhen submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_language_translation.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4af8b752c04ee454968ded370faea74b24693b08
266,432
ipynb
Jupyter Notebook
notebooks/02-SequenceComparison.ipynb
lukexyz/DNA-Toolbox
1cea784beb63d87c061478e6b32b53a502d6fb8b
[ "MIT" ]
3
2020-05-11T13:21:56.000Z
2020-07-24T13:07:53.000Z
notebooks/02-SequenceComparison.ipynb
lukexyz/DNA-Toolbox
1cea784beb63d87c061478e6b32b53a502d6fb8b
[ "MIT" ]
null
null
null
notebooks/02-SequenceComparison.ipynb
lukexyz/DNA-Toolbox
1cea784beb63d87c061478e6b32b53a502d6fb8b
[ "MIT" ]
null
null
null
177.621333
101,424
0.880499
[ [ [ "# 🔬 Sequence Comparison of DNA using `BioPython`\n### 🦠 `Covid-19`, `SARS`, `MERS`, and `Ebola` \n\n#### Analysis Techniques:\n* Compare their DNA sequence and Protein (Amino Acid) sequence\n* GC Content\n* Freq of Each Amino Acids\n* Find similarity between them\n * Alignment\n * hamming distance\n* 3D structure of each\n\n| DNA Sequence | Datasource |\n|:-----------------|:--------------------------------------------------------------|\n| Latest Sequence | https://www.ncbi.nlm.nih.gov/genbank/sars-cov-2-seqs/ |\n| Wuhan-Hu-1 | https://www.ncbi.nlm.nih.gov/nuccore/MN908947.3?report=fasta |\n| Covid19 | https://www.ncbi.nlm.nih.gov/nuccore/NC_045512.2?report=fasta |\n| SARS | https://www.ncbi.nlm.nih.gov/nuccore/NC_004718.3?report=fasta |\n| MERS | https://www.ncbi.nlm.nih.gov/nuccore/NC_019843.3?report=fasta |\n| EBOLA | https://www.ncbi.nlm.nih.gov/nuccore/NC_002549.1?report=fasta |\n\n### 1. Analysis Techniques", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings('ignore')\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline", "_____no_output_____" ], [ "from Bio.Seq import Seq\n\n# Create our sequence \nseq1 = Seq('ACTCGA')\nseq2 = Seq('AC')", "_____no_output_____" ] ], [ [ "\n#### GC Contents In DNA \n\n* `GC-content` (or guanine-cytosine content) is the **percentage of nitrogenous bases** in a DNA or RNA molecule that are either guanine (`G`) or cytosine (`C`)\n\n#### Usefulness \n\n* In polymerase chain reaction (PCR) experiments, the GC-content of short oligonucleotides known as primers is often used to predict their **annealing temperature** to the template DNA.\n * A `high` GC-content level indicates a relatively higher melting temperature.\n * DNA with `low` GC-content is less stable than DNA with high GC-content \n\n> Question: which sequence is more stable when heat is applied?", "_____no_output_____" ] ], [ [ "from Bio.SeqUtils import GC\n# Check GC (guanine-cytosine) percentage in sequence\n\nprint(f\"{GC(seq1)}% \\t({seq1})\")\nprint(f\"{GC(seq2)}% \\t({seq2})\")", "50.0% \t(ACTCGA)\n50.0% \t(AC)\n" ] ], [ [ "### Sequence Alignment\n* `Global alignment` finds the best concordance/agreement between all characters in two sequences\n* `Local Alignment` finds just the subsequences that align the best", "_____no_output_____" ] ], [ [ "from Bio import pairwise2\nfrom Bio.pairwise2 import format_alignment\n\nprint('seq1 =', seq1, '\\nseq2 =', seq2, '\\n\\n')\n\n# Global alignment\nalignments = pairwise2.align.globalxx(seq1, seq2)\n\nprint(f'Alignments found: {len(alignments)}')\nprint(*alignments)", "seq1 = ACTCGA \nseq2 = AC \n\n\nAlignments found: 2\n('ACTCGA', 'A--C--', 2.0, 0, 6) ('ACTCGA', 'AC----', 2.0, 0, 6)\n" ], [ "# Print nicely\nprint(format_alignment(*alignments[0]))", "ACTCGA\n| | \nA--C--\n Score=2\n\n" ], [ "# 2nd alignment\nprint(format_alignment(*alignments[1]))", "ACTCGA\n|| \nAC----\n Score=2\n\n" ], [ "# To see all possible alignments\nfor a in alignments:\n print(format_alignment(*a), '\\n')", "ACTCGA\n| | \nA--C--\n Score=2\n \n\nACTCGA\n|| \nAC----\n Score=2\n \n\n" ], [ "# Get the number of possible sequence alignments\nalignment_score = pairwise2.align.globalxx(seq1,seq2,one_alignment_only=True,score_only=True)\nalignment_score", "_____no_output_____" ] ], [ [ "#### Sequence Similarity\n* Fraction of nucleotides that is the same/ total number of nucleotides * 100%", "_____no_output_____" ] ], [ [ "alignment_score/len(seq1)*100", "_____no_output_____" ] ], [ [ "### Hamming Distance: `How Many Subsitutions are Required to Match Two Sequences?`\n\n* Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.\n* In other words, it measures the minimum number of substitutions required to change one string into the other, or the minimum number of errors that could have transformed one string into the other\n* It is used for error detection or error correction\n* It is used to quantify the similarity of DNA sequences \n\n#### Edit Distance\n * Is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other (e.g. Levenshtein distance)", "_____no_output_____" ] ], [ [ "def hamming_distance(lhs, rhs):\n return len([(x,y) for x,y in zip(lhs,rhs) if x != y])", "_____no_output_____" ], [ "hamming_distance('TT', 'ACCTA')", "_____no_output_____" ], [ "def hammer_time(s1, s2, verbose=True):\n \"\"\"Take two nucleotide sequences s1 and s2, and display \n the possible alignments and hamming distance.\n \"\"\"\n if verbose:\n print('s1 =', s1, '\\ns2 =', s2, '\\n\\n')\n print('Hamming Distance:', hamming_distance(s1, s2), '\\n(min substitutions for sequences to match)')\n print('\\nAlignment Options:\\n\\n')\n alignments = pairwise2.align.globalxx(s1, s2)\n for a in alignments:\n print(format_alignment(*a), '\\n')\n \n\ns1 = 'ACTCGAA'\ns2 = 'ACGA'\nhammer_time(s1, s2)", "s1 = ACTCGAA \ns2 = ACGA \n\n\nHamming Distance: 2 \n(min substitutions for sequences to match)\n\nAlignment Options:\n\n\nACTCGAA\n| || |\nA--CG-A\n Score=4\n \n\nACTCGAA\n|| | |\nAC--G-A\n Score=4\n \n\nACTCGAA\n| ||| \nA--CGA-\n Score=4\n \n\nACTCGAA\n|| || \nAC--GA-\n Score=4\n \n\n" ] ], [ [ "### Dot Plot\n* A dot plot is a graphical method that allows the **comparison of two biological sequences** and identify regions of **close similarity** between them.\n* Simplest explanation: put a dot wherever sequences are identical\n\n#### Usefulness\nDot plots can also be used to visually inspect sequences for\n - Direct or inverted repeats\n - Regions with low sequence complexity\n - Similar regions\n - Repeated sequences\n - Sequence rearrangements\n - RNA structures\n - Gene order\n\nAcknowledgement: https://stackoverflow.com/questions/40822400/how-to-create-a-dotplot-of-two-dna-sequence-in-python", "_____no_output_____" ] ], [ [ "def delta(x,y):\n return 0 if x == y else 1\n\ndef M(seq1,seq2,i,j,k):\n return sum(delta(x,y) for x,y in zip(seq1[i:i+k],seq2[j:j+k]))\n\ndef makeMatrix(seq1,seq2,k):\n n = len(seq1)\n m = len(seq2)\n return [[M(seq1,seq2,i,j,k) for j in range(m-k+1)] for i in range(n-k+1)]\n\ndef plotMatrix(M,t, seq1, seq2, nonblank = chr(0x25A0), blank = ' '):\n print(' |' + seq2)\n print('-'*(2 + len(seq2)))\n for label,row in zip(seq1,M):\n line = ''.join(nonblank if s < t else blank for s in row)\n print(label + '|' + line)\n\ndef dotplot(seq1,seq2,k = 1,t = 1):\n M = makeMatrix(seq1,seq2,k)\n plotMatrix(M, t, seq1,seq2) #experiment with character choice", "_____no_output_____" ], [ "# The dot plot: put a dot where the two sequences are identical\n\ns1 = 'ACTCGA'\ns2 = 'AC'\n\ndotplot(s1, s2)", " |AC\n----\nA|■ \nC| ■\nT| \nC| ■\nG| \nA|■ \n" ], [ "# Identical proteins will show a diagonal line.\ns1 = 'ACCTAG'\ns2 = 'ACCTAG'\n\ndotplot(s1, s2)\n\nprint('\\n\\n')\nhammer_time(s1, s2, verbose=False)", " |ACCTAG\n--------\nA|■ ■ \nC| ■■ \nC| ■■ \nT| ■ \nA|■ ■ \nG| ■\n\n\n\nACCTAG\n||||||\nACCTAG\n Score=6\n \n\n" ] ], [ [ "# 🔬 2. Comparative Analysis of Virus DNA\n### 🦠 `Covid-19`, `SARS`, `MERS`, `Ebola` \n\n\n* Covid19(`SARS-CoV2`) is a novel coronavirus identified as the cause of coronavirus disease 2019 (COVID-19) that began in Wuhan, China in late 2019 and spread worldwide.\n* MERS(`MERS-CoV`) was identified in 2012 as the cause of Middle East respiratory syndrome (MERS).\n* SARS(`SARS-CoV`) was identified in 2002 as the cause of an outbreak of severe acute respiratory syndrome (SARS).\n\n#### `fasta` DNA Sequence Files\n* Covid19 : https://www.rcsb.org/3d-view/6LU7\n* SARS: https://www.ncbi.nlm.nih.gov/nuccore/NC_004718.3?report=fasta\n* MERS: https://www.ncbi.nlm.nih.gov/nuccore/NC_019843.3?report=fasta\n* EBOLA:https://www.rcsb.org/structure/6HS4", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom Bio import SeqIO\n\ncovid = SeqIO.read(\"../data/01_COVID_MN908947.3.fasta\",\"fasta\")\nmers = SeqIO.read(\"../data/02_MERS_NC_019843.3.fasta\",\"fasta\")\nsars = SeqIO.read(\"../data/03_SARS_rcsb_pdb_5XES.fasta\",\"fasta\")\nebola = SeqIO.read(\"../data/04_EBOLA_rcsb_pdb_6HS4.fasta\",\"fasta\")\n\n# Convert imports to BioPython sequences\ncovid_seq = covid.seq\nmers_seq = mers.seq\nsars_seq = sars.seq\nebola_seq = ebola.seq\n\n# Create dataframe\ndf = pd.DataFrame({'name': ['COVID19', 'MERS', 'SARS', 'EBOLA'],\n 'seq': [covid_seq, mers_seq, sars_seq, ebola_seq]})\ndf", "_____no_output_____" ] ], [ [ "#### Length of Each Genome", "_____no_output_____" ] ], [ [ "df['len'] = df.seq.apply(lambda x: len(x))\n\ndf[['name', 'len']].sort_values('len', ascending=False) \\\n .style.bar(color='#cde8F6', vmin=0, width=100, align='left')", "_____no_output_____" ] ], [ [ "* `MERS`, `COVID` and `SARS` all have about the same genome length (30,000 base pairs)", "_____no_output_____" ], [ "#### Which of them is more heat stable?", "_____no_output_____" ] ], [ [ "# Check the GC content\ndf['gc_content'] = df.seq.apply(lambda x: GC(x))\n\ndf[['name', 'gc_content']].sort_values('gc_content', ascending=False) \\\n .style.bar(color='#cde8F6', vmin=0)", "_____no_output_____" ] ], [ [ "* `MERS` is the most stable with a GC of `41.24` followed by Ebola", "_____no_output_____" ], [ "#### Translate RNA into proteins \nHow many proteins are in each dna sequence?", "_____no_output_____" ] ], [ [ "# Translate the RNA into Proteins\ndf['proteins'] = df.seq.apply(lambda s: len(s.translate()))\n\ndf[['name', 'proteins']].sort_values('proteins', ascending=False) \\\n .style.bar(color='#cde8F6', vmin=0)", "_____no_output_____" ] ], [ [ "#### How Many Amino Acids are Created?", "_____no_output_____" ] ], [ [ "from Bio.SeqUtils.ProtParam import ProteinAnalysis\nfrom collections import Counter", "_____no_output_____" ], [ "# Method 1\ncovid_analysed = ProteinAnalysis(str(covid_protein))\nmers_analysed = ProteinAnalysis(str(mers_protein))\nsars_analysed = ProteinAnalysis(str(sars_protein))\nebola_analysed = ProteinAnalysis(str(ebola_protein))", "_____no_output_____" ], [ "# Check for the Frequence of AA\ncovid_analysed.count_amino_acids()", "_____no_output_____" ], [ "# Method 2\nfrom collections import Counter\n\n# Find the Amino Acid Frequency\ndf['aa_freq'] = df.seq.apply(lambda s: Counter(s.translate()))\ndf", "_____no_output_____" ] ], [ [ "#### Most Common Amino Acid", "_____no_output_____" ] ], [ [ "# For Covid\ndf[df.name=='COVID19'].aa_freq.values[0].most_common(10)", "_____no_output_____" ], [ "# Plot the Amino Acids of COVID-19\n\naa = df[df.name=='COVID19'].aa_freq.values[0]\nplt.bar(aa.keys(), aa.values())", "_____no_output_____" ], [ "# All viruses -- same chart (not stacked)\n\nfor virus in df.name:\n aa = df[df.name==virus].aa_freq.values[0]\n plt.bar(aa.keys(), aa.values())\nplt.show()", "_____no_output_____" ] ], [ [ "### Dot Plots of Opening Sequences", "_____no_output_____" ] ], [ [ "# COVID and MERS\ndotplot(covid_seq[0:10],mers_seq[0:10])", " |GATTTAAGTG\n------------\nA| ■ ■■ \nT| ■■■ ■ \nT| ■■■ ■ \nA| ■ ■■ \nA| ■ ■■ \nA| ■ ■■ \nG|■ ■ ■\nG|■ ■ ■\nT| ■■■ ■ \nT| ■■■ ■ \n" ], [ "# COVID and SARS\nn = 10\ndotplot(covid_seq[0:n],sars_seq[0:n])", " |ATATTAGGTT\n------------\nA|■ ■ ■ \nT| ■ ■■ ■■\nT| ■ ■■ ■■\nA|■ ■ ■ \nA|■ ■ ■ \nA|■ ■ ■ \nG| ■■ \nG| ■■ \nT| ■ ■■ ■■\nT| ■ ■■ ■■\n" ], [ "# Plotting function to illustrate deeper matches\n\ndef dotplotx(seq1, seq2, n):\n seq1=seq1[0:n]\n seq2=seq2[0:n]\n plt.imshow(np.array(makeMatrix(seq1,seq2,1)))\n # on x-axis list all sequences of seq 2\n xt=plt.xticks(np.arange(len(list(seq2))),list(seq2))\n # on y-axis list all sequences of seq 1\n yt=plt.yticks(np.arange(len(list(seq1))),list(seq1))\n plt.show()\n \ndotplotx(covid_seq, sars_seq, n=100)", "_____no_output_____" ] ], [ [ "Notice the large diagonal line for the second half of the first 100 nucleotides - indicating these are the same for `COVID19` and `SARS`", "_____no_output_____" ] ], [ [ "dotplotx(covid_seq, ebola_seq, n=100)", "_____no_output_____" ] ], [ [ "No corresponding matches for `EBOLA` and `COVID`", "_____no_output_____" ], [ "#### Calculate Pairwise Alignment for the First 100 Nucleotides\n", "_____no_output_____" ] ], [ [ "\ndef pairwise_alignment(s1, s2, n):\n if n == 'full': n = min(len(s1), len(s2))\n alignment = pairwise2.align.globalxx(s1[0:n], s2[0:n], one_alignment_only=True, score_only=True)\n print(f'Pairwise alignment: {alignment:.0f}/{n} ({(alignment/n)*100:0.1f}%)')\n\n \n# SARS and COVID \npairwise_alignment(covid_seq, sars_seq, n=100)", "Pairwise alignment: 89/100 (89.0%)\n" ], [ "pairwise_alignment(covid_seq, sars_seq, n=10000)", "Pairwise alignment: 7895/10000 (79.0%)\n" ], [ "pairwise_alignment(covid_seq, sars_seq, n=len(sars_seq))", "Pairwise alignment: 24654/29751 (82.9%)\n" ] ], [ [ "* `82.9`% of the COVID19 genome is exactly the same as SARS", "_____no_output_____" ] ], [ [ "pairwise_alignment(covid_seq, mers_seq, n='full')", "Pairwise alignment: 20778/29903 (69.5%)\n" ], [ "pairwise_alignment(covid_seq, ebola_seq, n='full')", "Pairwise alignment: 12377/18959 (65.3%)\n" ] ], [ [ "* `COVID19` and `SARS` have a `82.9`% similarity. Both are of the same genus and belong to `Sars_Cov`.\n* `COVID19` and `EBOLA` have a `65.3`% similarity since they are from a different family of virus", "_____no_output_____" ], [ "### Example of the Opening Sequence of `COVID19` and `SARS`\nSequencing found similar structure from `40:100` so lets use our functions to visualise it.", "_____no_output_____" ] ], [ [ "s1 = covid_seq[40:100]\ns2 = sars_seq[40:100]\n\nprint('Similarity matrix (look for diagonal)')\ndotplotx(s1, s2, n=100)\n\nprint('Possible alignment pathways: \\n\\n')\nhammer_time(s1, s2, verbose=False)", "Similarity matrix (look for diagonal)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4af8b91c23b62f22ef1b7e5d3c7ec54e71c93982
101,658
ipynb
Jupyter Notebook
stoppedflow-analysis.ipynb
YijieTang/stoppedflow-data-processor
254b678c2b3f1d94d129a38996ee924fa097b2fa
[ "MIT" ]
1
2019-11-10T00:00:02.000Z
2019-11-10T00:00:02.000Z
stoppedflow-analysis.ipynb
YijieTang/stoppedflow-data-processor
254b678c2b3f1d94d129a38996ee924fa097b2fa
[ "MIT" ]
null
null
null
stoppedflow-analysis.ipynb
YijieTang/stoppedflow-data-processor
254b678c2b3f1d94d129a38996ee924fa097b2fa
[ "MIT" ]
null
null
null
29.50029
273
0.565691
[ [ [ "<span style=\"font-size:20pt;color:blue\">Add title here</span>\n\nThis is a sample file of interactive stopped-flow data analysis. You do <b>NOT</b> need to understand python language to use this program. By replacing file names and options with your own, you can easily produce figures and interactively adjust plotting optinos. \n\nIt is strongly recommended to keep this file for reference, and make edits on a duplication of this file. ", "_____no_output_____" ], [ "# import libraries and define functions\n<span style=\"color:red\">Press Ctrl+Enter to run sections</span>", "_____no_output_____" ] ], [ [ "# import mpld3\n# mpld3.enable_notebook()\n%matplotlib widget\nfrom sf_utils import *\nfrom uv_utils import *", "_____no_output_____" ] ], [ [ "# compare multiple inputs on selected lines\nIn many cases, the same trace may be repeated for several times. This ", "_____no_output_____" ] ], [ [ "rcParams['figure.figsize'] = [6, 4.5]\ncsvfiles = [\n 'average-sample-10s-1.csv',\n 'average-sample-10s-2.csv',\n 'average-sample-10s-3.csv',\n]\n\n\nsfData = SFData.quickload_csv(csvfiles)\n\nsfData.plot_selected_kinetics()\ndisplay(widgets.HBox([sfData.add_logx_button(), sfData.plot_scan_wavelength_button()]))\nsfData.plot_interactive_buttons_for_kinetics()", "_____no_output_____" ] ], [ [ "# save averaged files", "_____no_output_____" ] ], [ [ "csvfiles = [\n 'average-sample-10s-1.csv',\n 'average-sample-10s-2.csv',\n 'average-sample-10s-3.csv',\n]\n\nsave_average(csvfiles)", "averaged file name is: average-sample-10s-ave.csv\n" ] ], [ [ "# plot full spectra with more options", "_____no_output_____" ], [ "## plot with table", "_____no_output_____" ] ], [ [ "df = pd.DataFrame(\n columns=['csvfile', 'legend', 'shift', 'scale', 'color', 'timepoint'],\n data=[\n ['average-sample-10s-ave.csv', '0.003s', 0, 1, 'black', 0.003],\n ['average-sample-10s-ave.csv', '0.01s', 0, 1, 'red', 0.01],\n ['average-sample-10s-ave.csv', '0.1s', 0, 1, 'blue', 0.1],\n ['average-sample-10s-ave.csv', '1s', 0, 1, 'orange', 1],\n ['average-sample-10s-ave.csv', '10s', 0, 1, 'green', 10],\n ]\n)\n\nbase = pd.DataFrame(\n columns=['csvfile', 'timepoint'],\n data=[\n ['average-sample-10s-ave.csv', 0.002],\n ]\n)\n\n# plot_from_df(df, valuetype='timepoint') # no subtraction\nplot_from_df(df, valuetype='timepoint', base=base) # subtract spectra at certain timepoint", "_____no_output_____" ] ], [ [ "## plot with variables (lower level API)", "_____no_output_____" ] ], [ [ "rcParams['figure.figsize'] = [6, 4.5]\nfig = plt.figure()\naxis = fig.gca()\n\ncsvfiles = [\n 'average-sample-10s-ave.csv',\n 'average-sample-10s-ave.csv',\n 'average-sample-10s-ave.csv',\n 'average-sample-10s-ave.csv',\n 'average-sample-10s-ave.csv',\n]\n\ndfs = list(map(load_data, csvfiles))\ndf_base = dfs[0].iloc[1,:]\ndfs = [df - df_base for df in dfs]\n\ntimepoints = [\n [0.003],\n [0.01],\n [0.1],\n [1],\n [10]\n]\n\nlegends = [\n ['0.003s'],\n ['0.01s'],\n ['0.1s'],\n ['1s'],\n ['10s']\n]\n\nshifts = [\n [0],\n [0],\n [0],\n [0],\n [0]\n]\n\nscales = [\n [1],\n [1],\n [1],\n [1],\n [1],\n]\n\ncolors = [\n ['black'],\n ['red'],\n ['blue'],\n ['orange'],\n ['green']\n]\n\nsfData = SFData(\n axis=axis,\n dfs=dfs,\n colors=colors,\n legends=legends,\n scales=scales,\n shifts=shifts,\n xlabel='Time (s)',\n ylabel='Abs',\n)\n\nsfData.plot_selected_spectra(timepoints)\n# display(widgets.HBox([sfData.plot_scan_timepoint_button()]))\nsfData.plot_interactive_buttons_for_spectra()", "_____no_output_____" ] ], [ [ "# plot kinetic curves with more options", "_____no_output_____" ], [ "## plot with table", "_____no_output_____" ] ], [ [ "df = pd.DataFrame(\n columns=['csvfile', 'legend', 'shift', 'scale', 'color', 'wavelength'],\n data=[\n ['average-sample-10s-ave.csv', '350nm', 0, 1, 'black', 350],\n ['average-sample-10s-ave.csv', '400nm', 0, 1, 'red', 400],\n ['average-sample-10s-ave.csv', '450nm', 0, 1, 'blue', 450],\n ]\n)\n\nbase = pd.DataFrame(\n columns=['csvfile', 'timepoint'],\n data=[\n ['average-sample-10s-ave.csv', 0.002],\n ]\n)\n\n# plot_from_df(df, valuetype='wavelength') \nplot_from_df(df, valuetype='wavelength', base=base)", "_____no_output_____" ] ], [ [ "## plot with variables (lower level API)", "_____no_output_____" ] ], [ [ "rcParams['figure.figsize'] = [6, 4.5]\nfig = plt.figure()\naxis = fig.gca()\n\ncsvfiles = [\n 'average-sample-10s-ave.csv',\n 'average-sample-10s-ave.csv',\n 'average-sample-10s-ave.csv',\n]\n\ndfs = list(map(load_data, csvfiles))\n\ndf_base = dfs[0].iloc[1,:]\ndfs = [df - df_base for df in dfs]\n\nwavelengths = [\n [350],\n [400],\n [450],\n]\n\nlegends = [\n ['350 nm'],\n ['400 nm'],\n ['450 nm'],\n]\n\nshifts = [\n [0],\n [0],\n [0],\n]\n\nscales = [\n [1],\n [1],\n [1],\n]\n\ncolors = [\n ['black'],\n ['red'],\n ['blue'],\n]\n\nsfData = SFData(\n axis=axis,\n dfs=dfs,\n colors=colors,\n legends=legends,\n scales=scales,\n shifts=shifts,\n xlabel='Time (s)',\n ylabel='Abs',\n)\n\nsfData.plot_selected_kinetics(wavelengths)\ndisplay(sfData.add_logx_button())\n# display(widgets.HBoxsfDataData.add_logx_button(), sfData.plot_scan_wavelength_button()]))\nsfData.plot_interactive_buttons_for_kinetics()", "_____no_output_____" ] ], [ [ "# overview - kinetic curve and full spectra\n<span style=\"color:red\">Warning: this section is slow</span>", "_____no_output_____" ] ], [ [ "rcParams['figure.figsize'] = [9, 4.5]\ncsvfile = 'average-sample-10s-ave.csv'\ndf = load_data(csvfile)\n(row, col) = (1, 2)\nfig, axs = plt.subplots(row, col, sharex=False, sharey=False)\naxis1 = axs[0] # first axis\naxis2 = axs[1] # second axis\n\nplot_all_kinetic(df, axis1)\nplot_all_spectra(df, axis2)", "_____no_output_____" ] ], [ [ "# overview - difference spectra\n<span style=\"color:red\">Warning: this section is slow</span>", "_____no_output_____" ] ], [ [ "rcParams['figure.figsize'] = [9, 4.5]\ndf = load_data(csvfile)\nbaseCurve = df.iloc[1,:] # select the second time point as baseline\ndiffDf = df - baseCurve\ndf1 = df - baseCurve\n(row, col) = (1, 2)\nfig, axs = plt.subplots(row, col, sharex=False, sharey=False)\naxis1 = axs[0] # first axis\naxis2 = axs[1] # second axis\n\nplot_all_kinetic(df1, axis1)\nplot_all_spectra(df1, axis2)", "_____no_output_____" ] ], [ [ "# export kintek input files", "_____no_output_____" ] ], [ [ "csvfile = 'kintek-sample-1-10s.csv'\nwavelengths = [440]\nkintekFileName = 'kintek-sample-1-10s-data.txt'\nexport_kintek(csvfile, wavelengths, kintekFileName)\n\ncsvfile = 'kintek-sample-2-10s.csv'\nwavelengths = [440]\nkintekFileName = 'kintek-sample-2-10s-data.txt'\nexport_kintek(csvfile, wavelengths, kintekFileName)", "kintek input file saved as kintek-sample-1-10s-data.txt\nkintek input file saved as kintek-sample-2-10s-data.txt\n" ] ], [ [ "# plot original kinetic and kintek simulation", "_____no_output_____" ] ], [ [ "rcParams['figure.figsize'] = [6, 4.5]\nrcParams.update({'xtick.labelsize': 14})\nrcParams.update({'ytick.labelsize': 14})\nrcParams.update({'axes.labelsize':16})\nrcParams.update({'legend.frameon': False})\nrcParams.update({'legend.fontsize': 14})\n\nsimfiles = [\n 'kintek-sample-1-10s-data.txt',\n 'kintek-sample-2-10s-data.txt',\n 'kintek-sample-1-10s-sim.txt',\n 'kintek-sample-2-10s-sim.txt',\n]\n\ndfs = list(map(read_kintek_simulation, simfiles))\n\ndf = pd.concat(dfs, axis=1)\ndf = df[df.index > 0.002] # filter the value range to plot\ndf = df[df.index < 0.8] # filter the value range to plot\n\naPlot = AdjustablePlot.quickload_df(df)\naPlot.colors = ['red', '#0080ff', 'black', 'black']\naPlot.shifts = [0.007, 0, 0.007, 0]\naPlot.legends = ['1', '2', '1-sim', '2-sim']\naPlot.plot()\n\naPlot.axis.set_xscale('log')\naPlot.axis.set_xlim([0.001, 1])\n# aPlot.axis.set_ylim([-0.019, 0.029])\n\nfor i in range(2):\n line = aPlot.axis.lines[i]\n line.set_marker('.')\n line.set_linewidth(0)\n line.set_markersize(5)\n\naPlot.axis.lines[-1].set_linestyle('dashed')\naPlot.plot_interactive_buttons()\n_ = aPlot.axis.legend().set_draggable(True)\n_ = aPlot.axis.set_xlabel('Time (s)')\n_ = aPlot.axis.set_ylabel('ΔAbs')", "_____no_output_____" ] ], [ [ "# plot UV-Vis titration data", "_____no_output_____" ], [ "## plot titration", "_____no_output_____" ] ], [ [ "rcParams['figure.figsize'] = [6, 4.5]\n\nuv_filenames = [\n 'titration_and_UV/2.0.CSV', \n 'titration_and_UV/2.1.CSV',\n 'titration_and_UV/2.2.CSV',\n 'titration_and_UV/2.3.CSV',\n 'titration_and_UV/2.4.CSV',\n 'titration_and_UV/2.5.CSV',\n 'titration_and_UV/2.6.CSV',\n 'titration_and_UV/2.7.CSV',\n 'titration_and_UV/2.8.CSV',\n 'titration_and_UV/2.9.CSV',\n]\ndf = read_multiple_uv_to_df(uv_filenames)\naPlot = AdjustablePlot.quickload_df(df)\n\naPlot.colors = color_range('red', 'black', len(uv_filenames))\n# calculate shift on each spectra to remove baseline floating issue\n# aPlot.shifts = shift_to_align_wavelength(df, wavelength=1000)\naPlot.legends = ['%5.1f eq aKG' % (0.5*i) for i in range(len(uv_filenames))]\n\n\naPlot.plot()\naPlot.plot_interactive_buttons()\n\naPlot.axis.set_xlim([320, 1100])\naPlot.axis.set_ylim([-0.2, 1.2])\naPlot.axis.set_title('Titration: PIsnB + 4Fe + 4TyrNC + n*0.5aKG')\naPlot.axis.set_xlabel('wavelength (nm)')\naPlot.axis.set_ylabel('Abs')", "_____no_output_____" ] ], [ [ "## subtraction", "_____no_output_____" ] ], [ [ "# subtract base\nbase = aPlot.df.iloc[:,[0]]\naPlot.df = aPlot.df - base.values\n\n# plot in a new figure\naPlot.axis = plt.figure().gca()\naPlot.plot()\naPlot.plot_interactive_buttons()\n\naPlot.axis.set_xlim([350, 1100])\naPlot.axis.set_ylim([-0.02, 0.15])\naPlot.axis.set_title('Titration: PIsnB + 4Fe + 4TyrNC + n*0.5aKG')\naPlot.axis.set_xlabel('wavelength (nm)')\naPlot.axis.set_ylabel('ΔAbs')", "_____no_output_____" ] ], [ [ "## remove baseline shift", "_____no_output_____" ] ], [ [ "# subtract base\nbase = aPlot.df.iloc[:,[0]]\naPlot.df = aPlot.df - base.values\n\n# remove baseline shift\naPlot.shifts = shift_to_align_wavelength(aPlot.df, wavelength=800)\n\n# plot in a new figure\naPlot.axis = plt.figure().gca()\naPlot.plot()\naPlot.plot_interactive_buttons()\n\naPlot.axis.set_xlim([350, 1100])\naPlot.axis.set_ylim([-0.02, 0.12])\naPlot.axis.set_title('Titration: PIsnB + 4Fe + 4TyrNC + n*0.5aKG')\naPlot.axis.set_xlabel('wavelength (nm)')\naPlot.axis.set_ylabel('ΔAbs')", "_____no_output_____" ] ], [ [ "## plot trend at certain x value", "_____no_output_____" ] ], [ [ "df_trace512 = aPlot.df.iloc[[get_index_of_closest_x_value(aPlot.df, 512)], :].transpose()\ndf_trace512.index = [0.5*i for i in range(len(uv_filenames))]\ntrace512Plot = AdjustablePlot.quickload_df(df_trace512)\ntrace512Plot.plot()\ntrace512Plot.plot_interactive_buttons()\n\n\ntrace512Plot.axis.lines[0].set_marker('o')\n\ntrace512Plot.axis.legend().set_draggable(True)\ntrace512Plot.axis.set_xlabel('equivalent of aKG')\ntrace512Plot.axis.set_ylabel('ΔAbs at 512 nm')", "_____no_output_____" ] ], [ [ "# Appendix: more options", "_____no_output_____" ] ], [ [ "# global settings\n# two semantics are equivalent\n# more options can be found at https://matplotlib.org/users/customizing.html\n# set figure size\nrcParams['figure.figsize'] = [9, 4.5]\n# set tick pointing inwards or outwards\nrcParams['xtick.direction'] = 'in'\nrcParams['ytick.direction'] = 'in'\n# set visibility of minor ticks\nrcParams['xtick.minor.visible'] = True\nrcParams['ytick.minor.visible'] = True\n# set ticks on top and right axes\nrcParams['xtick.top'] = True\nrcParams['ytick.right'] = True\n# set better layout for multiple plots in a figure\n# https://matplotlib.org/3.1.1/tutorials/intermediate/tight_layout_guide.html\nrcParams.update({'figure.autolayout': True})\n# set x and y label size\nrcParams.update({'axes.labelsize': 20})\n# set tick label size\nrcParams.update({'xtick.labelsize': 12})\nrcParams.update({'ytick.labelsize': 12})\n# turn on/off frame of legend box\nrcParams.update({'legend.frameon': False})\n# set legend fontsize\nrcParams.update({'legend.fontsize': 10})", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af8c1a2f0fa75027f4afde1e84203cef958c027
31,757
ipynb
Jupyter Notebook
sample-code/future-lectures/CovidExploration-Adv.ipynb
biplav-s/course-d2d-ai
bd478fb88d4247e9717a54d12e0ee115a074a559
[ "MIT" ]
1
2021-07-13T14:47:18.000Z
2021-07-13T14:47:18.000Z
sample-code/future-lectures/CovidExploration-Adv.ipynb
biplav-s/course-d2d-ai
bd478fb88d4247e9717a54d12e0ee115a074a559
[ "MIT" ]
null
null
null
sample-code/future-lectures/CovidExploration-Adv.ipynb
biplav-s/course-d2d-ai
bd478fb88d4247e9717a54d12e0ee115a074a559
[ "MIT" ]
null
null
null
73.511574
11,056
0.771011
[ [ [ "# Credits: based on code by Saina Srivastava\n# ", "_____no_output_____" ], [ "import pandas as pd\nimport numpy as np\nimport datetime as dt\nfrom datetime import date", "_____no_output_____" ], [ "# We can also try the latest data from NYT\nurl = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv'\n# Read data from local file\ndata_latest = pd.read_csv(url, parse_dates=['date'])\ndata_latest.tail()", "_____no_output_____" ], [ "data_latest.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 943233 entries, 0 to 943232\nData columns (total 6 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 date 943233 non-null datetime64[ns]\n 1 county 943233 non-null object \n 2 state 943233 non-null object \n 3 fips 934434 non-null float64 \n 4 cases 943233 non-null int64 \n 5 deaths 923068 non-null float64 \ndtypes: datetime64[ns](1), float64(2), int64(1), object(2)\nmemory usage: 43.2+ MB\n" ], [ "# FIPS Code is explained here: https://www.census.gov/quickfacts/fact/note/US/fips", "_____no_output_____" ], [ "# Finding the number of cases in a state\ndata_sc = data_latest[data_latest['state']=='South Carolina']", "_____no_output_____" ], [ "data_sc.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 14011 entries, 637 to 942446\nData columns (total 6 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 date 14011 non-null datetime64[ns]\n 1 county 14011 non-null object \n 2 state 14011 non-null object \n 3 fips 14008 non-null float64 \n 4 cases 14011 non-null int64 \n 5 deaths 14011 non-null float64 \ndtypes: datetime64[ns](1), float64(2), int64(1), object(2)\nmemory usage: 766.2+ KB\n" ], [ "data_sc.tail()", "_____no_output_____" ], [ "data = data_sc.set_index('date')", "_____no_output_____" ], [ "c = data['cases'].resample('M').mean()\nd = data['deaths'].resample('M').mean()", "_____no_output_____" ], [ "# A plot for cases\nc.plot.bar()", "_____no_output_____" ], [ "# A plot for deaths\nd.plot.bar()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af8c9c8972750947eb82ae2ead6fff1ed0a3c9a
177,958
ipynb
Jupyter Notebook
Simulated Phenomenon.ipynb
SharonNicG/52465-Project
53e5f8ca3a0bfa49dad6cb246d743573e709a926
[ "MIT" ]
null
null
null
Simulated Phenomenon.ipynb
SharonNicG/52465-Project
53e5f8ca3a0bfa49dad6cb246d743573e709a926
[ "MIT" ]
null
null
null
Simulated Phenomenon.ipynb
SharonNicG/52465-Project
53e5f8ca3a0bfa49dad6cb246d743573e709a926
[ "MIT" ]
null
null
null
131.140752
60,676
0.827701
[ [ [ "# supresses future warnings - See References #1\nimport warnings \nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n# Import the pandas library for df creation\nimport pandas as pd\n\n# Import the NumPy library to use the random package\nimport numpy as np\n\n# Import the matplotlib library for plotting\nimport matplotlib.pyplot as plt\n\n# set plot style\nplt.style.use('seaborn-whitegrid')\n\n# Use the magic function to ensure plots render in a notebook\n%matplotlib inline\n\n# Import the seaborn library for plotting\nimport seaborn as sns\n\n# The NumPy Package produces random numbers using Random Number Generators \n# This defines the process by which numbers are generated for use by NumPy functions \n# Generators are a reliable way to generate random numbers\n# numpy.random offers several Random Number Generators. \n# By defining the Generator the code becomes reliable and repeatable - See References #2\n# Sets Generator type (the default BitGenerator - PCG64) with a declared value of 100 - See References #3\nrng = np.random.default_rng(100)\n\n# Set number of samples based on the number of live births in 2016\nn = 63739", "_____no_output_____" ] ], [ [ "## Table of Contents\n\n- [Introduction](#introduction)\n - [Breastfeeding](#breastfeeding)\n - [What is breastfeeding and why is it important?](#w_breastfeeding)\n - [Variables](#variables)\n - [Age](#age)\n - [Civil Status](#civil_status)\n - [Health Insurance Status](#hel_ins_status)\n - [Initiate Breastfeeding](#int_breastfeeding)\n- [Dataset](#dataset)\n- [References](#references)\n- [Other Sources](#other_sources)\n\n\n## Introduction<a class=\"anchor\" id=\"introduction\"></a>\n\nThe project requires us to simulate a real-world phenomenon of our choosing.\nWe have been asked to model and synthesise data related to this phenomenon using Python, particularly the numpy.random library. The output of the project should be a synthesised data set.\n\nI will be examining the rate of breastfeeding initiation in Ireland. I will create a dataset of variables associated with breastfeeding. I will simulate the distribution of breastfeeding initiation in a random sample of an identified segment of the population. I will explore the relationships between these factors and how they may influence the rate of breastfeeding initiation.\n\nThis will include:\n1.\tThe distribution of breastfeeding initiation in an identified segment of the population\n2.\tThe factors contributing to breastfeeding initiation\n3.\tHow these factors are distributed in the identified segment of the population\n\nThis topic is of particular interest to me as I have been successfully breastfeeding my daughter for the past year. The publication of the Irish Maternity Indicator System National Report 2019 report <sup>[4]</sup> received widespread news coverage and highlighted the low breastfeeding rates in Ireland <sup>[5]</sup>. On reflection, I was unable to identify how I had decided to breastfeed. I began to read more on the topic, including how Irish rates compare to international rates and breastfeeding socio-cultural changes. From this, I identified influencing factors on breastfeeding initiation. While I meet some of the criteria, I do not meet all. And yet as a mother in Ireland exclusively breastfeeding for over 12 months, I am one of only 7%. This intrigued me, and I wanted to examine what factors may have influenced my breastfeeding journey.\n\n### Breastfeeding<a class=\"anchor\" id=\"breastfeeding\"></a>\n\n![Lactation Image](\"https://github.com/SharonNicG/52465-Project/blob/main/Lactation%20Image%20OS.jpg\")\n\n#### What is breastfeeding and why is it important?<a class=\"anchor\" id=\"w_breastfeeding\"></a>\nBreastfeeding, or nursing, is the process of providing an infant with their mother's breastmilk <sup>[6]</sup>. This is usually done directly from the breast but can also be provided indirectly using expressed breast milk <sup>[*Ibid.*]</sup>. \nBreastfeeding is important as it offers numerous health benefits for both mother and infant.\n\n**Benefits to infant:**\n* Breast milk is naturally designed to meet the calorific and nutritional needs of an infant <sup>[7]</sup> and adapts to meet the needs of the infant as they change <sup>[8]</sup>\n* Breast milk provides natural antibodies that help to protect against common infections and diseases <sup>[*Ibid.*]</sup>\n* Breastfeeding is associated with better long-term health and wellbeing outcomes including less likelihood of developing asthma or obesity, and higher income in later life <sup>[9]</sup>\n\n**Benefits to mother:** \n* Breastfeeding lowers the mother's risk of breast and ovarian cancer, osteoporosis, cardiovascular disease, and obesity <sup>[10]</sup>. \n* Breastfeeding is associated with lower rates of post-natal depression and fewer depressive symptoms for women who do develop post-natal depression while breastfeeding <sup>[11, 12]</sup>. \n* Breastfeeding is a cost-effective, safe and hygienic method of infant feeding <sup>[13]</sup>. \n\nThe World Health Organisation (WHO), and numerous other organizations recommend exclusively breastfeeding for the first six months of an infant's life and breastfeeding supplemented by other foods from 6 months on <sup>[14, 15, 16, 17]</sup>. However, globally nearly 2 out of 3 infants are not exclusively breastfed for the first six months <sup>[18]</sup>. \n\nIreland has one of the lowest breastfeeding initiation rates in the world, with 63.8% of mothers breastfeeding for their child's first feed <sup>[19]</sup>. The rate of breastfeeding drops substantially within days as on average, only 37.3% of mothers are breastfeeding on discharge from hospital <sup>[*Ibid.*]</sup>.\n\nGiven the physical, social and economic advantages to breastfeeding over artificial and combination feeding (a mix of breast and artificial) both the WHO and the HSE have undertaken a number of measures to increase the rates of breastfeeding initiation and exclusive breastfeeding for the first six months in Ireland <sup>[20, 21]</sup>.\n\nFunded research is one of these measures, including national longitudinal studies to identify factors that may influence breastfeeding rates <sup>[22]</sup>.\n\n### Variables<a class=\"anchor\" id=\"variables\"></a>\n\nA review of some of the completed research projects has identified common factors that have been researched and for which there is a bank of data to refer to. These are identified in the table below:\n\n| Variable Name | Description | Data Type | Distribution |\n|--------------------------|-------------------------------------|-----------|-------------------|\n| Age | Age of mother | Numeric | Normal/Triangular |\n| Civil Status | Civil status of mother | Boolean | Normal/Triangular |\n| Private Health Insurance | Whether mother has health insurance | Boolean | Normal/Triangular |\n\nThese factors will be used as the variables for the development of the dataset. The fourth variable will be 'Breastfeeding Initiation'. This will be informed by data from existing research and dependent on values assigned to records under the other variables. \n\n| Variable Name | Description | Data Type | Distribution |\n|--------------------------|--------------------|-----------|-------------------|\n| Breastfeeding Initiation | Dependent Variable | Boolean | Normal/Triangular |\n\nA trawl of information sources led to the decision to use data from 2016. While National Perinatal Reporting System (NPRS) produce annual reports <sup>[*Ibid.*]</sup>, they are published with a 12-month delay, and final versions (following feedback and review) are available after 24 months. This means the 2016 report is the latest final version available. \n\nAn initial search for information on Civil Status statistics led to the 2016 census data. While this ultimately wasn't used, it guided the use of the 2016 NPRS data. Similarily historical data on Private Health Insurance rates in Ireland varies greatly, and 2016 seemed to produce the most applicable data for use here. \n\nBelow is an outline of each variable; the data is based on and how it will be used for the development of a dataset. As the expected distributions for each variable are the same different approaches will be taken with each to generate them for the dataset.", "_____no_output_____" ], [ "#### Age<a class=\"anchor\" id=\"age\"></a>\n\nA review of data provided by the NPRS study is used here to determine how maternal age is distributed across the population - mothers with live births in 2016 <sup>[23]</sup>.\n\nWhile age is a numerical value, it is presented by NPRS as a categorical variable/discrete groups, ranging from under 20 years of age to 45 years of age and older. The NPRS study provides the frequency and percentages of births within each group.", "_____no_output_____" ] ], [ [ "# Downloaded NPRS_Age.csv from NPRS 2016 Report\nage = pd.read_csv(\"Data/Age_and_Feeding_Type.csv\", index_col='Age Group')\n\n# Transpose index and columns \nage = age.T\n\n# Integer based indexing for selection by position - See References #24\nage = age.iloc[0:4, 0:7]\n\nage", "_____no_output_____" ] ], [ [ "The grouping of data by age group reduces the usefulness of the `describe()` function on the data frame. However, an initial view of the NPRS data indicates that the data is somewhat normally distributed with births increasing in the 25 - 29 age group, peaking at 30 - 34 years of age and beginning to decline in the 35 - 39 age set. \n\nVisualising the data set supports this analysis. It shows a minimum value of fewer than 20 years of age increasing in a positive direction until it significant peak around 32 years of age - the midpoint of the age group with the greatest frequency of births. ", "_____no_output_____" ] ], [ [ "# Creates a figure and a set of subplots.\nfig, ax = plt.subplots(figsize=(5, 5), dpi=100)\nx_pos = np.arange(7)\n\n# Plot x versus y as markers\nax.plot(x_pos, age.iloc[0, :], marker='^', label='Breast')\nax.plot(x_pos, age.iloc[1, :], marker='^', label='Artificial')\nax.plot(x_pos, age.iloc[2, :], marker='^', label='Combined')\n\n# Set labels for chart and axes\nax.set_title('Age and Feeding Type')\nax.set_xlabel('Maternal Age at Time of Birth')\nax.set_ylabel('Frequency')\n\n# Create names on the x-axis\nax.set_xticks(x_pos)\n\n# Rotate to make labels easier to read\nax.set_xticklabels(age.columns, rotation=90)\n\n# Position legend\nax.legend(loc=\"best\")\n\n# Show plot\nplt.show()", "_____no_output_____" ] ], [ [ "The initial approach taken was to create a function that generated a random number using the percentages from the csv file and assigned this to each record. ", "_____no_output_____" ] ], [ [ "def age_distribution():\n y = rng.integers(1,100)\n if y <= 23:\n return random.randint(15,19)\n elif 23 < y <= 43:\n return random.randint(20,24)\n elif 43 < y <= 62:\n return random.randint(25,29)\n elif 62 < y <= 77:\n return random.randint(30,34)\n elif 77 < y <= 88:\n return random.randint(35,39)\n elif 88 < y <= 95:\n return random.randint(40,44)\n else:\n return random.randint(45,49)\n \nAge = age\n\ndata = {'Age': age}", "_____no_output_____" ] ], [ [ "Then I realised that the distribution visualised above could be replicated using a Triangular Distribution. This generates a random number from a weighted range by distributing events between the maximum and minimum values provided, based on a third value that indicates what the most likely outcome will be <sup>[25, 26]</sup>. Here we are looking for 100 events (births) distributed between the ages of 16 and 50 with a known peak where the mothers age is 32.", "_____no_output_____" ] ], [ [ "# Here we are looking for a random array with a lower limit of 16 an upper limit of 50\n# and 32 being the number that appears most frequently (the midpoint of the most frequent age group)\n# over n number of instances where n is the total number of births\n# and for the out to be presented on a Triangular Distribution plot\n\nTri_var = np.random.triangular(left = 20, mode = 30, right = 50, size = 100).astype(int)\nprint (\"Here is your triangular continuous random variable:\\n % s\" % (Tri_var)) # [55]\n\n# Triangular Distribution - See References #27\nplt.hist(np.ma.round(np.random.triangular(left = 20, mode = 30, right = 50, size = 100)).astype(int),\n range = (16, 50), bins = 300, density = True)\n\n# Set labels for chart and axes\nplt.title('Randomised Distribution of Age')\nplt.xlabel('Maternal Age at Birth of Child')\nplt.ylabel('Frequency')\n\n# Show plot\nplt.show()", "Here is your triangular continuous random variable:\n [28 23 21 28 29 34 41 42 46 37 25 45 46 38 29 32 24 22 31 29 26 37 32 31\n 31 44 44 22 27 28 37 32 24 42 32 31 37 44 23 27 32 36 35 32 37 47 39 32\n 31 39 41 43 36 25 32 39 35 33 45 33 43 36 26 37 42 26 30 37 26 32 37 34\n 35 25 38 44 32 35 22 29 27 29 43 33 44 22 23 44 29 29 28 25 29 36 27 32\n 43 39 36 40]\n" ] ], [ [ "#### Civil Status <a class=\"anchor\" id=\"civil_status\"></a>\n\nResearch has shown that maternal civil status at the time of birth is significantly associated with breastfeeding initiation <sup>[28,29,30]</sup>.\n\nData captured in the 2016 NPRS survey does not capture relational data between breastfeeding initiation and maternal civil status at the time of birth <sup>[31]</sup>. However, it does provide percentage values for maternal civil status across all age groups:\n\n| Maternal Civil Status at Birth | Percentage of Total births |\n|--------------------------------|----------------------------|\n| Married | 62.2 |\n| Single | 36.4 |\n| Other | 1.4 |\n\n\nCentral Statistics Office (CSO) data on civil status for 2016 does record information across all age groups <sup>[32]</sup>. However, as it only captures data for \n* Marriages\n* Civil partnerships\n* Divorces, Judicial Separation and Nullity applications received by the courts \n* Divorces, Judicial Separation and Nullity applications granted by the courts \n\nIt does not capture other civil arrangements such as informal separations or co-habitants.\n\nFor the purposes of this simulation, the NPRS data will be used.\n\nThis is a categorical variable that has three possible values\n1. Married\n2. Single\n3. Other (encompassing all other civil statutes as identified by the survey respondent)\n\nNote, that same sex marriage wasn't legal in 2016 and Civil Partnerships are recorded as Other in the NPRS Report.\n\nThe first approach was to link the age of a person to a civil status by calculating how many people within each age group may fall into each civil status category, based on the NPRS data. This was excessively complicated - requiring an If statement, a dictionary and a For Loop. While it produced a good distribution, it wasn't easily amendable if the figures changed as each line needed to be amended in the dictionary. ", "_____no_output_____" ] ], [ [ "def civil_status(x):\n \n def distribution(st):\n x = rng.integers(0,100)\n if x <= chances[0][0]:\n return chances[0][1]\n elif x <= chances[0][0] + chances[1][0]:\n return chances[1][1]\n return chances[2][1]\n \n status = { range(15,20) : [(0,'other'),(95,'Single'),(5,'Married')]}\n\n for i in status:\n if x in i:\n return distribution(status[i])", "_____no_output_____" ] ], [ [ "Instead, a much simpler way based on the information in the NPRS report `rng.choice` can be used to randomly distribute these values across the dataset population.", "_____no_output_____" ] ], [ [ "# Classifying Civil Status\n# 'single' if single, 'married' if married and 'other' for all other categories\ncivil_options = ['single', 'married', 'other']\n\n# Randomisation of civil status based on the probability provided\ncivil_status = rng.choice(civil_options, n, p=[.364, .622, .014])\n\n# Count of zero elements in array - See References #33 \nprint(\"Single: \", np.count_nonzero(civil_status == 'single'))\nprint(\"Married: \", np.count_nonzero(civil_status == 'married'))\nprint(\"Other: \", np.count_nonzero(civil_status == 'other'))", "Single: 23360\nMarried: 39496\nOther: 883\n" ] ], [ [ "#### Health Insurance Status<a class=\"anchor\" id=\"hel_ins_status\"></a>\n\nGallagher's research also highlighted a significant association between the health insurance status of a mother and breastfeeding initiation <sup>[34]</sup>. A review of other research into factors affecting breastfeeding initiation showed that access to enhanced peri- and postnatal medical care have considerable influence on breastfeeding initiation and continuance <sup>[35, 36, 37]</sup>. These were primarily completed in countries without a funded, or part-funded national health service. While these demonstrated that mothers with private health insurance were more likely to initiate breastfeeding, they weren't comparable in an Irish context. However, a follow-on study from Gallagher's research further supported her findings that maternal access to private health insurance increased the likelihood of breastfeeding <sup>[38]</sup>.\n\nThe Health Insurance Authority (HIA) in Ireland offers a comparison tool for health insurance policies, including the services available under each plan <sup>[39]</sup>. A review, carried out in December 2020, shows that of 314 plans on offer 237 provide outpatient maternity benefits which cover peri and postnatal cover care and support systems. These include one-to-one postnatal consultation with a lactation consultant. \n\nFor mothers without health insurance, maternity care in Ireland is provided under the Maternity and Infant Care Scheme <sup>[40]</sup>. This is a combined hospital and GP service for the duration of pregnancy and six weeks postpartum. No specific resources are made available to support breastfeeding, though maternity hospitals and units may offer breastfeeding information sessions and one-to-one lactation consultations where needed. Access to these supports is limited. The Coombe Women's and Children's Hospital, for example, handles around 8,000 births per year <sup>[41]</sup> and provides breastfeeding information sessions to less than 1,000 mothers per year <sup>[42]</sup>. There are a number of community supports for breastfeeding, including [Le Leche](https://www.lalecheleagueireland.com/), [Friends of Breastfeeding](https://www.friendsofbreastfeeding.ie/) and [Cuidiu](https://www.cuidiu.ie/) and private lactation consultants. Interestingly, neither Irish study assessed whether mothers accessed these services perinatally. \n\nGallagher's research showed that 66% of the insured mothers initiated breastfeeding <sup>[43]</sup>. As insurance status can only have two possible outcomes (True or False), a binomial distribution was initially used to evaluate distribution across `n` number of births. ", "_____no_output_____" ] ], [ [ "# Here we are looking for a Binomial Distribution \n# with probability of 0.66 for each trial\n# repeated `n` times\n# to be presented as a Binomial Bistribution plot\nsns.distplot(rng.binomial(n=10, p=0.66, size=n), hist=True, kde=False)\n\n# Set labels for chart and axes\nplt.title('Insurance Distribution Based on Percentage Insured')\nplt.xlabel('Age Distribution')\nplt.ylabel('Number Insured')\n\n# Show plot\nplt.show()", "_____no_output_____" ] ], [ [ "While this randomly allocated health insurance status, it didn't distribute this across the age groups in an informed way.\n\nThe HIA also provide historical market statistics on insurance in Ireland <sup>[44]</sup>. Data for 2016 based on the age groups previously used, the number of the total population insured within these groupings that are insured and the percentage of the total insured population these represent was extracted from the HIA historical market statistics into a csv file. ", "_____no_output_____" ] ], [ [ "# Downloaded HIA historicial market statistics\nins = pd.read_csv(\"Data/Insurance_by_Age.csv\")\nins", "_____no_output_____" ] ], [ [ "The extracted data shows a positive increase in the number of people insured from ages 20 to 35. Peaking significantly in the 35-39 category and declining thereafter. Visualising the data supports this analysis.", "_____no_output_____" ] ], [ [ "# Downloaded HIA historicial market statistics\nins = pd.read_csv('Data/Insurance_by_Age.csv', index_col='Age')\n\n# Transpose index and columns \nins = ins.T\nins\n\n# Creates a figure and a set of subplots\nfig, ax = plt.subplots(figsize=(5,3), dpi=100)\nx_pos = np.arange(7)\n\n# Integer based indexing for selection by position - See References #24 \n# Scaled down\ny = ins.iloc[1, :] / 100\ny = y*ins.iloc[0, :]\n\n# Plot x versus y as markers\nax.plot(x_pos, y, marker='o', label='Insurance')\n\n# Set labels for chart and axes\nax.set_title('Insurance by Age')\nax.set_xlabel('Maternal Age')\nax.set_ylabel('Number Insured')\n\n# Create names on the x-axis\nax.set_xticks(x_pos)\n\n# Rotate to make labels easier to read\nax.set_xticklabels(age.columns, rotation=90)\n\n# Show plot\nplt.show()", "_____no_output_____" ] ], [ [ "While it isn't possible to get a breakdown of insurance status by gender or linked to the parity of women within the given age groups, the above analysis has provided two points to work from in the generated dataset: the percentage of people within the age groups that are likely to have health insurance, and that 66% of pregnant women have health insurance. ", "_____no_output_____" ] ], [ [ "# ins_by_age(x) takes one argument - the age of the person\n# based on this number and the percentages identified from HIA \n# it gives each record a value of True or False\n\n# a dict that holds the HIA statistics\ndef ins_by_age (x):\n \n agerange_insurance = {range(15,20) : 10,\n range(20,25) : 9,\n range(25,30) : 9,\n range(30,35) : 14,\n range(35,40) : 19,\n range(40,45) : 19,\n range(45,50) : 20}\n \n# Introduce randomisation by assigning True or False based on\n# a randomly assigned number generated by rng.integers\n \n for i in agerange_insurance:\n if x in i:\n y = rng.integers(1,100)\n if y <= agerange_insurance[i]:\n return True \n return False\n \nhealth_ins_status = np.array([ins_by_age(i) for i in age])", "_____no_output_____" ] ], [ [ "#### Initiate Breastfeeding<a class=\"anchor\" id=\"int_breastfeeding\"></a>\n\nThis variable is based on the data used above and in Gallagher's study <sup>[45]</sup>. \n\nUsing the data from the NPRS report the percentage of women within each age group that are likely to initiate breastfeeding can be calculated.", "_____no_output_____" ] ], [ [ "# Percentage of total births that initiate breastfeeding\nage = pd.read_csv(\"Data/Age_and_Feeding_Type.csv\")\nage = age.iloc[0:7, 0:8]\nage['pct']=age['Breast']/(age['Total'])*100 \n\nage", "_____no_output_____" ] ], [ [ "Additionally, this variable will be a dependant variable influenced by data from the other variables and information Gallagher's study:\n1. Women with health insurance are more likely to initiate breastfeeding\n * 66% of women have access to health insurance <sup>[*Ibid*]</sup>\n2. Civil Status influences the likelihood of breastfeeding\n * Married women are three times more likely to breastfeed", "_____no_output_____" ], [ "## Dataset<a class=\"anchor\" id=\"dataset\"></a>", "_____no_output_____" ] ], [ [ "# the number of records\nn = 100", "_____no_output_____" ] ], [ [ "### Variable 1 - Age ", "_____no_output_____" ] ], [ [ "# A Triangular Distribution with a lower limit of 16 an upper limit of 50\n# and 32 being the number that appears most frequently (the midpoint of the most frequent age group)\n# over n number of instances where n is the total number of births\n\nage_dist = (np.random.triangular(left = 16, mode = 30, right = 50, size = 500)).astype(int)\n\n# Using rng.choice to randomise the output\nage = rng.choice(age_dist, n)\n\n# generating the dataframe using the the age distribution\ndf = pd.DataFrame(age, columns = ['Maternal Age'])", "_____no_output_____" ] ], [ [ "### Variable 2 - Civil Status", "_____no_output_____" ] ], [ [ "# Classifying Civil Status\n# 'single' if single, 'married' if married and 'other' for all other categories\ncivil_status = ['single', 'married', 'other']\n\n# Randomisation of civil status based on the probability provided\ncivil_status = rng.choice(civil_status, n, p=[.364, .622, .014])", "_____no_output_____" ] ], [ [ "### Varible 3 - Insurance Status", "_____no_output_____" ] ], [ [ "# ins_by_age(x) takes one argument - the age of the person\n# based on this number and the percentages identified from HIA \n# it gives each record a value of True or False\n\n# a dictionary that holds the HIA statistics\n\ndef ins_by_age (x):\n \n agerange_insurance = {range(15,20) : 10,\n range(20,25) : 9,\n range(25,30) : 9,\n range(30,35) : 14,\n range(35,40) : 19,\n range(40,45) : 19,\n range(45,50) : 20}\n\n # Introduce randomisation by assigning True or False based on\n # a randomly assigned number generated by rng.integers\n\n for i in agerange_insurance:\n if x in i:\n y = rng.integers(1,100)\n if y <= agerange_insurance[i]:\n return True \n return False\n \nhealth_ins_status = np.array([ins_by_age(i) for i in age])\n\ndf['Health Insurance Status'] = health_ins_status", "_____no_output_____" ] ], [ [ "### Variable 4 - Initate Breastfeeding", "_____no_output_____" ] ], [ [ "# ins_by_age(x) takes one argument - the age of the person\n# based on this number and the percentages identified from HIA \n# it gives each record a value of True or False\n\n# a dictionary that holds the calculated percentage statistics\n\ndef breastfeeding(x):\n \n bf_status = {range(15,20) : 23,\n range(20,25) : 32,\n range(25,30) : 43,\n range(30,35) : 53,\n range(35,40) : 55,\n range(40,45) : 53,\n range(45,50) : 50}\n\n a = age[x] # the age of the person\n b = health_ins_status[x] # the person's health insurance status\n c = civil_status[x] # the person's civil status\n\n q = 3 if c == 'Married' else 2 if c == 'Other' else 1 \n # If married they are 3 times more likely to start the program\n # Assigning 2 for people with Other as they may have an informal arrangemnt\n # Assigning 1 for people who identify as single\n\n # Introduce randomisation by assigning True or False based on\n # a randomly assigned number generated by rng.integers\n for i in bf_status:\n if a in i:\n y = rng.integers(1,1000)\n if y <= q*bf_status[i] or (b == True and y <= 66): # Using 66 as ^^% of insured women initiate breastfeeding\n return True \n return False\n\n# generating the variable based on the function\ninitiate_bf = np.array([breastfeeding(i) for i in age])\n\ndf['Initiate Breastfeeding'] = initiate_bf", "_____no_output_____" ] ], [ [ "### Dataset", "_____no_output_____" ] ], [ [ "# See References #46 and #47 \n\npd.set_option(\"expand_frame_repr\", True)\n\ndf", "_____no_output_____" ] ], [ [ "### References<a class=\"anchor\" id=\"references\"></a>\n\n1. Stack Overflow (2020) How to suppress pandas future warnings, Available at: https://stackoverflow.com/questions/15777951/how-to-suppress-pandas-future-warning\n\n2. Machine Learning Mastery, How to Generate Random Numbers in Python, Available at: https://machinelearningmastery.com/how-to-generate-random-numbers-in-python/\n\n3. The SciPy Community (2020) Random Generator, Available at: https://numpy.org/doc/stable/reference/random/generator.html \n\n4. National Women and Infants Health Programme Clinical Programme for Obstetrics and Gynaecology (2020) Irish Maternity Indicator System National Report 2019, Available at: https://www.hse.ie/eng/about/who/acute-hospitals-division/woman-infants/national-reports-on-womens-health/imis-national-report-2019.pdf\n\n5. Cullen, P (2020) Ireland has one of the lowest breastfeeding rates in the world – report, Available at: https://www.irishtimes.com/news/health/ireland-has-one-of-the-lowest-breastfeeding-rates-in-the-world-report-1.4391626\n\n6. World Health Organisation (2020) Breastfeeding, Available at https://www.who.int/health-topics/breastfeeding\n\n7. World Health Organisation (2020) Infant and young child feeding, Available at: https://www.who.int/news-room/fact-sheets/detail/infant-and-young-child-feeding\n\n8. National Health Service (2020) Benefits of breastfeeding - Your pregnancy and baby guide, Available at: https://www.nhs.uk/conditions/pregnancy-and-baby/benefits-breastfeeding/ \n\n9. Oddy, W. H., Sherriff, J. L., de Klerk, N. H., Kendall, G. E., Sly, P. D., Beilin, L. J., Blake, K. B., Landau, L. I., & Stanley, F. J. (2004) The Relation of Breastfeeding and Body Mass Index to Asthma and Atopy in Children: A Prospective Cohort Study to Age 6 Years, Available at: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1448489/\n\n10. National Health Service (2020) Benefits of breastfeeding, Available at: https://www.nhs.uk/conditions/baby/breastfeeding-and-bottle-feeding/breastfeeding/benefits/\n\n11. Borra, C., Iacovou, M., Sevilla, A. 2015. New evidence on breastfeeding and postpartum depression: the importance of understanding women’s intentions. Maternal and Child Health Journal, 19, pp. 887-907.\n\n12. Dennis, C.L., McQueen, K. 2009. The relationship between infant-feeding outcomes and postpartum depression: a qualitative systematic review. Pediatrics, 123, pp. 736-751\n\n13. UNICEF (2013) Breastfeeding is the cheapest and most effective life-saver in history, Available at: https://www.unicef.org/media/media_70044.html\n\n14. World Health Organisation (2020) Breastfeeding, Available at https://www.who.int/health-topics/breastfeeding\n\n15. American Academy of Pediatrics (2012) Breastfeeding and the Use of Human Milk, Available at: https://doi.org/10.1542/peds.2011-3552\n\n16. NHS (2020) How to breastfeed, Available at: https://www.nhs.uk/conditions/baby/breastfeeding-and-bottle-feeding/breastfeeding/\n\n17. HSE (2020) Extended breastfeeding, Available at: https://www2.hse.ie/wellbeing/child-health/extended-breastfeeding-beyond-1-year.html \n\n18. World Health Organisation (2020) Breastfeeding, Available at https://www.who.int/health-topics/breastfeeding\n\n19. National Women and Infants Health Programme Clinical Programme for Obstetrics and Gynaecology (2020) Irish Maternity Indicator System National Report 2019, Available at: https://www.hse.ie/eng/about/who/acute-hospitals-division/woman-infants/national-reports-on-womens-health/imis-national-report-2019.pdf\n\n20. World Health Organisation (2017) Protecting, promoting and supporting breastfeeding in facilities providing maternity and newborn services, Geneva, Switzerland, Available at: https://apps.who.int/iris/bitstream/handle/10665/259386/9789241550086-eng.pdf\n\n21. The Institute of Public Health in Ireland (2017) Breastfeeding on the island of Ireland, Available at: https://www.hse.ie/eng/about/who/healthwellbeing/our-priority-programmes/child-health-and-wellbeing/breastfeeding-healthy-childhood-programme/research-and-reports-breastfeeding/breastfeeding-on-the-island-of-ireland-report.pdf \n\n22. The Institute of Public Health in Ireland (2017) Breastfeeding on the island of Ireland, Available at: https://www.hse.ie/eng/about/who/healthwellbeing/our-priority-programmes/child-health-and-wellbeing/breastfeeding-healthy-childhood-programme/research-and-reports-breastfeeding/breastfeeding-on-the-island-of-ireland-report.pdf \n\n23. Healthcare Pricing Office (HPO), Health Service Executive (HSE) (2020) National Perinatal Statistics Report, 2017, Dublin: Health Service Executive. Available at: http://www.hpo.ie/latest_hipe_nprs_reports/NPRS_2017/Perinatal_Statistics_Report_2017.pdf\n\n24. The Pandas Development Team (2014) pandas.DataFrame.iloc, Available at: https://pandas.pydata.org/pandas-docs/version/1.0.2/reference/api/pandas.DataFrame.iloc.html?highlight=iloc\n\n25. numpy.random.triangular, Available at: https://numpy.org/doc/stable/reference/random/generated/numpy.random.triangular.html\n\n26. Python – Triangular Distribution in Statistics, Available at: https://www.geeksforgeeks.org/python-triangular-distribution-in-statistics/\n\n27. Stack Overflow (2020) A weighted version of random randint, Available at: https://stackoverflow.com/questions/60870070/a-weighted-version-of-random-randint\n\n28. Gallagher L, Begley C, Clarke M, Determinants of breastfeeding initiation in Ireland., Irish journal of medical science, 185, 3, 2015, 663 - 668 \n\n29. Thulier. D and Mercer, J. (2009) Variables Associated With Breastfeeding Duration, Available at: https://www.sciencedirect.com/science/article/abs/pii/S0884217515301866\n\n30. Masho, S.W., Morris, M.R. and Wallenborn, J. T. (2016) Role of Marital Status in the Association between Prepregnancy Body Mass Index and Breastfeeding Duration, Available at: https://www.sciencedirect.com/science/article/abs/pii/S1049386716300391\n\n31. Healthcare Pricing Office (HPO), Health Service Executive (HSE) (2020) National Perinatal Statistics Report, 2016, Dublin: Health Service Executive. Avilable at: http://www.hpo.ie/latest_hipe_nprs_reports/NPRS_2016/Perinatal_Statistics_Report_2016.pdf\n\n32. Central Statistics Office (2020) Marriages and Civil Partnerships 2016, Available at: https://www.cso.ie/en/releasesandpublications/er/mcp/marriagesandcivilpartnerships2016/\n\n33. Stack Overflow (2020) Efficiently count zero elements in numpy array, Available at: https://stackoverflow.com/questions/42916330/efficiently-count-zero-elements-in-numpy-array/42916378 \n\n34. Gallagher L, Begley C, Clarke M, Determinants of breastfeeding initiation in Ireland., Irish journal of medical science, 185, 3, 2015, 663 - 668\n\n35. Gurley-Calvez, T., Bullinger, L. and Kapinos, K.A. (2017) Effect of the Affordable Care Act on Breastfeeding Outcomes, Available at: https://ajph.aphapublications.org/doi/abs/10.2105/AJPH.2017.304108 \n\n36. Merewood, A., Brooks, D., Bauchner, H., MacAuley, L. and Mehta, S. D. (2006) Maternal Birthplace and Breastfeeding Initiation Among Term and Preterm Infants: A Statewide Assessment for Massachusetts, Available at: https://pediatrics.aappublications.org/content/118/4/e1048\n\n37. González de Cosío, T., Escobar-Zaragoza, L., González-Castell, LD. and Rivera-Dommarco, JÁ. Infant feeding practices and deterioration of breastfeeding in Mexico. (2013) Avilable at: https://europepmc.org/article/med/24626693\n\n38. Alberdi, G., O'Sullivan, E. J., Scully, H., Kelly, N., Kincaid, R., Murtagh, R., Murray, S., McGuinness, D., Clive, A., Brosnan, M., Sheehy, L., Dunn, E., McAuliffe, F.M. (2018) A feasibility study of a multidimensional breastfeeding-support intervention in Ireland,, Available at: https://doi.org/10.1016/j.midw.2017.12.018.\n\n39. The Health Insurance Authority (2020) The Health Insurance Authority, Available at: https://www.hia.ie/\n\n40. Health Service Executive (2020) Maternity and Infant Care Scheme, Available at: https://www.hse.ie/eng/services/list/3/maternity/combinedcare.html \n\n41. Irish Nurses & Midwives Organisation (2020) Over 11,000 babies born in Irish hospitals since COVID-19 arrived , Available at: https://www.inmo.ie/Home/Index/217/13585\n\n42. Coombe Women & Infants University Hospital (2019) Breastfeeding and breastfeeding support, Available at: http://www.d1048212.blacknight.com/index.php?nodeId=231\n\n43. Gallagher L, Begley C, Clarke M, Determinants of breastfeeding initiation in Ireland., Irish journal of medical science, 185, 3, 2015, 663 - 668\n\n44. The Health Insurance Authority (2019) Historical Data on the market, Available at: https://www.hia.ie/publication/market-statistics\n\n45. Gallagher L, Begley C, Clarke M, Determinants of breastfeeding initiation in Ireland., Irish journal of medical science, 185, 3, 2015, 663 - 668\n\n46. Stack Overflow (2014) How to display full (non-truncated) dataframe information, Available at: https://stackoverflow.com/questions/25351968/how-to-display-full-non-truncated-dataframe-information-in-html-when-convertin \n\n47. The Pandas Development Team (2020) Frequently used options, Available at: https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#frequently-used-options \n\n\n### Other Sources<a class=\"anchor\" id=\"Other_sources\"></a>\nYvonne L. Hauck, Ingrid Blixt, Ingegerd Hildingsson, Louise Gallagher, Christine Rubertsson, Brooke Thomson and Lucy Lewis, Australian, Irish and Swedish women's perceptions of what assisted them to breastfeed for six months: exploratory design using critical incident technique, BMC Public Health, 16, (1067), 2016\n\nAmerican Academy of Pediatrics. (2012). Breastfeeding and the use of human milk. Pediatrics, 129(3), e827–e841. Available at: https://pediatrics.aappublications.org/content/129/3/e827\n\nRemove Unnamed Columns in Pandas Dataframe, Avilable at: https://stackoverflow.com/questions/43983622/remove-unnamed-columns-in-pandas-dataframe\n\nBasic Syntax, Available at: https://www.markdownguide.org/basic-syntax/\n\nMastering Markdown, Available at: https://guides.github.com/features/mastering-markdown/\n\nMatplotlib: Visualization with Python, Available at: https://matplotlib.org/\n\nSeaborn User guide and tutorial, Available at: https://seaborn.pydata.org/tutorial.html", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "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" ] ]
4af8cfcfa459bc9b6f621114c18ea07cb6d0b948
345,405
ipynb
Jupyter Notebook
godley_&_lavoie/.ipynb_checkpoints/Python3 Chapter 5 Model LP-checkpoint.ipynb
gpetrini/pysolve3
9656a8ada89eee75e9884bf5ec63add4d0864ad8
[ "MIT" ]
6
2018-12-07T12:51:48.000Z
2022-03-08T18:46:36.000Z
monetary-economics/Chapter 5 Model LP.ipynb
gpetrini/pysolve3
9656a8ada89eee75e9884bf5ec63add4d0864ad8
[ "MIT" ]
1
2020-05-12T11:04:28.000Z
2020-05-12T11:23:48.000Z
monetary-economics/Chapter 5 Model LP.ipynb
gpetrini/pysolve3
9656a8ada89eee75e9884bf5ec63add4d0864ad8
[ "MIT" ]
1
2020-05-12T11:07:51.000Z
2020-05-12T11:07:51.000Z
302.721297
36,806
0.898887
[ [ [ "# Monetary Economics: Chapter 5", "_____no_output_____" ], [ "### Preliminaries", "_____no_output_____" ] ], [ [ "# This line configures matplotlib to show figures embedded in the notebook, \n# instead of opening a new window for each figure. More about that later. \n# If you are using an old version of IPython, try using '%pylab inline' instead.\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\n\nfrom pysolve.model import Model\nfrom pysolve.utils import is_close,round_solution\n", "_____no_output_____" ] ], [ [ "### Model LP1", "_____no_output_____" ] ], [ [ "def create_lp1_model():\n model = Model()\n\n model.set_var_default(0)\n model.var('Bcb', desc='Government bills held by the Central Bank')\n model.var('Bd', desc='Demand for government bills')\n model.var('Bh', desc='Government bills held by households')\n model.var('Bs', desc='Government bills supplied by government')\n model.var('BLd', desc='Demand for government bonds')\n model.var('BLh', desc='Government bonds held by households')\n model.var('BLs', desc='Supply of government bonds')\n model.var('CG', desc='Capital gains on bonds')\n model.var('CGe', desc='Expected capital gains on bonds')\n model.var('C', desc='Consumption')\n model.var('ERrbl', desc='Expected rate of return on bonds')\n model.var('Hd', desc='Demand for cash')\n model.var('Hh', desc='Cash held by households')\n model.var('Hs', desc='Cash supplied by the central bank')\n model.var('Pbl', desc='Price of bonds')\n model.var('Pble', desc='Expected price of bonds')\n model.var('Rb', desc='Interest rate on government bills')\n model.var('Rbl', desc='Interest rate on government bonds')\n model.var('T', desc='Taxes')\n model.var('V', desc='Household wealth')\n model.var('Ve', desc='Expected household wealth')\n model.var('Y', desc='Income = GDP')\n model.var('YDr', desc='Regular disposable income of households')\n model.var('YDre', desc='Expected regular disposable income of households')\n\n model.set_param_default(0)\n model.param('alpha1', desc='Propensity to consume out of income')\n model.param('alpha2', desc='Propensity to consume out of wealth')\n model.param('chi', desc='Weight of conviction in expected bond price')\n model.param('lambda10', desc='Parameter in asset demand function')\n model.param('lambda12', desc='Parameter in asset demand function')\n model.param('lambda13', desc='Parameter in asset demand function')\n model.param('lambda14', desc='Parameter in asset demand function')\n model.param('lambda20', desc='Parameter in asset demand function')\n model.param('lambda22', desc='Parameter in asset demand function')\n model.param('lambda23', desc='Parameter in asset demand function')\n model.param('lambda24', desc='Parameter in asset demand function')\n model.param('lambda30', desc='Parameter in asset demand function')\n model.param('lambda32', desc='Parameter in asset demand function')\n model.param('lambda33', desc='Parameter in asset demand function')\n model.param('lambda34', desc='Parameter in asset demand function')\n model.param('theta', desc='Tax rate')\n\n model.param('G', desc='Government goods')\n model.param('Rbar', desc='Exogenously set interest rate on govt bills')\n model.param('Pblbar', desc='Exogenously set price of bonds')\n\n model.add('Y = C + G') # 5.1\n model.add('YDr = Y - T + Rb(-1)*Bh(-1) + BLh(-1)') # 5.2\n model.add('T = theta *(Y + Rb(-1)*Bh(-1) + BLh(-1))') # 5.3\n model.add('V - V(-1) = (YDr - C) + CG') # 5.4\n model.add('CG = (Pbl - Pbl(-1))*BLh(-1)')\n model.add('C = alpha1*YDre + alpha2*V(-1)')\n model.add('Ve = V(-1) + (YDre - C) + CG')\n model.add('Hh = V - Bh - Pbl*BLh')\n model.add('Hd = Ve - Bd - Pbl*BLd')\n model.add('Bd = Ve*lambda20 + Ve*lambda22*Rb' +\n '- Ve*lambda23*ERrbl - lambda24*YDre')\n model.add('BLd = (Ve*lambda30 - Ve*lambda32*Rb ' +\n '+ Ve*lambda33*ERrbl - lambda34*YDre)/Pbl')\n model.add('Bh = Bd')\n model.add('BLh = BLd')\n model.add('Bs - Bs(-1) = (G + Rb(-1)*Bs(-1) + ' +\n 'BLs(-1)) - (T + Rb(-1)*Bcb(-1)) - (BLs - BLs(-1))*Pbl')\n model.add('Hs - Hs(-1) = Bcb - Bcb(-1)')\n model.add('Bcb = Bs - Bh')\n model.add('BLs = BLh')\n model.add('ERrbl = Rbl + chi * (Pble - Pbl) / Pbl')\n model.add('Rbl = 1./Pbl')\n model.add('Pble = Pbl')\n model.add('CGe = chi * (Pble - Pbl)*BLh')\n model.add('YDre = YDr(-1)')\n model.add('Rb = Rbar')\n model.add('Pbl = Pblbar')\n\n return model\n\nlp1_parameters = {'alpha1': 0.8,\n 'alpha2': 0.2,\n 'chi': 0.1,\n 'lambda20': 0.44196,\n 'lambda22': 1.1,\n 'lambda23': 1,\n 'lambda24': 0.03,\n 'lambda30': 0.3997,\n 'lambda32': 1,\n 'lambda33': 1.1,\n 'lambda34': 0.03,\n 'theta': 0.1938}\nlp1_exogenous = {'G': 20,\n 'Rbar': 0.03,\n 'Pblbar': 20}\nlp1_variables = {'V': 95.803,\n 'Bh': 37.839,\n 'Bs': 57.964,\n 'Bcb': 57.964 - 37.839,\n 'BLh': 1.892,\n 'BLs': 1.892,\n 'Hs': 20.125,\n 'YDr': 95.803,\n 'Rb': 0.03,\n 'Pbl': 20}\n", "_____no_output_____" ] ], [ [ "### Scenario: Interest rate shock", "_____no_output_____" ] ], [ [ "lp1 = create_lp1_model()\nlp1.set_values(lp1_parameters)\nlp1.set_values(lp1_exogenous)\nlp1.set_values(lp1_variables)\n\nfor _ in xrange(15):\n lp1.solve(iterations=100, threshold=1e-6)\n\n# shock the system\nlp1.set_values({'Rbar': 0.04,\n 'Pblbar': 15})\nfor _ in xrange(45):\n lp1.solve(iterations=100, threshold=1e-6)", "_____no_output_____" ] ], [ [ "###### Figure 5.2", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.2 Evolution of the wealth to disposable income ratio, following an increase\n in both the short-term and long-term interest rates, with model LP1'''\ndata = [s['V']/s['YDr'] for s in lp1.solutions[5:]]\n\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 1.1, 1.1])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(0.89, 1.01)\n\naxes.plot(data, 'k')\n\n# add labels\nplt.text(20, 0.98, 'Wealth to disposable income ratio')\nfig.text(0.1, -.05, caption);", "_____no_output_____" ] ], [ [ "###### Figure 5.3", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.3 Evolution of the wealth to disposable income ratio, following an increase\n in both the short-term and long-term interest rates, with model LP1'''\nydrdata = [s['YDr'] for s in lp1.solutions[5:]]\ncdata = [s['C'] for s in lp1.solutions[5:]]\n\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 1.1, 1.1])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(92.5, 101.5)\n\naxes.plot(ydrdata, 'k')\naxes.plot(cdata, linestyle='--', color='r')\n\n# add labels\nplt.text(16, 98, 'Disposable')\nplt.text(16, 97.6, 'income')\nplt.text(22, 95, 'Consumption')\nfig.text(0.1, -.05, caption);", "_____no_output_____" ] ], [ [ "###### Figure 5.4", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.4 Evolution of the bonds to wealth ration and the bills to wealth ratio,\n following an increase from 3% to 4% in the short-term interest rate, while the\n long-term interest rates moves from 5% to 6.67%, with model LP1'''\nbhdata = [s['Bh']/s['V'] for s in lp1.solutions[5:]]\npdata = [s['Pbl']*s['BLh']/s['V'] for s in lp1.solutions[5:]]\n\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 1.1, 1.1])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(0.382, 0.408)\n\naxes.plot(bhdata, 'k')\naxes.plot(pdata, linestyle='--', color='r')\n\n# add labels\nplt.text(14, 0.3978, 'Bonds to wealth ratio')\nplt.text(17, 0.39, 'Bills to wealth ratio')\nfig.text(0.1, -.05, caption);", "_____no_output_____" ] ], [ [ "### Model LP2", "_____no_output_____" ] ], [ [ "def create_lp2_model():\n model = Model()\n\n model.set_var_default(0)\n model.var('Bcb', desc='Government bills held by the Central Bank')\n model.var('Bd', desc='Demand for government bills')\n model.var('Bh', desc='Government bills held by households')\n model.var('Bs', desc='Government bills supplied by government')\n model.var('BLd', desc='Demand for government bonds')\n model.var('BLh', desc='Government bonds held by households')\n model.var('BLs', desc='Supply of government bonds')\n model.var('CG', desc='Capital gains on bonds')\n model.var('CGe', desc='Expected capital gains on bonds')\n model.var('C', desc='Consumption')\n model.var('ERrbl', desc='Expected rate of return on bonds')\n model.var('Hd', desc='Demand for cash')\n model.var('Hh', desc='Cash held by households')\n model.var('Hs', desc='Cash supplied by the central bank')\n model.var('Pbl', desc='Price of bonds')\n model.var('Pble', desc='Expected price of bonds')\n model.var('Rb', desc='Interest rate on government bills')\n model.var('Rbl', desc='Interest rate on government bonds')\n model.var('T', desc='Taxes')\n model.var('TP', desc='Target proportion in households portfolio')\n model.var('V', desc='Household wealth')\n model.var('Ve', desc='Expected household wealth')\n model.var('Y', desc='Income = GDP')\n model.var('YDr', desc='Regular disposable income of households')\n model.var('YDre', desc='Expected regular disposable income of households')\n model.var('z1', desc='Switch parameter')\n model.var('z2', desc='Switch parameter')\n\n model.set_param_default(0)\n model.param('add', desc='Random shock to expectations')\n model.param('alpha1', desc='Propensity to consume out of income')\n model.param('alpha2', desc='Propensity to consume out of wealth')\n model.param('beta', desc='Adjustment parameter in price of bills')\n model.param('betae', desc='Adjustment parameter in expectations')\n model.param('bot', desc='Bottom value for TP')\n model.param('chi', desc='Weight of conviction in expected bond price')\n model.param('lambda10', desc='Parameter in asset demand function')\n model.param('lambda12', desc='Parameter in asset demand function')\n model.param('lambda13', desc='Parameter in asset demand function')\n model.param('lambda14', desc='Parameter in asset demand function')\n model.param('lambda20', desc='Parameter in asset demand function')\n model.param('lambda22', desc='Parameter in asset demand function')\n model.param('lambda23', desc='Parameter in asset demand function')\n model.param('lambda24', desc='Parameter in asset demand function')\n model.param('lambda30', desc='Parameter in asset demand function')\n model.param('lambda32', desc='Parameter in asset demand function')\n model.param('lambda33', desc='Parameter in asset demand function')\n model.param('lambda34', desc='Parameter in asset demand function')\n model.param('theta', desc='Tax rate')\n model.param('top', desc='Top value for TP')\n\n model.param('G', desc='Government goods')\n model.param('Pblbar', desc='Exogenously set price of bonds')\n model.param('Rbar', desc='Exogenously set interest rate on govt bills')\n\n model.add('Y = C + G') # 5.1\n model.add('YDr = Y - T + Rb(-1)*Bh(-1) + BLh(-1)') # 5.2\n model.add('T = theta *(Y + Rb(-1)*Bh(-1) + BLh(-1))') # 5.3\n model.add('V - V(-1) = (YDr - C) + CG') # 5.4\n model.add('CG = (Pbl - Pbl(-1))*BLh(-1)')\n model.add('C = alpha1*YDre + alpha2*V(-1)')\n model.add('Ve = V(-1) + (YDre - C) + CG')\n model.add('Hh = V - Bh - Pbl*BLh')\n model.add('Hd = Ve - Bd - Pbl*BLd')\n model.add('Bd = Ve*lambda20 + Ve*lambda22*Rb' +\n '- Ve*lambda23*ERrbl - lambda24*YDre')\n model.add('BLd = (Ve*lambda30 - Ve*lambda32*Rb ' +\n '+ Ve*lambda33*ERrbl - lambda34*YDre)/Pbl')\n model.add('Bh = Bd')\n model.add('BLh = BLd')\n model.add('Bs - Bs(-1) = (G + Rb(-1)*Bs(-1) + BLs(-1))' +\n ' - (T + Rb(-1)*Bcb(-1)) - Pbl*(BLs - BLs(-1))')\n model.add('Hs - Hs(-1) = Bcb - Bcb(-1)')\n model.add('Bcb = Bs - Bh')\n model.add('BLs = BLh')\n model.add('ERrbl = Rbl + ((chi * (Pble - Pbl))/ Pbl)')\n model.add('Rbl = 1./Pbl')\n model.add('Pble = Pble(-1) - betae*(Pble(-1) - Pbl) + add')\n model.add('CGe = chi * (Pble - Pbl)*BLh')\n model.add('YDre = YDr(-1)')\n model.add('Rb = Rbar')\n model.add('Pbl = (1 + z1*beta - z2*beta)*Pbl(-1)')\n model.add('z1 = if_true(TP > top)')\n model.add('z2 = if_true(TP < bot)')\n model.add('TP = (BLh(-1)*Pbl(-1))/(BLh(-1)*Pbl(-1) + Bh(-1))')\n\n return model\n\nlp2_parameters = {'alpha1': 0.8,\n 'alpha2': 0.2,\n 'beta': 0.01,\n 'betae': 0.5,\n 'chi': 0.1,\n 'lambda20': 0.44196,\n 'lambda22': 1.1,\n 'lambda23': 1,\n 'lambda24': 0.03,\n 'lambda30': 0.3997,\n 'lambda32': 1,\n 'lambda33': 1.1,\n 'lambda34': 0.03,\n 'theta': 0.1938,\n 'bot': 0.495,\n 'top': 0.505 }\nlp2_exogenous = {'G': 20,\n 'Rbar': 0.03,\n 'Pblbar': 20,\n 'add': 0}\nlp2_variables = {'V': 95.803,\n 'Bh': 37.839,\n 'Bs': 57.964,\n 'Bcb': 57.964 - 37.839,\n 'BLh': 1.892,\n 'BLs': 1.892,\n 'Hs': 20.125,\n 'YDr': 95.803,\n 'Rb': 0.03,\n 'Pbl': 20,\n 'Pble': 20,\n 'TP': 1.892*20/(1.892*20+37.839), # BLh*Pbl/(BLh*Pbl+Bh)\n 'z1': 0,\n 'z2': 0}", "_____no_output_____" ] ], [ [ "### Scenario: interest rate shock", "_____no_output_____" ] ], [ [ "lp2_bill = create_lp2_model()\n\nlp2_bill.set_values(lp2_parameters)\nlp2_bill.set_values(lp2_exogenous)\nlp2_bill.set_values(lp2_variables)\n\nlp2_bill.set_values({'z1': lp2_bill.evaluate('if_true(TP > top)'),\n 'z2': lp2_bill.evaluate('if_true(TP < bot)')})\n\nfor _ in xrange(10):\n lp2_bill.solve(iterations=100, threshold=1e-4)\n\n# shock the system\nlp2_bill.set_values({'Rbar': 0.035})\n\nfor _ in xrange(45):\n lp2_bill.solve(iterations=100, threshold=1e-4)\n", "_____no_output_____" ] ], [ [ "###### Figure 5.5", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.5 Evolution of the long-term interest rate (the bond yield), following an\n increase in the short-term interest rate (the bill rate), as a result of the response of\n the central bank and the Treasury, with Model LP2.'''\nrbdata = [s['Rb'] for s in lp2_bill.solutions[5:]]\npbldata = [1./s['Pbl'] for s in lp2_bill.solutions[5:]]\n\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 1.1, 0.9])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.set_ylim(0.029, 0.036)\naxes.plot(rbdata, linestyle='--', color='r')\n\n\naxes2 = axes.twinx()\naxes2.spines['top'].set_visible(False)\naxes2.set_ylim(0.0495, 0.052)\n\naxes2.plot(pbldata, 'k')\n\n# add labels\nplt.text(12, 0.0518, 'Short-term interest rate')\nplt.text(15, 0.0513, 'Long-term interest rate')\nfig.text(0.05, 1.05, 'Bill rate')\nfig.text(1.15, 1.05, 'Bond yield')\nfig.text(0.1, -.1, caption);", "_____no_output_____" ] ], [ [ "###### Figure 5.6", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.6 Evolution of the target proportion (TP), that is the share of bonds in the\n government debt held by households, following an increase in the short-term interest\n rate (the bill rate) and the response of the central bank and of the Treasury, \n with Model LP2'''\ntpdata = [s['TP'] for s in lp2_bill.solutions[5:]]\ntopdata = [s['top'] for s in lp2_bill.solutions[5:]]\nbotdata = [s['bot'] for s in lp2_bill.solutions[5:]]\n\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 1.1, 1.1])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.set_ylim(0.490, 0.506)\n\naxes.plot(topdata, color='k')\naxes.plot(botdata, color='k')\naxes.plot(tpdata, linestyle='--', color='r')\n\n# add labels\nplt.text(30, 0.5055, 'Ceiling of target range')\nplt.text(30, 0.494, 'Floor of target range')\nplt.text(10, 0.493, 'Share of bonds')\nplt.text(10, 0.4922, 'in government debt')\nplt.text(10, 0.4914, 'held by households')\nfig.text(0.1, -.15, caption);", "_____no_output_____" ] ], [ [ "### Scenario: Shock to the bond price expectations", "_____no_output_____" ] ], [ [ "lp2_bond = create_lp2_model()\n\nlp2_bond.set_values(lp2_parameters)\nlp2_bond.set_values(lp2_exogenous)\nlp2_bond.set_values(lp2_variables)\nlp2_bond.set_values({'z1': 'if_true(TP > top)',\n 'z2': 'if_true(TP < bot)'})\n\nfor _ in xrange(10):\n lp2_bond.solve(iterations=100, threshold=1e-5)\n \n# shock the system\nlp2_bond.set_values({'add': -3})\nlp2_bond.solve(iterations=100, threshold=1e-5)\nlp2_bond.set_values({'add': 0})\n\nfor _ in xrange(43):\n lp2_bond.solve(iterations=100, threshold=1e-4)\n", "_____no_output_____" ] ], [ [ "###### Figure 5.7", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.7 Evolution of the long-term interest rate, following an anticipated fall in\n the price of bonds, as a consequence of the response of the central bank and of the\n Treasury, with Model LP2'''\npbldata = [1./s['Pbl'] for s in lp2_bond.solutions[5:]]\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 0.9, 0.9])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(0.0497, 0.0512)\n\naxes.plot(pbldata, linestyle='--', color='k')\n\n# add labels\nplt.text(15, 0.0509, 'Long-term interest rate')\nfig.text(0.1, -.1, caption);", "_____no_output_____" ] ], [ [ "###### Figure 5.8", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.8 Evolution of the expected and actual bond prices, following an anticipated\n fall in the price of bonds, as a consequence of the response of the central bank and of\n the Treasury, with Model LP2'''\npbldata = [s['Pbl'] for s in lp2_bond.solutions[5:]]\npbledata = [s['Pble'] for s in lp2_bond.solutions[5:]]\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 0.9, 0.9])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(16.5, 21)\n\naxes.plot(pbldata, linestyle='--', color='k')\naxes.plot(pbledata, linestyle='-', color='r')\n\n# add labels\nplt.text(8, 20, 'Actual price of bonds')\nplt.text(10, 19, 'Expected price of bonds')\nfig.text(0.1, -.1, caption);", "_____no_output_____" ] ], [ [ "###### Figure 5.9", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.9 Evolution of the target proportion (TP), that is the share of bonds in the\n government debt held by households, following an anticipated fall in the price of\n bonds, as a consequence of the response of the central bank and of the Treasury, with\n Model LP2'''\ntpdata = [s['TP'] for s in lp2_bond.solutions[5:]]\nbotdata = [s['top'] for s in lp2_bond.solutions[5:]]\ntopdata = [s['bot'] for s in lp2_bond.solutions[5:]]\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 0.9, 0.9])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(0.47, 0.52)\n\naxes.plot(tpdata, linestyle='--', color='r')\naxes.plot(botdata, linestyle='-', color='k')\naxes.plot(topdata, linestyle='-', color='k')\n\n# add labels\nplt.text(30, 0.508, 'Ceiling of target range')\nplt.text(30, 0.491, 'Floor of target range')\nplt.text(10, 0.49, 'Share of bonds in')\nplt.text(10, 0.487, 'government debt')\nplt.text(10, 0.484, 'held by households')\nfig.text(0.1, -.15, caption);", "_____no_output_____" ] ], [ [ "### Scenario: Model LP1, propensity to consume shock", "_____no_output_____" ] ], [ [ "lp1_alpha = create_lp1_model()\nlp1_alpha.set_values(lp1_parameters)\nlp1_alpha.set_values(lp1_exogenous)\nlp1_alpha.set_values(lp1_variables)\n\nfor _ in xrange(10):\n lp1_alpha.solve(iterations=100, threshold=1e-6)\n\n# shock the system\nlp1_alpha.set_values({'alpha1': 0.7})\n\nfor _ in xrange(45):\n lp1_alpha.solve(iterations=100, threshold=1e-6)", "_____no_output_____" ] ], [ [ "### Model LP3", "_____no_output_____" ] ], [ [ "def create_lp3_model():\n model = Model()\n\n model.set_var_default(0)\n model.var('Bcb', desc='Government bills held by the Central Bank')\n model.var('Bd', desc='Demand for government bills')\n model.var('Bh', desc='Government bills held by households')\n model.var('Bs', desc='Government bills supplied by government')\n model.var('BLd', desc='Demand for government bonds')\n model.var('BLh', desc='Government bonds held by households')\n model.var('BLs', desc='Supply of government bonds')\n model.var('CG', desc='Capital gains on bonds')\n model.var('CGe', desc='Expected capital gains on bonds')\n model.var('C', desc='Consumption')\n model.var('ERrbl', desc='Expected rate of return on bonds')\n model.var('Hd', desc='Demand for cash')\n model.var('Hh', desc='Cash held by households')\n model.var('Hs', desc='Cash supplied by the central bank')\n model.var('Pbl', desc='Price of bonds')\n model.var('Pble', desc='Expected price of bonds')\n model.var('PSBR', desc='Public sector borrowing requirement (PSBR)')\n model.var('Rb', desc='Interest rate on government bills')\n model.var('Rbl', desc='Interest rate on government bonds')\n model.var('T', desc='Taxes')\n model.var('TP', desc='Target proportion in households portfolio')\n model.var('V', desc='Household wealth')\n model.var('Ve', desc='Expected household wealth')\n model.var('Y', desc='Income = GDP')\n model.var('YDr', desc='Regular disposable income of households')\n model.var('YDre', desc='Expected regular disposable income of households')\n model.var('z1', desc='Switch parameter')\n model.var('z2', desc='Switch parameter')\n model.var('z3', desc='Switch parameter')\n model.var('z4', desc='Switch parameter')\n\n # no longer exogenous\n model.var('G', desc='Government goods')\n\n model.set_param_default(0)\n model.param('add', desc='Random shock to expectations')\n model.param('add2', desc='Addition to the government expenditure setting rule')\n model.param('alpha1', desc='Propensity to consume out of income')\n model.param('alpha2', desc='Propensity to consume out of wealth')\n model.param('beta', desc='Adjustment parameter in price of bills')\n model.param('betae', desc='Adjustment parameter in expectations')\n model.param('bot', desc='Bottom value for TP')\n model.param('chi', desc='Weight of conviction in expected bond price')\n model.param('lambda10', desc='Parameter in asset demand function')\n model.param('lambda12', desc='Parameter in asset demand function')\n model.param('lambda13', desc='Parameter in asset demand function')\n model.param('lambda14', desc='Parameter in asset demand function')\n model.param('lambda20', desc='Parameter in asset demand function')\n model.param('lambda22', desc='Parameter in asset demand function')\n model.param('lambda23', desc='Parameter in asset demand function')\n model.param('lambda24', desc='Parameter in asset demand function')\n model.param('lambda30', desc='Parameter in asset demand function')\n model.param('lambda32', desc='Parameter in asset demand function')\n model.param('lambda33', desc='Parameter in asset demand function')\n model.param('lambda34', desc='Parameter in asset demand function')\n model.param('theta', desc='Tax rate')\n model.param('top', desc='Top value for TP')\n\n model.param('Pblbar', desc='Exogenously set price of bonds')\n model.param('Rbar', desc='Exogenously set interest rate on govt bills')\n\n model.add('Y = C + G') # 5.1\n model.add('YDr = Y - T + Rb(-1)*Bh(-1) + BLh(-1)') # 5.2\n model.add('T = theta *(Y + Rb(-1)*Bh(-1) + BLh(-1))') # 5.3\n model.add('V - V(-1) = (YDr - C) + CG') # 5.4\n model.add('CG = (Pbl - Pbl(-1))*BLh(-1)')\n model.add('C = alpha1*YDre + alpha2*V(-1)')\n model.add('Ve = V(-1) + (YDre - C) + CG')\n model.add('Hh = V - Bh - Pbl*BLh')\n model.add('Hd = Ve - Bd - Pbl*BLd')\n model.add('Bd = Ve*lambda20 + Ve*lambda22*Rb' +\n '- Ve*lambda23*ERrbl - lambda24*YDre')\n model.add('BLd = (Ve*lambda30 - Ve*lambda32*Rb ' +\n '+ Ve*lambda33*ERrbl - lambda34*YDre)/Pbl')\n model.add('Bh = Bd')\n model.add('BLh = BLd')\n model.add('Bs - Bs(-1) = (G + Rb(-1)*Bs(-1) + BLs(-1))' +\n ' - (T + Rb(-1)*Bcb(-1)) - Pbl*(BLs - BLs(-1))')\n model.add('Hs - Hs(-1) = Bcb - Bcb(-1)')\n model.add('Bcb = Bs - Bh')\n model.add('BLs = BLh')\n model.add('ERrbl = Rbl + ((chi * (Pble - Pbl))/ Pbl)')\n model.add('Rbl = 1./Pbl')\n model.add('Pble = Pble(-1) - betae*(Pble(-1) - Pbl) + add')\n model.add('CGe = chi * (Pble - Pbl)*BLh')\n model.add('YDre = YDr(-1)')\n model.add('Rb = Rbar')\n model.add('Pbl = (1 + z1*beta - z2*beta)*Pbl(-1)')\n model.add('z1 = if_true(TP > top)')\n model.add('z2 = if_true(TP < bot)')\n model.add('TP = (BLh(-1)*Pbl(-1))/(BLh(-1)*Pbl(-1) + Bh(-1))')\n model.add('PSBR = (G + Rb*Bs(-1) + BLs(-1)) - (T + Rb*Bcb(-1))')\n model.add('z3 = if_true((PSBR(-1)/Y(-1)) > 0.03)')\n model.add('z4 = if_true((PSBR(-1)/Y(-1)) < -0.03)')\n model.add('G = G(-1) - (z3 + z4)*PSBR(-1) + add2')\n\n return model\n\nlp3_parameters = {'alpha1': 0.8,\n 'alpha2': 0.2,\n 'beta': 0.01,\n 'betae': 0.5,\n 'chi': 0.1,\n 'lambda20': 0.44196,\n 'lambda22': 1.1,\n 'lambda23': 1,\n 'lambda24': 0.03,\n 'lambda30': 0.3997,\n 'lambda32': 1,\n 'lambda33': 1.1,\n 'lambda34': 0.03,\n 'theta': 0.1938,\n 'bot': 0.495,\n 'top': 0.505 }\nlp3_exogenous = {'Rbar': 0.03,\n 'Pblbar': 20,\n 'add': 0,\n 'add2': 0}\nlp3_variables = {'G': 20,\n 'V': 95.803,\n 'Bh': 37.839,\n 'Bs': 57.964,\n 'Bcb': 57.964 - 37.839,\n 'BLh': 1.892,\n 'BLs': 1.892,\n 'Hs': 20.125,\n 'YDr': 95.803,\n 'Rb': 0.03,\n 'Pbl': 20,\n 'Pble': 20,\n 'PSBR': 0,\n 'Y': 115.8,\n 'TP': 1.892*20/(1.892*20+37.839), # BLh*Pbl/(BLh*Pbl+Bh)\n 'z1': 0,\n 'z2': 0,\n 'z3': 0,\n 'z4': 0}", "_____no_output_____" ] ], [ [ "### Scenario: LP3, decrease in propensity to consume", "_____no_output_____" ] ], [ [ "lp3_alpha = create_lp3_model()\nlp3_alpha.set_values(lp3_parameters)\nlp3_alpha.set_values(lp3_exogenous)\nlp3_alpha.set_values(lp3_variables)\n\nfor _ in xrange(10):\n lp3_alpha.solve(iterations=100, threshold=1e-6)\n\n# shock the system\nlp3_alpha.set_values({'alpha1': 0.7})\n\nfor _ in xrange(45):\n lp3_alpha.solve(iterations=100, threshold=1e-6)", "_____no_output_____" ] ], [ [ "###### Figure 5.10", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.10 Evolution of national income (GDP), following a sharp decrease in the\n propensity to consume out of current income, with Model LP1'''\nydata = [s['Y'] for s in lp1_alpha.solutions[5:]]\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 0.9, 0.9])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(90, 128)\n\naxes.plot(ydata, linestyle='--', color='k')\n\n# add labels\nplt.text(20, 110, 'Gross Domestic Product')\nfig.text(0.1, -.05, caption);", "_____no_output_____" ] ], [ [ "###### Figure 5.11", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.11 Evolution of national income (GDP), following a sharp decrease in the\n propensity to consume out of current income, with Model LP3'''\nydata = [s['Y'] for s in lp3_alpha.solutions[5:]]\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 0.9, 0.9])\naxes.tick_params(top='off', right='off')\naxes.spines['top'].set_visible(False)\naxes.spines['right'].set_visible(False)\naxes.set_ylim(90, 128)\n\naxes.plot(ydata, linestyle='--', color='k')\n\n# add labels\nplt.text(20, 110, 'Gross Domestic Product')\nfig.text(0.1, -.05, caption);", "_____no_output_____" ] ], [ [ "###### Figure 5.12", "_____no_output_____" ] ], [ [ "caption = '''\n Figure 5.12 Evolution of pure government expenditures and of the government deficit\n to national income ratio (the PSBR to GDP ratio), following a sharp decrease in the\n propensity to consume out of current income, with Model LP3'''\ngdata = [s['G'] for s in lp3_alpha.solutions[5:]]\nratiodata = [s['PSBR']/s['Y'] for s in lp3_alpha.solutions[5:]]\n\nfig = plt.figure()\naxes = fig.add_axes([0.1, 0.1, 0.9, 0.9])\naxes.tick_params(top='off')\naxes.spines['top'].set_visible(False)\naxes.set_ylim(16, 20.5)\naxes.plot(gdata, linestyle='--', color='r')\n\nplt.text(5, 20.4, 'Pure government')\nplt.text(5, 20.15, 'expenditures (LHS)')\nplt.text(30, 18, 'Deficit to national')\nplt.text(30, 17.75, 'income ration (RHS)')\n\naxes2 = axes.twinx()\naxes2.tick_params(top='off')\naxes2.spines['top'].set_visible(False)\naxes2.set_ylim(-.01, 0.04)\naxes2.plot(ratiodata, linestyle='-', color='b')\n\n# add labels\nfig.text(0.1, 1.05, 'G')\nfig.text(0.9, 1.05, 'PSBR to Y ratio')\nfig.text(0.1, -.1, caption);", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af8e9b65e58a0892f9ab7cb064f1431b1d758b3
10,828
ipynb
Jupyter Notebook
example_feature_types.ipynb
yu-iskw/auto-sklearn-examples
816af2d1d136bbcc197d30691e5785e088fee040
[ "Apache-2.0" ]
14
2017-06-13T05:34:01.000Z
2020-04-05T14:06:59.000Z
example_feature_types.ipynb
afcarl/auto-sklearn-examples
816af2d1d136bbcc197d30691e5785e088fee040
[ "Apache-2.0" ]
null
null
null
example_feature_types.ipynb
afcarl/auto-sklearn-examples
816af2d1d136bbcc197d30691e5785e088fee040
[ "Apache-2.0" ]
9
2018-06-10T17:21:06.000Z
2021-02-20T14:09:05.000Z
28.124675
165
0.414204
[ [ [ "import pandas as pd\n\nimport sklearn.model_selection\nimport sklearn.datasets\nimport sklearn.metrics\n\nimport autosklearn.classification\n\ntry:\n import openml\nexcept ImportError:\n print(\"#\"*80 + \"\"\"\n To run this example you need to install openml-python:\n pip install git+https://github.com/renatopp/liac-arff\n pip install requests xmltodict\n pip install git+https://github.com/openml/openml-python@develop --no-deps\\n\"\"\" +\n \"#\"*80)\n raise", "_____no_output_____" ], [ "# Load adult dataset from openml.org, see https://www.openml.org/t/2117\nopenml.config.apikey = '610344db6388d9ba34f6db45a3cf71de'\n\ntask = openml.tasks.get_task(2117)\ntrain_indices, test_indices = task.get_train_test_split_indices()\nX, y = task.get_X_and_y()", "_____no_output_____" ], [ "pd.DataFrame(X).head()", "_____no_output_____" ], [ "pd.DataFrame(y).head()", "_____no_output_____" ], [ "X_train = X[train_indices]\ny_train = y[train_indices]\nX_test = X[test_indices]\ny_test = y[test_indices]\n\ndataset = task.get_dataset()\n_, _, categorical_indicator = dataset.\\\n get_data(target=task.target_name, return_categorical_indicator=True)\n\n# Create feature type list from openml.org indicator and run autosklearn\nfeat_type = ['Categorical' if ci else 'Numerical'\n for ci in categorical_indicator]\n\ncls = autosklearn.classification.\\\n AutoSklearnClassifier(time_left_for_this_task=120,\n per_run_time_limit=30)\ncls.fit(X_train, y_train, feat_type=feat_type)\n\npredictions = cls.predict(X_test)\nprint(\"Accuracy score\", sklearn.metrics.accuracy_score(y_test, predictions))", "[WARNING] [2017-05-17 16:24:01,222:smac.intensification.intensification.Intensifier] Challenger was the same as the current incumbent; Skipping challenger\n[WARNING] [2017-05-17 16:24:01,222:smac.intensification.intensification.Intensifier] Challenger was the same as the current incumbent; Skipping challenger\n[WARNING] [2017-05-17 16:24:01,227:smac.intensification.intensification.Intensifier] Challenger was the same as the current incumbent; Skipping challenger\n[WARNING] [2017-05-17 16:24:01,227:smac.intensification.intensification.Intensifier] Challenger was the same as the current incumbent; Skipping challenger\nAccuracy score 0.851523236334\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4af8eab9583049a31e4f4554d56f7645c8d08d66
143,967
ipynb
Jupyter Notebook
DataScience365/Day 9/EDA Cannabis.ipynb
HiteshGorana/DataScience365
1be776e6a6794ef8a1c33210f4dcafa26fd51bd5
[ "MIT" ]
49
2018-09-06T10:52:13.000Z
2021-11-13T07:31:14.000Z
DataScience365/Day 9/EDA Cannabis.ipynb
HiteshGorana/awesome-data-science
1be776e6a6794ef8a1c33210f4dcafa26fd51bd5
[ "MIT" ]
2
2018-09-06T11:13:14.000Z
2018-10-03T09:51:29.000Z
DataScience365/Day 9/EDA Cannabis.ipynb
HiteshGorana/awesome-data-science
1be776e6a6794ef8a1c33210f4dcafa26fd51bd5
[ "MIT" ]
16
2018-09-06T11:14:34.000Z
2021-07-01T13:19:59.000Z
271.635849
39,456
0.914897
[ [ [ "# `Cannabis (drug)`", "_____no_output_____" ], [ "#### `INFORMATION`:\n\n### Everything we need to know about marijuana (cannabis)\n\n>`Cannabis, also known as marijuana among other names, is a psychoactive drug from the Cannabis plant used for medical or recreational purposes. The main psychoactive part of cannabis is tetrahydrocannabinol (THC), one of 483 known compounds in the plant, including at least 65 other cannabinoids. Cannabis can be used by smoking, vaporizing, within food, or as an extract`\n\n>[For more information](https://www.medicalnewstoday.com/articles/246392.php)\n\n[VIDEO](https://youtu.be/GhTYI3DeNgA)", "_____no_output_____" ], [ "![](https://cdn.shopify.com/s/files/1/0975/1130/files/GLPlantInfo_58b4c4d0-eda7-4fc3-97ed-1319ca431e62.jpg?v=1525710776)", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport missingno\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"dark\")\nimport warnings\nwarnings.simplefilter(\"ignore\")\nimport numpy as np", "_____no_output_____" ], [ "df = pd.read_csv(\"cannabis.csv\");df.head()", "_____no_output_____" ] ], [ [ "`Understainding attributes`\n\n>| Attribute Name | Info |\n| -------------- | -------------------------------------------- |\n| Strain Name | Given Name of strain |\n| Type | type of Strain(namly indica, sativa, hybrid) |\n| rating | User Rating |\n| Effects | Different effects optained |\n| Description | other backround info |\n", "_____no_output_____" ], [ "### UNDERSTAING DATA \nlike finding null values", "_____no_output_____" ] ], [ [ "df.shape#showing (row , columns)", "_____no_output_____" ], [ "df.info()#geting basic information like datatypes ", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 2351 entries, 0 to 2350\nData columns (total 6 columns):\nStrain 2351 non-null object\nType 2351 non-null object\nRating 2351 non-null float64\nEffects 2351 non-null object\nFlavor 2305 non-null object\nDescription 2318 non-null object\ndtypes: float64(1), object(5)\nmemory usage: 110.3+ KB\n" ], [ "#we can clearly see there are some missing values in Flavor and Description\nmissingno.matrix(df);\ndf.isnull().sum()#see null values", "_____no_output_____" ], [ "print(df.Type.value_counts())#counting the occurence of values\nsns.categorical.countplot(df.Type);#displaying it through graph", "hybrid 1212\nindica 699\nsativa 440\nName: Type, dtype: int64\n" ], [ "plt.ylabel(\"distribuition\")\nsns.distplot(df.Rating);\n#by this we can see that all the types have rating more than 3.5", "_____no_output_____" ], [ "#finding max rating to each type\ndf.groupby([\"Type\"])[\"Rating\"].max()", "_____no_output_____" ], [ "#finding min rating to each type\ndf.groupby([\"Type\"])[\"Rating\"].min()", "_____no_output_____" ], [ "#mean rating\ndf.groupby([\"Type\"])[\"Rating\"].mean()", "_____no_output_____" ], [ "#Now we will extract the values in Effects and Flavor and pass to a new column\neffect = pd.DataFrame(df.Effects.str.split(',',4).tolist(),\n columns = ['Eone','Etwo','Ethree','Efour','Efive'])\n\nflavors = pd.DataFrame(df.Flavor.str.split(',',n=2,expand=True).values.tolist(),\n columns = ['Fone','Ftwo','Fthree'])", "_____no_output_____" ], [ "df = pd.concat([df, effect], axis=1)\ndf = pd.concat([df, flavors], axis=1)#concating the two dataframes\n#for more information plz visit\n#link => http://pandas.pydata.org/pandas-docs/stable/merging.html", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "#finding top 5 effects\nprint(df.Eone.value_counts().head())\nplt.figure(figsize=(15,10))\nsns.boxplot(x = \"Eone\",y = \"Rating\",hue=\"Type\",data=df[df.Rating > 3.5]);", "Relaxed 825\nHappy 476\nEuphoric 249\nUplifted 244\nSleepy 89\nName: Eone, dtype: int64\n" ], [ "#finding top 5 Flavor\ndf.Eone.value_counts().head()\nplt.figure(figsize=(15,10))\nplt.xticks(rotation=90)\nsns.countplot(x = \"Fone\",data=df);", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af8f5954f87e4c18d0a7a35d933527fb0eebaf4
13,642
ipynb
Jupyter Notebook
category_pdf_processing/pdf_tables/extract_tables_camelot.ipynb
Anshul-GH/upwork_projects
600c2ccf79e5ed5cf962f1ae05c59f18ad411f63
[ "MIT" ]
2
2020-07-23T19:32:58.000Z
2020-10-24T20:54:09.000Z
category_pdf_processing/pdf_tables/extract_tables_camelot.ipynb
Anshul-GH/upwork_projects
600c2ccf79e5ed5cf962f1ae05c59f18ad411f63
[ "MIT" ]
null
null
null
category_pdf_processing/pdf_tables/extract_tables_camelot.ipynb
Anshul-GH/upwork_projects
600c2ccf79e5ed5cf962f1ae05c59f18ad411f63
[ "MIT" ]
1
2021-07-11T14:41:04.000Z
2021-07-11T14:41:04.000Z
87.448718
3,169
0.676147
[ [ [ "import ctypes\nfrom ctypes.util import find_library", "_____no_output_____" ], [ "find_library(''.join(('gsdll', str(ctypes.sizeof(ctypes.c_voidp) * 8), \".dll\")))", "_____no_output_____" ], [ "import tkinter", "_____no_output_____" ], [ "!pip install \"camelot-py[cv]\"", "Collecting camelot-py[cv]\n Downloading camelot_py-0.8.2-py3-none-any.whl (42 kB)\nRequirement already satisfied: openpyxl>=2.5.8 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from camelot-py[cv]) (3.0.4)\nRequirement already satisfied: numpy>=1.13.3 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from camelot-py[cv]) (1.18.5)\nCollecting pdfminer.six>=20200726\n Downloading pdfminer.six-20201018-py3-none-any.whl (5.6 MB)\nRequirement already satisfied: pandas>=0.23.4 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from camelot-py[cv]) (1.0.5)\nCollecting PyPDF2>=1.26.0\n Downloading PyPDF2-1.26.0.tar.gz (77 kB)\nRequirement already satisfied: chardet>=3.0.4 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from camelot-py[cv]) (3.0.4)\nRequirement already satisfied: click>=6.7 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from camelot-py[cv]) (7.1.2)\nCollecting opencv-python>=3.4.2.17; extra == \"cv\"\n Downloading opencv_python-4.4.0.44-cp38-cp38-win_amd64.whl (33.5 MB)\nRequirement already satisfied: et-xmlfile in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from openpyxl>=2.5.8->camelot-py[cv]) (1.0.1)\nRequirement already satisfied: jdcal in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from openpyxl>=2.5.8->camelot-py[cv]) (1.4.1)\nRequirement already satisfied: sortedcontainers in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from pdfminer.six>=20200726->camelot-py[cv]) (2.2.2)\nRequirement already satisfied: cryptography in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from pdfminer.six>=20200726->camelot-py[cv]) (2.9.2)\nRequirement already satisfied: pytz>=2017.2 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from pandas>=0.23.4->camelot-py[cv]) (2020.1)\nRequirement already satisfied: python-dateutil>=2.6.1 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from pandas>=0.23.4->camelot-py[cv]) (2.8.1)\nRequirement already satisfied: six>=1.4.1 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from cryptography->pdfminer.six>=20200726->camelot-py[cv]) (1.15.0)\nRequirement already satisfied: cffi!=1.11.3,>=1.8 in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from cryptography->pdfminer.six>=20200726->camelot-py[cv]) (1.14.0)\nRequirement already satisfied: pycparser in c:\\users\\anshul_jain\\anaconda3\\lib\\site-packages (from cffi!=1.11.3,>=1.8->cryptography->pdfminer.six>=20200726->camelot-py[cv]) (2.20)\nBuilding wheels for collected packages: PyPDF2\n Building wheel for PyPDF2 (setup.py): started\n Building wheel for PyPDF2 (setup.py): finished with status 'done'\n Created wheel for PyPDF2: filename=PyPDF2-1.26.0-py3-none-any.whl size=61087 sha256=ee35b288f45c014efcf60f663fc3d17f1d902d97b7b090cbb925b8343855a13c\n Stored in directory: c:\\users\\anshul_jain\\appdata\\local\\pip\\cache\\wheels\\b1\\1a\\8f\\a4c34be976825a2f7948d0fa40907598d69834f8ab5889de11\nSuccessfully built PyPDF2\nInstalling collected packages: pdfminer.six, PyPDF2, opencv-python, camelot-py\nSuccessfully installed PyPDF2-1.26.0 camelot-py-0.8.2 opencv-python-4.4.0.44 pdfminer.six-20201018\n" ], [ "import camelot", "_____no_output_____" ], [ "# pdf file to extract tables from\nfile_name = 'foo.pdf'", "_____no_output_____" ], [ "!dir", " Volume in drive D is DATA\n Volume Serial Number is B287-58A3\n\n Directory of d:\\code\\freelance_projects-master\\freelance_projects-master\\category_python_doc_processing\\pdf_tables\n\n10/21/2020 01:01 AM <DIR> .\n10/21/2020 01:01 AM <DIR> ..\n10/21/2020 12:54 AM 0 extract_tables_pdf.ipynb\n10/20/2020 11:41 PM 84,158 foo.pdf\n10/21/2020 12:54 AM 31 README.md\n 3 File(s) 84,189 bytes\n 2 Dir(s) 731,079,385,088 bytes free\n" ], [ "tables = camelot.read_pdf(file_name)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af915441abeb8f87d6eb3b48c55dda78ea9ff54
26,659
ipynb
Jupyter Notebook
notebooks/deeplearning.ai/02-quiz.ipynb
gyuho/dplearn
ca65d481a33233213ac1070314935fcad4e9ee63
[ "MIT" ]
69
2017-11-08T02:02:39.000Z
2020-12-27T15:47:01.000Z
notebooks/deeplearning.ai/02-quiz.ipynb
gyuho/dplearn
ca65d481a33233213ac1070314935fcad4e9ee63
[ "MIT" ]
1
2022-03-02T01:10:13.000Z
2022-03-02T01:10:13.000Z
notebooks/deeplearning.ai/02-quiz.ipynb
gyuho/dplearn
ca65d481a33233213ac1070314935fcad4e9ee63
[ "MIT" ]
14
2017-11-10T05:58:30.000Z
2021-07-07T03:58:53.000Z
33.449184
423
0.568213
[ [ [ "##### week1-Q1.\n\nWhat does the analogy “AI is the new electricity” refer to?\n\n1. Through the “smart grid”, AI is delivering a new wave of electricity.\n2. AI runs on computers and is thus powered by electricity, but it is letting computers do things not possible before.\n3. Similar to electricity starting about 100 years ago, AI is transforming multiple industries.\n4. AI is powering personal devices in our homes and offices, similar to electricity.\n\n<span style=\"color:blue\">\nAnswer: 3.\nAI is transforming many fields from the car industry to agriculture to supply-chain.\n</span>", "_____no_output_____" ], [ "##### week1-Q2.\n\nWhich of these are reasons for Deep Learning recently taking off? (Check the three options that apply.)\n\n1. Deep learning has resulted in significant improvements in important applications such as online advertising, speech recognition, and image recognition.\n2. Neural Networks are a brand new field.\n3. We have access to a lot more data.\n4. We have access to a lot more computational power.\n\n<span style=\"color:blue\">\nAnswer: 1,3,4.\nThe digitalization of our society has played a huge role in this. The development of hardware, perhaps especially GPU computing, has significantly improved deep learning algorithms' performance.\n</span>", "_____no_output_____" ], [ "##### week1-Q3.\n\nRecall this diagram of iterating over different ML ideas. Which of the statements below are true? (Check all that apply.)\n\n<img src=\"images/cycle.png\" alt=\"cycle.png\" style=\"width:300px\"/>\n\n1. Being able to try out ideas quickly allows deep learning engineers to iterate more quickly.\n2. Faster computation can help speed up how long a team takes to iterate to a good idea.\n3. It is faster to train on a big dataset than a small dataset.\n4. Recent progress in deep learning algorithms has allowed us to train good models faster (even without changing the CPU/GPU hardware).\n\n<span style=\"color:blue\">\nAnswer: 1,2,4.\nFor example, we discussed how switching from sigmoid to ReLU activation functions allows faster training.\n</span>", "_____no_output_____" ], [ "##### week1-Q4.\n\nWhen an experienced deep learning engineer works on a new problem, they can usually use insight from previous problems to train a good model on the first try, without needing to iterate multiple times through different models. True/False?\n\n<span style=\"color:blue\">\nAnswer: False.\nFinding the characteristics of a model is key to have good performance. Although experience can help, it requires multiple iterations to build a good model.\n</span>", "_____no_output_____" ], [ "##### week1-Q5.\n\nReLU activation function?\n\n![relu-quiz.png](images/relu-quiz.png)", "_____no_output_____" ], [ "##### week1-Q6.\n\nImages for cat recognition is an example of “structured” data, because it is represented as a structured array in a computer. True/False?\n\n<span style=\"color:blue\">\nAnswer: False.\nImages for cat recognition is an example of “unstructured” data.\n</span>", "_____no_output_____" ], [ "##### week1-Q7.\n\nA demographic dataset with statistics on different cities' population, GDP per capita, economic growth is an example of “unstructured” data because it contains data coming from different sources. True/False?\n\n<span style=\"color:blue\">\nAnswer: False.\nA demographic dataset with statistics on different cities' population, GDP per capita, economic growth is an example of “structured” data by opposition to image, audio or text datasets.\n</span>", "_____no_output_____" ], [ "##### week1-Q8.\n\nWhy is an RNN (Recurrent Neural Network) used for machine translation, say translating English to French? (Check all that apply.)\n\n1. It can be trained as a supervised learning problem.\n2. It is strictly more powerful than a Convolutional Neural Network (CNN).\n3. It is applicable when the input/output is a sequence (e.g., a sequence of words).\n4. RNNs represent the recurrent process of Idea->Code->Experiment->Idea->....\n\n<span style=\"color:blue\">\nAnswer: 1,3.\nAn RNN can map from a sequence of english words to a sequence of french words.\n</span>", "_____no_output_____" ], [ "##### week1-Q9.\n\nIn this diagram which we hand-drew in lecture, what do the horizontal axis (x-axis) and vertical axis (y-axis) represent?\n\n<img src=\"images/networks.png\" alt=\"networks.png\" style=\"width:550px\"/>\n\n<span style=\"color:blue\">\nAnswer: x-axis is the amount of data.\ny-axis (vertical axis) is the performance of the algorithm.\n</span>", "_____no_output_____" ], [ "##### week1-Q10.\n\nAssuming the trends described in the previous question's figure are accurate (and hoping you got the axis labels right), which of the following are true? (Check all that apply.)\n\n1. Decreasing the training set size generally does not hurt an algorithm’s performance, and it may help significantly.\n2. Increasing the size of a neural network generally does not hurt an algorithm’s performance, and it may help significantly.\n3. Increasing the training set size generally does not hurt an algorithm’s performance, and it may help significantly.\n4. Decreasing the size of a neural network generally does not hurt an algorithm’s performance, and it may help significantly.\n\n<span style=\"color:blue\">\nAnswer: 2,3.\nAccording to the trends in the figure above, big networks usually perform better than small networks.\nBringing more data to a model is almost always beneficial.\n</span>", "_____no_output_____" ], [ "##### week2-Q3.\n\nSuppose img is a `(32,32,3)` array, representing a 32x32 image with 3 color channels red, green and blue. How do you reshape this into a column vector?\n\n<span style=\"color:blue\">\nAnswer: x = img.reshape((32\\*32\\*3,1)).\n</span>", "_____no_output_____" ], [ "##### week2-Q4.\n\nConsider the two following random arrays \"a\" and \"b\".\nWhat will be the shape of \"c\"?", "_____no_output_____" ] ], [ [ "import numpy as np\na = np.random.randn(2, 3) # a.shape = (2, 3)\nb = np.random.randn(2, 1) # b.shape = (2, 1)\nc = a + b\nprint(c.shape)", "(2, 3)\n" ] ], [ [ "<span style=\"color:blue\">\nAnswer: This is broadcasting. b (column vector) is copied 3 times so that it can be summed to each column of a.\n</span>", "_____no_output_____" ], [ "##### week2-Q5.\n\nConsider the two following random arrays \"a\" and \"b\".\nWhat will be the shape of \"c\"?", "_____no_output_____" ] ], [ [ "a = np.random.randn(4, 3) # a.shape = (4, 3)\nb = np.random.randn(3, 2) # b.shape = (3, 2)\n\n# operands could not be broadcast together with shapes (4,3) (3,2) \n# print((a*b).shape)\n\nprint((np.dot(a,b)).shape)", "(4, 2)\n" ] ], [ [ "<span style=\"color:blue\">\nAnswer: The computation cannot happen because the sizes don't match. It's going to be \"Error\"!\nIn numpy the \"*\" operator indicates element-wise multiplication. It is different from \"np.dot()\". If you would try \"c = np.dot(a,b)\" you would get c.shape = (4, 2).\n</span>", "_____no_output_____" ], [ "##### week2-Q7.\n\nRecall that \"np.dot(a,b)\" performs a matrix multiplication on a and b, whereas \"a*b\" performs an element-wise multiplication.\n\nConsider the two following random arrays \"a\" and \"b\":", "_____no_output_____" ] ], [ [ "a = np.random.randn(12288, 150) # a.shape = (12288, 150)\nb = np.random.randn(150, 45) # b.shape = (150, 45)\nc = np.dot(a,b)\nprint(c.shape)", "(12288, 45)\n" ] ], [ [ "<span style=\"color:blue\">\nAnswer: Remember that a np.dot(a, b) has shape (number of rows of a, number of columns of b). The sizes match because : \"number of columns of a = 150 = number of rows of b\"\n</span>", "_____no_output_____" ], [ "##### week2-Q8.\n\nConsider the following code snippet. How do you vectorize this?", "_____no_output_____" ] ], [ [ "a = np.random.randn(3,4)\nb = np.random.randn(4,1)\n\nfor i in range(3):\n for j in range(4):\n c[i][j] = a[i][j] + b[j]\n\nprint(c.shape)", "(3, 4)\n" ], [ "c = a + b.T\nprint(c.shape)", "(3, 4)\n" ] ], [ [ "##### week2-Q9.\n\nConsider the following code:", "_____no_output_____" ] ], [ [ "a = np.random.randn(3, 3)\nb = np.random.randn(3, 1)\nc = a*b\nprint(c.shape)", "(3, 3)\n" ] ], [ [ "What will be c? (If you’re not sure, feel free to run this in python to find out).\n\n<span style=\"color:blue\">\nAnswer: This will invoke broadcasting, so b is copied three times to become (3,3), and ∗ is an element-wise product so c.shape will be (3, 3).\n</span>", "_____no_output_____" ], [ "##### week3-Q5.\n\nConsider the following code:", "_____no_output_____" ] ], [ [ "import numpy as np\nA = np.random.randn(4,3)\nB = np.sum(A, axis=1, keepdims=True)\nprint(B.shape)", "(4, 1)\n" ] ], [ [ "<span style=\"color:blue\">\nAnswer: We use (keepdims = True) to make sure that A.shape is (4,1) and not (4, ). It makes our code more rigorous.\n</span>", "_____no_output_____" ], [ "##### week2-Q10.\n\nConsider the following computation graph.\n\n<img src=\"images/computation.png\" alt=\"computation.png\" style=\"width:600px\"/>\n\nWhat is the output J?\n\n<span style=\"color:blue\">\nAnswer: `J = (a - 1) * (b + c)`\n\n`J = u + v - w = a*b + a*c - (b + c) = a * (b + c) - (b + c) = (a - 1) * (b + c)`.\n</span>", "_____no_output_____" ], [ "##### week2-Q2.\n\nWhich of these is the \"Logistic Loss\"?\n\n<span style=\"color:blue\">\nAnswer: $\\mathcal{L}^{(i)}(\\hat{y}^{(i)}, y^{(i)}) = y^{(i)}\\log(\\hat{y}^{(i)}) + (1- y^{(i)})\\log(1-\\hat{y}^{(i)})$\n</span>", "_____no_output_____" ], [ "##### week-Q6.\n\nHow many layers does this network have?\n\n<img src=\"images/n4.png\" alt=\"n4.png\" style=\"width:400px\" />\n\n<span style=\"color:blue\">\nAnswer: The number of layers $L$ is 4. The number of hidden layers is 3. As seen in lecture, the number of layers is counted as the number of hidden layers + 1. The input and output layers are not counted as hidden layers.\n</span>", "_____no_output_____" ], [ "##### week3-Q1.\n\nWhich of the following are true? (Check all that apply.)\n\n- $a^{[2]}$ denotes the activation vector of the $2^{nd}$ layer. <span style=\"color:blue\">(True)</span>\n- $a^{[2]}_4$ is the activation output by the $4^{th}$ neuron of the $2^{nd}$ layer. <span style=\"color:blue\">(True)</span>\n- $a^{[2](12)}$ denotes the activation vector of the $2^{nd}$ layer for the $12^{th}$ training example.<span style=\"color:blue\">(True)</span>\n- $X$ is a matrix in which each column is one training example. <span style=\"color:blue\">(True)</span>", "_____no_output_____" ], [ "##### week2-Q1.\n\nWhat does a neuron compute?\n\n<span style=\"color:blue\">\nAnswer: A neuron computes a linear function `(z = Wx + b)` followed by an activation function.\nThe output of a neuron is `a = g(Wx + b)` where `g` is the activation function (sigmoid, tanh, ReLU, ...).\n</span>", "_____no_output_____" ], [ "##### week3-Q3.\n\nVectorized implementation of forward propagation for layer $l$, where $1 \\leq l \\leq L$?\n\n<span style=\"color:blue\">\nAnswer:\n$$Z^{[l]} = W^{[l]} A^{[l-1]}+ b^{[l]}$$\n$$A^{[l]} = g^{[l]}(Z^{[l]})$$\n</span>", "_____no_output_____" ], [ "##### week-Q4.\n\nVectorization allows you to compute forward propagation in an L-layer neural network without an explicit for-loop (or any other explicit iterative loop) over the layers l=1, 2, …,L. True/False?\n\n<span style=\"color:blue\">\nAnswer: False.\nForward propagation propagates the input through the layers, although for shallow networks we may just write all the lines ($a^{[2]} = g^{[2]}(z^{[2]})$, $z^{[2]}= W^{[2]}a^{[1]}+b^{[2]}$, ...) in a deeper network, we cannot avoid a for loop iterating over the layers: ($a^{[l]} = g^{[l]}(z^{[l]})$, $z^{[l]} = W^{[l]}a^{[l-1]} + b^{[l]}$, ...).\n</span>", "_____no_output_____" ], [ "##### week-Q5.\n\nAssume we store the values for $n^{[l]}$ in an array called layers, as follows: layer_dims = $[n_x,4,3,2,1]$. So layer 1 has four hidden units, layer 2 has 3 hidden units and so on. Which of the following for-loops will allow you to initialize the parameters for the model?\n\n```python\nfor(i in range(1, len(layer_dims))):\n parameter[‘W’ + str(i)] = np.random.randn(layers[i], layers[i-1]) * 0.01\n parameter[‘b’ + str(i)] = np.random.randn(layers[i], 1) * 0.01\n```", "_____no_output_____" ], [ "##### week4-Q10.\n\nWhereas the previous question used a specific network, in the general case what is the dimension of $W^{[l]}$, the weight matrix associated with layer $l$?\n\n<span style=\"color:blue\">\nAnswer: $W^{[l]}$ has shape $(n^{[l]}, n^{[l-1]})$.\n</span>", "_____no_output_____" ], [ "##### week4-Q9.\n\nWhich of the following statements are True? (Check all that apply).\n\n<img src=\"./images/n2.png\" alt=\"n2.png\" style=\"width: 450px;\"/>\n\n1. $W^{[1]}$ will have shape (4, 4). <span style=\"color:blue\">True, shape of $W^{[l]}$ is $(n^{[l]}, n^{[l-1]})$</span>\n3. $W^{[2]}$ will have shape (3, 4). <span style=\"color:blue\">True, shape of $W^{[l]}$ is $(n^{[l]}, n^{[l-1]})$</span>\n3. $W^{[3]}$ will have shape (1, 3). <span style=\"color:blue\">True, shape of $W^{[l]}$ is $(n^{[l]}, n^{[l-1]})$</span>\n2. $b^{[1]}$ will have shape (4, 1). <span style=\"color:blue\">True, shape of $b^{[l]}$ is $(n^{[l]}, 1)$</span>\n4. $b^{[2]}$ will have shape (3, 1). <span style=\"color:blue\">True, shape of $b^{[l]}$ is $(n^{[l]}, 1)$</span>\n4. $b^{[3]}$ will have shape (1, 1). <span style=\"color:blue\">True, shape of $b^{[l]}$ is $(n^{[l]}, 1)$</span>", "_____no_output_____" ], [ "##### week3-Q9.\n\nConsider the following 1 hidden layer neural network:\n\n![1-hidden.png](images/1-hidden.png)\n\nWhich of the following statements are True? (Check all that apply).\n\n- $W^{[1]}$ will have shape (4, 2) <span style=\"color:blue\">(True)</span>\n- $W^{[2]}$ will have shape (1, 4) <span style=\"color:blue\">(True)</span>\n- $b^{[1]}$ will have shape (4, 1) <span style=\"color:blue\">(True)</span>\n- $b^{[2]}$ will have shape (1, 1) <span style=\"color:blue\">(True)</span>", "_____no_output_____" ], [ "##### week2-Q6.\n\nSuppose you have nx input features per example. Recall that $X = [x^{(1)} x^{(2)} ... x^{(m)}]$. What is the dimension of X?\n\n<span style=\"color:blue\">\nAnswer: $(n_x, m)$\n</span>", "_____no_output_____" ], [ "##### week3-Q10.\n\nIn the same network as the previous question, what are the dimensions of $Z^{[1]}$ and $A^{[1]}$?\n\n<span style=\"color:blue\">\nAnswer: $Z^{[1]}$ and $A^{[1]}$ are (4, m).\n</span>", "_____no_output_____" ], [ "##### week3-Q4.\n\nYou are building a binary classifier for recognizing cucumbers (y=1) vs. watermelons (y=0). Which one of these activation functions would you recommend using for the output layer?\n\n<span style=\"color:blue\">\nAnswer: sigmoid.\nSigmoid outputs a value between 0 and 1 which makes it a very good choice for binary classification. You can classify as 0 if the output is less than 0.5 and classify as 1 if the output is more than 0.5. It can be done with tanh as well but it is less convenient as the output is between -1 and 1.\n</span>", "_____no_output_____" ], [ "##### week3-Q2.\n\nThe tanh activation usually works better than sigmoid activation function for hidden units because the mean of its output is closer to zero, and so it centers the data better for the next layer. True/False?\n\n<span style=\"color:blue\">\nAnswer: True, as seen in lecture the output of the tanh is between -1 and 1, it thus centers the data which makes the learning simpler for the next layer.\n</span>", "_____no_output_____" ], [ "##### week3-Q8.\n\nYou have built a network using the tanh activation for all the hidden units. You initialize the weights to relative large values, using `np.random.randn(..,..)*1000`. What will happen?\n\n<span style=\"color:blue\">\nAnswer: This will cause the inputs of the tanh to also be very large, thus causing gradients to be close to zero. The optimization algorithm will thus become slow. `tanh` becomes flat for large values, this leads its gradient to be close to zero. This slows down the optimization algorithm.\n</span>", "_____no_output_____" ], [ "##### week3-Q6.\n\nSuppose you have built a neural network. You decide to initialize the weights and biases to be zero. Which of the following statements is true?\n\n<span style=\"color:blue\">\nAnswer: Each neuron in the first hidden layer will perform the same computation. So even after multiple iterations of gradient descent each neuron in the layer will be computing the same thing as other neurons.\n</span>", "_____no_output_____" ], [ "##### week3-Q7.\n\nLogistic regression’s weights w should be initialized randomly rather than to all zeros, because if you initialize to all zeros, then logistic regression will fail to learn a useful decision boundary because it will fail to “break symmetry”, True/False?\n\n<span style=\"color:blue\">\nAnswer: False.\nLogistic Regression doesn't have a hidden layer. If you initialize the weights to zeros, the first example x fed in the logistic regression will output zero but the derivatives of the Logistic Regression depend on the input x (because there's no hidden layer) which is not zero. So at the second iteration, the weights values follow x's distribution and are different from each other if x is not a constant vector.\n</span>", "_____no_output_____" ], [ "##### week4-Q1.\n\nWhat is the \"cache\" used for in our implementation of forward propagation and backward propagation?\n\n<span style=\"color:blue\">\nAnswer: We use it to pass variables computed during forward propagation to the corresponding backward propagation step. It contains useful values for backward propagation to compute derivatives. The \"cache\" records values from the forward propagation units and sends it to the backward propagation units because it is needed to compute the chain rule derivatives.\n</span>", "_____no_output_____" ], [ "##### week4-Q2.\n\nAmong the following, which ones are \"hyperparameters\"? (Check all that apply.)\n\n<span style=\"color:blue\">\nAnswer: learning rate $\\alpha$, number of layers $L$ in the neural network, number of iterations, size of the hidden layers $n^{[l]}$.\n</span>\n\n<span style=\"color:red\">\nNot hyperparameters: bias vectors $b^{[l]}$, weight matrices $W^{[l]}$, activation values $a^{[l]}$.\n</span>", "_____no_output_____" ], [ "##### week4-Q3.\n\nWhich of the following statements is true?\n\n1. The deeper layers of a neural network are typically computing more complex features of the input than the earlier layers.\n2. The earlier layers of a neural network are typically computing more complex features of the input than the deeper layers.\n\n<span style=\"color:blue\">\nAnswer: 1.\n</span>", "_____no_output_____" ], [ "##### week-Q7.\n\nDuring forward propagation, in the forward function for a layer l you need to know what is the activation function in a layer (Sigmoid, tanh, ReLU, etc.). During backpropagation, the corresponding backward function also needs to know what is the activation function for layer l, since the gradient depends on it. True/False?\n\n<span style=\"color:blue\">\nAnswer: True, as you've seen in the week 3 each activation has a different derivative. Thus, during backpropagation you need to know which activation was used in the forward propagation to be able to compute the correct derivative.\n</span>", "_____no_output_____" ], [ "##### week-Q8.\n\nThere are certain functions with the following properties:\n\n(i) To compute the function using a shallow network circuit, you will need a large network (where we measure size by the number of logic gates in the network), but (ii) To compute it using a deep network circuit, you need only an exponentially smaller network. True/False?\n\n<span style=\"color:blue\">\nAnswer: True.\n</span>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af9162844261e326c5aa362ba51e727494af0d3
364,699
ipynb
Jupyter Notebook
ML & DL Prediction Model/Diabetes Diseases/Diabetes Datasets with all Algorithms.ipynb
ankiii07/Automate-Diagnosis
3954db2669e35599847260df6e2cb278b31a4707
[ "Apache-2.0" ]
4
2021-09-03T14:43:52.000Z
2021-09-12T06:00:40.000Z
ML & DL Prediction Model/Diabetes Diseases/Diabetes Datasets with all Algorithms.ipynb
ankiii07/Automate-Diagnosis
3954db2669e35599847260df6e2cb278b31a4707
[ "Apache-2.0" ]
null
null
null
ML & DL Prediction Model/Diabetes Diseases/Diabetes Datasets with all Algorithms.ipynb
ankiii07/Automate-Diagnosis
3954db2669e35599847260df6e2cb278b31a4707
[ "Apache-2.0" ]
1
2021-09-03T14:42:56.000Z
2021-09-03T14:42:56.000Z
107.327546
31,592
0.706632
[ [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np", "_____no_output_____" ], [ "%matplotlib inline\nsns.set_style(\"whitegrid\")\nplt.style.use(\"fivethirtyeight\")", "_____no_output_____" ], [ "df = pd.read_csv('diabetes.csv')\ndf[0:10]", "_____no_output_____" ], [ "pd.set_option(\"display.float\", \"{:.2f}\".format)\ndf.describe()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 768 entries, 0 to 767\nData columns (total 9 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Pregnancies 768 non-null int64 \n 1 Glucose 768 non-null int64 \n 2 BloodPressure 768 non-null int64 \n 3 SkinThickness 768 non-null int64 \n 4 Insulin 768 non-null int64 \n 5 BMI 768 non-null float64\n 6 DiabetesPedigreeFunction 768 non-null float64\n 7 Age 768 non-null int64 \n 8 Outcome 768 non-null int64 \ndtypes: float64(2), int64(7)\nmemory usage: 54.1 KB\n" ], [ "missing_values_count = df.isnull().sum()\n\ntotal_cells = np.product(df.shape)\n\ntotal_missing = missing_values_count.sum()\n\npercentage_missing = (total_missing/total_cells)*100\nprint(percentage_missing)", "0.0\n" ], [ "from sklearn.ensemble import RandomForestRegressor", "_____no_output_____" ], [ "x = df.copy()\ny = x.pop('Outcome')", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split\nX_train,X_test,Y_train,Y_test = train_test_split(x,y,test_size=0.20,random_state=0)", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score", "_____no_output_____" ] ], [ [ "## logistic regression", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression()\n\nlr.fit(X_train,Y_train)\n\nY_pred_lr = lr.predict(X_test)", "C:\\Users\\ANKIT\\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" ], [ "score_lr = round(accuracy_score(Y_pred_lr,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using Logistic Regression is: \"+str(score_lr)+\" %\")", "The accuracy score achieved using Logistic Regression is: 82.47 %\n" ] ], [ [ "## Navie bayes", "_____no_output_____" ] ], [ [ "from sklearn.naive_bayes import GaussianNB\n\nnb = GaussianNB()\n\nnb.fit(X_train,Y_train)\n\nY_pred_nb = nb.predict(X_test)", "_____no_output_____" ], [ "score_nb = round(accuracy_score(Y_pred_nb,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using Naive Bayes is: \"+str(score_nb)+\" %\")", "The accuracy score achieved using Naive Bayes is: 79.22 %\n" ] ], [ [ "## Support Vector Machine", "_____no_output_____" ] ], [ [ "from sklearn import svm\n\nsv = svm.SVC(kernel='linear')\n\nsv.fit(X_train, Y_train)\n\nY_pred_svm = sv.predict(X_test)", "_____no_output_____" ], [ "score_svm = round(accuracy_score(Y_pred_svm,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using Linear SVM is: \"+str(score_svm)+\" %\")", "The accuracy score achieved using Linear SVM is: 81.82 %\n" ] ], [ [ "## KNN", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsClassifier\n\nknn = KNeighborsClassifier(n_neighbors=7)\nknn.fit(X_train,Y_train)\nY_pred_knn=knn.predict(X_test)", "_____no_output_____" ], [ "score_knn = round(accuracy_score(Y_pred_knn,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using KNN is: \"+str(score_knn)+\" %\")", "The accuracy score achieved using KNN is: 75.97 %\n" ] ], [ [ "## XG Boost", "_____no_output_____" ] ], [ [ "import xgboost as xgb\n\nxgb_model = xgb.XGBClassifier(objective=\"binary:logistic\", random_state=42)\nxgb_model.fit(X_train, Y_train)\n\nY_pred_xgb = xgb_model.predict(X_test)", "[18:40:58] WARNING: ..\\src\\learner.cc:1095: 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" ], [ "score_xgb = round(accuracy_score(Y_pred_xgb,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using XGBoost is: \"+str(score_xgb)+\" %\")", "The accuracy score achieved using XGBoost is: 75.97 %\n" ] ], [ [ "## Feature Scaling", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)", "_____no_output_____" ] ], [ [ "# Neural Network", "_____no_output_____" ] ], [ [ "from keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import Dense", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(Dense(11,activation='relu',input_dim=8))\nmodel.add(Dense(1,activation='sigmoid'))", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 11) 99 \n_________________________________________________________________\ndense_1 (Dense) (None, 1) 12 \n=================================================================\nTotal params: 111\nTrainable params: 111\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])", "_____no_output_____" ], [ "history = model.fit(X_train,Y_train, validation_data=(X_test, Y_test),epochs=200, batch_size=10)", "Epoch 1/200\n62/62 [==============================] - 0s 3ms/step - loss: 0.7180 - accuracy: 0.5586 - val_loss: 0.6417 - val_accuracy: 0.7143\nEpoch 2/200\n62/62 [==============================] - 0s 902us/step - loss: 0.6407 - accuracy: 0.6466 - val_loss: 0.5720 - val_accuracy: 0.7727\nEpoch 3/200\n62/62 [==============================] - 0s 902us/step - loss: 0.5888 - accuracy: 0.7003 - val_loss: 0.5261 - val_accuracy: 0.7922\nEpoch 4/200\n62/62 [==============================] - 0s 884us/step - loss: 0.5533 - accuracy: 0.7264 - val_loss: 0.4931 - val_accuracy: 0.7792\nEpoch 5/200\n62/62 [==============================] - 0s 923us/step - loss: 0.5268 - accuracy: 0.7459 - val_loss: 0.4695 - val_accuracy: 0.7922\nEpoch 6/200\n62/62 [==============================] - 0s 910us/step - loss: 0.5096 - accuracy: 0.7492 - val_loss: 0.4528 - val_accuracy: 0.7857\nEpoch 7/200\n62/62 [==============================] - 0s 939us/step - loss: 0.4968 - accuracy: 0.7590 - val_loss: 0.4423 - val_accuracy: 0.8052\nEpoch 8/200\n62/62 [==============================] - 0s 985us/step - loss: 0.4884 - accuracy: 0.7606 - val_loss: 0.4348 - val_accuracy: 0.8052\nEpoch 9/200\n62/62 [==============================] - 0s 918us/step - loss: 0.4827 - accuracy: 0.7638 - val_loss: 0.4295 - val_accuracy: 0.8117\nEpoch 10/200\n62/62 [==============================] - 0s 952us/step - loss: 0.4787 - accuracy: 0.7655 - val_loss: 0.4273 - val_accuracy: 0.8052\nEpoch 11/200\n62/62 [==============================] - 0s 983us/step - loss: 0.4758 - accuracy: 0.7704 - val_loss: 0.4247 - val_accuracy: 0.7987\nEpoch 12/200\n62/62 [==============================] - 0s 885us/step - loss: 0.4733 - accuracy: 0.7671 - val_loss: 0.4234 - val_accuracy: 0.8117\nEpoch 13/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4709 - accuracy: 0.7704 - val_loss: 0.4220 - val_accuracy: 0.8052\nEpoch 14/200\n62/62 [==============================] - 0s 969us/step - loss: 0.4692 - accuracy: 0.7720 - val_loss: 0.4221 - val_accuracy: 0.8052\nEpoch 15/200\n62/62 [==============================] - 0s 979us/step - loss: 0.4677 - accuracy: 0.7704 - val_loss: 0.4228 - val_accuracy: 0.7922\nEpoch 16/200\n62/62 [==============================] - 0s 911us/step - loss: 0.4662 - accuracy: 0.7769 - val_loss: 0.4233 - val_accuracy: 0.7987\nEpoch 17/200\n62/62 [==============================] - 0s 936us/step - loss: 0.4649 - accuracy: 0.7736 - val_loss: 0.4227 - val_accuracy: 0.7922\nEpoch 18/200\n62/62 [==============================] - 0s 870us/step - loss: 0.4643 - accuracy: 0.7785 - val_loss: 0.4242 - val_accuracy: 0.7987\nEpoch 19/200\n62/62 [==============================] - 0s 923us/step - loss: 0.4629 - accuracy: 0.7801 - val_loss: 0.4238 - val_accuracy: 0.7857\nEpoch 20/200\n62/62 [==============================] - 0s 884us/step - loss: 0.4615 - accuracy: 0.7769 - val_loss: 0.4240 - val_accuracy: 0.7857\nEpoch 21/200\n62/62 [==============================] - 0s 921us/step - loss: 0.4608 - accuracy: 0.7801 - val_loss: 0.4246 - val_accuracy: 0.7987\nEpoch 22/200\n62/62 [==============================] - 0s 883us/step - loss: 0.4599 - accuracy: 0.7801 - val_loss: 0.4245 - val_accuracy: 0.7922\nEpoch 23/200\n62/62 [==============================] - 0s 921us/step - loss: 0.4593 - accuracy: 0.7834 - val_loss: 0.4243 - val_accuracy: 0.7857\nEpoch 24/200\n62/62 [==============================] - 0s 885us/step - loss: 0.4581 - accuracy: 0.7818 - val_loss: 0.4244 - val_accuracy: 0.7922\nEpoch 25/200\n62/62 [==============================] - 0s 953us/step - loss: 0.4580 - accuracy: 0.7818 - val_loss: 0.4246 - val_accuracy: 0.7922\nEpoch 26/200\n62/62 [==============================] - 0s 866us/step - loss: 0.4568 - accuracy: 0.7818 - val_loss: 0.4263 - val_accuracy: 0.7987\nEpoch 27/200\n62/62 [==============================] - 0s 913us/step - loss: 0.4568 - accuracy: 0.7818 - val_loss: 0.4253 - val_accuracy: 0.7922\nEpoch 28/200\n62/62 [==============================] - 0s 908us/step - loss: 0.4556 - accuracy: 0.7850 - val_loss: 0.4269 - val_accuracy: 0.7987\nEpoch 29/200\n62/62 [==============================] - 0s 915us/step - loss: 0.4553 - accuracy: 0.7834 - val_loss: 0.4268 - val_accuracy: 0.7922\nEpoch 30/200\n62/62 [==============================] - 0s 960us/step - loss: 0.4544 - accuracy: 0.7866 - val_loss: 0.4274 - val_accuracy: 0.7922\nEpoch 31/200\n62/62 [==============================] - 0s 931us/step - loss: 0.4539 - accuracy: 0.7850 - val_loss: 0.4270 - val_accuracy: 0.8052\nEpoch 32/200\n62/62 [==============================] - 0s 963us/step - loss: 0.4537 - accuracy: 0.7834 - val_loss: 0.4280 - val_accuracy: 0.7922\nEpoch 33/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4530 - accuracy: 0.7866 - val_loss: 0.4280 - val_accuracy: 0.7922\nEpoch 34/200\n62/62 [==============================] - 0s 980us/step - loss: 0.4527 - accuracy: 0.7899 - val_loss: 0.4282 - val_accuracy: 0.7987\nEpoch 35/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4527 - accuracy: 0.7883 - val_loss: 0.4281 - val_accuracy: 0.7987\nEpoch 36/200\n62/62 [==============================] - 0s 975us/step - loss: 0.4517 - accuracy: 0.7866 - val_loss: 0.4296 - val_accuracy: 0.7987\nEpoch 37/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4523 - accuracy: 0.7834 - val_loss: 0.4318 - val_accuracy: 0.7987\nEpoch 38/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4509 - accuracy: 0.7883 - val_loss: 0.4301 - val_accuracy: 0.8052\nEpoch 39/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4505 - accuracy: 0.7899 - val_loss: 0.4306 - val_accuracy: 0.7987\nEpoch 40/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4504 - accuracy: 0.7883 - val_loss: 0.4314 - val_accuracy: 0.7987\nEpoch 41/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4498 - accuracy: 0.7866 - val_loss: 0.4313 - val_accuracy: 0.7987\nEpoch 42/200\n62/62 [==============================] - 0s 1ms/step - loss: 0.4500 - accuracy: 0.7883 - val_loss: 0.4332 - val_accuracy: 0.7987\nEpoch 43/200\n62/62 [==============================] - 0s 896us/step - loss: 0.4491 - accuracy: 0.7883 - val_loss: 0.4321 - val_accuracy: 0.7922\nEpoch 44/200\n62/62 [==============================] - 0s 880us/step - loss: 0.4485 - accuracy: 0.7883 - val_loss: 0.4340 - val_accuracy: 0.7987\nEpoch 45/200\n62/62 [==============================] - 0s 894us/step - loss: 0.4480 - accuracy: 0.7883 - val_loss: 0.4335 - val_accuracy: 0.7987\nEpoch 46/200\n62/62 [==============================] - 0s 951us/step - loss: 0.4488 - accuracy: 0.7883 - val_loss: 0.4317 - val_accuracy: 0.7987\nEpoch 47/200\n62/62 [==============================] - 0s 887us/step - loss: 0.4478 - accuracy: 0.7866 - val_loss: 0.4336 - val_accuracy: 0.7987\nEpoch 48/200\n62/62 [==============================] - 0s 901us/step - loss: 0.4473 - accuracy: 0.7883 - val_loss: 0.4339 - val_accuracy: 0.7987\nEpoch 49/200\n62/62 [==============================] - 0s 871us/step - loss: 0.4470 - accuracy: 0.7899 - val_loss: 0.4340 - val_accuracy: 0.7987\nEpoch 50/200\n62/62 [==============================] - 0s 894us/step - loss: 0.4472 - accuracy: 0.7883 - val_loss: 0.4339 - val_accuracy: 0.7987\nEpoch 51/200\n62/62 [==============================] - 0s 893us/step - loss: 0.4467 - accuracy: 0.7899 - val_loss: 0.4339 - val_accuracy: 0.7987\nEpoch 52/200\n62/62 [==============================] - 0s 895us/step - loss: 0.4460 - accuracy: 0.7883 - val_loss: 0.4360 - val_accuracy: 0.7987\nEpoch 53/200\n62/62 [==============================] - 0s 902us/step - loss: 0.4462 - accuracy: 0.7866 - val_loss: 0.4356 - val_accuracy: 0.7987\nEpoch 54/200\n62/62 [==============================] - 0s 865us/step - loss: 0.4456 - accuracy: 0.7850 - val_loss: 0.4371 - val_accuracy: 0.7987\nEpoch 55/200\n62/62 [==============================] - 0s 870us/step - loss: 0.4453 - accuracy: 0.7883 - val_loss: 0.4372 - val_accuracy: 0.7922\nEpoch 56/200\n62/62 [==============================] - 0s 900us/step - loss: 0.4454 - accuracy: 0.7883 - val_loss: 0.4367 - val_accuracy: 0.7922\nEpoch 57/200\n62/62 [==============================] - 0s 879us/step - loss: 0.4451 - accuracy: 0.7866 - val_loss: 0.4384 - val_accuracy: 0.7987\nEpoch 58/200\n" ], [ "import matplotlib.pyplot as plt\n%matplotlib inline\n# Model accuracy\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'])\nplt.show()", "_____no_output_____" ], [ "# Model Losss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'])\nplt.show()", "_____no_output_____" ], [ "Y_pred_nn = model.predict(X_test)\nrounded = [round(x[0]) for x in Y_pred_nn]\nY_pred_nn = rounded", "_____no_output_____" ], [ "score_nn = round(accuracy_score(Y_pred_nn,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using Neural Network is: \"+str(score_nn)+\" %\")", "The accuracy score achieved using Neural Network is: 78.57 %\n" ] ], [ [ "# Convolutional Neural Network", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten,BatchNormalization\nfrom tensorflow.keras.layers import Conv1D, MaxPool1D\nfrom tensorflow.keras.optimizers import Adam\nprint(tf.__version__)", "2.6.0\n" ], [ "X_train.shape", "_____no_output_____" ], [ "X_test.shape", "_____no_output_____" ], [ "x_train = X_train.reshape(614,8,1)\nx_test = X_test.reshape(154,8,1)", "_____no_output_____" ], [ "epochs = 100\nmodel = Sequential()\nmodel.add(Conv1D(filters=32, kernel_size=2, activation='relu', input_shape=(8,1)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv1D(filters=32, kernel_size=2, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv1D(filters=32, kernel_size=2, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(64,activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(1, activation='sigmoid'))", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv1d (Conv1D) (None, 7, 32) 96 \n_________________________________________________________________\nbatch_normalization (BatchNo (None, 7, 32) 128 \n_________________________________________________________________\ndropout (Dropout) (None, 7, 32) 0 \n_________________________________________________________________\nconv1d_1 (Conv1D) (None, 6, 32) 2080 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 6, 32) 128 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 6, 32) 0 \n_________________________________________________________________\nconv1d_2 (Conv1D) (None, 5, 32) 2080 \n_________________________________________________________________\nbatch_normalization_2 (Batch (None, 5, 32) 128 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 5, 32) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 160) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 64) 10304 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 64) 0 \n_________________________________________________________________\ndense_3 (Dense) (None, 1) 65 \n=================================================================\nTotal params: 15,009\nTrainable params: 14,817\nNon-trainable params: 192\n_________________________________________________________________\n" ], [ "model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.00005),metrics=['accuracy'])", "C:\\Users\\ANKIT\\anaconda3\\lib\\site-packages\\keras\\optimizer_v2\\optimizer_v2.py:355: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n warnings.warn(\n" ], [ "hists = model.fit(x_train, Y_train,validation_data=(x_test, Y_test), epochs=200, verbose=1)", "Epoch 1/200\n20/20 [==============================] - 1s 10ms/step - loss: 1.3487 - accuracy: 0.4430 - val_loss: 0.6906 - val_accuracy: 0.5260\nEpoch 2/200\n20/20 [==============================] - 0s 4ms/step - loss: 1.3368 - accuracy: 0.4397 - val_loss: 0.6831 - val_accuracy: 0.6688\nEpoch 3/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.3156 - accuracy: 0.4528 - val_loss: 0.6761 - val_accuracy: 0.6883\nEpoch 4/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.2257 - accuracy: 0.4479 - val_loss: 0.6694 - val_accuracy: 0.7013\nEpoch 5/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.2744 - accuracy: 0.4300 - val_loss: 0.6625 - val_accuracy: 0.6818\nEpoch 6/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.2613 - accuracy: 0.4788 - val_loss: 0.6548 - val_accuracy: 0.6818\nEpoch 7/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.2426 - accuracy: 0.4593 - val_loss: 0.6478 - val_accuracy: 0.6948\nEpoch 8/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.2635 - accuracy: 0.4528 - val_loss: 0.6403 - val_accuracy: 0.6948\nEpoch 9/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.1947 - accuracy: 0.4560 - val_loss: 0.6319 - val_accuracy: 0.7143\nEpoch 10/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.1105 - accuracy: 0.5081 - val_loss: 0.6248 - val_accuracy: 0.7143\nEpoch 11/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.1518 - accuracy: 0.5147 - val_loss: 0.6161 - val_accuracy: 0.7273\nEpoch 12/200\n20/20 [==============================] - 0s 4ms/step - loss: 1.1086 - accuracy: 0.4837 - val_loss: 0.6072 - val_accuracy: 0.7273\nEpoch 13/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.1768 - accuracy: 0.5033 - val_loss: 0.6000 - val_accuracy: 0.7338\nEpoch 14/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.1338 - accuracy: 0.4951 - val_loss: 0.5937 - val_accuracy: 0.7208\nEpoch 15/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.0458 - accuracy: 0.5391 - val_loss: 0.5882 - val_accuracy: 0.7338\nEpoch 16/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.1253 - accuracy: 0.5016 - val_loss: 0.5817 - val_accuracy: 0.7597\nEpoch 17/200\n20/20 [==============================] - 0s 4ms/step - loss: 1.1472 - accuracy: 0.4723 - val_loss: 0.5748 - val_accuracy: 0.7662\nEpoch 18/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.0534 - accuracy: 0.5114 - val_loss: 0.5687 - val_accuracy: 0.7532\nEpoch 19/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.0121 - accuracy: 0.5179 - val_loss: 0.5629 - val_accuracy: 0.7403\nEpoch 20/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9932 - accuracy: 0.5293 - val_loss: 0.5578 - val_accuracy: 0.7338\nEpoch 21/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9973 - accuracy: 0.5489 - val_loss: 0.5543 - val_accuracy: 0.7403\nEpoch 22/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.0572 - accuracy: 0.5358 - val_loss: 0.5511 - val_accuracy: 0.7532\nEpoch 23/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.1564 - accuracy: 0.5130 - val_loss: 0.5480 - val_accuracy: 0.7662\nEpoch 24/200\n20/20 [==============================] - 0s 3ms/step - loss: 1.0260 - accuracy: 0.5309 - val_loss: 0.5440 - val_accuracy: 0.7662\nEpoch 25/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9658 - accuracy: 0.5342 - val_loss: 0.5414 - val_accuracy: 0.7727\nEpoch 26/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9977 - accuracy: 0.5537 - val_loss: 0.5392 - val_accuracy: 0.7727\nEpoch 27/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9981 - accuracy: 0.5456 - val_loss: 0.5376 - val_accuracy: 0.7727\nEpoch 28/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9736 - accuracy: 0.5619 - val_loss: 0.5346 - val_accuracy: 0.7727\nEpoch 29/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9821 - accuracy: 0.5440 - val_loss: 0.5319 - val_accuracy: 0.7662\nEpoch 30/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9315 - accuracy: 0.5814 - val_loss: 0.5291 - val_accuracy: 0.7792\nEpoch 31/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9588 - accuracy: 0.5847 - val_loss: 0.5273 - val_accuracy: 0.7792\nEpoch 32/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9636 - accuracy: 0.5342 - val_loss: 0.5250 - val_accuracy: 0.7792\nEpoch 33/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9643 - accuracy: 0.5896 - val_loss: 0.5231 - val_accuracy: 0.7792\nEpoch 34/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9510 - accuracy: 0.5375 - val_loss: 0.5211 - val_accuracy: 0.7792\nEpoch 35/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9453 - accuracy: 0.5635 - val_loss: 0.5201 - val_accuracy: 0.7792\nEpoch 36/200\n20/20 [==============================] - 0s 4ms/step - loss: 0.8894 - accuracy: 0.5798 - val_loss: 0.5176 - val_accuracy: 0.7792\nEpoch 37/200\n20/20 [==============================] - 0s 4ms/step - loss: 0.8628 - accuracy: 0.5847 - val_loss: 0.5162 - val_accuracy: 0.7792\nEpoch 38/200\n20/20 [==============================] - 0s 4ms/step - loss: 0.8583 - accuracy: 0.6042 - val_loss: 0.5150 - val_accuracy: 0.7857\nEpoch 39/200\n20/20 [==============================] - 0s 4ms/step - loss: 0.9206 - accuracy: 0.5619 - val_loss: 0.5136 - val_accuracy: 0.7857\nEpoch 40/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9223 - accuracy: 0.5570 - val_loss: 0.5113 - val_accuracy: 0.7857\nEpoch 41/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8489 - accuracy: 0.6140 - val_loss: 0.5097 - val_accuracy: 0.7857\nEpoch 42/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8887 - accuracy: 0.6010 - val_loss: 0.5074 - val_accuracy: 0.7857\nEpoch 43/200\n20/20 [==============================] - 0s 4ms/step - loss: 0.8528 - accuracy: 0.5847 - val_loss: 0.5059 - val_accuracy: 0.7857\nEpoch 44/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8904 - accuracy: 0.5798 - val_loss: 0.5046 - val_accuracy: 0.7857\nEpoch 45/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8656 - accuracy: 0.5945 - val_loss: 0.5035 - val_accuracy: 0.7857\nEpoch 46/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8966 - accuracy: 0.5945 - val_loss: 0.5022 - val_accuracy: 0.7857\nEpoch 47/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8226 - accuracy: 0.5863 - val_loss: 0.5014 - val_accuracy: 0.7857\nEpoch 48/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9297 - accuracy: 0.5879 - val_loss: 0.5002 - val_accuracy: 0.7857\nEpoch 49/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9312 - accuracy: 0.5831 - val_loss: 0.4984 - val_accuracy: 0.7857\nEpoch 50/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9186 - accuracy: 0.5603 - val_loss: 0.4973 - val_accuracy: 0.7857\nEpoch 51/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8526 - accuracy: 0.5961 - val_loss: 0.4968 - val_accuracy: 0.7857\nEpoch 52/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.9245 - accuracy: 0.5847 - val_loss: 0.4961 - val_accuracy: 0.7857\nEpoch 53/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8537 - accuracy: 0.6075 - val_loss: 0.4952 - val_accuracy: 0.7857\nEpoch 54/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8250 - accuracy: 0.6189 - val_loss: 0.4946 - val_accuracy: 0.7857\nEpoch 55/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8370 - accuracy: 0.5896 - val_loss: 0.4938 - val_accuracy: 0.7857\nEpoch 56/200\n20/20 [==============================] - 0s 4ms/step - loss: 0.8705 - accuracy: 0.6059 - val_loss: 0.4933 - val_accuracy: 0.7857\nEpoch 57/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8562 - accuracy: 0.6156 - val_loss: 0.4930 - val_accuracy: 0.7857\nEpoch 58/200\n20/20 [==============================] - 0s 3ms/step - loss: 0.8791 - accuracy: 0.6156 - val_loss: 0.4922 - val_accuracy: 0.7792\n" ], [ "# Model accuracy\nplt.plot(hists.history['accuracy'])\nplt.plot(hists.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'])\nplt.show()", "_____no_output_____" ], [ "# Model Losss\nplt.plot(hists.history['loss'])\nplt.plot(hists.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'])\nplt.show()", "_____no_output_____" ], [ "# Predicting the Test set results\ny_pred_cnn = model.predict(x_test)\nrounded = [round(x[0]) for x in y_pred_cnn]\nY_pred_cnn = rounded", "_____no_output_____" ], [ "score_cnn = round(accuracy_score(Y_pred_cnn,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using artificial Neural Network is: \"+str(score_cnn)+\" %\")", "The accuracy score achieved using artificial Neural Network is: 81.17 %\n" ] ], [ [ "# Artificial Neural Network", "_____no_output_____" ] ], [ [ "import keras \nfrom keras.models import Sequential\nfrom keras.layers import Dense", "_____no_output_____" ], [ "# Intinialising the ANN\nclassifier = Sequential()\n\n# Adding the input layer and the first Hidden layer \nclassifier.add(Dense(activation=\"relu\", input_dim=8, units=7, kernel_initializer=\"uniform\"))\n\n# Adding the output layer \nclassifier.add(Dense(activation=\"sigmoid\", input_dim=8, units=1, kernel_initializer=\"uniform\"))", "_____no_output_____" ], [ "# Compiling the ANN\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])", "_____no_output_____" ], [ "# Fitting the ANN to the training set\nhist = classifier.fit(X_train, Y_train,validation_data=(X_test, Y_test), batch_size=10, epochs=500)", "Epoch 1/500\n62/62 [==============================] - 0s 2ms/step - loss: 0.6870 - accuracy: 0.6352 - val_loss: 0.6728 - val_accuracy: 0.6948\nEpoch 2/500\n62/62 [==============================] - 0s 984us/step - loss: 0.6605 - accuracy: 0.6726 - val_loss: 0.6264 - val_accuracy: 0.7662\nEpoch 3/500\n62/62 [==============================] - 0s 869us/step - loss: 0.6157 - accuracy: 0.7508 - val_loss: 0.5661 - val_accuracy: 0.7987\nEpoch 4/500\n62/62 [==============================] - 0s 951us/step - loss: 0.5697 - accuracy: 0.7573 - val_loss: 0.5189 - val_accuracy: 0.8052\nEpoch 5/500\n62/62 [==============================] - 0s 885us/step - loss: 0.5362 - accuracy: 0.7590 - val_loss: 0.4861 - val_accuracy: 0.7792\nEpoch 6/500\n62/62 [==============================] - 0s 902us/step - loss: 0.5154 - accuracy: 0.7573 - val_loss: 0.4667 - val_accuracy: 0.7792\nEpoch 7/500\n62/62 [==============================] - 0s 924us/step - loss: 0.5020 - accuracy: 0.7476 - val_loss: 0.4521 - val_accuracy: 0.7857\nEpoch 8/500\n62/62 [==============================] - 0s 946us/step - loss: 0.4936 - accuracy: 0.7541 - val_loss: 0.4440 - val_accuracy: 0.7987\nEpoch 9/500\n62/62 [==============================] - 0s 906us/step - loss: 0.4884 - accuracy: 0.7524 - val_loss: 0.4384 - val_accuracy: 0.8052\nEpoch 10/500\n62/62 [==============================] - 0s 967us/step - loss: 0.4848 - accuracy: 0.7573 - val_loss: 0.4359 - val_accuracy: 0.7987\nEpoch 11/500\n62/62 [==============================] - 0s 879us/step - loss: 0.4824 - accuracy: 0.7622 - val_loss: 0.4330 - val_accuracy: 0.8117\nEpoch 12/500\n62/62 [==============================] - 0s 989us/step - loss: 0.4805 - accuracy: 0.7622 - val_loss: 0.4307 - val_accuracy: 0.8052\nEpoch 13/500\n62/62 [==============================] - 0s 962us/step - loss: 0.4789 - accuracy: 0.7655 - val_loss: 0.4295 - val_accuracy: 0.8117\nEpoch 14/500\n62/62 [==============================] - 0s 895us/step - loss: 0.4776 - accuracy: 0.7655 - val_loss: 0.4289 - val_accuracy: 0.8052\nEpoch 15/500\n62/62 [==============================] - 0s 945us/step - loss: 0.4764 - accuracy: 0.7638 - val_loss: 0.4272 - val_accuracy: 0.7987\nEpoch 16/500\n62/62 [==============================] - 0s 964us/step - loss: 0.4751 - accuracy: 0.7655 - val_loss: 0.4284 - val_accuracy: 0.7987\nEpoch 17/500\n62/62 [==============================] - 0s 945us/step - loss: 0.4745 - accuracy: 0.7638 - val_loss: 0.4277 - val_accuracy: 0.7987\nEpoch 18/500\n62/62 [==============================] - 0s 1ms/step - loss: 0.4734 - accuracy: 0.7638 - val_loss: 0.4274 - val_accuracy: 0.7987\nEpoch 19/500\n62/62 [==============================] - 0s 921us/step - loss: 0.4723 - accuracy: 0.7655 - val_loss: 0.4268 - val_accuracy: 0.7987\nEpoch 20/500\n62/62 [==============================] - 0s 898us/step - loss: 0.4722 - accuracy: 0.7671 - val_loss: 0.4267 - val_accuracy: 0.7987\nEpoch 21/500\n62/62 [==============================] - 0s 915us/step - loss: 0.4714 - accuracy: 0.7622 - val_loss: 0.4272 - val_accuracy: 0.7922\nEpoch 22/500\n62/62 [==============================] - 0s 899us/step - loss: 0.4706 - accuracy: 0.7687 - val_loss: 0.4262 - val_accuracy: 0.7987\nEpoch 23/500\n62/62 [==============================] - 0s 915us/step - loss: 0.4697 - accuracy: 0.7622 - val_loss: 0.4265 - val_accuracy: 0.7987\nEpoch 24/500\n62/62 [==============================] - 0s 898us/step - loss: 0.4687 - accuracy: 0.7671 - val_loss: 0.4270 - val_accuracy: 0.7987\nEpoch 25/500\n62/62 [==============================] - 0s 926us/step - loss: 0.4677 - accuracy: 0.7687 - val_loss: 0.4267 - val_accuracy: 0.8052\nEpoch 26/500\n62/62 [==============================] - 0s 882us/step - loss: 0.4671 - accuracy: 0.7704 - val_loss: 0.4266 - val_accuracy: 0.7987\nEpoch 27/500\n62/62 [==============================] - 0s 902us/step - loss: 0.4665 - accuracy: 0.7671 - val_loss: 0.4271 - val_accuracy: 0.8052\nEpoch 28/500\n62/62 [==============================] - 0s 976us/step - loss: 0.4661 - accuracy: 0.7655 - val_loss: 0.4278 - val_accuracy: 0.7987\nEpoch 29/500\n62/62 [==============================] - 0s 905us/step - loss: 0.4653 - accuracy: 0.7704 - val_loss: 0.4282 - val_accuracy: 0.7987\nEpoch 30/500\n62/62 [==============================] - 0s 893us/step - loss: 0.4648 - accuracy: 0.7720 - val_loss: 0.4288 - val_accuracy: 0.8052\nEpoch 31/500\n62/62 [==============================] - 0s 929us/step - loss: 0.4643 - accuracy: 0.7720 - val_loss: 0.4283 - val_accuracy: 0.7987\nEpoch 32/500\n62/62 [==============================] - 0s 885us/step - loss: 0.4637 - accuracy: 0.7752 - val_loss: 0.4288 - val_accuracy: 0.7987\nEpoch 33/500\n62/62 [==============================] - 0s 943us/step - loss: 0.4638 - accuracy: 0.7720 - val_loss: 0.4284 - val_accuracy: 0.7987\nEpoch 34/500\n62/62 [==============================] - 0s 995us/step - loss: 0.4629 - accuracy: 0.7720 - val_loss: 0.4296 - val_accuracy: 0.7987\nEpoch 35/500\n62/62 [==============================] - 0s 896us/step - loss: 0.4627 - accuracy: 0.7736 - val_loss: 0.4293 - val_accuracy: 0.7987\nEpoch 36/500\n62/62 [==============================] - 0s 956us/step - loss: 0.4617 - accuracy: 0.7720 - val_loss: 0.4303 - val_accuracy: 0.7987\nEpoch 37/500\n62/62 [==============================] - 0s 974us/step - loss: 0.4614 - accuracy: 0.7687 - val_loss: 0.4298 - val_accuracy: 0.7922\nEpoch 38/500\n62/62 [==============================] - 0s 903us/step - loss: 0.4611 - accuracy: 0.7704 - val_loss: 0.4309 - val_accuracy: 0.7987\nEpoch 39/500\n62/62 [==============================] - 0s 995us/step - loss: 0.4607 - accuracy: 0.7704 - val_loss: 0.4312 - val_accuracy: 0.7922\nEpoch 40/500\n62/62 [==============================] - 0s 849us/step - loss: 0.4605 - accuracy: 0.7720 - val_loss: 0.4329 - val_accuracy: 0.7922\nEpoch 41/500\n62/62 [==============================] - 0s 889us/step - loss: 0.4599 - accuracy: 0.7704 - val_loss: 0.4323 - val_accuracy: 0.7922\nEpoch 42/500\n62/62 [==============================] - 0s 870us/step - loss: 0.4598 - accuracy: 0.7704 - val_loss: 0.4328 - val_accuracy: 0.7922\nEpoch 43/500\n62/62 [==============================] - 0s 917us/step - loss: 0.4592 - accuracy: 0.7704 - val_loss: 0.4333 - val_accuracy: 0.7922\nEpoch 44/500\n62/62 [==============================] - 0s 893us/step - loss: 0.4592 - accuracy: 0.7704 - val_loss: 0.4335 - val_accuracy: 0.7922\nEpoch 45/500\n62/62 [==============================] - 0s 924us/step - loss: 0.4586 - accuracy: 0.7736 - val_loss: 0.4346 - val_accuracy: 0.7922\nEpoch 46/500\n62/62 [==============================] - 0s 973us/step - loss: 0.4586 - accuracy: 0.7720 - val_loss: 0.4342 - val_accuracy: 0.7922\nEpoch 47/500\n62/62 [==============================] - 0s 886us/step - loss: 0.4584 - accuracy: 0.7752 - val_loss: 0.4320 - val_accuracy: 0.7922\nEpoch 48/500\n62/62 [==============================] - 0s 870us/step - loss: 0.4581 - accuracy: 0.7769 - val_loss: 0.4348 - val_accuracy: 0.7857\nEpoch 49/500\n62/62 [==============================] - 0s 890us/step - loss: 0.4575 - accuracy: 0.7720 - val_loss: 0.4354 - val_accuracy: 0.7857\nEpoch 50/500\n62/62 [==============================] - 0s 869us/step - loss: 0.4573 - accuracy: 0.7736 - val_loss: 0.4349 - val_accuracy: 0.7857\nEpoch 51/500\n62/62 [==============================] - 0s 897us/step - loss: 0.4569 - accuracy: 0.7769 - val_loss: 0.4356 - val_accuracy: 0.7857\nEpoch 52/500\n62/62 [==============================] - 0s 860us/step - loss: 0.4567 - accuracy: 0.7752 - val_loss: 0.4356 - val_accuracy: 0.7857\nEpoch 53/500\n62/62 [==============================] - 0s 964us/step - loss: 0.4560 - accuracy: 0.7752 - val_loss: 0.4368 - val_accuracy: 0.7857\nEpoch 54/500\n62/62 [==============================] - 0s 915us/step - loss: 0.4559 - accuracy: 0.7736 - val_loss: 0.4369 - val_accuracy: 0.7857\nEpoch 55/500\n62/62 [==============================] - 0s 941us/step - loss: 0.4561 - accuracy: 0.7801 - val_loss: 0.4372 - val_accuracy: 0.7857\nEpoch 56/500\n62/62 [==============================] - 0s 858us/step - loss: 0.4554 - accuracy: 0.7736 - val_loss: 0.4368 - val_accuracy: 0.7857\nEpoch 57/500\n62/62 [==============================] - 0s 881us/step - loss: 0.4554 - accuracy: 0.7818 - val_loss: 0.4375 - val_accuracy: 0.7857\n" ], [ "# Model accuracy\nplt.plot(hist.history['accuracy'])\nplt.plot(hist.history['val_accuracy'])\nplt.title('Model Accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'])\nplt.show()", "_____no_output_____" ], [ "# Model Losss\nplt.plot(hist.history['loss'])\nplt.plot(hist.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'])\nplt.show()", "_____no_output_____" ], [ "# Predicting the Test set results\ny_pred_ann = classifier.predict(X_test)\nrounded = [round(x[0]) for x in y_pred_ann]\nY_pred_ann = rounded", "_____no_output_____" ], [ "score_ann = round(accuracy_score(Y_pred_ann,Y_test)*100,2)\n\nprint(\"The accuracy score achieved using artificial Neural Network is: \"+str(score_ann)+\" %\")", "The accuracy score achieved using artificial Neural Network is: 79.87 %\n" ] ], [ [ "## model with best score", "_____no_output_____" ] ], [ [ "scores = [score_lr,score_nb,score_svm,score_knn,score_xgb,score_nn,score_ann,score_cnn]\nalgorithms = [\"Logistic Regression\",\"Naive Bayes\",\"Support Vector Machine\",\"K-Nearest Neighbors\",\"XGBoost\",\"Neural Network\",\"Art. Neural Network\",\"Conv. Neural Network\"] \n\nfor i in range(len(algorithms)):\n print(\"The accuracy score achieved using \"+algorithms[i]+\" is: \"+str(scores[i])+\" %\")", "The accuracy score achieved using Logistic Regression is: 82.47 %\nThe accuracy score achieved using Naive Bayes is: 79.22 %\nThe accuracy score achieved using Support Vector Machine is: 81.82 %\nThe accuracy score achieved using K-Nearest Neighbors is: 75.97 %\nThe accuracy score achieved using XGBoost is: 75.97 %\nThe accuracy score achieved using Neural Network is: 78.57 %\nThe accuracy score achieved using Art. Neural Network is: 79.87 %\nThe accuracy score achieved using Conv. Neural Network is: 81.17 %\n" ], [ "sns.set(rc={'figure.figsize':(15,7)})\nplt.xlabel(\"Algorithms\")\nplt.ylabel(\"Accuracy score\")\n\nsns.barplot(algorithms,scores)", "C:\\Users\\ANKIT\\anaconda3\\lib\\site-packages\\seaborn\\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.\n warnings.warn(\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "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" ], [ "markdown" ], [ "code", "code" ] ]
4af92310ffcede4e89a60b49c3d36941e6395f9c
15,284
ipynb
Jupyter Notebook
multiLSTM.ipynb
ebrukultur/ms-thesis
5fe4d5802fc7b7a4a04b1a5ed76878cf85042ece
[ "Apache-2.0" ]
null
null
null
multiLSTM.ipynb
ebrukultur/ms-thesis
5fe4d5802fc7b7a4a04b1a5ed76878cf85042ece
[ "Apache-2.0" ]
null
null
null
multiLSTM.ipynb
ebrukultur/ms-thesis
5fe4d5802fc7b7a4a04b1a5ed76878cf85042ece
[ "Apache-2.0" ]
null
null
null
39.089514
171
0.56039
[ [ [ "# Importing the Libraries", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport seaborn as sns \nfrom scipy import interp\nimport matplotlib.pyplot as plt\nfrom itertools import cycle\n# Importing the Keras libraries and packages\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import callbacks\n# Importing the libraries for evaluation\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import (precision_score, recall_score,f1_score)\nfrom sklearn.metrics import multilabel_confusion_matrix\nfrom sklearn.metrics import balanced_accuracy_score\nfrom sklearn.metrics import precision_recall_curve\nfrom imblearn.metrics import geometric_mean_score", "_____no_output_____" ] ], [ [ "# Loading the dataset", "_____no_output_____" ] ], [ [ "def load_dataset():\n X_train_load = np.loadtxt('data\\X_train_reshaped_multi.csv', delimiter=',')\n X_train_scaled = np.reshape(X_train_load, (X_train_load.shape[0], X_train_load.shape[1], 1)) \n X_test_load = np.loadtxt('data\\X_test_reshaped_multi.csv', delimiter=',')\n X_test_scaled = np.reshape(X_test_load, (X_test_load.shape[0], X_test_load.shape[1], 1)) \n y_train_scaled = np.loadtxt('data\\y_train_reshaped_multi.csv', delimiter=',')\n y_test_scaled = np.loadtxt('data\\y_test_reshaped_multi.csv', delimiter=',')\n X_val_load = np.loadtxt('data\\X_val_reshaped_multi.csv', delimiter=',')\n X_val_scaled = np.reshape(X_val_load, (X_val_load.shape[0], X_val_load.shape[1], 1))\n y_val_scaled = np.loadtxt('data\\y_val_reshaped_multi.csv', delimiter=',')\n return X_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled, X_val_scaled, y_val_scaled", "_____no_output_____" ] ], [ [ "# Creating the LSTM model for multi-class classification", "_____no_output_____" ] ], [ [ "def create_model(X_train_scaled):\n model = Sequential() \n # Adding the first LSTM layer and Dropout regularization\n model.add(LSTM(units= 76, return_sequences= True, input_shape= ( X_train_scaled.shape[1], 1)))\n model.add(Dropout(0.2))\n # Adding the second LSTM layer and Dropout regularization\n model.add(LSTM(units= 76, return_sequences= True))\n model.add(Dropout(0.2)) \n # Adding the third LSTM layer and Dropout regularization\n model.add(LSTM(units= 76, return_sequences= True))\n model.add(Dropout(0.2)) \n # Adding the fourth LSTM layer and Dropout regularization\n model.add(LSTM(units= 76))\n model.add(Dropout(0.2)) \n # Adding the output layer\n model.add(Dense(units= 15))\n model.add(Activation('softmax')) \n opt = Adam(lr=0.00002) \n # Compiling the LSTM\n model.compile(optimizer= opt, loss= 'categorical_crossentropy', metrics=['accuracy'])\n model.summary()\n return model", "_____no_output_____" ] ], [ [ "# Training the model", "_____no_output_____" ] ], [ [ "def train_model(model, X_train_scaled, y_train_scaled, X_val_scaled, y_val_scaled):\n earlystopping = callbacks.EarlyStopping(monitor =\"val_loss\",\n \t\t\t\t\t\t\t\t\t\tmode =\"min\", patience = 5,\n \t\t\t\t\t\t\t\t\t\trestore_best_weights = True) \n hist = model.fit(X_train_scaled, y_train_scaled, batch_size = 1024, epochs = 40, validation_data =(X_val_scaled, y_val_scaled), callbacks = earlystopping) \n fin_epoch = earlystopping.stopped_epoch\n return(hist, fin_epoch)", "_____no_output_____" ] ], [ [ "# Evaluating the model", "_____no_output_____" ] ], [ [ "def evaluate_model(X_test_scaled, y_test_scaled, model, hist):\n # Predicting values\n y_pred = model.predict_classes(X_test_scaled)\n n_values = np.max(y_pred) + 1\n y_prednew = np.eye(n_values)[y_pred]\n y_prednew = np.reshape(y_prednew, (y_prednew.shape[0], -1))\n y_testnew = np.where(y_test_scaled==1)[1]\n y_prednew2 = model.predict(X_test_scaled)\n # Calculating the performance metrics\n training_loss = hist.history['loss']\n training_acc = hist.history['accuracy']\n loss, accuracy = model.evaluate(X_test_scaled, y_test_scaled)\n balanced_accuracy = balanced_accuracy_score(y_testnew, y_pred)\n gmean_score = geometric_mean_score(y_testnew, y_pred)\n recall = recall_score(y_test_scaled, y_prednew , average=\"weighted\")\n precision = precision_score(y_test_scaled, y_prednew , average=\"weighted\")\n f1 = f1_score(y_test_scaled, y_prednew, average=\"weighted\") \n print(\"Training Loss:\", training_loss)\n print(\"Training Accuracy:\", training_acc)\n print(\"Overall Accuracy:\", accuracy)\n print(\"Overall Loss:\", loss)\n print(\"Balanced Accuracy:\", balanced_accuracy)\n print(\"Geometric Mean:\", gmean_score)\n print(\"Recall:\", recall)\n print(\"Precision:\", precision)\n print(\"F1 Score:\", f1)\n # Multiclass Confusion Matrix\n multi_cm = multilabel_confusion_matrix(y_test_scaled, y_prednew)\n return(y_pred, y_prednew, y_prednew2, multi_cm, training_loss, training_acc)", "_____no_output_____" ] ], [ [ "# Plotting the results", "_____no_output_____" ] ], [ [ "# Plot Training Accuracy & Loss vs. Epochs\ndef plot_acc_loss(fin_epoch, training_loss, training_acc):\n if fin_epoch > 0: \n epoch = fin_epoch\n else:\n epoch = 40\n xc = range(epoch)\n plt.figure(1,figsize=(15,epoch)) \n plt.plot(xc,training_loss)\n plt.xlabel('No. of Epochs') \n plt.ylabel('loss') \n plt.title('Training Loss') \n plt.grid(True) \n plt.legend(['Train']) \n plt.figure(2,figsize=(15,epoch)) \n plt.plot(xc,training_acc) \n plt.xlabel('No. of Epochs') \n plt.ylabel('Accuracy') \n plt.title('Training Accuracy') \n plt.grid(True) \n plt.legend(['Train'],loc=4)", "_____no_output_____" ], [ "# Plot the confusion matrix wrt one-vs-rest\ndef calc_cm(multi_cm, axes, label, class_names, fontsize=25):\n df_cm = pd.DataFrame(\n multi_cm, index=class_names, columns=class_names)\n try:\n sns.set(font_scale=2.2)\n heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\", cbar=False, ax=axes, cmap=\"Blues\")\n except ValueError:\n raise ValueError(\"CM values must be integers.\")\n heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)\n heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)\n axes.set_ylabel('True label')\n axes.set_xlabel('Predicted label')\n axes.set_title(\"CM for the class - \" + label)", "_____no_output_____" ], [ "# Plot ROC Curve\ndef plot_roc_auc(y_test_scaled, y_prednew2, class_labels):\n # Compute ROC curve and ROC area for each class\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n n_classes = len(class_labels)\n for i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(y_test_scaled[:, i], y_prednew2[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test_scaled.ravel(), y_prednew2.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"]) \n # Compute macro-average value for ROC curve and ROC area \n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)])) \n mean_tpr = np.zeros_like(all_fpr)\n for i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n mean_tpr /= n_classes \n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n # Plot all ROC curves\n fig = plt.figure(figsize=(8,6))\n plt.tick_params(axis='both', which='major', labelsize=13)\n prop_cycle = plt.rcParams['axes.prop_cycle']\n colors = plt.cm.jet(np.linspace(0, 1, 15))\n for i,color in zip(range(n_classes), colors):\n plt.plot(fpr[i], \n tpr[i], \n color=color,\n lw=1.5,\n label=\"{}, AUC={:.3f}\".format(class_labels[i], roc_auc[i]))\n plt.plot([0,1], [0,1], color='orange', linestyle='--') \n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel(\"False Positive Rate\", fontsize=15)\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.ylabel(\"True Positive Rate\", fontsize=15)\n plt.title('ROC Curve Analysis', fontweight='bold', fontsize=15)\n plt.legend(prop={'size':13}, loc='center left', bbox_to_anchor=(1, 0.5))\n plt.show()", "_____no_output_____" ], [ "# Plot PR curve\ndef plot_pr_auc(y_test_scaled, y_prednew, class_labels):\n precision = dict()\n recall = dict()\n pr_auc = dict()\n n_classes = len(class_labels)\n colors = plt.cm.jet(np.linspace(0, 1, 15))\n for i in range(n_classes):\n precision[i], recall[i], _ = precision_recall_curve(y_test_scaled[:, i], y_prednew[:, i])\n pr_auc[i] = auc(recall[i], precision[i])\n fig = plt.figure(figsize=(8,6))\n plt.tick_params(axis='both', which='major', labelsize=13)\n for i,color in zip(range(n_classes), colors):\n plt.plot(recall[i], \n precision[i], \n color=color,\n lw=1.5,\n label=\"{}, AUC={:.3f}\".format(class_labels[i], pr_auc[i]))\n plt.plot([0,1], [0.5,0.5], color='orange', linestyle='--')\n plt.xticks(np.arange(0.0, 1.1, step=0.1))\n plt.xlabel(\"Recall Rate\", fontsize=15)\n plt.yticks(np.arange(0.0, 1.1, step=0.1))\n plt.ylabel(\"Precision Rate\", fontsize=15)\n plt.title('Precision Recall Curve', fontweight='bold', fontsize=15)\n plt.legend(prop={'size':13}, loc='center left', bbox_to_anchor=(1, 0.5))\n plt.show()", "_____no_output_____" ], [ "def main():\n class_labels = [\"Benign\",\n \"Bot\",\n \"Brute Force -Web\",\n \"Brute Force -XSS\",\n \"DDOS attack-HOIC\",\n \"DDOS attack-LOIC-UDP\",\n \"DDoS attacks-LOIC-HTTP\",\n \"DoS attacks-GoldenEye\",\n \"DoS attacks-Hulk\",\n \"DoS attacks-SlowHTTPTest\",\n \"DoS attacks-Slowloris\",\n \"FTP-BruteForce\",\n \"Infiltration\",\n \"SQL Injection\",\n \"SSH-Bruteforce\"]\n X_train_scaled, X_test_scaled, y_train_scaled, y_test_scaled, X_val_scaled, y_val_scaled = load_dataset() \n model = create_model(X_train_scaled)\n hist = train_model(model, X_train_scaled, y_train_scaled, X_val_scaled, y_val_scaled)\n y_pred, y_prednew, y_prednew2, multi_cm, class_report = evaluate_model(X_test_scaled, y_test_scaled, model, hist)\n # Plot Classification Report\n sns.set(font_scale=0.8)\n sns.heatmap(pd.DataFrame(class_report).iloc[:-1, :].T, annot=True)\n # Plot Confusion Matrix\n fig, ax = plt.subplots(2, 2, figsize=(20, 20))\n for axes, cfs_matrix, label in zip(ax.flatten(), multi_cm, class_labels):\n print_confusion_matrix(cfs_matrix, axes, label, [\"N\", \"Y\"])\n fig.tight_layout()\n plt.show()\n # Plot ROC Curve\n plot_roc_auc(y_test_scaled, y_prednew2, class_labels)\n # Plot PR Curve\n plot_pr_auc(y_test_scaled, y_prednew, class_labels)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4af93315ed12ff2d05f5001426db2d7274779ab4
156,797
ipynb
Jupyter Notebook
section_fastslam/fastslam4.ipynb
kentaroy47/LNPR_BOOK_CODES
f0d1bef336423ebdf04539ce833f0ce4cffc51f5
[ "MIT" ]
148
2019-03-27T00:20:16.000Z
2022-03-30T22:34:11.000Z
section_fastslam/fastslam4.ipynb
kentaroy47/LNPR_BOOK_CODES
f0d1bef336423ebdf04539ce833f0ce4cffc51f5
[ "MIT" ]
3
2018-11-07T04:33:13.000Z
2018-12-31T01:35:16.000Z
section_fastslam/fastslam4.ipynb
kentaroy47/LNPR_BOOK_CODES
f0d1bef336423ebdf04539ce833f0ce4cffc51f5
[ "MIT" ]
116
2019-04-18T08:35:53.000Z
2022-03-24T05:17:46.000Z
160.817436
115,847
0.840246
[ [ [ "import sys \nsys.path.append('../scripts/')\nfrom mcl import *\nfrom kf import * ", "_____no_output_____" ], [ "class EstimatedLandmark(Landmark):\n def __init__(self):\n super().__init__(0,0) \n self.cov = None\n \n def draw(self, ax, elems): \n if self.cov is None:\n return\n \n ##推定位置に青い星を描く##\n c = ax.scatter(self.pos[0], self.pos[1], s=100, marker=\"*\", label=\"landmarks\", color=\"blue\")\n elems.append(c)\n elems.append(ax.text(self.pos[0], self.pos[1], \"id:\" + str(self.id), fontsize=10))\n \n ##誤差楕円を描く##\n e = sigma_ellipse(self.pos, self.cov, 3)\n elems.append(ax.add_patch(e))", "_____no_output_____" ], [ "class MapParticle(Particle): \n def __init__(self, init_pose, weight, landmark_num):\n super().__init__(init_pose, weight)\n self.map = Map()\n \n for i in range(landmark_num):\n self.map.append_landmark(EstimatedLandmark())\n \n def init_landmark_estimation(self, landmark, z, distance_dev_rate, direction_dev):\n landmark.pos = z[0]*np.array([np.cos(self.pose[2] + z[1]), np.sin(self.pose[2] + z[1])]).T + self.pose[0:2]\n H = matH(self.pose, landmark.pos)[0:2,0:2] #カルマンフィルタのHの右上2x2を取り出す\n Q = matQ(distance_dev_rate*z[0], direction_dev)\n landmark.cov = np.linalg.inv(H.T.dot( np.linalg.inv(Q) ).dot(H))\n \n def observation_update_landmark(self, landmark, z, distance_dev_rate, direction_dev): ###fastslam4landestm\n estm_z = IdealCamera.observation_function(self.pose, landmark.pos) #ランドマークの推定位置から予想される計測値\n if estm_z[0] < 0.01: # 推定位置が近すぎると計算がおかしくなるので回避\n return\n\n H = - matH(self.pose, landmark.pos)[0:2,0:2] #ここは符号の整合性が必要\n Q = matQ(distance_dev_rate*estm_z[0], direction_dev)\n K = landmark.cov.dot(H.T).dot( np.linalg.inv(Q + H.dot(landmark.cov).dot(H.T)) )\n landmark.pos = K.dot(z - estm_z) + landmark.pos\n landmark.cov = (np.eye(2) - K.dot(H)).dot(landmark.cov)\n \n def observation_update(self, observation, distance_dev_rate, direction_dev): ###fastslam4obsupdate\n for d in observation:\n z = d[0]\n landmark = self.map.landmarks[d[1]]\n \n if landmark.cov is None:\n self.init_landmark_estimation(landmark, z, distance_dev_rate, direction_dev)\n else: #追加\n self.observation_update_landmark(landmark, z, distance_dev_rate, direction_dev)", "_____no_output_____" ], [ "class FastSlam(Mcl):\n def __init__(self, init_pose, particle_num, landmark_num, motion_noise_stds={\"nn\":0.19, \"no\":0.001, \"on\":0.13, \"oo\":0.2},\\\n distance_dev_rate=0.14, direction_dev=0.05):\n super().__init__(None, init_pose, particle_num, motion_noise_stds, distance_dev_rate, direction_dev)\n \n self.particles = [MapParticle(init_pose, 1.0/particle_num, landmark_num) for i in range(particle_num)]\n self.ml = self.particles[0]\n \n def observation_update(self, observation): \n for p in self.particles:\n p.observation_update(observation, self.distance_dev_rate, self.direction_dev) #self.mapを削除\n self.set_ml()\n self.resampling() \n \n def draw(self, ax, elems):\n super().draw(ax, elems)\n self.ml.map.draw(ax, elems)", "_____no_output_____" ], [ "def trial():\n time_interval = 0.1\n world = World(30, time_interval, debug=False) \n\n ###真の地図を作成###\n m = Map()\n for ln in [(-4,2), (2,-3), (3,3)]: m.append_landmark(Landmark(*ln))\n world.append(m)\n\n ### ロボットを作る ###\n init_pose = np.array([0,0,0]).T\n pf = FastSlam(init_pose,100, len(m.landmarks)) \n a = EstimationAgent(time_interval, 0.2, 10.0/180*math.pi, pf)\n r = Robot(init_pose, sensor=Camera(m), agent=a, color=\"red\")\n world.append(r)\n\n world.draw()\n \ntrial()", "_____no_output_____" ], [ "#a.estimator.particles[10].map.landmarks[2].cov", "_____no_output_____" ], [ "#math.sqrt(0.0025)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4af9420c8a9ce289af6c1ce7330adb3fc380140a
4,038
ipynb
Jupyter Notebook
module2-loadingdata/LS_DS_112_Loading_Data.ipynb
echiyembekeza/DS-Unit-1-Sprint-1-Dealing-With-Data
c571596cff9c28cd989fae48f8aecf1f54556e35
[ "MIT" ]
null
null
null
module2-loadingdata/LS_DS_112_Loading_Data.ipynb
echiyembekeza/DS-Unit-1-Sprint-1-Dealing-With-Data
c571596cff9c28cd989fae48f8aecf1f54556e35
[ "MIT" ]
null
null
null
module2-loadingdata/LS_DS_112_Loading_Data.ipynb
echiyembekeza/DS-Unit-1-Sprint-1-Dealing-With-Data
c571596cff9c28cd989fae48f8aecf1f54556e35
[ "MIT" ]
null
null
null
52.441558
452
0.76845
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af95164e2abf4a25b39945494ec859b361ea18f
15,596
ipynb
Jupyter Notebook
notebookpraktikum/Praktikum 08.ipynb
mkhoirun-najiboi/metnum.jl
a6e35d04dc277318e32256f9b432264157e9b8f4
[ "MIT" ]
null
null
null
notebookpraktikum/Praktikum 08.ipynb
mkhoirun-najiboi/metnum.jl
a6e35d04dc277318e32256f9b432264157e9b8f4
[ "MIT" ]
null
null
null
notebookpraktikum/Praktikum 08.ipynb
mkhoirun-najiboi/metnum.jl
a6e35d04dc277318e32256f9b432264157e9b8f4
[ "MIT" ]
null
null
null
24.36875
189
0.469992
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af95ab24e5e96fad20bd53b0f6bd2a8fcbea394
3,701
ipynb
Jupyter Notebook
00-Python3 Object and Data Structure Basics/01-Keywords and Identifiers.ipynb
rameshsahoo111/LearnPython
16d75d8c7f52b360c8c66457db0eb993e2e4eec2
[ "Apache-2.0" ]
null
null
null
00-Python3 Object and Data Structure Basics/01-Keywords and Identifiers.ipynb
rameshsahoo111/LearnPython
16d75d8c7f52b360c8c66457db0eb993e2e4eec2
[ "Apache-2.0" ]
null
null
null
00-Python3 Object and Data Structure Basics/01-Keywords and Identifiers.ipynb
rameshsahoo111/LearnPython
16d75d8c7f52b360c8c66457db0eb993e2e4eec2
[ "Apache-2.0" ]
null
null
null
30.841667
303
0.522021
[ [ [ "# Keywords\n\n", "_____no_output_____" ], [ "In Python, Keywords are the reserved words. Keyword cannot be used as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. There are **33** keywords in Python 3.8. This number can vary slightly over the course of time.\n\nAll the keywords except **True**, **False** and **None** are in lowercase and they must be written as they are. The list of all the keywords is given below.\n", "_____no_output_____" ], [ "| | | | Python | Keywords| | | | \n|:---------|:--------:|:------:|:------:|:-------:|:----:|:------:|---------:|\n| False | await | else | import | pass | None | break | except |\n| in | raise | True | class | finally | is | return | and |\n| continue | for | lambda | try | as | def | from | nonlocal |\n| while | assert | del | global | not | with | async | elif |\n| if | or | yield | | | | | |\n", "_____no_output_____" ] ], [ [ "# To list complete keywords \nimport keyword", "_____no_output_____" ], [ "print(keyword.kwlist)\nprint(f\"\\nTotal length of keywords:{len(keyword.kwlist)}\")", "['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n\nTotal length of keywords:33\n" ] ], [ [ "## Python Identifiers", "_____no_output_____" ], [ "An identifier is a name given to entities like variable, class, functions, etc. It helps to differentiate one entity from another. \n\n### Rules for writing identifiers\n\n1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example.\n\n2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.\n\n3. Keywords cannot be used as identifiers.\n\n4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.\n\n5. An identifier can be of any length.", "_____no_output_____" ], [ "#### Reference\nhttps://www.programiz.com/python-programming/keywords-identifier", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
4af95b7616e660cd91478a3dbeec90f478ab24d1
28,119
ipynb
Jupyter Notebook
demo/ES-Deployment-Walkthrough.ipynb
azurecloudhunter/CET-NorthStar1
e1e835473dccfe2c2338b2a917955f83a62972a5
[ "MIT" ]
null
null
null
demo/ES-Deployment-Walkthrough.ipynb
azurecloudhunter/CET-NorthStar1
e1e835473dccfe2c2338b2a917955f83a62972a5
[ "MIT" ]
null
null
null
demo/ES-Deployment-Walkthrough.ipynb
azurecloudhunter/CET-NorthStar1
e1e835473dccfe2c2338b2a917955f83a62972a5
[ "MIT" ]
1
2021-03-18T03:16:57.000Z
2021-03-18T03:16:57.000Z
21.367021
230
0.527295
[ [ [ "# Welcome to Enterprise-Scale!", "_____no_output_____" ], [ "## Verify Pre-req", "_____no_output_____" ], [ "Powershell Version > 7.0", "_____no_output_____" ] ], [ [ "$psversiontable", "_____no_output_____" ] ], [ [ "Git Version > 2.24", "_____no_output_____" ] ], [ [ "git --version", "_____no_output_____" ] ], [ [ "## Login to Azure", "_____no_output_____" ], [ "Clear Azure Context", "_____no_output_____" ] ], [ [ "Clear-AzContext -Force", "_____no_output_____" ] ], [ [ "Login to Azure with SPN or User Account that has permission at '/' scope", "_____no_output_____" ] ], [ [ "$user = \"\"\n$password = \"\"\n$tenantid = \"\"\n$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force\n$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $secureStringPwd\nConnect-AzAccount -TenantId $tenantid -ServicePrincipal -Credential $cred \n", "_____no_output_____" ] ], [ [ "Verify SPN/user account is logged in for the Tenant", "_____no_output_____" ] ], [ [ "get-azcontext | fl", "_____no_output_____" ] ], [ [ "## Bootstrap new Tenant\n", "_____no_output_____" ], [ "Set GitHub token to access raw content", "_____no_output_____" ] ], [ [ "$GitHubToken = 'AD4QREEEQ7XNHXIAN4IHMSK62YTRG'\nWrite-Output $GitHubToken", "_____no_output_____" ] ], [ [ "View Template File", "_____no_output_____" ] ], [ [ "echo \"https://raw.githubusercontent.com/Azure/CET-NorthStar/master/examples/Enterprise-Scale-Template-Deployment.json?token=$GitHubToken\"", "_____no_output_____" ], [ "(Invoke-WebRequest -Uri \"https://raw.githubusercontent.com/Azure/CET-NorthStar/master/examples/Enterprise-Scale-Template-Deployment.json?token=$GitHubToken\").Content | ConvertFrom-Json", "_____no_output_____" ] ], [ [ "Set Management Group Prefix", "_____no_output_____" ] ], [ [ "$TopLevelManagementGroupPrefix = 'ES'\n$TemplateParameterObject = @{'TopLevelManagementGroupPrefix'='ES'}", "_____no_output_____" ] ], [ [ "Initialize Tenant Deployment Parameter ", "_____no_output_____" ] ], [ [ "\n$parameters = @{\n 'Name' = 'Enterprise-Scale-Template'\n 'Location' = 'North Europe'\n 'TemplateUri' = \"https://raw.githubusercontent.com/Azure/CET-NorthStar/master/examples/Enterprise-Scale-Template-Deployment.json?token=$GitHubToken\"\n 'TemplateParameterObject' = $TemplateParameterObject\n 'Verbose' = $true\n}\n", "_____no_output_____" ] ], [ [ "Invoke Tenant Level Deployment", "_____no_output_____" ] ], [ [ "New-AzTenantDeployment @parameters", "_____no_output_____" ] ], [ [ "View Tenant Level Deployment", "_____no_output_____" ] ], [ [ "Get-AzTenantDeployment | select DeploymentName, ProvisioningState, Timestamp,location |sort-object Timestamp -Descending", "_____no_output_____" ] ], [ [ "View Management Group Level Deployment", "_____no_output_____" ] ], [ [ "Get-AzManagementGroupDeployment -ManagementGroupId $TopLevelManagementGroupPrefix | select DeploymentName, ProvisioningState, Timestamp |sort-object Timestamp -Descending", "_____no_output_____" ] ], [ [ "## Setting up Git", "_____no_output_____" ], [ "Ephermal space for Git", "_____no_output_____" ] ], [ [ "jupyter --runtime-dir", "_____no_output_____" ] ], [ [ "Git Clone Your repo (Skip this step if you have already cloned).\n\nPlease Ensure your Git Credentails are available for PowerShell to use in your session.", "_____no_output_____" ] ], [ [ "git clone https://github.com/uday31in/NorthStar.git", "_____no_output_____" ] ], [ [ "Change Path to Git Root", "_____no_output_____" ] ], [ [ "Write-Host \"Changing Current Directory to: $(jupyter --runtime-dir)\\NorthStar\"\ncd \"$(jupyter --runtime-dir)\\NorthStar\"", "_____no_output_____" ] ], [ [ "Add upstream repo", "_____no_output_____" ] ], [ [ "git remote add upstream https://github.com/Azure/CET-NorthStar.git", "_____no_output_____" ] ], [ [ "Verify Remote", "_____no_output_____" ] ], [ [ "git remote -v ", "_____no_output_____" ] ], [ [ "Pull latest upstream/master in your local master branch", "_____no_output_____" ] ], [ [ "git pull upstream master -X theirs -f", "_____no_output_____" ] ], [ [ "## Initialize Enviornment", "_____no_output_____" ], [ "Ensure Current Path is set to Git Root of your repo", "_____no_output_____" ] ], [ [ "Write-Host \"Changing Current Directory to: $(jupyter --runtime-dir)\\NorthStar\"\ncd \"$(jupyter --runtime-dir)\\NorthStar\"", "_____no_output_____" ] ], [ [ "Ensure Azure Login", "_____no_output_____" ] ], [ [ "Get-AzContext | fl", "_____no_output_____" ] ], [ [ "Import PowerShell Module", "_____no_output_____" ] ], [ [ "Import-Module .\\src\\AzOps.psd1 -force\nGet-ChildItem -Path .\\src -Include *.ps1 -Recurse | ForEach-Object { .$_.FullName }", "_____no_output_____" ] ], [ [ "Intialize Git Repo for your Azure Enviornement.\n\nPlease Note: This will take few minutes to compelte depending size of an enviornment", "_____no_output_____" ] ], [ [ "Initialize-AzOpsRepository -Verbose -SkipResourceGroup", "_____no_output_____" ] ], [ [ "Commit Change to Feaure Branch \"initial-discovery\"", "_____no_output_____" ] ], [ [ "git checkout -b initial-discovery", "_____no_output_____" ] ], [ [ "Commit Changes to AzOps", "_____no_output_____" ] ], [ [ "git add .\\azops", "_____no_output_____" ] ], [ [ "View Git Status", "_____no_output_____" ] ], [ [ "git status", "_____no_output_____" ] ], [ [ "Git commit", "_____no_output_____" ] ], [ [ "git commit -m \"Initializing Azure Enviornment\"", "_____no_output_____" ] ], [ [ "Push your changes to your Git repo", "_____no_output_____" ] ], [ [ "git push origin initial-discovery", "_____no_output_____" ] ], [ [ "Submit PR in Git Portal and merge to master before proceeding to next step", "_____no_output_____" ] ], [ [ "git remote get-url --all origin", "_____no_output_____" ] ], [ [ "## Enable Git Action", "_____no_output_____" ], [ "Ensure Current Path is set to Git Root of your repo", "_____no_output_____" ] ], [ [ "Write-Host \"Changing Current Directory to: $(jupyter --runtime-dir)\\NorthStar\"\ncd \"$(jupyter --runtime-dir)\\NorthStar\"", "_____no_output_____" ] ], [ [ "Commit Change to Feaure Branch \"initial-discovery\"", "_____no_output_____" ] ], [ [ "git checkout -b enable-git-action", "_____no_output_____" ] ], [ [ "Enable Action by copying \".github\\workflows\\azops-pull.yml.disabled\" to \".github\\workflows\\azops-pull.yml\"", "_____no_output_____" ] ], [ [ "copy \"$(jupyter --runtime-dir)\\NorthStar\\.github\\workflows\\azops-push.yml.disabled\" \"$(jupyter --runtime-dir)\\NorthStar\\.github\\workflows\\azops-push.yml\"", "_____no_output_____" ] ], [ [ "Add File to Git", "_____no_output_____" ] ], [ [ "git add .github\\workflows\\azops-push.yml", "_____no_output_____" ] ], [ [ "View Git Status", "_____no_output_____" ] ], [ [ "git status", "_____no_output_____" ] ], [ [ "Git commit", "_____no_output_____" ] ], [ [ "git commit -m \"Enable Git Action\"", "_____no_output_____" ] ], [ [ "Push your changes to your Git repo", "_____no_output_____" ] ], [ [ "git push origin enable-git-action", "_____no_output_____" ] ], [ [ "Submit PR in Git Portal and merge to master", "_____no_output_____" ] ], [ [ "git remote get-url --all origin", "_____no_output_____" ] ], [ [ "## Deploying New Policy Assignment using pipeline", "_____no_output_____" ], [ "Ensure Current Path is set to Git Root of your repo", "_____no_output_____" ] ], [ [ "Write-Host \"Changing Current Directory to: $(jupyter --runtime-dir)\\NorthStar\"\ncd \"$(jupyter --runtime-dir)\\NorthStar\"", "_____no_output_____" ] ], [ [ "Create Branch deploy-loganalytics", "_____no_output_____" ] ], [ [ "git checkout -b deploy-loganalytics", "_____no_output_____" ] ], [ [ "View Policy Assignment", "_____no_output_____" ] ], [ [ "echo 'https://github.com/Azure/CET-NorthStar/raw/master/azopsreference/3fc1081d-6105-4e19-b60c-1ec1252cf560/contoso/platform/management/.AzState/Microsoft.Authorization_policyAssignments-Deploy-Log-Analytics.parameters.json'", "_____no_output_____" ] ], [ [ "Create Policy Assignment Parameter file", "_____no_output_____" ] ], [ [ "@\"\n{\n \"`$schema\": \"http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#\",\n \"contentVersion\": \"1.0.0.0\",\n \"parameters\": {\n \"input\": {\n \"value\": {\n \"Name\": \"Deploy-Log-Analytics\",\n \"ResourceType\": \"Microsoft.Authorization/policyAssignments\",\n \"Location\": \"northeurope\", \n \"Identity\": {\n \"type\": \"SystemAssigned\"\n },\n \"Properties\": {\n \"displayName\": \"Deploy-LogAnalytics\",\n \"policyDefinitionId\": \"/providers/Microsoft.Management/managementGroups/$($TopLevelManagementGroupPrefix)/providers/Microsoft.Authorization/policyDefinitions/Deploy-Log-Analytics\",\n \"scope\": \"/providers/Microsoft.Management/managementGroups/$($TopLevelManagementGroupPrefix)-management\",\n \"notScopes\": [],\n \"parameters\": {\n \"workspaceName\": {\n \"value\": \"$($TopLevelManagementGroupPrefix)-weu-la\"\n },\n \"automationAccountName\": {\n \"value\": \"$($TopLevelManagementGroupPrefix)-weu-aa\"\n },\n \"workspaceRegion\": {\n \"value\": \"westeurope\"\n },\n \"automationRegion\": {\n \"value\": \"westeurope\"\n },\n \"rgName\": {\n \"value\": \"$($TopLevelManagementGroupPrefix)-weu-mgmt\"\n }\n },\n \"enforcementMode\": \"Default\"\n }\n }\n }\n }\n}\n\"@ > \".\\azops\\Tenant Root Group\\ES\\ES-platform\\ES-management\\.AzState\\Microsoft.Authorization_policyAssignments-Deploy-Log-Analytics.parameters.json\"", "_____no_output_____" ] ], [ [ "Add File to Git", "_____no_output_____" ] ], [ [ "git add \".\\azops\\Tenant Root Group\\ES\\ES-platform\\ES-management\\.AzState\\Microsoft.Authorization_policyAssignments-Deploy-Log-Analytics.parameters.json\"", "_____no_output_____" ] ], [ [ "View Git Status", "_____no_output_____" ] ], [ [ "git status", "_____no_output_____" ] ], [ [ "Git commit", "_____no_output_____" ] ], [ [ "git commit -m \"Deploy Log Analytics Policy\"", "_____no_output_____" ] ], [ [ "Push your changes to your Git repo", "_____no_output_____" ] ], [ [ "git push origin deploy-loganalytics", "_____no_output_____" ] ], [ [ "Submit PR in Git Portal and wait for GitHub to action to complete.\n\nDO NOT merge, Pull request to master branch before GitHub actions complete.", "_____no_output_____" ], [ "Go To Portal and verify Policy Assigment is created.", "_____no_output_____" ], [ "Pull Master barnach locally", "_____no_output_____" ] ], [ [ "git checkout master && git pull", "_____no_output_____" ] ], [ [ "## Demo Drift Detection", "_____no_output_____" ], [ "<Manual> User Portal to make changes e.g. Add new management Group or update exisitng policy definition or assignment. \n \nTo simulate OOB changes, we are making imperative change via PowerShell.", "_____no_output_____" ] ], [ [ "$GroupName = \"$TopLevelManagementGroupPrefix-IAB\"\n$ParentId = \"/providers/Microsoft.Management/managementGroups/$TopLevelManagementGroupPrefix\"\n\nNew-AzManagementGroup -GroupName $GroupName -DisplayName $GroupName -ParentId $ParentId", "_____no_output_____" ] ], [ [ "Create Branch deploy-vWan", "_____no_output_____" ] ], [ [ "git checkout -b deploy-vWan", "_____no_output_____" ] ], [ [ "View Policy Assignment", "_____no_output_____" ] ], [ [ "echo 'https://github.com/Azure/CET-NorthStar/blob/master/azopsreference/3fc1081d-6105-4e19-b60c-1ec1252cf560/contoso/platform/connectivity/.AzState/Microsoft.Authorization_policyAssignments-Deploy-vWAN.parameters.json'", "_____no_output_____" ] ], [ [ "Create Policy Assignment Parameter file", "_____no_output_____" ] ], [ [ "@\"\n{\n \"`$schema\": \"http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#\",\n \"contentVersion\": \"1.0.0.0\",\n \"parameters\": {\n \"input\": {\n \"value\": {\n \"Name\": \"Deploy-VWAN\",\n \"ResourceType\": \"Microsoft.Authorization/policyAssignments\",\n \"Location\": \"northeurope\", \n \"Identity\": {\n \"type\": \"SystemAssigned\"\n },\n \"Properties\": {\n \"displayName\": \"Deploy-vWAN\",\n \"policyDefinitionId\": \"/providers/Microsoft.Management/managementGroups/$($TopLevelManagementGroupPrefix)/providers/Microsoft.Authorization/policyDefinitions/Deploy-vWAN\",\n \"scope\": \"/providers/Microsoft.Management/managementGroups/$($TopLevelManagementGroupPrefix)-connectivity\",\n \"notScopes\": [],\n \"parameters\": {\n \"vwanname\": {\n \"value\": \"$($TopLevelManagementGroupPrefix)-vwan\"\n },\n \"vwanRegion\": {\n \"value\": \"northeurope\"\n },\n \"rgName\": {\n \"value\": \"$($TopLevelManagementGroupPrefix)-global-vwan\"\n }\n },\n \"description\": \"\",\n \"enforcementMode\": \"Default\"\n }\n }\n }\n }\n}\n\"@ > \".\\azops\\Tenant Root Group\\ES\\ES-platform\\ES-connectivity\\.AzState\\Microsoft.Authorization_policyAssignments-Deploy-vWAN.parameters.json\"", "_____no_output_____" ] ], [ [ "Add File to Git", "_____no_output_____" ] ], [ [ "git add \".\\azops\\Tenant Root Group\\ES\\ES-platform\\ES-connectivity\\.AzState\\Microsoft.Authorization_policyAssignments-Deploy-vWAN.parameters.json\"", "_____no_output_____" ] ], [ [ "View Git Status", "_____no_output_____" ] ], [ [ "git status", "_____no_output_____" ] ], [ [ "Git commit", "_____no_output_____" ] ], [ [ "git commit -m \"Deploy vWAN Policy\"", "_____no_output_____" ] ], [ [ "Push your changes to your Git repo", "_____no_output_____" ] ], [ [ "git push origin deploy-vWan", "_____no_output_____" ] ], [ [ "Submit PR in Git Portal and wait for GitHub to action to complete.\n\nDO NOT merge, Pull request to master branch before GitHub actions complete.", "_____no_output_____" ], [ "When Git Action runs, it should detect ", "_____no_output_____" ], [ "## Clean-up Previous Install", "_____no_output_____" ], [ "Import-Module", "_____no_output_____" ] ], [ [ "Import-Module .\\src\\AzOps.psd1 -force\nGet-ChildItem -Path .\\src -Include *.ps1 -Recurse | ForEach-Object { .$_.FullName }", "_____no_output_____" ] ], [ [ "Management Group To Clean-up", "_____no_output_____" ] ], [ [ "$ManagementGroupPrefix = \"ES\"", "_____no_output_____" ] ], [ [ "Clean-up Management Group", "_____no_output_____" ] ], [ [ "if (Get-AzManagementGroup -GroupName $ManagementGroupPrefix -ErrorAction SilentlyContinue) {\n Write-Verbose \"Cleaning up Tailspin Management Group\"\n Remove-AzOpsManagementGroup -groupName $ManagementGroupPrefix -Verbose\n}", "_____no_output_____" ] ], [ [ "Clean-up Tenant Deployment", "_____no_output_____" ], [ "If you see an error \"Your Azure credentials have not been set up or have expired\", please re-run command. It might take several retries.", "_____no_output_____" ] ], [ [ "#Clean up Tenant Level Deployments\nGet-AzTenantDeployment | Foreach-Object -Parallel { Remove-AzTenantDeployment -Name $_.DeploymentName -Confirm:$false}\n", "_____no_output_____" ] ], [ [ "Delete initial-discovery remote branch", "_____no_output_____" ] ], [ [ "git branch -D initial-discovery", "_____no_output_____" ], [ "git push origin --delete initial-discovery", "_____no_output_____" ] ], [ [ "Delete enable-git-action remote branch", "_____no_output_____" ] ], [ [ "git branch -D enable-git-action", "_____no_output_____" ], [ "git push origin --delete enable-git-action", "_____no_output_____" ] ], [ [ "Delete deploy-loganalytics remote branch", "_____no_output_____" ] ], [ [ "git branch -D deploy-loganalytics", "_____no_output_____" ], [ "git push origin --delete deploy-loganalytics", "_____no_output_____" ] ], [ [ "Delete deploy-loganalytics remote branch", "_____no_output_____" ] ], [ [ "git branch -D deploy-vWAN", "_____no_output_____" ], [ "git push origin --delete deploy-vWAN", "_____no_output_____" ] ], [ [ "Reset upstream master branch", "_____no_output_____" ] ], [ [ "git checkout master -f ", "_____no_output_____" ], [ "git pull upstream master\ngit reset --hard upstream/master", "_____no_output_____" ], [ "git push -f", "_____no_output_____" ] ], [ [ "Remove Local Git Folder", "_____no_output_____" ] ], [ [ "rm -recurse -force \"$(jupyter --runtime-dir)\\NorthStar\"", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "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" ], [ "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", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4af95d0e87e49ee3062366a4b110db6fa293a212
15,135
ipynb
Jupyter Notebook
20.Network.ipynb
YongBeomKim/data-science-from-scratch
c9324aa0cca0d515fb31092cddf09d7ad86047a4
[ "MIT" ]
null
null
null
20.Network.ipynb
YongBeomKim/data-science-from-scratch
c9324aa0cca0d515fb31092cddf09d7ad86047a4
[ "MIT" ]
null
null
null
20.Network.ipynb
YongBeomKim/data-science-from-scratch
c9324aa0cca0d515fb31092cddf09d7ad86047a4
[ "MIT" ]
null
null
null
30.029762
120
0.493294
[ [ [ "# **밑바닥부터 시작하는 데이터과학**\nData Science from Scratch\n- https://github.com/joelgrus/data-science-from-scratch/blob/master/first-edition/code-python3/network_analysis.py", "_____no_output_____" ], [ "## **선형대수 작업에 필요한 함수**\n앞에서 작업했던 함수들을 호출 합니다", "_____no_output_____" ] ], [ [ "# linear_algebra.py\ndef dot(v, w):\n return sum(v_i * w_i for v_i, w_i in zip(v, w))\n\ndef squared_distance(v, w):\n return sum_of_squares(vector_subtract(v, w))\n\ndef sum_of_squares(v):\n return dot(v, v)\n\ndef vector_subtract(v, w):\n return [v_i - w_i for v_i, w_i in zip(v,w)]", "_____no_output_____" ], [ "# from linear_algebra import dot, get_row, get_column,\\\n# make_matrix, magnitude, scalar_multiply, shape, distance\nimport math\ndef dot(v, w):\n return sum(v_i * w_i for v_i, w_i in zip(v, w))\n\ndef get_row(A, i):\n return A[i]\n\ndef get_column(A, j):\n return [A_i[j] for A_i in A]\n\ndef make_matrix(num_rows, num_cols, entry_fn):\n return [[entry_fn(i, j) for j in range(num_cols)]\n for i in range(num_rows)]\n\ndef magnitude(v):\n return math.sqrt(sum_of_squares(v))\n\ndef scalar_multiply(c, v):\n return [c * v_i for v_i in v]\n\ndef shape(A):\n num_rows = len(A)\n num_cols = len(A[0]) if A else 0\n return num_rows, num_cols\n\ndef distance(v, w):\n return math.sqrt(squared_distance(v, w))\n\ndef sum_of_squares(v):\n return sum(v_i ** 2 for v_i in v)", "_____no_output_____" ] ], [ [ "<br></br>\n# **21장 네트워크 분석**\n데이터 문제는 **노드(Node)** 와 사이를 연결하는 **엣지(edge)** 로 구성되는 **네트워크(Network)** 관점으로 해석할 수 있습니다\n1. 개별 **속성이 Node**, 속성들의 **관계가 edge** 입니다\n1. 이러한 **관계는 상호적** 인 특징으로 구분할 수 있어서 **뱡향성 Network** 라고도 합니다\n1. 네트워크를 분석하는 방법으로 **임의의 두 사람의 최단경로** 를 계산할 수 있습니다.\n\n<img src=\"https://miro.medium.com/max/912/1*EKWy0bQjzoJ4RJ-iTTLa4w.png\" align=\"left\" width=\"400\">", "_____no_output_____" ], [ "## **1 Edge 와 Node 데이터 생성하기**\n앞에서 활용하였던 **친구관계 NetWork** 데이터를 호출합니다", "_____no_output_____" ] ], [ [ "# 1장에서 친구관계 Network 를 호출 합니다\nusers = [\n { \"id\": 0, \"name\": \"Hero\" },\n { \"id\": 1, \"name\": \"Dunn\" },\n { \"id\": 2, \"name\": \"Sue\" },\n { \"id\": 3, \"name\": \"Chi\" },\n { \"id\": 4, \"name\": \"Thor\" },\n { \"id\": 5, \"name\": \"Clive\" },\n { \"id\": 6, \"name\": \"Hicks\" },\n { \"id\": 7, \"name\": \"Devin\" },\n { \"id\": 8, \"name\": \"Kate\" },\n { \"id\": 9, \"name\": \"Klein\" }\n]\n\nfriendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),\n (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]\n\n# 친구목록을 각 사용자의 dict 에 추가 합니다\nfor user in users:\n user[\"friends\"] = []\n\nfor i, j in friendships:\n users[i][\"friends\"].append(users[j]) # j를 i의 친구로 추가\n users[j][\"friends\"].append(users[i]) # i를 j의 친구로 ", "_____no_output_____" ] ], [ [ "## **2 매개 중심성**\n1. 관계를 분석할 때에는 **최단 경로상에 빈번하게 등장하는 Node** 의 중요도가 높다\n1. 이러한 중심에 위치하는 **Node** 를 **매개중심성(betweeness centrality)** 라고 합니다", "_____no_output_____" ] ], [ [ "from collections import deque\n# 특정 사용자로부터 다른 사용자까지 최단경로 {dict}\ndef shortest_paths_from(from_user):\n shortest_paths_to = { from_user[\"id\"] : [[]] }\n # (이전_user, 다음_user) que 계산을 (from_user, friend_user 친구) 로 합니다\n frontier = deque((from_user, friend) for friend in from_user[\"friends\"])\n # que 가 빌때까지 반복\n while frontier:\n prev_user, user = frontier.popleft() # que 첫번째 사용자\n user_id = user[\"id\"]\n # que 에 사용자 추가\n paths_to_prev = shortest_paths_to[prev_user[\"id\"]]\n paths_via_prev = [path + [user_id] for path in paths_to_prev]\n old_paths_to_here = shortest_paths_to.get(user_id, []) # 최단경로를 안다면\n if old_paths_to_here: # 지금까지의 최단경로는?\n min_path_length = len(old_paths_to_here[0])\n else: min_path_length = float('inf')\n\n # 길지 않은 새로운 경로를 지정\n new_paths_to_here = [path_via_prev\n for path_via_prev in paths_via_prev\n if len(path_via_prev) <= min_path_length\n and path_via_prev not in old_paths_to_here]\n\n shortest_paths_to[user_id] = old_paths_to_here + new_paths_to_here\n frontier.extend((user, friend) # 새로 추가되는 이웃을 frontier 에 추가\n for friend in user[\"friends\"]\n if friend[\"id\"] not in shortest_paths_to)\n return shortest_paths_to", "_____no_output_____" ], [ "# 매개 중심성 계산하기\nfor user in users:\n user[\"shortest_paths\"] = shortest_paths_from(user)\n\nfor user in users:\n user[\"betweenness_centrality\"] = 0.0\n\nfor source in users:\n source_id = source[\"id\"]\n for target_id, paths in source[\"shortest_paths\"].items():\n if source_id < target_id: # don't double count\n num_paths = len(paths) # how many shortest paths?\n contrib = 1 / num_paths # contribution to centrality\n for path in paths:\n for id in path:\n if id not in [source_id, target_id]:\n users[id][\"betweenness_centrality\"] += contrib\n\nprint(\"Betweenness Centrality >>\")\nfor user in users:\n print(user[\"id\"], user[\"betweenness_centrality\"])", "Betweenness Centrality >>\n0 0.0\n1 3.5\n2 3.5\n3 18.0\n4 20.0\n5 20.5\n6 6.0\n7 6.0\n8 8.5\n9 0.0\n" ] ], [ [ "## **2 근접 중심성 (Closeness Centrality)**\n먼저 개별 사용자의 **원접성(farness : from_user 와 다른 사용자와 최단거리 총합)** 을 측정합니다.\n1. **측정방법이 복잡** 하고, **근접 중심성의 편차값이 작아서** 자주 사용하지 않습니다 ", "_____no_output_____" ] ], [ [ "# 모든 사용자와의 최단거리 합\ndef farness(user):\n return sum(len(paths[0]) for paths in user[\"shortest_paths\"].values())\n\nfor user in users:\n user[\"closeness_centrality\"] = 1 / farness(user)\n \nprint(\"Closeness Centrality >>\")\nfor user in users:\n print(user[\"id\"], user[\"closeness_centrality\"])", "Closeness Centrality >>\n0 0.029411764705882353\n1 0.037037037037037035\n2 0.037037037037037035\n3 0.045454545454545456\n4 0.05\n5 0.05\n6 0.041666666666666664\n7 0.041666666666666664\n8 0.03571428571428571\n9 0.027777777777777776\n" ] ], [ [ "## **3 고유벡터 중심성 (eigenvector centrality)**\n덜 직관적이지만 **계산이 용이한** 고유벡터 중심성을 자주 활용 합니다\n1. 연결의 수가 많고, 중심성이 높은 사용자들은 **고유벡터 중심성이 높다** \n1. **1, 2 번 사용자** 의 중심성이 높은데 이는 **중심성이 높은 사용자와 3번 연결 되었기 때문이다**", "_____no_output_____" ] ], [ [ "# 행렬의 곱 계산하기\nfrom functools import partial\ndef matrix_product_entry(A, B, i, j):\n return dot(get_row(A, i), get_column(B, j))\n\ndef matrix_multiply(A, B):\n n1, k1 = shape(A)\n n2, k2 = shape(B)\n if k1 != n2:\n raise ArithmeticError(\"incompatible shapes!\")\n return make_matrix(n1, k2, partial(matrix_product_entry, A, B))\n\n# [list] 형태의 벡터를 n X 1 행렬로 변환\ndef vector_as_matrix(v):\n return [[v_i] for v_i in v]\n\n# n X 1 행렬을 [list] 로 변환\ndef vector_from_matrix(v_as_matrix):\n return [row[0] for row in v_as_matrix]\n\ndef matrix_operate(A, v):\n v_as_matrix = vector_as_matrix(v)\n product = matrix_multiply(A, v_as_matrix)\n return vector_from_matrix(product)", "_____no_output_____" ], [ "# 고유벡터를 계산 합니다\ndef find_eigenvector(A, tolerance=0.00001):\n guess = [1 for __ in A]\n\n while True:\n result = matrix_operate(A, guess)\n length = magnitude(result)\n next_guess = scalar_multiply(1/length, result)\n\n if distance(guess, next_guess) < tolerance:\n return next_guess, length # eigenvector, eigenvalue\n\n guess = next_guess", "_____no_output_____" ], [ "# 중심성의 계산\ndef entry_fn(i, j):\n return 1 if (i, j) in friendships or (j, i) in friendships else 0\n\nn = len(users)\nadjacency_matrix = make_matrix(n, n, entry_fn)\neigenvector_centralities, _ = find_eigenvector(adjacency_matrix)\n\nprint(\"Eigenvector Centrality >>\")\nfor user_id, centrality in enumerate(eigenvector_centralities):\n print(user_id, centrality)", "Eigenvector Centrality >>\n0 0.38578006614957344\n1 0.5147902322356226\n2 0.5147902322356226\n3 0.47331220396377677\n4 0.23361029944966002\n5 0.1501458150031844\n6 0.08355561051056493\n7 0.08355561051056493\n8 0.07284034177922594\n9 0.027294660139652423\n" ] ], [ [ "## **4 방향성 그래프(Directed Graphs) 와 페이지랭크**\n다른 과학자로 부터 **보증을 몇 번 받았는지** 를 계산 합니다.\n1. (특정인 **index**, 보증한 사람 **value**) 데이터 목록 입니다\n1. **가짜계정을 여러개** 생성, **친구끼리 보증** 하는 등의 조작이 가능합니다\n1. 이를 피하는 방법으로 **누가 보증을 하는지**를 계산하는 방법 입니다.", "_____no_output_____" ] ], [ [ "# directed graphs\nendorsements = [(0, 1), (1, 0), (0, 2), (2, 0), (1, 2), (2, 1), (1, 3),\n (2, 3), (3, 4), (5, 4), (5, 6), (7, 5), (6, 8), (8, 7), (8, 9)]\n\nfor user in users:\n user[\"endorses\"] = [] # 다른 사람을 보증하는 정보 [list]\n user[\"endorsed_by\"] = [] # 보증받는 것에 대한 정보를 유지하는 [list]\n\nfor source_id, target_id in endorsements:\n users[source_id][\"endorses\"].append(users[target_id])\n users[target_id][\"endorsed_by\"].append(users[source_id])\n\nendorsements_by_id = [(user[\"id\"], len(user[\"endorsed_by\"])) for user in users]\nsorted(endorsements_by_id, key=lambda x: x[1], reverse=True)", "_____no_output_____" ] ], [ [ "이러한 보증은 조작이 용이한 단점이 있어서 **PageRank** 알고리즘을 적용 합니다.\n1. 모든 Node 에 **동일한 초기값** 을 배당 합니다.\n1. **각 Step** 을 거칠때 마다 Node 에 **배당된 PageRank 에 균등하게 배당을** 합니다\n1. **외부로 향하는 Link** 에 배당을 합니다", "_____no_output_____" ] ], [ [ "def page_rank(users, damping = 0.85, num_iters = 100):\n num_users = len(users)\n pr = { user[\"id\"] : 1 / num_users for user in users } # 동일한 초기값\n \n # Step 마다 각 Node 에 PageRank 를 조금씩 배당 합니다\n base_pr = (1 - damping) / num_users\n for __ in range(num_iters):\n next_pr = { user[\"id\"] : base_pr for user in users }\n \n # PageRank 는 외부로 향하는 Link에 배당을 합니다\n for user in users: \n links_pr = pr[user[\"id\"]] * damping\n for endorsee in user[\"endorses\"]:\n next_pr[endorsee[\"id\"]] += links_pr / len(user[\"endorses\"])\n pr = next_pr\n return pr\n\nprint(\"PageRank >>\")\nfor user_id, pr in page_rank(users).items():\n print(user_id, pr)", "PageRank >>\n0 0.0404553415061296\n1 0.044921190893169885\n2 0.044921190893169885\n3 0.0404553415061296\n4 0.06785083675770529\n5 0.04344422700587085\n6 0.03346379647749512\n7 0.03346379647749512\n8 0.04344422700587085\n9 0.03346379647749512\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af968c486fea2f829380e9de6ac5be417ad17e5
176,111
ipynb
Jupyter Notebook
notebooks/demo.ipynb
covid-modeling/covid-model-evaluation
4cfa1a196bf568f1f84249752110ff00c69f322a
[ "MIT" ]
1
2020-08-07T14:07:40.000Z
2020-08-07T14:07:40.000Z
notebooks/demo.ipynb
covid-modeling/covid-model-evaluation
4cfa1a196bf568f1f84249752110ff00c69f322a
[ "MIT" ]
2
2020-07-24T11:05:26.000Z
2020-07-24T18:13:55.000Z
notebooks/demo.ipynb
covid-modeling/covid-model-evaluation
4cfa1a196bf568f1f84249752110ff00c69f322a
[ "MIT" ]
null
null
null
469.629333
85,144
0.94148
[ [ [ "Put `coveval` folder into our path for easy import of modules:", "_____no_output_____" ] ], [ [ "import sys\nsys.path.append('../')", "_____no_output_____" ] ], [ [ "# Load data", "_____no_output_____" ] ], [ [ "from coveval import utils\nfrom coveval.connectors import generic", "_____no_output_____" ] ], [ [ "Let's load some data corresponding to the state of New-York and look at the number of daily fatalities:", "_____no_output_____" ] ], [ [ "df_reported = utils.get_outbreak_data_usa(prefix='reported_').loc['US-NY']\ndf_predicted = generic.load_predictions('../data/demo/predictions.json', prefix='predicted_')\ndata = utils.add_outbreak_data(df_predicted, df_reported)[['reported_deathIncrease', 'predicted_incDeath']]", "_____no_output_____" ], [ "_ = utils.show_data(df=data,\n cols=['reported_deathIncrease', 'predicted_incDeath'],\n t_min='2020-02',\n t_max='2021-01',\n colors={'cols':{'reported_deathIncrease': '#85C5FF', 'predicted_incDeath': '#FFAD66'}},\n linewidths={'reported_deathIncrease': 3, 'predicted_incDeath': 3},\n show_leg={'reported_deathIncrease': 'reported', 'predicted_incDeath': 'predicted'},\n y_label='daily fatalities',\n x_label='date',\n figsize=(11,5))", "_____no_output_____" ] ], [ [ "# Smooth reported values", "_____no_output_____" ] ], [ [ "from coveval.core import smoothing", "_____no_output_____" ] ], [ [ "We want to smooth out noise in the reported data due to reporting errors and delays. To do so we can use for instance the \"missed case\" smoother.\n\nAnd it's also useful to smooth out high frequency noise in the predictions made by stochastc models as they do not correspond to a useful signal and pollute trend comparisons. A simple low-pass filter can be appropriate here.", "_____no_output_____" ] ], [ [ "# define smoothers\nsmoothers = {'missed': smoothing.missed_cases(cost_missing=.1, cost_der1=10, cost_der2=1),\n 'gaussian': smoothing.gaussian(sigma=2)}\n\n# smooth reported data\ncol = 'reported_deathIncrease'\ns_name = 'missed'\nsmoothers[s_name].smooth_df(data, col, inplace=True)\ndata.rename(columns={col + '_smoothed' : col + '_smoothed_' + s_name}, inplace=True)\n\n# smooth predictions\ncol = 'predicted_incDeath'\ns_name = 'gaussian'\nsmoothers[s_name].smooth_df(data, col, inplace=True)\ndata.rename(columns={col + '_smoothed' : col + '_smoothed_' + s_name}, inplace=True)", "_____no_output_____" ], [ "_ = utils.show_data(data,\n cols=['reported_deathIncrease_smoothed_missed','predicted_incDeath_smoothed_gaussian'],\n scatter=['reported_deathIncrease'],\n colors={'cols':{'reported_deathIncrease_smoothed_missed': '#85C5FF',\n 'predicted_incDeath_smoothed_gaussian': '#FFAD66'}},\n date_auto=False,\n t_min='2020-03',\n t_max='2020-06-20',\n show_leg={'reported_deathIncrease': 'reported',\n 'reported_deathIncrease_smoothed_missed': 'reported smoothed \"missed\"',\n 'predicted_incDeath_smoothed_gaussian': 'predicted smoothed \"gaussian\"'},\n y_label='daily fatalities',\n x_label='date',\n figsize=(11,5))", "_____no_output_____" ] ], [ [ "# Normalise predicted values", "_____no_output_____" ] ], [ [ "from coveval.core import normalising", "_____no_output_____" ] ], [ [ "The goal here is to avoid repeatedly punishing predictions made by a model due to e.g. the model getting the start of the outbreak wrong.", "_____no_output_____" ] ], [ [ "normaliser_scaling = normalising.dynamic_scaling()\nnormaliser_scaling.normalise_df(df=data,\n col_truth='reported_deathIncrease_smoothed_missed',\n col_pred='predicted_incDeath_smoothed_gaussian',\n inplace=True)\n\n# let's store the difference between the truth and the normalised predictions\ndata['predicted_incDeath_smoothed_gaussian_norm_match'] = data['reported_deathIncrease_smoothed_missed'] - data['predicted_incDeath_smoothed_gaussian_norm']", "_____no_output_____" ], [ "fig = utils.show_normalisation(data,\n truth='reported_deathIncrease',\n pred_raw='predicted_incDeath_smoothed_gaussian',\n pred_norm='predicted_incDeath_smoothed_gaussian_norm',\n pred_match='predicted_incDeath_smoothed_gaussian_norm_match',\n truth_smoothed='reported_deathIncrease_smoothed_missed')", "_____no_output_____" ] ], [ [ "# Compare to truth", "_____no_output_____" ] ], [ [ "from coveval.core import losses", "_____no_output_____" ] ], [ [ "Now we can use a simple Poisson loss to judge how well each normalised prediction compares to the reported data and compute an overall score that can be compared with that of other models.", "_____no_output_____" ] ], [ [ "poisson_loss = losses.poisson()\npoisson_loss.compute_df(df=data,\n col_truth='reported_deathIncrease_smoothed_missed',\n col_pred='predicted_incDeath_smoothed_gaussian_norm',\n inplace=True)\ndata['predicted_incDeath_smoothed_gaussian_norm_loss'].mean()", "_____no_output_____" ] ], [ [ "# All in one: scorer", "_____no_output_____" ] ], [ [ "from coveval.scoring import scorer", "_____no_output_____" ] ], [ [ "The scorer object performes the above operations in a single call - with the exception of smoothing the predictions as for some models this is not necessary.", "_____no_output_____" ] ], [ [ "default_scorer = scorer(smoother=smoothers['missed'],\n normaliser=normaliser_scaling,\n loss=poisson_loss)\nresults = default_scorer.score_df(df=data,\n col_truth='reported_deathIncrease',\n col_pred='predicted_incDeath_smoothed_gaussian')", "_____no_output_____" ], [ "# the average loss is the score (so the closer to 0 the better)\nresults['score']", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4af96a3d08be150b456da7d1dc0955e6d83d7a52
97,820
ipynb
Jupyter Notebook
nbs/00_dl_101_pytorch_fastai.ipynb
muellerzr/walk-with-deep-learning
4adbf26da4885d122ed305eccef3efbb6fb10df5
[ "Apache-2.0" ]
1
2021-09-05T12:42:46.000Z
2021-09-05T12:42:46.000Z
nbs/00_dl_101_pytorch_fastai.ipynb
muellerzr/walk-with-deep-learning
4adbf26da4885d122ed305eccef3efbb6fb10df5
[ "Apache-2.0" ]
null
null
null
nbs/00_dl_101_pytorch_fastai.ipynb
muellerzr/walk-with-deep-learning
4adbf26da4885d122ed305eccef3efbb6fb10df5
[ "Apache-2.0" ]
null
null
null
86.337158
13,528
0.822337
[ [ [ "# default_exp dl_101", "_____no_output_____" ] ], [ [ "# Deep learning 101 with Pytorch and fastai\n\n> Some code and text snippets have been extracted from the book [\\\"Deep Learning for Coders with Fastai and Pytorch: AI Applications Without a PhD\\\"](https://course.fast.ai/), and from these blog posts [[ref1](https://muellerzr.github.io/fastblog/2021/02/14/Pytorchtofastai.html)].", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.showdoc import *\nfrom fastcore.all import *", "_____no_output_____" ], [ "# export\nimport torch\nfrom torch.utils.data import TensorDataset\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nfrom wwdl.utils import *", "_____no_output_____" ], [ "use_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\ndevice", "_____no_output_____" ] ], [ [ "## Linear regression model in Pytorch", "_____no_output_____" ], [ "### Datasets and Dataloaders", "_____no_output_____" ], [ "We'll create a dataset that contains $(x,y)$ pairs sampled from the linear function $y = ax + b+ \\epsilon$. To do this, we'll create a PyTorch's `TensorDataset`.\n\nA PyTorch tensor is nearly the same thing as a NumPy array. The vast majority of methods and operators supported by NumPy on these structures are also supported by PyTorch, but PyTorch tensors have additional capabilities. One major capability is that these structures can live on the GPU, in which case their computation will be optimized for the GPU and can run much faster (given lots of values to work on). In addition, PyTorch can automatically calculate derivatives of these operations, including combinations of operations. These two things are critical for deep learning", "_____no_output_____" ] ], [ [ "# export\ndef linear_function_dataset(a, b, n=100, show_plot=False):\n r\"\"\"\n Creates a Pytorch's `TensorDataset` with `n` random samples of the \n linear function y = `a`*x + `b`. `show_plot` dcides whether or not to \n plot the dataset\n \"\"\"\n x = torch.randn(n, 1)\n y = a*x + b + 0.1*torch.randn(n, 1)\n if show_plot:\n show_TensorFunction1D(x, y, marker='.')\n return TensorDataset(x, y)", "_____no_output_____" ], [ "a = 2\nb = 3\nn = 100\ndata = linear_function_dataset(a, b, n, show_plot=True)\ntest_eq(type(data), TensorDataset)", "_____no_output_____" ] ], [ [ "In every machine/deep learning experiment, we need to have at least two datasets:\n - training: used to train the model\n - validation: used to validate the model after each training step. It allows to detect overfitting and adjust the hyperparameters of the model properly", "_____no_output_____" ] ], [ [ "train_ds = linear_function_dataset(a, b, n=100, show_plot=True)\nvalid_ds = linear_function_dataset(a, b, n=20, show_plot=True)", "_____no_output_____" ] ], [ [ "A dataloader combines a dataset an a sampler that samples data into **batches**, and provides an iterable over the given dataset. ", "_____no_output_____" ] ], [ [ "bs = 10\ntrain_dl = torch.utils.data.DataLoader(train_ds, batch_size=bs, shuffle=True)\nvalid_dl = torch.utils.data.DataLoader(valid_ds, batch_size=bs, shuffle=False)", "_____no_output_____" ], [ "for i, data in enumerate(train_dl, 1):\n x, y = data\n print(f'batch {i}: x={x.shape} ({x.device}), y={y.shape} ({y.device})')", "batch 1: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 2: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 3: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 4: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 5: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 6: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 7: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 8: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 9: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\nbatch 10: x=torch.Size([10, 1]) (cpu), y=torch.Size([10, 1]) (cpu)\n" ] ], [ [ "### Defining a linear regression model in Pytorch", "_____no_output_____" ], [ "The class `torch.nn.Module` is the base structure for all models in Pytorch. It mostly helps to register all the trainable parameters. A module is an object of a class that inherits from the PyTorch `nn.Module` class.\n\nTo implement an `nn.Module` you just need to:\n\n- Make sure the superclass __init__ is called first when you initialize it.\n- Define any parameters of the model as attributes with nn.Parameter. To tell `Module` that we want to treat a tensor as a parameter, we have to wrap it in the `nn.Parameter` class. All PyTorch modules use `nn.Parameter` for any trainable parameters. This class doesn't actually add any functionality (other than automatically calling `requires_grad`). It's only used as a \"marker\" to show what to include in parameters:\n- Define a forward function that returns the output of your model.", "_____no_output_____" ] ], [ [ "#export\nclass LinRegModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.a = nn.Parameter(torch.randn(1))\n self.b = nn.Parameter(torch.randn(1))\n \n def forward(self, x): return self.a*x + self.b", "_____no_output_____" ], [ "model = LinRegModel()\npa, pb = model.parameters()\npa, pa.shape, pb, pb.shape", "_____no_output_____" ] ], [ [ "Objects of this class behave identically to standard Python functions, in that you can call them using parentheses and they will return the activations of a model.", "_____no_output_____" ] ], [ [ "x = torch.randn(10, 1)\nout = model(x)\nx, x.shape, out, out.shape ", "_____no_output_____" ] ], [ [ "### Loss function and optimizer", "_____no_output_____" ], [ "The loss is the thing the machine is using as the measure of performance to decide how to update model parameters. The loss function is simple enough for a regression problem, we'll just use the Mean Square Error (MSE)", "_____no_output_____" ] ], [ [ "loss_func = nn.MSELoss()\nloss_func(x, out)", "_____no_output_____" ] ], [ [ "We have data, a model, and a loss function; we only need one more thing we can fit a model, and that's an optimizer.", "_____no_output_____" ] ], [ [ "opt_func = torch.optim.SGD(model.parameters(), lr = 1e-3)", "_____no_output_____" ] ], [ [ "### Training loop", "_____no_output_____" ], [ "During training, we need to push our model and our batches to the GPU. Calling `cuda()` on a model or a tensor this class puts all these parameters on the GPU:", "_____no_output_____" ] ], [ [ "model = model.to(device)", "_____no_output_____" ] ], [ [ "To train a model, we will need to compute all the gradients of a given loss with respect to its parameters, which is known as the *backward pass*. The *forward pass* is where we compute the output of the model on a given input, based on the matrix products. PyTorch computes all the gradients we need with a magic call to `loss.backward`. The backward pass is the chain rule applied multiple times, computing the gradients from the output of our model and going back, one layer at a time. \n\nIn Pytorch, Each basic function we need to differentiate is written as a `torch.autograd.Function` object that has a `forward` and a `backward` method. PyTorch will then keep trace of any computation we do to be able to properly run the backward pass, unless we set the `requires_grad` attribute of our tensors to `False`. \n\nFor minibatch gradient descent (the usual way of training in deep learning), we calculate gradients on batches. Before moving onto the next batch, we modify our model's parameters based on the gradients. For each iteration through our dataset (which would be called an **epoch**), the optimizer would perform as many updates as we have batches.\n\nThere are two important methods in a Pytorch optimizer:\n- `zero_grad`: In PyTorch, we need to set the gradients to zero before starting to do backpropragation because PyTorch accumulates the gradients on subsequent backward passes. `zero_grad` just loops through the parameters of the model and sets the gradients to zero. It also calls `detach_`, which removes any history of gradient computation, since it won't be needed after `zero_grad`.", "_____no_output_____" ] ], [ [ "n_epochs = 10", "_____no_output_____" ], [ "# export\ndef train(model, device, train_dl, loss_func, opt_func, epoch_idx):\n r\"\"\"\n Train `model` for one epoch, whose index is given in `epoch_idx`. The \n training loop will iterate through all the batches of `train_dl`, using\n the the loss function given in `loss_func` and the optimizer given in `opt_func`\n \"\"\"\n running_loss = 0.0\n batches_processed = 0\n for batch_idx, (x, y) in enumerate(train_dl, 1):\n x, y = x.to(device), y.to(device) # Push data to GPU\n\n opt_func.zero_grad() # Reset gradients\n # Forward pass\n output = model(x)\n loss = loss_func(output, y)\n # Backward pass\n loss.backward()\n # Optimizer step\n opt_func.step()\n\n # print statistics\n running_loss += loss.item()\n batches_processed += 1\n print(f'Train loss [Epoch {epoch_idx}]: {running_loss/batches_processed : .2f})')", "_____no_output_____" ], [ "for epoch in range(1, n_epochs+1):\n train(model, device, train_dl, loss_func, opt_func, epoch)", "Train loss [Epoch 1]: 22.46)\nTrain loss [Epoch 2]: 21.61)\nTrain loss [Epoch 3]: 20.79)\nTrain loss [Epoch 4]: 20.01)\nTrain loss [Epoch 5]: 19.25)\nTrain loss [Epoch 6]: 18.53)\nTrain loss [Epoch 7]: 17.83)\nTrain loss [Epoch 8]: 17.16)\nTrain loss [Epoch 9]: 16.51)\nTrain loss [Epoch 10]: 15.89)\n" ] ], [ [ "We can see how the parameters of the regression model are getting closer to the truth values `a` and `b` from the linear function.", "_____no_output_____" ] ], [ [ "L(model.named_parameters())", "_____no_output_____" ] ], [ [ "### Validating the model", "_____no_output_____" ], [ "Validating the model requires only a forward pass, it's just inference. Disabling gradient calculation with the method `torch.no_grad()` is useful for inference, when you are sure that you will not call :meth:`Tensor.backward()`. ", "_____no_output_____" ] ], [ [ "#export\ndef validate(model, device, dl):\n running_loss = 0.\n total_batches = 0\n with torch.no_grad():\n for x, y in valid_dl:\n x, y = x.to(device), y.to(device)\n output = model(x)\n loss = loss_func(output, y)\n running_loss += loss.item()\n total_batches += 1\n\n print(f'Valid loss: {running_loss/total_batches : .2f}')", "_____no_output_____" ], [ "validate(model, device, valid_dl)", "Valid loss: 15.52\n" ] ], [ [ "In order to spot overfitting, it is useful to validate the model after each training epoch. ", "_____no_output_____" ] ], [ [ "for epoch in range(1, n_epochs +1):\n train(model, device, train_dl, loss_func, opt_func, epoch)\n validate(model, device, valid_dl)", "Train loss [Epoch 1]: 15.29)\nValid loss: 14.97\nTrain loss [Epoch 2]: 14.72)\nValid loss: 14.43\nTrain loss [Epoch 3]: 14.16)\nValid loss: 13.92\nTrain loss [Epoch 4]: 13.63)\nValid loss: 13.42\nTrain loss [Epoch 5]: 13.12)\nValid loss: 12.94\nTrain loss [Epoch 6]: 12.63)\nValid loss: 12.48\nTrain loss [Epoch 7]: 12.16)\nValid loss: 12.04\nTrain loss [Epoch 8]: 11.71)\nValid loss: 11.61\nTrain loss [Epoch 9]: 11.27)\nValid loss: 11.20\nTrain loss [Epoch 10]: 10.84)\nValid loss: 10.80\n" ] ], [ [ "## Abstracting the manual training loop: moving from Pytorch to fastai", "_____no_output_____" ] ], [ [ "from fastai.basics import *\nfrom fastai.callback.progress import ProgressCallback", "_____no_output_____" ] ], [ [ "We can entirely replace the custom training loop with fastai's. That means you can get rid of `train()`, `validate()`, and the epoch loop in the original code, and replace it all with a couple of lines.\n\nfastai's training loop lives in a `Learner`. The Learner is the glue that merges everything together (Datasets, Dataloaders, model and optimizer) and enables to train by just calling a `fit` function.\n\nfastai's `Learner` expects DataLoaders to be used, rather than simply one DataLoader, so let's make that. We could just do `dls = Dataloaders(train_dl, valid_dl)`, to keep the PyTorch Dataloaders. However, by using a fastai `DataLoader` instead, created directly from the `TensorDataset` objects, we have some automations, such as automatic pushing of the data to GPU. ", "_____no_output_____" ] ], [ [ "dls = DataLoaders.from_dsets(train_ds, valid_ds, bs=10)", "_____no_output_____" ], [ "learn = Learner(dls, model=LinRegModel(), loss_func=nn.MSELoss(), opt_func=SGD)", "_____no_output_____" ] ], [ [ "Now we have everything needed to do a basic `fit`:", "_____no_output_____" ] ], [ [ "learn.fit(10, lr=1e-3)", "epoch train_loss valid_loss time \n0 15.458996 14.695848 00:00 \n1 15.154875 14.153360 00:00 \n2 14.765175 13.631460 00:00 \n3 14.432601 13.129395 00:00 \n4 14.095567 12.646358 00:00 \n5 13.762318 12.181554 00:00 \n6 13.400099 11.734407 00:00 \n7 13.051410 11.304171 00:00 \n8 12.670809 10.890233 00:00 \n9 12.305409 10.491939 00:00 \n" ] ], [ [ "Having a Learner allows us to easily gather the model predictions for the validation set, which we can use for visualisation and analysis", "_____no_output_____" ] ], [ [ "inputs, preds, outputs = learn.get_preds(with_input=True)\ninputs.shape, preds.shape, outputs.shape", "█\r" ], [ "show_TensorFunction1D(inputs, outputs, y_hat=preds, marker='.')", "_____no_output_____" ] ], [ [ "## Building a simple neural network", "_____no_output_____" ], [ "For the next example, we will create the dataset by sampling values from a non linear sample $y(x) = -\\frac{1}{100}x^7 - x^4 - 2x^2 - 4x + 1$", "_____no_output_____" ] ], [ [ "# export\ndef nonlinear_function_dataset(n=100, show_plot=False):\n r\"\"\"\n Creates a Pytorch's `TensorDataset` with `n` random samples of the \n nonlinear function y = (-1/100)*x**7 -x**4 -2*x**2 -4*x + 1 with a bit \n of noise. `show_plot` decides whether or not to plot the dataset\n \"\"\"\n x = torch.rand(n, 1)*20 - 10 # Random values between [-10 and 10]\n y = (-1/100)*x**7 -x**4 -2*x**2 -4*x + 1 + 0.1*torch.randn(n, 1)\n if show_plot:\n show_TensorFunction1D(x, y, marker='.')\n return TensorDataset(x, y)", "_____no_output_____" ], [ "n = 100\nds = nonlinear_function_dataset(n, show_plot=True)\nx, y = ds.tensors\ntest_eq(x.shape, y.shape)", "_____no_output_____" ] ], [ [ "We will create the trainin and test dataset, and build the Dataloaders with them, this time directly in fastai, using the `Dataloaders.from_dsets` method.", "_____no_output_____" ] ], [ [ "train_ds = nonlinear_function_dataset(n=1000)\nvalid_ds = nonlinear_function_dataset(n=200)", "_____no_output_____" ] ], [ [ "Normalization in deep learning are used to make optimization easier by smoothing the loss surface of the network. We will normalize the data based on the mean and std of the train dataset", "_____no_output_____" ] ], [ [ "norm_mean = train_ds.tensors[1].mean()\nnorm_std = train_ds.tensors[1].std()", "_____no_output_____" ], [ "train_ds_norm = TensorDataset(train_ds.tensors[0],\n (train_ds.tensors[1] - norm_mean)/norm_std)\nvalid_ds_norm = TensorDataset(valid_ds.tensors[0],\n (valid_ds.tensors[1] - norm_mean)/norm_std)", "_____no_output_____" ], [ "dls = DataLoaders.from_dsets(train_ds_norm, valid_ds_norm, bs = 32)", "_____no_output_____" ] ], [ [ "We will build a Multi Layer Perceptron with 3 hidden layers. These networks are also known as Feed-Forward Neural Networks. The layers aof this type of networks are known as Fully Connected Layers, because, between every subsequent pair of layers, all the neurons are connected to each other.", "_____no_output_____" ], [ "<img alt=\"Neural network architecture\" caption=\"Neural network\" src=\"https://i.imgur.com/5ZWPtRS.png\">", "_____no_output_____" ], [ "The easiest way of wrapping several layers in Pytorch is using the `nn.Sequential` module. It creates a module with a `forward` method that will call each of the listed layers or functions in turn, without us having to do the loop manually in the forward pass.", "_____no_output_____" ] ], [ [ "#export\nclass MLP3(nn.Module):\n r\"\"\"\n Multilayer perceptron with 3 hidden layers, with sizes `nh1`, `nh2` and\n `nh3` respectively.\n \"\"\"\n def __init__(self, n_in=1, nh1=200, nh2=100, nh3=50, n_out=1):\n super().__init__()\n self.layers = nn.Sequential(\n nn.Linear(n_in, nh1),\n nn.ReLU(), \n nn.Linear(nh1, nh2),\n nn.ReLU(),\n nn.Linear(nh2, nh3),\n nn.ReLU(),\n nn.Linear(nh3, n_out)\n )\n \n def forward(self, x): return self.layers(x)", "_____no_output_____" ], [ "x, y = dls.one_batch()\nmodel = MLP3()\noutput = model(x)\noutput.shape", "_____no_output_____" ], [ "learn = Learner(dls, MLP3(), loss_func=nn.MSELoss(), opt_func=Adam)", "_____no_output_____" ], [ "learn.fit(10, lr=1e-3)", "epoch train_loss valid_loss time \n0 0.459803 0.466981 00:00 \n1 0.438433 0.516446 00:00 \n2 0.401076 0.453653 00:00 \n3 0.350414 0.371717 00:00 \n4 0.302308 0.275682 00:00 \n5 0.253566 0.217735 00:00 \n6 0.226006 0.210842 00:00 \n7 0.184073 0.144207 00:00 \n8 0.151972 0.141578 00:00 \n9 0.133385 0.187222 00:00 \n" ], [ "inputs, preds, outputs = learn.get_preds(with_input = True)\nshow_TensorFunction1D(inputs, outputs, y_hat=preds, marker='.')", "█\r" ] ], [ [ "Let's compare these results with the ones by our previous linear regression model", "_____no_output_____" ] ], [ [ "learn_lin = Learner(dls, LinRegModel(), loss_func=nn.MSELoss(), opt_func=Adam)", "_____no_output_____" ], [ "learn_lin.fit(20, lr=1e-3)", "epoch train_loss valid_loss time \n0 10.620963 11.626534 00:00 \n1 9.930543 10.454909 00:00 \n2 9.147982 9.378319 00:00 \n3 8.353152 8.373522 00:00 \n4 7.507308 7.453660 00:00 \n5 6.782170 6.624144 00:00 \n6 6.080751 5.855684 00:00 \n7 5.407598 5.149915 00:00 \n8 4.749566 4.501391 00:00 \n9 4.186591 3.931699 00:00 \n10 3.655168 3.401416 00:00 \n11 3.205692 2.940045 00:00 \n12 2.760517 2.516037 00:00 \n13 2.365197 2.147783 00:00 \n14 2.006961 1.831295 00:00 \n15 1.711961 1.557886 00:00 \n16 1.441852 1.325928 00:00 \n17 1.231405 1.134470 00:00 \n18 1.048274 0.974520 00:00 \n19 0.894268 0.849143 00:00 \n" ], [ "inputs, preds, outputs = learn_lin.get_preds(with_input = True)\nshow_TensorFunction1D(inputs, outputs, y_hat=preds, marker='.')", "█\r" ] ], [ [ "## Export", "_____no_output_____" ] ], [ [ "#hide\nfrom nbdev.export import notebook2script\nnotebook2script()", "Converted 00_dl_101_pytorch_fastai.ipynb.\nConverted index.ipynb.\nConverted utils.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", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4af96b8ee6f7774000deb91272c828482d1d86cf
44,700
ipynb
Jupyter Notebook
Starting_Project.ipynb
jonathanyepez/WhatToDo_Quito
074d91e721e2c5c58282306e3b980fc1c20c4698
[ "MIT" ]
null
null
null
Starting_Project.ipynb
jonathanyepez/WhatToDo_Quito
074d91e721e2c5c58282306e3b980fc1c20c4698
[ "MIT" ]
null
null
null
Starting_Project.ipynb
jonathanyepez/WhatToDo_Quito
074d91e721e2c5c58282306e3b980fc1c20c4698
[ "MIT" ]
null
null
null
45.940391
7,012
0.517405
[ [ [ "## Program that searches for Bars nearby ", "_____no_output_____" ], [ "starting coordinates: Home - Romero y Cordero 209", "_____no_output_____" ] ], [ [ "import requests # library to handle requests\nimport pandas as pd # library for data analsysis\nimport numpy as np # library to handle data in a vectorized manner\nimport random # library for random number generation\n\nfrom geopy.geocoders import Nominatim # module to convert an address into latitude and longitude values\n\n# libraries for displaying images\nfrom IPython.display import Image \nfrom IPython.core.display import HTML \n \n# tranforming json file into a pandas dataframe library\nfrom pandas.io.json import json_normalize\n\n\nimport folium # plotting library\n\nprint('Folium imported')\nprint('Libraries imported.')", "Folium imported\nLibraries imported.\n" ], [ "CLIENT_ID = '2BOJBTIFPAIFAECFCKJT4H5W404CWPNYYY0SVHFFOFKPWNZV' # your Foursquare ID\nCLIENT_SECRET = '5VNGWKFYYVIEHTGME0IBVR5AQ5LCP5WPBVLSSQFUMOZMSFKM' # your Foursquare Secret\nVERSION = '20180604'\nLIMIT = 30\nprint('Your credentails:')\nprint('CLIENT_ID: ' + CLIENT_ID)\nprint('CLIENT_SECRET:' + CLIENT_SECRET)", "Your credentails:\nCLIENT_ID: 2BOJBTIFPAIFAECFCKJT4H5W404CWPNYYY0SVHFFOFKPWNZV\nCLIENT_SECRET:5VNGWKFYYVIEHTGME0IBVR5AQ5LCP5WPBVLSSQFUMOZMSFKM\n" ], [ "lati=-0.141189\nlongi=-78.479422\nsearch_query = 'bar' #what type of restaurant for example\nradius = 500 #search radius from initial location\nprint(search_query + ' .... OK!')", "bar .... OK!\n" ], [ "url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&v={}&query={}&radius={}&limit={}'.format(CLIENT_ID, CLIENT_SECRET, lati, longi, VERSION, search_query, radius, LIMIT)\nurl", "_____no_output_____" ], [ "results = requests.get(url).json()\nresults", "_____no_output_____" ], [ "# assign relevant part of JSON to venues\nvenues = results['response']['venues']\n\n# tranform venues into a dataframe\ndataframe = json_normalize(venues)\ndataframe.head()", "_____no_output_____" ], [ "# keep only columns that include venue name, and anything that is associated with location\nfiltered_columns = ['name', 'categories'] + [col for col in dataframe.columns if col.startswith('location.')] + ['id']\ndataframe_filtered = dataframe.loc[:, filtered_columns]\n\n# function that extracts the category of the venue\ndef get_category_type(row):\n try:\n categories_list = row['categories']\n except:\n categories_list = row['venue.categories']\n \n if len(categories_list) == 0:\n return None\n else:\n return categories_list[0]['name']\n\n# filter the category for each row\ndataframe_filtered['categories'] = dataframe_filtered.apply(get_category_type, axis=1)\n\n# clean column names by keeping only last term\ndataframe_filtered.columns = [column.split('.')[-1] for column in dataframe_filtered.columns]\n\ndataframe_filtered", "_____no_output_____" ], [ "#dataframe_filtered.name #to visualize the venues nearby\ndataframe_filtered = dataframe_filtered[(dataframe_filtered.categories == 'Bar')]#|(dataframe_filtered.categories == 'Seafood Restaurant')]\ndataframe_filtered.head()", "_____no_output_____" ], [ "venues_map = folium.Map(location=[lati, longi], zoom_start=15) # generate map centred around the Conrad Hotel\n\n# add a red circle marker to represent the starting point (Home)\nfolium.CircleMarker(\n [lati, longi],\n radius=10,\n color='red',\n popup='You Are Here!',\n fill = True,\n fill_color = 'red',\n fill_opacity = 0.6\n).add_to(venues_map)\n\n# add the Italian restaurants as blue circle markers\nfor lat, lng, label in zip(dataframe_filtered.lat, dataframe_filtered.lng, dataframe_filtered.name):\n folium.CircleMarker(\n [lat, lng],\n radius=5,\n color='blue',\n popup=label,\n fill = True,\n fill_color='blue',\n fill_opacity=0.6\n ).add_to(venues_map)\n\n# display map\nvenues_map", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af982a68af1421ce471fddb618cb81e979bd8ae
3,093
ipynb
Jupyter Notebook
pyanthem/example.ipynb
nicthib/anthem
ba7ffca3ac5e85f788a28663712d0f5c6430e20c
[ "MIT" ]
null
null
null
pyanthem/example.ipynb
nicthib/anthem
ba7ffca3ac5e85f788a28663712d0f5c6430e20c
[ "MIT" ]
2
2020-07-06T01:13:22.000Z
2020-07-06T02:48:44.000Z
pyanthem/example.ipynb
nicthib/anthem
ba7ffca3ac5e85f788a28663712d0f5c6430e20c
[ "MIT" ]
null
null
null
20.483444
95
0.51859
[ [ [ "import pyanthem\nfrom pyanthem_vars import *", "pyanthem version 0.49\n" ], [ "g=pyanthem.run(display=False)\n", "_____no_output_____" ], [ "cfg = example_cfg[0]\ndata_file = example_files_decomp[0]\ng.load_config(filein=cfg)\ng.load_data(filein=data_file)\ng.cfg['save_path']=r'C:\\Users\\dnt21\\Desktop\\outputs'\ng.write_AV().cleanup()\n", "Video file written to C:\\Users\\dnt21\\Desktop\\outputs\nAudio file written to C:\\Users\\dnt21\\Desktop\\outputs\nA/V file written to C:\\Users\\dnt21\\Desktop\\outputs\nA/V only videos removed\n" ], [ "raw_file = r'/Users/Nic/Desktop/anthem_datasets/demo1_raw.mat'\ng = pyanthem.GUI(display=False)\ng.process_raw(file_in=raw_file,n_clusters=20,frame_rate=20,save=True)\n", "Performing k-means...done.\nPerforming NNLS...done.\nDecomposed data file saved to /Users/Nic/Desktop/anthem_datasets/demo1_raw_decomp.mat\n" ], [ "help(pyanthem.GUI.cleanup)", "Help on function cleanup in module pyanthem:\n\ncleanup(self)\n Tries to remove any files that are video or audio only.\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4af9957ded679ddc9a2558be5bcea766d2bd0966
963
ipynb
Jupyter Notebook
08-visualisation.ipynb
nsaunier/CIV8760
c4bb9a9dbabf8c26ba0c7942c7a866b91678dffc
[ "MIT" ]
1
2021-02-08T04:54:52.000Z
2021-02-08T04:54:52.000Z
08-visualisation.ipynb
nsaunier/CIV8760
c4bb9a9dbabf8c26ba0c7942c7a866b91678dffc
[ "MIT" ]
null
null
null
08-visualisation.ipynb
nsaunier/CIV8760
c4bb9a9dbabf8c26ba0c7942c7a866b91678dffc
[ "MIT" ]
3
2020-09-08T17:11:21.000Z
2021-02-08T04:54:27.000Z
23.487805
174
0.5919
[ [ [ "< 7. [Modèles statistiques](07-modeles-statistiques.ipynb) | [Contents](index.ipynb) | 9. [Fouille de données](09-fouille-donnees.ipynb) >", "_____no_output_____" ], [ "* Mobules Python matplotlib http://matplotlib.org/, pandas https://pandas.pydata.org/pandas-docs/stable/reference/plotting.html et seaborn http://seaborn.pydata.org/\n* Bibliothèque Javascript https://d3js.org/", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown" ] ]
4af9a1a97d1277c3d630f456bb4623387c52ad5a
165,101
ipynb
Jupyter Notebook
2. Convolutional Neural Network in Tensorflow/AZ/01_mnist_aug_02.ipynb
AmirRazaMBA/TensorFlow-Certification
ec0990007cff6daf36beac6d00d95c81cdf80353
[ "MIT" ]
1
2020-11-20T14:46:45.000Z
2020-11-20T14:46:45.000Z
2. Convolutional Neural Network in Tensorflow/AZ/01_mnist_aug_02.ipynb
AmirRazaMBA/TF_786
ec0990007cff6daf36beac6d00d95c81cdf80353
[ "MIT" ]
null
null
null
2. Convolutional Neural Network in Tensorflow/AZ/01_mnist_aug_02.ipynb
AmirRazaMBA/TF_786
ec0990007cff6daf36beac6d00d95c81cdf80353
[ "MIT" ]
1
2021-11-17T02:40:23.000Z
2021-11-17T02:40:23.000Z
133.038678
37,888
0.873859
[ [ [ "# CNN - Example 01", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "### Load Keras Dataset", "_____no_output_____" ] ], [ [ "from tensorflow.keras.datasets import mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()", "_____no_output_____" ] ], [ [ "#### Visualize data", "_____no_output_____" ] ], [ [ "print(x_train.shape)\nsingle_image = x_train[0]\nprint(single_image.shape)\nplt.imshow(single_image)", "(60000, 28, 28)\n(28, 28)\n" ] ], [ [ "### Pre-Process data", "_____no_output_____" ], [ "#### One Hot encode", "_____no_output_____" ] ], [ [ "# Make it one hot encoded otherwise it will think as a regression problem on a continuous axis\nfrom tensorflow.keras.utils import to_categorical\nprint(\"Shape before one hot encoding\" +str(y_train.shape))\ny_example = to_categorical(y_train)\nprint(y_example)\nprint(\"Shape after one hot encoding\" +str(y_train.shape))\ny_example[0]", "Shape before one hot encoding(60000,)\n[[0. 0. 0. ... 0. 0. 0.]\n [1. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n ...\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 1. 0.]]\nShape after one hot encoding(60000,)\n" ], [ "y_cat_test = to_categorical(y_test,10)\ny_cat_train = to_categorical(y_train,10)", "_____no_output_____" ] ], [ [ "#### Normalize the images", "_____no_output_____" ] ], [ [ "x_train = x_train/255\nx_test = x_test/255", "_____no_output_____" ], [ "scaled_single = x_train[0]\nplt.imshow(scaled_single)", "_____no_output_____" ] ], [ [ "#### Reshape the images", "_____no_output_____" ] ], [ [ "# Reshape to include channel dimension (in this case, 1 channel)\n# x_train.shape\nx_train = x_train.reshape(60000, 28, 28, 1) \nx_test = x_test.reshape(10000,28,28,1)", "_____no_output_____" ], [ "# ### Image data augmentation\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator", "_____no_output_____" ] ], [ [ "help(ImageDataGenerator)", "_____no_output_____" ] ], [ [ "datagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True)", "_____no_output_____" ], [ "datagen.fit(x_train)", "_____no_output_____" ], [ "it = datagen.flow(x_train, y_cat_train, batch_size=32)", "_____no_output_____" ], [ "# Preparing the Samples and Plot for displaying output\nfor i in range(9):\n\t# preparing the subplot\n\tplt.subplot(330 + 1 + i)\n\t# generating images in batches\n\tbatch = it.next()\n\t# Remember to convert these images to unsigned integers for viewing \n\timage = batch[0][0].astype('uint8')\n\t# Plotting the data\n\tplt.imshow(image)\n# Displaying the figure\nplt.show()", "_____no_output_____" ] ], [ [ "### Model # 1", "_____no_output_____" ] ], [ [ "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten", "_____no_output_____" ], [ "model = Sequential()", "_____no_output_____" ], [ "model.add(Conv2D(filters=32, kernel_size=(4,4), input_shape=(28, 28, 1), activation='relu',))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))", "_____no_output_____" ] ], [ [ "Notes : If y is not one hot coded then loss= sparse_categorical_crossentropy", "_____no_output_____" ] ], [ [ "model.compile(loss='categorical_crossentropy', \n optimizer='adam',\n metrics=['accuracy', 'categorical_accuracy']) \n # we can add in additional metrics https://keras.io/metrics/", "_____no_output_____" ], [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 25, 25, 32) 544 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 12, 12, 32) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 4608) 0 \n_________________________________________________________________\ndense (Dense) (None, 128) 589952 \n_________________________________________________________________\ndense_1 (Dense) (None, 10) 1290 \n=================================================================\nTotal params: 591,786\nTrainable params: 591,786\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "#### Add Early Stopping", "_____no_output_____" ] ], [ [ "from tensorflow.keras.callbacks import EarlyStopping\nearly_stop = EarlyStopping(monitor='val_loss', patience=2)", "_____no_output_____" ] ], [ [ "##### Training using one hot encoding", "_____no_output_____" ] ], [ [ "# fits the model on batches with real-time data augmentation:\nhistory = model.fit(datagen.flow(x_train, y_cat_train, batch_size=32),\n epochs=10,\n steps_per_epoch=len(x_train) / 32,\n validation_data=(x_test,y_cat_test),\n callbacks=[early_stop])", "Epoch 1/10\n1875/1875 [==============================] - 39s 21ms/step - loss: 0.7936 - accuracy: 0.7314 - categorical_accuracy: 0.7314 - val_loss: 1.2845 - val_accuracy: 0.6130 - val_categorical_accuracy: 0.6130\nEpoch 2/10\n1875/1875 [==============================] - 40s 21ms/step - loss: 0.4378 - accuracy: 0.8566 - categorical_accuracy: 0.8566 - val_loss: 1.2633 - val_accuracy: 0.6164 - val_categorical_accuracy: 0.6164\nEpoch 3/10\n1875/1875 [==============================] - 38s 20ms/step - loss: 0.3534 - accuracy: 0.8854 - categorical_accuracy: 0.8854 - val_loss: 1.3131 - val_accuracy: 0.5655 - val_categorical_accuracy: 0.5655 - loss: 0.3545 - accuracy: 0.8847 - categ\nEpoch 4/10\n1875/1875 [==============================] - 38s 20ms/step - loss: 0.3062 - accuracy: 0.9017 - categorical_accuracy: 0.9017 - val_loss: 1.3775 - val_accuracy: 0.5831 - val_categorical_accuracy: 0.5831\n" ] ], [ [ "#### Save model", "_____no_output_____" ], [ "Saving model\nfrom tensorflow.keras.models import load_model\nmodel_file = 'D:\\\\Sandbox\\\\Github\\\\MODELS\\\\' + '01_mnist.h5'\nmodel.save(model_file)", "_____no_output_____" ], [ "#### Retreive model", "_____no_output_____" ], [ "Retrieve model\nmodel = load_model(model_file)", "_____no_output_____" ], [ "#### Evaluate", "_____no_output_____" ], [ "Rule of thumb\n1. High Bias accuracy = 80% val-accuracy = 78% (2% gap)\n2. High Variance accuracy = 98% val-accuracy = 80% (18% gap)\n3. High Bias and High Variance accuracy = 80% val-accuracy = 60% (20% gap)\n4. Low Bias and Low Variance accuracy = 98% val-accuracy = 96% (2% gap)", "_____no_output_____" ], [ "#### Eval - Train", "_____no_output_____" ] ], [ [ "model.metrics_names", "_____no_output_____" ], [ "pd.DataFrame(history.history).head()\n#pd.DataFrame(model.history.history).head()", "_____no_output_____" ] ], [ [ "pd.DataFrame(history.history).plot()", "_____no_output_____" ] ], [ [ "losses = pd.DataFrame(history.history)", "_____no_output_____" ], [ "losses[['loss','val_loss']].plot()", "_____no_output_____" ], [ "losses[['accuracy','val_accuracy']].plot()", "_____no_output_____" ], [ "# Plot loss per iteration\nplt.plot(history.history['loss'], label='loss')\nplt.plot(history.history['val_loss'], label='val_loss')\nplt.legend()", "_____no_output_____" ], [ "# Plot accuracy per iteration\nplt.plot(history.history['accuracy'], label='acc')\nplt.plot(history.history['val_accuracy'], label='val_acc')\nplt.legend()", "_____no_output_____" ] ], [ [ "#### Eval - Test", "_____no_output_____" ] ], [ [ "test_metrics = model.evaluate(x_test,y_cat_test,verbose=1)", "313/313 [==============================] - 2s 5ms/step - loss: 1.3775 - accuracy: 0.5831 - categorical_accuracy: 0.5831\n" ], [ "print('Loss on test dataset:', test_metrics[0])\nprint('Accuracy on test dataset:', test_metrics[1])", "Loss on test dataset: 1.377543568611145\nAccuracy on test dataset: 0.5831000208854675\n" ], [ "print(\"Loss and Accuracy on Train dataset:\")", "Loss and Accuracy on Train dataset:\n" ], [ "pd.DataFrame(history.history).tail(1)", "_____no_output_____" ] ], [ [ "As it turns out, the accuracy on the test dataset is smaller than the accuracy on the training dataset. \nThis is completely normal, since the model was trained on the `train_dataset`. \nWhen the model sees images it has never seen during training, (that is, from the `test_dataset`), \nwe can expect performance to go down. ", "_____no_output_____" ], [ "#### Prediction", "_____no_output_____" ] ], [ [ "y_prediction = np.argmax(model.predict(x_test), axis=-1)", "_____no_output_____" ] ], [ [ "#### Reports", "_____no_output_____" ] ], [ [ "from sklearn.metrics import classification_report,confusion_matrix\nprint(classification_report(y_test, y_prediction))\nprint(confusion_matrix(y_test, y_prediction))", " precision recall f1-score support\n\n 0 0.87 0.92 0.90 980\n 1 1.00 0.03 0.06 1135\n 2 0.98 0.47 0.64 1032\n 3 0.87 0.40 0.55 1010\n 4 0.47 0.93 0.62 982\n 5 0.98 0.22 0.36 892\n 6 0.94 0.81 0.87 958\n 7 1.00 0.41 0.58 1028\n 8 0.26 0.99 0.41 974\n 9 0.91 0.74 0.81 1009\n\n accuracy 0.58 10000\n macro avg 0.83 0.59 0.58 10000\nweighted avg 0.83 0.58 0.57 10000\n\n[[905 0 0 0 0 0 17 0 50 8]\n [ 54 36 3 0 998 0 2 0 42 0]\n [ 21 0 486 10 9 0 26 0 478 2]\n [ 10 0 1 402 0 2 3 0 587 5]\n [ 2 0 0 0 911 0 2 0 51 16]\n [ 4 0 4 51 1 196 1 1 629 5]\n [ 21 0 2 0 13 0 774 0 146 2]\n [ 1 0 2 0 8 1 0 418 562 36]\n [ 13 0 0 0 0 0 1 0 960 0]\n [ 4 0 0 1 11 0 0 0 250 743]]\n" ] ], [ [ "Recall (sensivity) : Fraud detection recall because you want to catch FN (real fraud guys)\nPrecision (specificity): Sentiment analysis precision is important. You want to catch all feeling FP ()\nF1 score : Higher is better to compare two or more models\naccuracy : higher is better\nerror : 1 - accuracy\nIdeally, We want both Precision & Recall to be 1 but it is a zero-sum game. You can't have both ", "_____no_output_____" ] ], [ [ "import seaborn as sns\nplt.figure(figsize=(10,6))\nsns.heatmap(confusion_matrix(y_test,y_prediction),annot=True)", "_____no_output_____" ] ], [ [ "#### Predictions go wrong!", "_____no_output_____" ] ], [ [ "# Show some misclassified examples\nmisclassified_idx = np.where(y_prediction != y_test)[0]\ni = np.random.choice(misclassified_idx)\nplt.imshow(x_test[i].reshape(28,28), cmap='gray')\nplt.title(\"True label: %s Predicted: %s\" % (y_test[i], y_prediction[i]));", "_____no_output_____" ] ], [ [ "#### Final thoughts", "_____no_output_____" ], [ "Rule of thumb\n1. High Bias accuracy = 80% val-accuracy = 78% (2% gap)\n2. High Variance accuracy = 98% val-accuracy = 80% (18% gap)\n3. High Bias and High Variance accuracy = 80% val-accuracy = 60% (20% gap)\n4. Low Bias and Low Variance accuracy = 98% val-accuracy = 96% (2% gap)", "_____no_output_____" ] ], [ [ "print(\"Percentage of wrong predcitions : \" + str(len(misclassified_idx)/len(y_prediction)*100) + \" %\")\nprint(\"Models maximum accuracy : \" + str(np.max(history.history['accuracy'])*100) + \" %\")\nprint(\"Models maximum validation accuracy : \" + str(np.max(history.history['val_accuracy'])*100) + \" %\")", "Percentage of wrong predcitions : 41.69 %\nModels maximum accuracy : 90.17333388328552 %\nModels maximum validation accuracy : 61.640000343322754 %\n" ] ], [ [ "Model has Low Bias and High Variance with more than 29% gap. The recall is also bad. Image augmentation \ndoesn't help here. Augumentation with rotation and tilting doesn't help b/c it is a unique digital shape.", "_____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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4af9a8ca91d638619c4df6043b58cc13b4d7e646
24,255
ipynb
Jupyter Notebook
HeroesOfPymoli/.ipynb_checkpoints/HeroesOfPymoli_starter-Copy1-checkpoint 2.ipynb
fati165/pandas-challenge
1a2890a450eb39a3d0b8945e885d8314c629542b
[ "ADSL" ]
null
null
null
HeroesOfPymoli/.ipynb_checkpoints/HeroesOfPymoli_starter-Copy1-checkpoint 2.ipynb
fati165/pandas-challenge
1a2890a450eb39a3d0b8945e885d8314c629542b
[ "ADSL" ]
null
null
null
HeroesOfPymoli/.ipynb_checkpoints/HeroesOfPymoli_starter-Copy1-checkpoint 2.ipynb
fati165/pandas-challenge
1a2890a450eb39a3d0b8945e885d8314c629542b
[ "ADSL" ]
null
null
null
34.502134
506
0.516883
[ [ [ "### Note\n* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.", "_____no_output_____" ] ], [ [ "# Dependencies and Setup\nimport pandas as pd\n\n# File to Load (Remember to Change These)\nfile_to_load = \"Resources/purchase_data.csv\"\n\n# Read Purchasing File and store into Pandas data frame\npurchase_data = pd.read_csv(file_to_load)\n", "_____no_output_____" ] ], [ [ "## Player Count", "_____no_output_____" ], [ "* Display the total number of players\n", "_____no_output_____" ] ], [ [ "#number of players: do SN to count the names, w/o counting duplicate use unique\n#when using unique use len\nplayers= len(purchase_data[\"SN\"].unique())\n# Create a data frame with total players named player count\ncount = pd.DataFrame({\"players count\":[players]})\ncount", "_____no_output_____" ] ], [ [ "## Purchasing Analysis (Total)", "_____no_output_____" ], [ "* Run basic calculations to obtain number of unique items, average price, etc.\n\n\n* Create a summary data frame to hold the results\n\n\n* Optional: give the displayed data cleaner formatting\n\n\n* Display the summary data frame\n", "_____no_output_____" ] ], [ [ "#number of unique items\n# with len for unique. unique item use unique (not sure but it sounds like it make sense)\nunique_items = len(purchase_data[\"Item ID\"].unique())\n\n#average price\n#name=df[].mean()\nAverage_Price = purchase_data[\"Price\"].mean()\n\n#Number of Purchases\n#same formula^^\nNumber_of_Purchases = purchase_data[\"Purchase ID\"].count()\n\n#sum\n#same same\ntotal_revenue = purchase_data[\"Price\"].sum()\n\n#summary data frame \n# make dictionary?\n#df.add: is it simplier or more complicated?\n#purchase_data[\"Number of Unique Items\"]= len(purchase_data[\"Item ID\"].unique())?\n #^no!\n#make new dataframe, do method 1: list of dictionaries\n#words not in quotes belong in brackets\n#assign names to bracket values in a dictionary\n\n#use pd.DataFrame to make a table from the dict!!! otherwise it wont be organized\n\nsumm_df = pd.DataFrame({\"unique items\": [unique_items],\n \"Average Price\": [Average_Price],\n \"Number of Purchases\" : [Number_of_Purchases],\n \"total revenue\" :[total_revenue]})\nsumm_df\n\n# add dollars and 2 decimals for price and revenue\n#summ_df.style.format= ({\"Average Price\":\"${:.2f}\"})\n#summ_df.style.format= ({\"total revenue\" : \"${:.2f}\"})\n#summ_df.format\n #^^^doesn't work\n \n#combine!\nsumm_df.style.format({\"Average Price\": \"${:.2f}\", \"total revenue\": \"${:.2f}\"})", "_____no_output_____" ] ], [ [ "## Gender Demographics", "_____no_output_____" ], [ "* Percentage and Count of Male Players\n\n\n* Percentage and Count of Female Players\n\n\n* Percentage and Count of Other / Non-Disclosed\n\n\n", "_____no_output_____" ] ], [ [ "#Total count \n#make a variable that'll hold the total to use for calculations\nallGender= purchase_data[\"SN\"].count()\n\n#match gender to usernames. \"SN\"\n\n# count for sum\nmalecount = purchase_data[purchase_data[\"Gender\"] == \"Male\"][\"SN\"].nunique()\nfemalecount = purchase_data[purchase_data[\"Gender\"] == \"Female\"][\"SN\"].nunique()\nother = purchase_data[purchase_data[\"Gender\"] == \"Other / Non-Disclosed\"][\"SN\"].nunique()\n\n# calc for percent\n\nmalecalc= ((malecount/allGender)*100)\nfemalecalc= ((femalecount/allGender)*100)\nothercalc= ((other/allGender)*100)\n\n#make new dataframe to compile results\n\ngenders = pd.DataFrame({\"Gender\": [\"Male\", \"Female\", \"Other / Non-Disclosed\"],\n \"Total Count\": [malecount, femalecount, other],#no quotations, they hold the count\n \"Percentage of Players\": [malecalc, femalecalc, othercalc]\n })\n\ngenders.style.format({\"Percentage of Players\": \"{:.2f}%\" })\n", "_____no_output_____" ] ], [ [ "\n## Purchasing Analysis (Gender)", "_____no_output_____" ], [ "* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender\n\n\n\n\n* Create a summary data frame to hold the results\n\n\n* Optional: give the displayed data cleaner formatting\n\n\n* Display the summary data frame", "_____no_output_____" ] ], [ [ "#Purchase analysis for all genders\n#same formats just change names and .formulas. use count, mean, sum respectively\n#Purchase Count\n#use price and gender\n#use count to count total of each gender \nmalecount = purchase_data[purchase_data[\"Gender\"] == \"Male\"][\"SN\"].nunique()\nfemalecount = purchase_data[purchase_data[\"Gender\"] == \"Female\"][\"SN\"].nunique()\nothercount = purchase_data[purchase_data[\"Gender\"] == \"Other / Non-Disclosed\"][\"SN\"].nunique()\n\n# avg purchase price\n# use .mean to get mean\nmalemean = purchase_data[purchase_data[\"Gender\"] == \"Male\"][\"Price\"].mean()\nfemalemean = purchase_data[purchase_data[\"Gender\"] == \"Female\"][\"Price\"].mean()\nothermean = purchase_data[purchase_data[\"Gender\"] == \"Other / Non-Disclosed\"][\"Price\"].mean()\n\n\n#purchase total per gender\n#use .sum to sum total purchase\nmalesum = purchase_data[purchase_data[\"Gender\"] == \"Male\"][\"Price\"].sum()\nfemalesum = purchase_data[purchase_data[\"Gender\"] == \"Female\"][\"Price\"].sum()\nothersum = purchase_data[purchase_data[\"Gender\"] == \"Other / Non-Disclosed\"][\"Price\"].sum()\n\n#avg purchase by the total poeple in a gender\n#use variables ^^ to calculate\n#use the sum of total purchase per gender and divide by the count per gender so...\n# use malesum/malecount\navgpergender_male= (malesum/malecount)\navgpergender_female= (femalesum/femalecount)\navgpergender_other= (othersum/othercount)\n\n#make dataframe to table\npurchase= pd.DataFrame ({\"Gender\" : [\"Male\", \"Female\", \"Other / Non-Disclosed\"],\n \" Purchase Count\": [malecount, femalecount, othercount],\n \"Average Purchase Price\" : [malemean, femalemean, othermean],\n \"Total Purchase Value\" : [malesum, femalesum, othersum],\n \"Avg Total Purchase per Person\" : [avgpergender_male, avgpergender_female, avgpergender_other]\n })\n\n\npurchase.style.format({\"Average Purchase Price\": \"${:.2f}\",\"Avg Total Purchase per Person\": \"${:.2f}\", \"Total Purchase Value\":\"${:.2f}\"})\n", "_____no_output_____" ] ], [ [ "## Age Demographics", "_____no_output_____" ], [ "* Establish bins for ages\n\n\n* Categorize the existing players using the age bins. Hint: use pd.cut()\n\n\n* Calculate the numbers and percentages by age group\n\n\n* Create a summary data frame to hold the results\n\n\n* Optional: round the percentage column to two decimal points\n\n\n* Display Age Demographics Table\n", "_____no_output_____" ] ], [ [ "#age data analysis \n#print(purchase_data[\"Age\"].max())\n#print(purchase_data[\"Age\"].min())\n\nbins = [0,10,14,19,24,29,34,39,40]\ngroup_labels= [\"<10\", \"10-14\", \"15-19\", \"20-24\", \"25-29\", \"30-34\", \"35-39\", \"40+\"]\npd.cut(purchase_data[\"Age\"], bins, labels= group_labels)\n\n\npurchase_data[\"Age Group\"] = pd.cut(purchase_data[\"Age\"], bins, labels=group_labels)\n#purchase_data.head()\n\npurchase_group = purchase_data.groupby(\"Age Group\")\n\nTotal_count= purchase_group[\"Age Group\"].count()\n\n#purchase_group[[\"Total Count\", \"Percentage of Players\"]]\nage_group = pd.DataFrame ({ \"Age Groups\" : [group_labels],\n \"Total Count\": [Total_count],\n })\nage_group\n#age_group[[\"Age Groups\", \"Total Count\"]].count() \n#age_group\n#output= (\n # f\"Age Groups: {group_labels}\"+\n # f\"Total Count: {Total_count}\")\n#print (output)\n\n", "_____no_output_____" ] ], [ [ "## Purchasing Analysis (Age)", "_____no_output_____" ], [ "* Bin the purchase_data data frame by age\n\n\n* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below\n\n\n* Create a summary data frame to hold the results\n\n\n* Optional: give the displayed data cleaner formatting\n\n\n* Display the summary data frame", "_____no_output_____" ] ], [ [ "#purchase by age only\n", "_____no_output_____" ] ], [ [ "## Top Spenders", "_____no_output_____" ], [ "* Run basic calculations to obtain the results in the table below\n\n\n* Create a summary data frame to hold the results\n\n\n* Sort the total purchase value column in descending order\n\n\n* Optional: give the displayed data cleaner formatting\n\n\n* Display a preview of the summary data frame\n\n", "_____no_output_____" ], [ "## Most Popular Items", "_____no_output_____" ], [ "* Retrieve the Item ID, Item Name, and Item Price columns\n\n\n* Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value\n\n\n* Create a summary data frame to hold the results\n\n\n* Sort the purchase count column in descending order\n\n\n* Optional: give the displayed data cleaner formatting\n\n\n* Display a preview of the summary data frame\n\n", "_____no_output_____" ], [ "## Most Profitable Items", "_____no_output_____" ], [ "* Sort the above table by total purchase value in descending order\n\n\n* Optional: give the displayed data cleaner formatting\n\n\n* Display a preview of the data frame\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4af9a913cdfc5ce258b9675f233fe4f948258b10
5,680
ipynb
Jupyter Notebook
DataDistillation.ipynb
adines/ATLASS
e0b7a68437ed0cca98cc672b78ad18ca0c65d346
[ "MIT" ]
2
2021-06-16T14:52:52.000Z
2022-02-14T16:58:51.000Z
DataDistillation.ipynb
adines/ATLASS
e0b7a68437ed0cca98cc672b78ad18ca0c65d346
[ "MIT" ]
7
2020-03-24T17:56:41.000Z
2022-01-13T01:52:56.000Z
DataDistillation.ipynb
adines/ATLASS
e0b7a68437ed0cca98cc672b78ad18ca0c65d346
[ "MIT" ]
null
null
null
5,680
5,680
0.666725
[ [ [ "## Data Distillation\n\n", "_____no_output_____" ], [ "In this notebook we train models using data distillation.", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "_____no_output_____" ], [ "from google.colab import files\nuploaded = files.upload()\n!unzip dataset.zip -d dataset", "_____no_output_____" ], [ "import warnings\nimport os\nimport shutil\nimport glob\nimport random\nimport random\nimport cv2\nfrom fastai.vision import *\nfrom fastai.utils.mem import *\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module=\"torch.nn.functional\")\n\ndataset=\"dataset\"\nclassesPaths=sorted(glob.glob(dataset+'/*'))\nclasses=[pt.split(os.sep)[-1] for pt in classesPaths if os.path.isdir(pt)]\nimages=[pt for pt in classesPaths if not os.path.isdir(pt)]\n\nos.makedirs(dataset+'/train')\nos.makedirs(dataset+'/valid')\nos.makedirs(dataset+'/images')\n\nfor im in images:\n shutil.move(im,dataset+'/images/')\n\nfor cl in classes:\n os.mkdir(dataset+'/train/'+cl)\n images=sorted(glob.glob(dataset+'/'+cl+'/*'))\n for i in range(int(len(images)*0.75)):\n images=sorted(glob.glob(dataset+'/'+cl+'/*'))\n j=random.randint(0,len(images)-1)\n shutil.move(images[j],dataset+'/train/'+cl)\n os.mkdir(dataset+'/valid/'+cl)\n images=sorted(glob.glob(dataset+'/'+cl+'/*'))\n for i in range(len(images)):\n shutil.move(images[i],dataset+'/valid/'+cl)\n\ndef learn_with_model(dataset,model):\n data=ImageDataBunch.from_folder(dataset,\n ds_tfms=get_transforms(), size=224,bs=32).normalize(imagenet_stats)\n learn = cnn_learner(data, model, metrics=accuracy)\n learn.fit_one_cycle(2)\n learn.unfreeze()\n learn.lr_find()\n lr=learn.recorder.lrs[np.argmin(learn.recorder.losses)]\n if lr<1e-05:\n lr=1e-03\n learn.fit_one_cycle(8,max_lr=slice(lr/100,lr))\n return learn,data\n\ndef moda(lista):\n tam=len(lista[0][2])\n x=np.zeros(tam)\n for l in lista:\n x=x+l[2].numpy()\n x=x/len(lista)\n maximo=x.argmax()\n return maximo, x[maximo]\n\ndef omniData(dataset,learn,th):\n images=sorted(glob.glob(dataset+\"/images/*\"))\n\n for image in images:\n im=cv2.imread(image,1)\n im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)\n lista=[]\n n=Image(pil2tensor(im, dtype=np.float32).div_(255))\n pn=learn.predict(n)\n lista.append(pn)\n h_im=cv2.flip(im,0)\n h=Image(pil2tensor(h_im, dtype=np.float32).div_(255))\n ph=learn.predict(h)\n lista.append(ph)\n v_im=cv2.flip(im,1)\n v=Image(pil2tensor(v_im, dtype=np.float32).div_(255))\n pv=learn.predict(v)\n lista.append(pv)\n b_im=cv2.flip(im,-1)\n b=Image(pil2tensor(b_im, dtype=np.float32).div_(255))\n pb=learn.predict(b)\n lista.append(pb)\n blur_im=cv2.blur(im,(5,5))\n blur=Image(pil2tensor(blur_im, dtype=np.float32).div_(255))\n pblur=learn.predict(blur)\n lista.append(pblur)\n invGamma=1.0\n table=np.array([((i/255.0)**invGamma)*255 for i in np.arange(0,256)]).astype('uint8')\n gamma_im=cv2.LUT(im,table)\n gamma=Image(pil2tensor(gamma_im, dtype=np.float32).div_(255))\n pgamma=learn.predict(gamma)\n lista.append(pgamma)\n gblur_im=cv2.GaussianBlur(im,(5,5),cv2.BORDER_DEFAULT)\n gblur=Image(pil2tensor(gblur_im, dtype=np.float32).div_(255))\n pgblur=learn.predict(gblur)\n lista.append(pgblur)\n\n mod, predMax=moda(lista)\n if predMax>th:\n shutil.copyfile(image,dataset+'/train/'+data.classes[mod]+'/'+data.classes[mod]+'_'+image.split('/')[-1])\n os.remove(image)\n print(image+\" --> \"+dataset+'/train/'+data.classes[mod]+'/'+data.classes[mod]+'_'+image.split('/')[-1])\n\nlearner_resnet50,data=learn_with_model(dataset,models.resnet50)\nshutil.copytree(dataset, 'dataset_resnet50')\nomniData('dataset_resnet50',learner_resnet50,0)\nlearnerDD_resnet50,data=learn_with_model('dataset_resnet50',models.resnet50)\nlearnerDD_resnet50.export('/content/drive/My Drive/learnerDD_resnet50.pkl')\n\nlearner_resnet34,data=learn_with_model(dataset,models.resnet34)\nshutil.copytree(dataset, 'dataset_resnet34')\nomniData('dataset_resnet34',learner_resnet34,0)\nlearnerDD_resnet34,data=learn_with_model('dataset_resnet34',models.resnet34)\nlearnerDD_resnet34.export('/content/drive/My Drive/learnerDD_resnet34.pkl')\n\nlearner_resnet101,data=learn_with_model(dataset,models.resnet101)\nshutil.copytree(dataset, 'dataset_resnet101')\nomniData('dataset_resnet101',learner_resnet101,0)\nlearnerDD_resnet101,data=learn_with_model('dataset_resnet101',models.resnet101)\nlearnerDD_resnet101.export('/content/drive/My Drive/learnerDD_resnet101.pkl')\n\n", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
4af9ae23fcd5ec045c929a67ced94fafa0b96e8b
216,784
ipynb
Jupyter Notebook
caffe/experiments/intermed-vis/150225_Yixuan_sandbox.ipynb
Evolving-AI-Lab/innovation-engine
58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba
[ "MIT" ]
31
2015-09-20T03:03:29.000Z
2022-01-25T06:50:20.000Z
caffe/experiments/intermed-vis/150225_Yixuan_sandbox.ipynb
Evolving-AI-Lab/innovation-engine
58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba
[ "MIT" ]
1
2016-08-11T07:24:50.000Z
2016-08-17T01:19:57.000Z
caffe/experiments/intermed-vis/150225_Yixuan_sandbox.ipynb
Evolving-AI-Lab/innovation-engine
58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba
[ "MIT" ]
10
2015-11-15T01:52:25.000Z
2018-06-11T23:42:58.000Z
416.892308
130,869
0.909089
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4af9aea1a0ec4d1d126904fa869d81e1f60c9eec
10,084
ipynb
Jupyter Notebook
nbs/00c_utils_blitz.ipynb
scribbler00/fastrenewables
f1a722b19376d0e3f26707aa4af6caf7ba8a8dfa
[ "Apache-2.0" ]
4
2021-11-04T13:04:59.000Z
2022-03-30T19:26:55.000Z
nbs/00c_utils_blitz.ipynb
scribbler00/fastrenewables
f1a722b19376d0e3f26707aa4af6caf7ba8a8dfa
[ "Apache-2.0" ]
null
null
null
nbs/00c_utils_blitz.ipynb
scribbler00/fastrenewables
f1a722b19376d0e3f26707aa4af6caf7ba8a8dfa
[ "Apache-2.0" ]
null
null
null
29.658824
145
0.540163
[ [ [ "# default_exp utils_blitz", "_____no_output_____" ] ], [ [ "# uitls_blitz\n\n> API details.", "_____no_output_____" ] ], [ [ "#export\n#hide\nfrom blitz.modules import BayesianLinear\nfrom blitz.modules import BayesianEmbedding, BayesianConv1d, BayesianConv2d, BayesianConv3d\nfrom blitz.modules.base_bayesian_module import BayesianModule\nfrom torch import nn\nimport torch\nfrom fastcore.basics import patch", "_____no_output_____" ], [ "@patch\ndef extra_repr(self: BayesianLinear):\n return f\"Shape: {list(self.weight_sampler.mu.shape)}\"\n\n@patch\ndef extra_repr(self: BayesianConv1d):\n return f\"in_channels={self.in_channels}, out_channels={self.out_channels}, kernelel_size={self.kernel_size}, stride={self.stride}\"\n\n@patch\ndef extra_repr(self: BayesianConv2d):\n return f\"in_channels={self.in_channels}, out_channels={self.out_channels}, kernelel_size={self.kernel_size}, stride={self.stride}\"\n\n@patch\ndef extra_repr(self: BayesianConv3d):\n return f\"in_channels={self.in_channels}, out_channels={self.out_channels}, kernelel_size={self.kernel_size}, stride={self.stride}\"\n", "_____no_output_____" ], [ "#export\ndef convert_layer_to_bayesian(layer, config: dict):\n if isinstance(layer, torch.nn.Linear):\n new_layer = BayesianLinear(\n layer.in_features,\n layer.out_features,\n prior_sigma_1=config[\"prior_sigma_1\"],\n prior_sigma_2=config[\"prior_sigma_2\"],\n prior_pi=config[\"prior_pi\"],\n posterior_mu_init=config[\"posterior_mu_init\"],\n posterior_rho_init=config[\"posterior_rho_init\"],\n )\n elif isinstance(layer, nn.Embedding):\n new_layer = BayesianEmbedding(\n layer.num_embeddings,\n layer.embedding_dim,\n prior_sigma_1=config[\"prior_sigma_1\"],\n prior_sigma_2=config[\"prior_sigma_2\"],\n prior_pi=config[\"prior_pi\"],\n posterior_mu_init=config[\"posterior_mu_init\"],\n posterior_rho_init=config[\"posterior_rho_init\"],\n )\n elif isinstance(layer, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):\n matching_class = BayesianConv1d\n kernel_size = layer.kernel_size[0]\n if type(layer) == nn.Conv2d:\n kernel_size = layer.kernel_size\n matching_class = BayesianConv2d\n elif type(layer) == nn.Conv3d:\n matching_class = BayesianConv3d\n kernel_size = layer.kernel_size\n new_layer = matching_class(\n layer.in_channels,\n layer.out_channels,\n kernel_size=kernel_size,\n groups=layer.groups,\n padding=layer.padding,\n dilation=layer.dilation,\n prior_sigma_1=config[\"prior_sigma_1\"],\n prior_sigma_2=config[\"prior_sigma_2\"],\n prior_pi=config[\"prior_pi\"],\n posterior_mu_init=config[\"posterior_mu_init\"],\n posterior_rho_init=config[\"posterior_rho_init\"],\n )\n else:\n Warning(\n f\"Could not find correct type for conversion of layer {layer} with type {type(layer)}\"\n )\n new_layer = layer\n\n return new_layer", "_____no_output_____" ], [ "config = {\"prior_sigma_1\":0.1,\n \"prior_sigma_2\":0.4,\n \"prior_pi\":1,\n \"posterior_mu_init\":0,\n \"posterior_rho_init\":-7}", "_____no_output_____" ], [ "convert_layer_to_bayesian(nn.Linear(10,2), config)", "_____no_output_____" ], [ "convert_layer_to_bayesian(nn.Embedding(10,2), config)", "_____no_output_____" ], [ "convert_layer_to_bayesian(nn.Conv1d(1,2,3), config)", "_____no_output_____" ], [ "convert_layer_to_bayesian(nn.Conv2d(1,2,(3,3)), config)", "_____no_output_____" ], [ "convert_layer_to_bayesian(nn.Conv2d(1,2,(3,3, 3)), config)", "_____no_output_____" ], [ "#export\ndef convert_to_bayesian_model(model, config: dict):\n for p in model.named_children():\n cur_layer_name = p[0]\n cur_layer = p[1]\n if len(list(cur_layer.named_children())) > 0:\n convert_to_bayesian_model(cur_layer, config)\n elif not isinstance(cur_layer, BayesianModule):\n new_layer = convert_layer_to_bayesian(cur_layer, config)\n setattr(model, cur_layer_name, new_layer)\n\n return model", "_____no_output_____" ], [ "convert_to_bayesian_model(nn.Sequential(nn.Linear(3,4), nn.Linear(4,1)), config)", "_____no_output_____" ], [ "#export\ndef set_train_mode(model, mode):\n if isinstance(model, BayesianModule):\n model.freeze = not mode\n\n for module in model.children():\n set_train_mode(module, mode)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af9b17d8dfd0790c1940a40527d4e7a4c70b4c5
100,390
ipynb
Jupyter Notebook
cs168/notebooks/mini_project_1.ipynb
garfieldnate/Stanford-CS-168_Modern_Algorithmic_Toolbox
96f1dcc65db160e6e6b21083dba02c9c478b284d
[ "Apache-2.0" ]
null
null
null
cs168/notebooks/mini_project_1.ipynb
garfieldnate/Stanford-CS-168_Modern_Algorithmic_Toolbox
96f1dcc65db160e6e6b21083dba02c9c478b284d
[ "Apache-2.0" ]
null
null
null
cs168/notebooks/mini_project_1.ipynb
garfieldnate/Stanford-CS-168_Modern_Algorithmic_Toolbox
96f1dcc65db160e6e6b21083dba02c9c478b284d
[ "Apache-2.0" ]
null
null
null
68.153428
36,648
0.787469
[ [ [ "###########\n# PRELUDE #\n###########\n\n# auto-reload changed python files\n%load_ext autoreload\n%autoreload 2\n\n# Format cells with %%black\n%load_ext blackcellmagic\n\n# nice interactive plots\n%matplotlib inline\n\n# add repository directory to include path\nfrom pathlib import Path\nimport sys\nPROJECT_DIR = Path('../..').resolve()\nsys.path.append(str(PROJECT_DIR))\n\nfrom IPython.display import display, Markdown\ndef markdown(s):\n return display(Markdown(s))\n\nmarkdown(\"Surround markdown cells with `<div class=\\\"alert alert-block alert-info\\\">\\\\n\\\\n ... \\\\n\\\\n</div>` to mark professor-provided assignment content\")", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n# Part 1: The Power of Two Choices\n\n</div>", "_____no_output_____" ] ], [ [ "from collections import Counter\nimport matplotlib.pyplot as plt\nfrom random import randrange, choice as randchoice\nfrom tqdm import trange", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n## Goal\n\nThe goal of this part of the assignment is to gain an appreciation for the unreasonable effectiveness of simple randomized load balancing, and measure the benefits of some lightweight optimizations.\n\n</div>", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n## Description\nWe consider random processes of the following type: there are N bins, and we throw N\nballs into them, one by one. \\[This is an abstraction of the sort of allocation problem that arises throughout computing—e.g. allocating tasks on servers, routing packets within parallel networks, etc..] We’ll compare four different strategies for choosing the bin in which to place a given ball.\n\n</div>", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n1. Select one of the N bins uniformly at random, and place the current ball in it.\n\n</div>", "_____no_output_____" ] ], [ [ "def choose_bin_1(N, bins):\n return randrange(N)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n2. Select two of the N bins uniformly at random (either with or without replacement), and look at how many balls are already in each. If one bin has strictly fewer balls than the other, place the current ball in that bin. If both bins have the same number of balls, pick one of the two at random and place the current ball in it.\n\n</div>", "_____no_output_____" ] ], [ [ "def choose_bin_2(N, bins):\n bin_1 = choose_bin_1(N, bins)\n bin_2 = choose_bin_1(N, bins)\n \n bin_1_size = bins[bin_1]\n bin_2_size = bins[bin_2]\n if bin_1_size == bin_2_size:\n return randchoice([bin_1, bin_2])\n\n elif bin_1_size < bin_2_size:\n return bin_1\n else:\n return bin_2", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n3. Same as the previous strategy, except choosing three bins at random rather than two.\n\n</div>", "_____no_output_____" ] ], [ [ "def choose_bin_3(N, bins):\n bin_1 = choose_bin_1(N, bins)\n bin_2 = choose_bin_1(N, bins)\n bin_3 = choose_bin_1(N, bins)\n\n bin_1_size = bins[bin_1]\n bin_2_size = bins[bin_2]\n bin_3_size = bins[bin_3]\n\n if bin_1_size == bin_2_size == bin_3_size:\n # TODO: is this really necessary? Can't we just pick bin_1?\n return randchoice([bin_1, bin_2, bin_3])\n\n min_size = bin_1_size\n min_bin = bin_1\n \n if bin_2_size < min_size:\n min_size = bin_2_size\n min_bin = bin_2\n \n if bin_3_size < min_size:\n min_bin = bin_3\n \n return min_bin", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n4. Select two bins as follows: the first bin is selected uniformly from the first N/2 bins, and the second uniformly from the last N/2 bins. (You can assume that N is even.) If one bin has strictly fewer balls than the other, place the current ball in that bin. If both bins have the same number of balls, place the current ball (deterministically) in the first of the two bins.\n\n</div>", "_____no_output_____" ] ], [ [ "def choose_bin_4(N, bins):\n halfN = N // 2\n bin_1 = choose_bin_1(halfN, bins)\n bin_2 = choose_bin_1(halfN, bins) + halfN\n \n bin_1_size = bins[bin_1]\n bin_2_size = bins[bin_2]\n if bin_1_size < bin_2_size:\n return bin_1\n elif bin_2_size < bin_1_size:\n return bin_2\n else:\n return bin_1\n # return randchoice([bin_1, bin_2])", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n(a) (5 points) Write code to simulate strategies 1–4. For each strategy, there should be a function that takes the number N of balls and bins as input, simulates a run of the corresponding random process, and outputs the number of balls in the most populated bin (denoted by X below). Before running your code, try to guess how the above schemes will compare to eachother.\n\n</div>", "_____no_output_____" ] ], [ [ "def ball_toss(N, bin_chooser):\n \"\"\"Place N balls into N bins, choosing the bin using the bin_chooser function.\n Return the maximum number of balls in any bin.\"\"\"\n bins = [0] * N\n max_size = 0\n \n for _ in range(N):\n landed_bin = bin_chooser(N, bins)\n bins[landed_bin] += 1\n \n if bins[landed_bin] > max_size:\n max_size = bins[landed_bin]\n return max_size\n\n# test each bin chooser function\nball_toss(10, choose_bin_1)\nball_toss(10, choose_bin_2)\nball_toss(10, choose_bin_3)\nball_toss(10, choose_bin_4)\n\"OK\"", "_____no_output_____" ] ], [ [ "### Hypothesis\n\nI think 1 should do the worst job of load balancing; the nature of randomness is such that some bins will happen to be hit many times. 2 should be better, 3 even better than that. I think 4 should be equivalent to 2, since, unless our random function is not very good, there should not be any structure in the array of bins, and thus it should not help to choose them specifically from the first and second half of the array.", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n(b) (10 points) Let N = 200, 000 and simulate each of the four strategies 30 times. For each strategy, plot the histogram of the 30 values of X. Discuss the pros and cons of the different strategies. Does one of them stand out as a “sweet spot”? \\[As with many of the mini-projects, there is no single “right answer” to this question. Instead, the idea is to have you think about the processes and your experiments, and draw reasonable conclusions from this analysis.]\n\n</div>", "_____no_output_____" ] ], [ [ "def simulate(bin_chooser):\n max_values = []\n N = 200_000\n for _ in trange(100):\n max_values.append(ball_toss(N, bin_chooser))\n return max_values", "_____no_output_____" ], [ "max_values_1 = simulate(choose_bin_1)", "100%|██████████| 100/100 [00:21<00:00, 4.59it/s]\n" ], [ "max_values_2 = simulate(choose_bin_2)", "100%|██████████| 100/100 [00:52<00:00, 1.91it/s]\n" ], [ "max_values_3 = simulate(choose_bin_3)", "100%|██████████| 100/100 [01:08<00:00, 1.45it/s]\n" ], [ "max_values_4 = simulate(choose_bin_4)", "100%|██████████| 100/100 [00:46<00:00, 2.15it/s]\n" ], [ "data = [\n (\"Method 1\", max_values_1),\n (\"Method 2\", max_values_2), \n (\"Method 3\", max_values_3), \n (\"Method 4\", max_values_4)]\n\n# output raw data, since it's hard to see in the histogram plots\nmarkdown(\"### Number of occurrences of maximum bin values\")\nfor d in data:\n markdown(f'#### {d[0]}')\n sorted_occurences = sorted(Counter(d[1]).items())\n print(', '.join(f'{key}: {val}' for key, val in sorted_occurences))\n # print(sorted(Counter(d[1]).items()))\n\n# fig, axes = plt.subplots(1, 4, sharex=True, sharey=True, figsize=(10,3))\nfig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(6,5))\nfor ax, d in zip(axes.flatten(), data):\n ax.hist(d[1], bins=range(2,12), rwidth=.5, align='left')\n ax.set_title(d[0])\nfig.subplots_adjust(hspace=2.0, wspace=1.0)\nfig.suptitle(\"Simulated Performance of Bin-Choosing Functions\")\nfig.supxlabel(\"Maximum Bin Value\", size=14)\nfig.supylabel(\"Simulated Frequency\")\nfig.tight_layout()", "_____no_output_____" ] ], [ [ "### Analysis\n\nLooks like we can rank the performance as follows: 3 > 4 > 2 > 1; 4 perform only slightly worse than 3. I did not expect 4 to perform better than 2, but in retrospect it makes sense: random numbers tend to cluster, and could even be the same twice in a row! Method 4 guarantees that the 2 choices of bin are not the same, and probably also aleves the clustering issue more generally. The run time of 4 was better than 2 and 3, too, since the implementation was also simpler, so it does stand out as a possible sweet spot, assuming that over time the runtime improvement over method 1 outweighs the loss caused by a more complex algorithm.\n\nI do have an open question regarding the resolution of ties. Methods 2 and 3 resolve ties via random choice; I tried deterministically choosing the first bin in method 2, but there was no change in final outcome (suggesting this is probably fine to do for time optimization). However, I also tried changing method 4 to use a random choice instead of always picking the first bin, and the final outcomes worsened, matching method 2 almost perfectly. Why would this be?", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n(c) (5 points) Propose an analogy between the first of the random processes above and the standard implementation of hashing N elements into a hash table with N buckets, and resolving collisions via chaining (i.e., one linked list per bucket). Discuss in particular any relationships between X and search times in the hash table.\n\n</div>", "_____no_output_____" ], [ "The hypothetical hash table performance can be compared to strategy 1 above: a pseudo-random hash function picks the bucket to put a value in, just as the function placed balls in random bins. The maximum number of balls in a bin is analogous to the number of values placed in a single bucket (in Java these are all placed in `TreeMap` when possible, otherwise a `LinkedList`). The maximum numbers in the ball-tossing simulation indicate the maximum number of iterate-and-compare steps required to find a value in the hash table.", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n(d) (5 points) Do the other random processes suggest alternative implementations of hash tables with chaining? Discuss the trade-offs between the different hash table implementations that you propose (e.g., in terms of insertion time vs. search time).\n\n</div>", "_____no_output_____" ], [ "One could use multiple hash functions to place a value into one of multiple buckets, choosing the bucket with the fewest entries. Then the query method would search through all of the relevant buckets. The total number of iterations should still be the same on average, but the worst case performance should occur less often because we will do a better job of distributing the values. It's possible that the CPU cache behavior would be a worse, since we would access more disparate memory locations more often. Not sure about that, though.", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n# Part 2: Conservative Updates in a Count-Min Sketch\n\n</div>", "_____no_output_____" ] ], [ [ "from hashlib import md5\nfrom random import shuffle\nfrom statistics import mean\n", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n## Goal\nThe goal of this part is to understand the count-min sketch (from Lecture #2) via an implementation, and to explore the benefits of a “conservative updates” optimization.\n\n</div>", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n## Description\n\nYou’ll use a count-min sketch with 4 independent hash tables, each with 256 counters. You\nwill run 10 independent trials. This lets you measure not only the accuracy of the sketch, but the distribution of the accuracy over multiple datasets with the same frequency distribution. Your sketch should take a “trial” as input, and the hash value of an element x during trial i (i = 1, 2, . . . , 10) for table j (j = 1, 2, 3, 4) is calculated as follows:\n\n* Consider the input x as a string, and append i − 1 as a string to the end of the string.\n* Calculate the MD5 score of the resulting string. Do not implement the MD5 algorithm yourself; most modern programming languages have packages that calculate MD5 scores for you. For example, in Python 3, you can use the hashlib library and `hashlib.md5(foo.encode('utf-8')).hexdigest()` to compute the MD5 score of the string foo (returning a hexadecimal string).\n* The hash value is the j-th byte of the score.\n\nAs an example, to compute the hash value of 100 in the 4th table of the 9th trial, we calculate the MD5 score of the string \"1008\", which is (in hexadecimal):\n\n 15 87 96 5f b4 d4 b5 af e8 42 8a 4a 02 4f eb 0d\n\nThe 4th byte is 5f in hexadecimal, which is 95 in decimal. In Python, you can parse the hexadecimal string 5f with `int(\"5f\", 16)`.\n\n(a) (5 points) Implement the count-min sketch, as above.\n\n</div>", "_____no_output_____" ] ], [ [ "# returns an array of hash values to use for assignng buckets in the count-min hash sketch\ndef count_min_hashes(x, trial):\n return md5(f\"{x}{trial - 1}\".encode())\n\nassert count_min_hashes(100, 9).hexdigest() == \"1587965fb4d4b5afe8428a4a024feb0d\"\n\"OK\"", "_____no_output_____" ], [ "# Note: assignment says to use digest indices j=1..4, but it was easier to work with 0..3\nclass CountMinSketch:\n def __init__(self, trial: int, conservative: bool=False):\n \"\"\"Create a new count min sketch. \n - trial: used to seed the hash function for experiments in this notebook\n - conservative: use conservative update optimization\"\"\"\n self.table = [[0] * 256 for i in range(4)]\n self.trial = trial\n self.conservative = conservative\n self.total = 0\n \n def increment(self, x):\n self.total += 1\n \n digest = count_min_hashes(x, self.trial).digest()\n if self.conservative:\n min_val = min(\n self.table[0][digest[0]],\n self.table[1][digest[1]],\n self.table[2][digest[2]],\n self.table[3][digest[3]]\n )\n for index, table in enumerate(self.table):\n if table[digest[index]] == min_val:\n table[digest[index]] += 1\n else:\n self.table[0][digest[0]] += 1\n self.table[1][digest[1]] += 1\n self.table[2][digest[2]] += 1\n self.table[3][digest[3]] += 1\n\n def count(self, x):\n digest = count_min_hashes(x, self.trial).digest()\n return min([\n self.table[0][digest[0]], \n self.table[1][digest[1]], \n self.table[2][digest[2]], \n self.table[3][digest[3]]])", "_____no_output_____" ], [ "def run_trials(stream, conservative=False):\n sketches = []\n for trial in range(1, 11):\n sketch = CountMinSketch(trial, conservative)\n for el in stream:\n sketch.increment(el)\n sketches.append(sketch)\n return sketches", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\nYou will be feeding data streams (i.e., sequences of elements) into count-min sketches. Every element of each stream is an integer between 1 and 9050 (inclusive). The frequencies are given by:\n* Integers $1000 \\times (i − 1) + 1$ to $1000 \\times i$, for $1 ≤ i ≤ 9$, appear i times in the stream. That is, the integers 1 to 1000 appear once in the stream; 1001 to 2000 appear twice; and so on.\n* An integer $9000 + i$, for $1 ≤ i ≤ 50$, appears $i^2$ times in the stream. For example, the integer 9050 appears 2500 times.\n\n(Each time an integer appears in the stream, it has a count of 1 associated with it.)", "_____no_output_____" ] ], [ [ "def create_stream():\n stream = []\n for i in range(1, 10):\n sub_stream = range(1000 * (i-1) + 1, 1000 * i + 1)\n for j in range(i):\n stream.extend(sub_stream)\n for i in range(1, 51):\n stream.extend([9000 + i] * (i**2))\n return stream", "_____no_output_____" ], [ "# Confirming distribution of values in created stream\nstream = create_stream()\n\nfig, ax1 = plt.subplots()\nax1.hist(create_stream(), rwidth=.5)\nax1.set_ylabel(\"Occurrences\")\nax1.set_xlabel(\"Element Values\")\nNone", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n(b) (2 points) Call an integer a heavy hitter if the number of times it appears is at least 1% of the total number of stream elements. How many heavy hitters are there in a stream with the above frequencies?\n\n</div>", "_____no_output_____" ] ], [ [ "def heavy_hitters(stream):\n total = len(stream)\n freqs = Counter(stream)\n threshold = total / 100\n heavies = []\n for (k, v) in freqs.items():\n if v >= threshold:\n heavies.append(k)\n return heavies\n\nhh = heavy_hitters(create_stream())\nprint(f\"The heavy hitters are the values {hh[0]} through {hh[-1]}\")", "The heavy hitters are the values 9030 through 9050\n" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\nNext, you will consider 3 different data streams, each corresponding to the elements above in a different order.\n\n1. Forward: the elements appear in non-decreasing order.\n2. Reverse: the elements appear in non-increasing order.\n3. Random: the elements appear in a random order.\n\n</div>", "_____no_output_____" ] ], [ [ "def forward_stream():\n stream = create_stream()\n return sorted(stream)\n\ndef reverse_stream():\n stream = create_stream()\n return sorted(stream, reverse=True)\n\ndef random_stream():\n stream = create_stream()\n shuffle(stream)\n return stream\n\nassert forward_stream()[:10] == list(range(1, 11))\nassert reverse_stream()[:10] == [9050] * 10\n# too difficult to check this automatically\nprint('Confirm that this stream looks shuffled:')\nprint(random_stream()[:10])", "Confirm that this stream looks shuffled:\n[9025, 9037, 2521, 7505, 2396, 9030, 4836, 9049, 6376, 6988]\n" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n(c) (6 points) For each of the three data streams, feed it into a count-min sketch (i.e., successively insert its elements), and compute the values of the following quantities, averaged over the 10 trials, for each order of the stream:\n\n* The sketch’s estimate for the frequency of element 9050.\n* The sketch’s estimate for the number of heavy hitters (elements with estimated frequency at least 1% of the stream length).\n\nRecord the mean estimate for each of the three orders. Does the order of the stream affect the estimated counts? Explain your answer.\n\n</div>", "_____no_output_____" ] ], [ [ "forward_stream_sketches = run_trials(forward_stream())\nreverse_stream_sketches = run_trials(reverse_stream())\nrandom_stream_sketches = run_trials(random_stream())", "_____no_output_____" ] ], [ [ "The order of the stream passed into a count-min sketch does not matter at all; count-min sketches only store frequencies, completely ignoring ordering of any kind. Therefore, the accumulated data will be exactly the same, and thus the estimated counts will also be exactly the same. Verification below:", "_____no_output_____" ] ], [ [ "for forward_sketch, reverse_sketch, random_sketch in zip(\n forward_stream_sketches, reverse_stream_sketches, random_stream_sketches\n):\n assert forward_sketch.table == reverse_sketch.table == random_sketch.table\n markdown(f\"* Trial {forward_sketch.trial} sketches are identical\")\nprint(\"Sketches for all trials are identical\")", "_____no_output_____" ] ], [ [ "Therefore, we don't need to report separate numbers for each data stream.", "_____no_output_____" ] ], [ [ "def sketch_statistics(sketches):\n threshold = forward_stream_sketches[0].total / 100\n heavy_hitter_count = []\n for sketch in sketches:\n count = 0\n for i in range(1,9051):\n if sketch.count(i) >= threshold:\n count += 1\n heavy_hitter_count.append(count)\n estimated_highest_count = mean([sketch.count(9050) for sketch in sketches])\n return heavy_hitter_count, mean(heavy_hitter_count), estimated_highest_count", "_____no_output_____" ], [ "heavy_hitter_count, avg_heavy_hitters, estimated_highest_count = sketch_statistics(forward_stream_sketches)\nmarkdown(f'* The average estimated count of element 9050 is {estimated_highest_count}')\nmarkdown(f'* The estimated number of heavy hitters in each trial were {heavy_hitter_count}')\nmarkdown(f'* The average estimate was {avg_heavy_hitters}')", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-info\">\n\n\n(d) (3 points) Implement the conservative updates optimization, as follows. When updating the counters during an insert, instead of incrementing all 4 counters, we only increment the subset of these 4 counters that have the lowest current count (if two or more of them are tied for the minimum current count, then we increment each of these).\n\n</div>", "_____no_output_____" ], [ "#### Implementation Notes\n\nThe `CountMinSketch` class above was refactored to take a `conservative` flag in the constructor which turns on this optimization. The implementation was straightforward, but one structural difference I needed to account for was that it was no longer possible to get the total number of elements aded to the sketch using `sum(sketch.table[0])` as before; since not all of the tables are updated on each `increment` call, the tables can no longer answer the question \"how many items have we seen\"? This was easy to make up for with a separate `total` field.", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n(e) (3 points) Explain why, even with conservative updates, the count-min sketch never underestimates the count of a value.\n\n</div>", "_____no_output_____" ], [ "The minimum value of the four tables constitutes a count-min sketch's best guess of the frequency of an element. Even with the conservative optimization, we always update this minimum value for each element encountered, so it is still equal to or greater than the actual number of occurrences of an element. Note also that it's important that we update all tables when there's a tie for the minimum value, since skipping the update for any of them would cause the sketch to underestimate the frequency of an item.", "_____no_output_____" ], [ "<div class=\"alert alert-block alert-info\">\n\n(f) (6 points) Repeat part (c) with conservative updates.\n\n</div>", "_____no_output_____" ] ], [ [ "forward_stream_sketches_2 = run_trials(forward_stream(), True)\nreverse_stream_sketches_2 = run_trials(reverse_stream(), True)\nrandom_stream_sketches_2 = run_trials(random_stream(), True)", "_____no_output_____" ] ], [ [ "As shown below, when using the conservative update optimization the order of inputs *does* change the final state of the count-min sketches:", "_____no_output_____" ] ], [ [ "all_identical = True\nfor forward_sketch, reverse_sketch, random_sketch in zip(\n forward_stream_sketches_2, reverse_stream_sketches_2, random_stream_sketches_2\n):\n all_identical = all_identical and (\n forward_sketch.table == reverse_sketch.table == random_sketch.table\n )\n if all_identical:\n markdown(f\"* Trial {forward_sketch.trial} sketches are identical\")\n else:\n markdown(f\"* Trail {forward_sketch.trial} sketches are not identical; breaking now\")\n break\nif all_identical:\n print(\"Through some miracle (or more likely a bug), sketches for all trials are identical\")\nelse:\n print(\"The sketches are not all identical (the expected outcome)\")", "_____no_output_____" ], [ "data = [\n (\"sorted stream\", forward_stream_sketches_2), \n (\"reverse sorted stream\", reverse_stream_sketches_2), \n (\"shuffled stream\", random_stream_sketches_2)]\n\nfor name, stream in data:\n heavy_hitter_count, avg_heavy_hitters, estimated_highest_count = sketch_statistics(stream)\n markdown(f'#### Results for {name}')\n markdown(f'* The average estimated count of element 9050 is {estimated_highest_count}')\n markdown(f'* The estimated number of heavy hitters in each trial were \\\\{heavy_hitter_count}')\n markdown(f'* The average estimate was {avg_heavy_hitters}')", "_____no_output_____" ] ], [ [ "The conservative update optimization improved the count estimations for all stream types. Performance was worse with the forward-sorted stream than for the other two sorts, but it was still better than the estimation without the optimization.", "_____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", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4af9b5028ab2d6e6f8c0ba56911c90fc44a6cd72
431,038
ipynb
Jupyter Notebook
data analysis/Buldyrev_vs_RGG/.ipynb_checkpoints/Ploting Graph_finding intra thres-checkpoint.ipynb
junohpark221/BSc_individual_project
44f49d3cbb93298880f046551056185b72324d17
[ "MIT" ]
1
2021-07-04T15:38:52.000Z
2021-07-04T15:38:52.000Z
data analysis/Buldyrev_vs_RGG/.ipynb_checkpoints/Ploting Graph_finding intra thres-checkpoint.ipynb
junohpark221/BSc_individual_project
44f49d3cbb93298880f046551056185b72324d17
[ "MIT" ]
null
null
null
data analysis/Buldyrev_vs_RGG/.ipynb_checkpoints/Ploting Graph_finding intra thres-checkpoint.ipynb
junohpark221/BSc_individual_project
44f49d3cbb93298880f046551056185b72324d17
[ "MIT" ]
null
null
null
178.705638
34,208
0.859669
[ [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport statistics", "_____no_output_____" ], [ "rep5_04_002_data = pd.read_csv('proc_rep5_04_002.csv')\n\ndel rep5_04_002_data['Unnamed: 0']", "_____no_output_____" ], [ "rep5_04_002_data", "_____no_output_____" ], [ "rgg_rgg_data = rep5_04_002_data.copy()\nrgg_rand_data = rep5_04_002_data.copy()\nrand_rgg_data = rep5_04_002_data.copy()\nrand_rand_data = rep5_04_002_data.copy()\n\nrgg_rgg_drop_list = []\nrgg_rand_drop_list = []\nrand_rgg_drop_list = []\nrand_rand_drop_list = []\n\nfor i in range(400):\n if i % 4 == 0:\n rgg_rand_drop_list.append(i)\n rand_rgg_drop_list.append(i)\n rand_rand_drop_list.append(i)\n elif i % 4 == 1:\n rgg_rgg_drop_list.append(i)\n rand_rgg_drop_list.append(i)\n rand_rand_drop_list.append(i)\n elif i % 4 == 2:\n rgg_rgg_drop_list.append(i)\n rgg_rand_drop_list.append(i)\n rand_rand_drop_list.append(i)\n elif i % 4 == 3:\n rgg_rgg_drop_list.append(i)\n rgg_rand_drop_list.append(i)\n rand_rgg_drop_list.append(i) \n\nrgg_rgg_data = rgg_rgg_data.drop(rgg_rgg_drop_list)\nrgg_rand_data = rgg_rand_data.drop(rgg_rand_drop_list)\nrand_rgg_data = rand_rgg_data.drop(rand_rgg_drop_list)\nrand_rand_data = rand_rand_data.drop(rand_rand_drop_list)\n\nrgg_rgg_data = rgg_rgg_data.reset_index(drop=True)\nrgg_rand_data = rgg_rand_data.reset_index(drop=True)\nrand_rgg_data = rand_rgg_data.reset_index(drop=True)\nrand_rand_data = rand_rand_data.reset_index(drop=True)", "_____no_output_____" ], [ "rgg_rgg_data", "_____no_output_____" ], [ "rgg_rgg_for_rand_data", "_____no_output_____" ], [ "rgg_rgg_dict = {}\nrgg_rand_dict = {}\nrand_rgg_dict = {}\nrand_rand_dict = {}\n\nfor i in range(49):\n target = [i*5 + 0, i*5 + 1, i*5 + 2, i*5 + 3, i*5 + 4]\n \n temp_rgg_rgg = rgg_rgg_data[i*5 + 0 : i*5 + 5]\n temp_rgg_rand = rgg_rand_data[i*5 + 0 : i*5 + 5]\n temp_rand_rgg = rand_rgg_data[i*5 + 0 : i*5 + 5]\n temp_rand_rand = rand_rand_data[i*5 + 0 : i*5 + 5]\n \n if i == 0:\n rgg_rgg_dict['intra_thres'] = [statistics.mean(temp_rgg_rgg['intra_thres'].values.tolist())]\n rgg_rgg_dict['alive_nodes'] = [statistics.mean(temp_rgg_rgg['alive_nodes'].values.tolist())]\n \n rgg_rand_dict['intra_thres'] = [statistics.mean(temp_rgg_rand['intra_thres'].values.tolist())]\n rgg_rand_dict['alive_nodes'] = [statistics.mean(temp_rgg_rand['alive_nodes'].values.tolist())]\n \n rand_rgg_dict['intra_thres'] = [statistics.mean(temp_rand_rgg['intra_thres'].values.tolist())]\n rand_rgg_dict['alive_nodes'] = [statistics.mean(temp_rand_rgg['alive_nodes'].values.tolist())]\n \n rand_rand_dict['intra_thres'] = [statistics.mean(temp_rand_rand['intra_thres'].values.tolist())]\n rand_rand_dict['alive_nodes'] = [statistics.mean(temp_rand_rand['alive_nodes'].values.tolist())]\n else:\n rgg_rgg_dict['intra_thres'].append(statistics.mean(temp_rgg_rgg['intra_thres'].values.tolist()))\n rgg_rgg_dict['alive_nodes'].append(statistics.mean(temp_rgg_rgg['alive_nodes'].values.tolist()))\n \n rgg_rand_dict['intra_thres'].append(statistics.mean(temp_rgg_rand['intra_thres'].values.tolist()))\n rgg_rand_dict['alive_nodes'].append(statistics.mean(temp_rgg_rand['alive_nodes'].values.tolist()))\n \n rand_rgg_dict['intra_thres'].append(statistics.mean(temp_rand_rgg['intra_thres'].values.tolist()))\n rand_rgg_dict['alive_nodes'].append(statistics.mean(temp_rand_rgg['alive_nodes'].values.tolist()))\n \n rand_rand_dict['intra_thres'].append(statistics.mean(temp_rand_rand['intra_thres'].values.tolist()))\n rand_rand_dict['alive_nodes'].append(statistics.mean(temp_rand_rand['alive_nodes'].values.tolist()))", "_____no_output_____" ], [ "rgg_rgg_for_rand_dict = {}\nrgg_rand_for_rand_dict = {}\nrand_rgg_for_rand_dict = {}\nrand_rand_for_rand_dict = {}\n\nfor i in range(21):\n target = [i*5 + 0, i*5 + 1, i*5 + 2, i*5 + 3, i*5 + 4]\n \n temp_rgg_rgg = rgg_rgg_for_rand_data[i*5 + 0 : i*5 + 5]\n temp_rgg_rand = rgg_rand_for_rand_data[i*5 + 0 : i*5 + 5]\n temp_rand_rgg = rand_rgg_for_rand_data[i*5 + 0 : i*5 + 5]\n temp_rand_rand = rand_rand_for_rand_data[i*5 + 0 : i*5 + 5]\n \n if i == 0:\n rgg_rgg_for_rand_dict['intra_thres'] = [statistics.mean(temp_rgg_rgg['intra_thres'].values.tolist())]\n rgg_rgg_for_rand_dict['alive_nodes'] = [statistics.mean(temp_rgg_rgg['alive_nodes'].values.tolist())]\n \n rgg_rand_for_rand_dict['intra_thres'] = [statistics.mean(temp_rgg_rand['intra_thres'].values.tolist())]\n rgg_rand_for_rand_dict['alive_nodes'] = [statistics.mean(temp_rgg_rand['alive_nodes'].values.tolist())]\n \n rand_rgg_for_rand_dict['intra_thres'] = [statistics.mean(temp_rand_rgg['intra_thres'].values.tolist())]\n rand_rgg_for_rand_dict['alive_nodes'] = [statistics.mean(temp_rand_rgg['alive_nodes'].values.tolist())]\n \n rand_rand_for_rand_dict['intra_thres'] = [statistics.mean(temp_rand_rand['intra_thres'].values.tolist())]\n rand_rand_for_rand_dict['alive_nodes'] = [statistics.mean(temp_rand_rand['alive_nodes'].values.tolist())]\n else:\n rgg_rgg_for_rand_dict['intra_thres'].append(statistics.mean(temp_rgg_rgg['intra_thres'].values.tolist()))\n rgg_rgg_for_rand_dict['alive_nodes'].append(statistics.mean(temp_rgg_rgg['alive_nodes'].values.tolist()))\n \n rgg_rand_for_rand_dict['intra_thres'].append(statistics.mean(temp_rgg_rand['intra_thres'].values.tolist()))\n rgg_rand_for_rand_dict['alive_nodes'].append(statistics.mean(temp_rgg_rand['alive_nodes'].values.tolist()))\n \n rand_rgg_for_rand_dict['intra_thres'].append(statistics.mean(temp_rand_rgg['intra_thres'].values.tolist()))\n rand_rgg_for_rand_dict['alive_nodes'].append(statistics.mean(temp_rand_rgg['alive_nodes'].values.tolist()))\n \n rand_rand_for_rand_dict['intra_thres'].append(statistics.mean(temp_rand_rand['intra_thres'].values.tolist()))\n rand_rand_for_rand_dict['alive_nodes'].append(statistics.mean(temp_rand_rand['alive_nodes'].values.tolist()))", "_____no_output_____" ], [ "plt.plot(rgg_rgg_dict['intra_thres'], rgg_rgg_dict['alive_nodes'])\nplt.plot(rgg_rgg_dict['intra_thres'], rgg_rand_dict['alive_nodes'])\nplt.plot(rgg_rgg_dict['intra_thres'], rand_rgg_dict['alive_nodes'])\nplt.plot(rgg_rgg_dict['intra_thres'], rand_rand_dict['alive_nodes'])\nplt.legend(['RGG-RGG', 'RGG-Rand', 'Rand-RGG', 'Rand-Rand'])\nplt.title('Mean Alive nodes')\nplt.show()", "_____no_output_____" ], [ "plt.plot(rgg_rgg_for_rand_dict['intra_thres'], rgg_rgg_for_rand_dict['alive_nodes'])\nplt.plot(rgg_rgg_for_rand_dict['intra_thres'], rgg_rand_for_rand_dict['alive_nodes'])\nplt.plot(rgg_rgg_for_rand_dict['intra_thres'], rand_rgg_for_rand_dict['alive_nodes'])\nplt.plot(rgg_rgg_for_rand_dict['intra_thres'], rand_rand_for_rand_dict['alive_nodes'])\nplt.legend(['RGG-RGG', 'RGG-Rand', 'Rand-RGG', 'Rand-Rand'])\nplt.title('Mean Alive nodes')\nplt.show()", "_____no_output_____" ], [ "step_nums = []\nstep_nums.append(statistics.mean(rgg_rgg_data['cas_steps'].values.tolist()))\nstep_nums.append(statistics.mean(rgg_rand_data['cas_steps'].values.tolist()))\nstep_nums.append(statistics.mean(rand_rgg_data['cas_steps'].values.tolist()))\nstep_nums.append(statistics.mean(rand_rand_data['cas_steps'].values.tolist()))\n\nindex = np.arange(4)\ngraph_types = ['RGG-RGG', 'RGG-Rand', 'Rand-RGG', 'Rand-Rand']\n\nplt.bar(index, step_nums, width=0.3, color='gray')\nplt.xticks(index, graph_types)\nplt.title('Number of steps')\nplt.savefig('The number of steps.png')\nplt.show()", "_____no_output_____" ], [ "rgg_rgg_isol = []\nrgg_rgg_unsupp = []\nrgg_rand_isol = []\nrgg_rand_unsupp = []\nrand_rgg_isol = []\nrand_rgg_unsupp = []\nrand_rand_isol = []\nrand_rand_unsupp =[]", "_____no_output_____" ], [ "index = 1\nfor col_name in rgg_rgg_data:\n if col_name == ('step%d_isol' % index):\n rgg_rgg_isol.append(statistics.mean(rgg_rgg_data[col_name].values.tolist()))\n if col_name == ('step%d_unsupp' % index):\n rgg_rgg_unsupp.append(statistics.mean(rgg_rgg_data[col_name].values.tolist()))\n index += 1\n \nindex = 1\nfor col_name in rgg_rand_data:\n if col_name == ('step%d_isol' % index):\n rgg_rand_isol.append(statistics.mean(rgg_rand_data[col_name].values.tolist()))\n if col_name == ('step%d_unsupp' % index):\n rgg_rand_unsupp.append(statistics.mean(rgg_rand_data[col_name].values.tolist()))\n index += 1\n \nindex = 1\nfor col_name in rand_rgg_data:\n if col_name == ('step%d_isol' % index):\n rand_rgg_isol.append(statistics.mean(rand_rgg_data[col_name].values.tolist()))\n if col_name == ('step%d_unsupp' % index):\n rand_rgg_unsupp.append(statistics.mean(rand_rgg_data[col_name].values.tolist()))\n index += 1\n \nindex = 1\nfor col_name in rand_rand_data:\n if col_name == ('step%d_isol' % index):\n rand_rand_isol.append(statistics.mean(rand_rand_data[col_name].values.tolist()))\n if col_name == ('step%d_unsupp' % index):\n rand_rand_unsupp.append(statistics.mean(rand_rand_data[col_name].values.tolist()))\n index += 1", "_____no_output_____" ], [ "print(len(rgg_rgg_isol))\nprint(len(rgg_rgg_unsupp))\nprint(len(rgg_rand_isol))\nprint(len(rgg_rand_unsupp))\nprint(len(rand_rgg_isol))\nprint(len(rand_rgg_unsupp))\nprint(len(rand_rand_isol))\nprint(len(rand_rand_unsupp))", "62\n62\n14\n14\n65\n65\n27\n27\n" ], [ "cum_rgg_rgg_isol = []\ncum_rgg_rgg_unsupp = []\ncum_rgg_rand_isol = []\ncum_rgg_rand_unsupp = []\ncum_rand_rgg_isol = []\ncum_rand_rgg_unsupp = []\ncum_rand_rand_isol = []\ncum_rand_rand_unsupp = []\n\ntotal = []\nfor i in range(len(rgg_rgg_isol)):\n if i == 0:\n total.append(rgg_rgg_isol[i])\n total.append(rgg_rgg_unsupp[i])\n else:\n total[0] += rgg_rgg_isol[i]\n total[1] += rgg_rgg_unsupp[i]\n cum_rgg_rgg_isol.append(total[0])\n cum_rgg_rgg_unsupp.append(total[1])\n \ntotal = []\nfor i in range(len(rgg_rand_isol)):\n if i == 0:\n total.append(rgg_rand_isol[i])\n total.append(rgg_rand_unsupp[i])\n else:\n total[0] += rgg_rand_isol[i]\n total[1] += rgg_rand_unsupp[i]\n cum_rgg_rand_isol.append(total[0])\n cum_rgg_rand_unsupp.append(total[1])\n \ntotal = []\nfor i in range(len(rand_rgg_isol)):\n if i == 0:\n total.append(rand_rgg_isol[i])\n total.append(rand_rgg_unsupp[i])\n else:\n total[0] += rand_rgg_isol[i]\n total[1] += rand_rgg_unsupp[i]\n cum_rand_rgg_isol.append(total[0])\n cum_rand_rgg_unsupp.append(total[1])\n \ntotal = []\nfor i in range(len(rand_rand_isol)):\n if i == 0:\n total.append(rand_rand_isol[i])\n total.append(rand_rand_unsupp[i])\n else:\n total[0] += rand_rand_isol[i]\n total[1] += rand_rand_unsupp[i]\n cum_rand_rand_isol.append(total[0])\n cum_rand_rand_unsupp.append(total[1])", "_____no_output_____" ] ], [ [ "## Isolation vs Unsupport", "_____no_output_____" ] ], [ [ "plt.plot(range(len(cum_rgg_rgg_isol)), cum_rgg_rgg_isol)\nplt.plot(range(len(cum_rgg_rgg_isol)), cum_rgg_rgg_unsupp)\nplt.legend(['rgg_rgg_isol','rgg_rgg_unsupp'])\nplt.title('Isolation vs Unsupport: RGG-RGG')\nplt.savefig('Isolation vs Unsupport_RGG-RGG.png')\nplt.show()", "_____no_output_____" ], [ "plt.plot(range(len(cum_rgg_rand_isol)), cum_rgg_rand_isol)\nplt.plot(range(len(cum_rgg_rand_isol)), cum_rgg_rand_unsupp)\nplt.legend(['rgg_rand_isol','rgg_rand_unsupp'])\nplt.title('Isolation vs Unsupport: RGG-Rand')\nplt.savefig('Isolation vs Unsupport_RGG-Rand.png')\nplt.show()", "_____no_output_____" ], [ "plt.plot(range(len(cum_rand_rgg_isol)), cum_rand_rgg_isol)\nplt.plot(range(len(cum_rand_rgg_isol)), cum_rand_rgg_unsupp)\nplt.legend(['rand_rgg_isol','rand_rgg_unsupp'])\nplt.title('Isolation vs Unsupport: Rand-RGG')\nplt.savefig('Isolation vs Unsupport_Rand-RGG.png')\nplt.show()", "_____no_output_____" ], [ "plt.plot(range(len(cum_rand_rand_isol)), cum_rand_rand_isol)\nplt.plot(range(len(cum_rand_rand_isol)), cum_rand_rand_unsupp)\nplt.legend(['rand_rand_isol','rand_rand_unsupp'])\nplt.title('Isolation vs Unsupport: Rand-Rand')\nplt.savefig('Isolation vs Unsupport_Rand-Rand.png')\nplt.show()", "_____no_output_____" ], [ "df_len = []\n\ndf_len.append(list(rgg_rgg_isol))\ndf_len.append(list(rgg_rand_isol))\ndf_len.append(list(rand_rgg_isol))\ndf_len.append(list(rand_rand_isol))\n\nmax_df_len = max(df_len, key=len)\n\nx_val = list(range(len(max_df_len)))", "_____no_output_____" ], [ "proc_isol = []\nproc_unsupp = []\n\nproc_isol.append(cum_rgg_rgg_isol)\nproc_isol.append(cum_rgg_rand_isol)\nproc_isol.append(cum_rand_rgg_isol)\nproc_isol.append(cum_rand_rand_isol)\n\nproc_unsupp.append(cum_rgg_rgg_unsupp)\nproc_unsupp.append(cum_rgg_rand_unsupp)\nproc_unsupp.append(cum_rand_rgg_unsupp)\nproc_unsupp.append(cum_rand_rand_unsupp)\n\nfor x in x_val:\n if len(rgg_rgg_isol) <= x:\n proc_isol[0].append(cum_rgg_rgg_isol[len(rgg_rgg_isol) - 1])\n proc_unsupp[0].append(cum_rgg_rgg_unsupp[len(rgg_rgg_isol) - 1])\n if len(rgg_rand_isol) <= x:\n proc_isol[1].append(cum_rgg_rand_isol[len(rgg_rand_isol) - 1])\n proc_unsupp[1].append(cum_rgg_rand_unsupp[len(rgg_rand_isol) - 1])\n if len(rand_rgg_isol) <= x:\n proc_isol[2].append(cum_rand_rgg_isol[len(rand_rgg_isol) - 1])\n proc_unsupp[2].append(cum_rand_rgg_unsupp[len(rand_rgg_isol) - 1])\n if len(rand_rand_isol) <= x:\n proc_isol[3].append(cum_rand_rand_isol[len(rand_rand_isol) - 1])\n proc_unsupp[3].append(cum_rand_rand_unsupp[len(rand_rand_isol) - 1])", "_____no_output_____" ], [ "plt.plot(x_val, proc_isol[0])\nplt.plot(x_val, proc_isol[1])\nplt.plot(x_val, proc_isol[2])\nplt.plot(x_val, proc_isol[3])\nplt.legend(['rgg_rgg_isol','rgg_rand_isol', 'rand_rgg_isol', 'rand_rand_isol'])\nplt.title('Isolation trend')\nplt.show()", "_____no_output_____" ], [ "plt.plot(x_val, proc_unsupp[0])\nplt.plot(x_val, proc_unsupp[1])\nplt.plot(x_val, proc_unsupp[2])\nplt.plot(x_val, proc_unsupp[3])\nplt.legend(['rgg_rgg_unsupp','rgg_rand_unsupp', 'rand_rgg_unsupp', 'rand_rand_unsupp'])\nplt.title('Unsupport trend')\nplt.show()", "_____no_output_____" ] ], [ [ "## Pie Chart", "_____no_output_____" ] ], [ [ "init_death = 150\nlabels = ['Alive nodes', 'Initial death', 'Dead nodes from isolation', 'Dead nodes from unsupport']\n\nalive = []\nalive.append(statistics.mean(rgg_rgg_data['alive_nodes']))\nalive.append(statistics.mean(rgg_rand_data['alive_nodes']))\nalive.append(statistics.mean(rand_rgg_data['alive_nodes']))\nalive.append(statistics.mean(rand_rand_data['alive_nodes']))\n\ntot_isol = []\ntot_isol.append(statistics.mean(rgg_rgg_data['tot_isol_node']))\ntot_isol.append(statistics.mean(rgg_rand_data['tot_isol_node']))\ntot_isol.append(statistics.mean(rand_rgg_data['tot_isol_node']))\ntot_isol.append(statistics.mean(rand_rand_data['tot_isol_node']))\n\ntot_unsupp = []\ntot_unsupp.append(statistics.mean(rgg_rgg_data['tot_unsupp_node']))\ntot_unsupp.append(statistics.mean(rgg_rand_data['tot_unsupp_node']))\ntot_unsupp.append(statistics.mean(rand_rgg_data['tot_unsupp_node']))\ntot_unsupp.append(statistics.mean(rand_rand_data['tot_unsupp_node']))", "_____no_output_____" ], [ "deaths = [alive[0], init_death, tot_isol[0], tot_unsupp[0]]\n\nplt.pie(deaths, labels=labels, autopct='%.1f%%')\nplt.title('RGG-RGG death trend')\nplt.show()", "_____no_output_____" ], [ "deaths = [alive[1], init_death, tot_isol[1], tot_unsupp[1]]\n\nplt.pie(deaths, labels=labels, autopct='%.1f%%')\nplt.title('RGG-Rand death trend')\nplt.show()", "_____no_output_____" ], [ "deaths = [alive[2], init_death, tot_isol[2], tot_unsupp[2]]\n\nplt.pie(deaths, labels=labels, autopct='%.1f%%')\nplt.title('Rand-RGG death trend')\nplt.show()", "_____no_output_____" ], [ "deaths = [alive[3], init_death, tot_isol[3], tot_unsupp[3]]\n\nplt.pie(deaths, labels=labels, autopct='%.1f%%')\nplt.title('Rand-Rand death trend')\nplt.show()", "_____no_output_____" ] ], [ [ "## Compute the number of nodes", "_____no_output_____" ] ], [ [ "x_val = np.arange(4)\nlabels = ['initial', 'final']\n\nplt.bar(x_val, alive)\nplt.xticks(x_val, graph_types)\nplt.title('Alive nodes')\nplt.savefig('alive nodes.png')\nplt.show()", "_____no_output_____" ] ], [ [ "## Compare the number of edges", "_____no_output_____" ] ], [ [ "init_intra = []\ninit_intra.append(statistics.mean(rgg_rgg_data['init_intra_edge']))\ninit_intra.append(statistics.mean(rgg_rand_data['init_intra_edge']))\ninit_intra.append(statistics.mean(rand_rgg_data['init_intra_edge']))\ninit_intra.append(statistics.mean(rand_rand_data['init_intra_edge']))\n\ninit_inter = []\ninit_inter.append(statistics.mean(rgg_rgg_data['init_inter_edge']))\ninit_inter.append(statistics.mean(rgg_rand_data['init_inter_edge']))\ninit_inter.append(statistics.mean(rand_rgg_data['init_inter_edge']))\ninit_inter.append(statistics.mean(rand_rand_data['init_inter_edge']))\n\ninit_supp = []\ninit_supp.append(statistics.mean(rgg_rgg_data['init_supp_edge']))\ninit_supp.append(statistics.mean(rgg_rand_data['init_supp_edge']))\ninit_supp.append(statistics.mean(rand_rgg_data['init_supp_edge']))\ninit_supp.append(statistics.mean(rand_rand_data['init_supp_edge']))\n\nfin_intra = []\nfin_intra.append(statistics.mean(rgg_rgg_data['fin_intra_edge']))\nfin_intra.append(statistics.mean(rgg_rand_data['fin_intra_edge']))\nfin_intra.append(statistics.mean(rand_rgg_data['fin_intra_edge']))\nfin_intra.append(statistics.mean(rand_rand_data['fin_intra_edge']))\n\nfin_inter = []\nfin_inter.append(statistics.mean(rgg_rgg_data['fin_inter_edge']))\nfin_inter.append(statistics.mean(rgg_rand_data['fin_inter_edge']))\nfin_inter.append(statistics.mean(rand_rgg_data['fin_inter_edge']))\nfin_inter.append(statistics.mean(rand_rand_data['fin_inter_edge']))\n\nfin_supp = []\nfin_supp.append(statistics.mean(rgg_rgg_data['fin_supp_edge']))\nfin_supp.append(statistics.mean(rgg_rand_data['fin_supp_edge']))\nfin_supp.append(statistics.mean(rand_rgg_data['fin_supp_edge']))\nfin_supp.append(statistics.mean(rand_rand_data['fin_supp_edge']))", "_____no_output_____" ], [ "plt.bar(x_val-0.1, init_intra, width=0.2)\nplt.bar(x_val+0.1, fin_intra, width=0.2)\nplt.legend(labels)\nplt.xticks(x_val, graph_types)\nplt.title('Initial_intra_edge vs Final_intra_edge')\nplt.show()", "_____no_output_____" ], [ "plt.bar(x_val-0.1, init_inter, width=0.2)\nplt.bar(x_val+0.1, fin_inter, width=0.2)\nplt.legend(labels)\nplt.xticks(x_val, graph_types)\nplt.title('Initial_inter_edge vs Final_inter_edge')\nplt.show()", "_____no_output_____" ], [ "plt.bar(x_val-0.1, init_supp, width=0.2)\nplt.bar(x_val+0.1, fin_supp, width=0.2)\nplt.legend(labels)\nplt.xticks(x_val, graph_types)\nplt.title('Initial_support_edge vs Final_support_edge')\nplt.show()", "_____no_output_____" ] ], [ [ "## Network Analysis", "_____no_output_____" ] ], [ [ "init_far = []\ninit_far.append(statistics.mean(rgg_rgg_data['init_far_node']))\ninit_far.append(statistics.mean(rgg_rand_data['init_far_node']))\ninit_far.append(statistics.mean(rand_rgg_data['init_far_node']))\ninit_far.append(statistics.mean(rand_rand_data['init_far_node']))\n\nfin_far = []\nfin_far.append(statistics.mean(rgg_rgg_data['fin_far_node']))\nfin_far.append(statistics.mean(rgg_rand_data['fin_far_node']))\nfin_far.append(statistics.mean(rand_rgg_data['fin_far_node']))\nfin_far.append(statistics.mean(rand_rand_data['fin_far_node']))", "_____no_output_____" ], [ "plt.bar(x_val-0.1, init_far, width=0.2)\nplt.bar(x_val+0.1, fin_far, width=0.2)\nplt.legend(labels)\nplt.xticks(x_val, graph_types)\nplt.title('Initial_far_node vs Final_far_node')\nplt.show()", "_____no_output_____" ], [ "init_clust = []\ninit_clust.append(statistics.mean(rgg_rgg_data['init_clust']))\ninit_clust.append(statistics.mean(rgg_rand_data['init_clust']))\ninit_clust.append(statistics.mean(rand_rgg_data['init_clust']))\ninit_clust.append(statistics.mean(rand_rand_data['init_clust']))\n\nfin_clust = []\nfin_clust.append(statistics.mean(rgg_rgg_data['fin_clust']))\nfin_clust.append(statistics.mean(rgg_rand_data['fin_clust']))\nfin_clust.append(statistics.mean(rand_rgg_data['fin_clust']))\nfin_clust.append(statistics.mean(rand_rand_data['fin_clust']))", "_____no_output_____" ], [ "plt.bar(x_val-0.1, init_clust, width=0.2)\nplt.bar(x_val+0.1, fin_clust, width=0.2)\nplt.legend(labels)\nplt.xticks(x_val, graph_types)\nplt.title('Initial_clustering_coefficient vs Final_clustering_coefficient')\nplt.show()", "_____no_output_____" ], [ "init_mean_deg = []\ninit_mean_deg.append(statistics.mean(rgg_rgg_data['init_mean_deg']))\ninit_mean_deg.append(statistics.mean(rgg_rand_data['init_mean_deg']))\ninit_mean_deg.append(statistics.mean(rand_rgg_data['init_mean_deg']))\ninit_mean_deg.append(statistics.mean(rand_rand_data['init_mean_deg']))\n\nfin_mean_deg = []\nfin_mean_deg.append(statistics.mean(rgg_rgg_data['fin_mean_deg']))\nfin_mean_deg.append(statistics.mean(rgg_rand_data['fin_mean_deg']))\nfin_mean_deg.append(statistics.mean(rand_rgg_data['fin_mean_deg']))\nfin_mean_deg.append(statistics.mean(rand_rand_data['fin_mean_deg']))", "_____no_output_____" ], [ "plt.bar(x_val-0.1, init_mean_deg, width=0.2)\nplt.bar(x_val+0.1, fin_mean_deg, width=0.2)\nplt.legend(labels)\nplt.xticks(x_val, graph_types)\nplt.title('Initial_mean_degree vs Final_mean_degree')\nplt.show()", "_____no_output_____" ], [ "init_larg_comp = []\ninit_larg_comp.append(statistics.mean(rgg_rgg_data['init_larg_comp']))\ninit_larg_comp.append(statistics.mean(rgg_rand_data['init_larg_comp']))\ninit_larg_comp.append(statistics.mean(rand_rgg_data['init_larg_comp']))\ninit_larg_comp.append(statistics.mean(rand_rand_data['init_larg_comp']))\n\nfin_larg_comp = []\nfin_larg_comp.append(statistics.mean(rgg_rgg_data['fin_larg_comp']))\nfin_larg_comp.append(statistics.mean(rgg_rand_data['fin_larg_comp']))\nfin_larg_comp.append(statistics.mean(rand_rgg_data['fin_larg_comp']))\nfin_larg_comp.append(statistics.mean(rand_rand_data['fin_larg_comp']))", "_____no_output_____" ], [ "plt.bar(x_val-0.1, init_larg_comp, width=0.2)\nplt.bar(x_val+0.1, fin_larg_comp, width=0.2)\nplt.legend(labels)\nplt.xticks(x_val, graph_types)\nplt.title('Initial_largest_component_size vs Final_largest_component_size')\nplt.show()", "_____no_output_____" ], [ "deg_assort = []\n\na = rgg_rgg_data['deg_assort'].fillna(0)\nb = rgg_rand_data['deg_assort'].fillna(0)\nc = rand_rgg_data['deg_assort'].fillna(0)\nd = rand_rand_data['deg_assort'].fillna(0)\n\ndeg_assort.append(statistics.mean(a))\ndeg_assort.append(statistics.mean(b))\ndeg_assort.append(statistics.mean(c))\ndeg_assort.append(statistics.mean(d))", "_____no_output_____" ], [ "plt.bar(x_val, deg_assort)\nplt.xticks(x_val, graph_types)\nplt.title('Degree Assortativity')\nplt.show()", "_____no_output_____" ], [ "dist_deg_cent = []\ndist_deg_cent.append(statistics.mean(rgg_rgg_data['dist_deg_cent']))\ndist_deg_cent.append(statistics.mean(rgg_rand_data['dist_deg_cent']))\ndist_deg_cent.append(statistics.mean(rand_rgg_data['dist_deg_cent']))\ndist_deg_cent.append(statistics.mean(rand_rand_data['dist_deg_cent']))", "_____no_output_____" ], [ "plt.bar(x_val, dist_deg_cent)\nplt.xticks(x_val, graph_types)\nplt.title('Distance to degree centre from the attack point')\nplt.show()", "_____no_output_____" ], [ "dist_bet_cent = []\ndist_bet_cent.append(statistics.mean(rgg_rgg_data['dist_bet_cent']))\ndist_bet_cent.append(statistics.mean(rgg_rand_data['dist_bet_cent']))\ndist_bet_cent.append(statistics.mean(rand_rgg_data['dist_bet_cent']))\ndist_bet_cent.append(statistics.mean(rand_rand_data['dist_bet_cent']))", "_____no_output_____" ], [ "plt.bar(x_val, dist_bet_cent)\nplt.xticks(x_val, graph_types)\nplt.title('Distance to betweenes centre from the attack point')\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4af9c968beb73366653ea8bf07b97ba68dc0ec9d
160,673
ipynb
Jupyter Notebook
04_CNN_advances/cnn_mnist_simple.ipynb
jastarex/DL_Notes
4da8c5c90283d25655abde95263e44432aad343a
[ "Apache-2.0" ]
203
2017-11-19T08:45:03.000Z
2022-02-17T08:39:02.000Z
04_CNN_advances/cnn_mnist_simple.ipynb
jastarex/DL_Notes
4da8c5c90283d25655abde95263e44432aad343a
[ "Apache-2.0" ]
3
2017-09-19T17:18:46.000Z
2017-10-23T02:30:05.000Z
04_CNN_advances/cnn_mnist_simple.ipynb
jastarex/DL_Notes
4da8c5c90283d25655abde95263e44432aad343a
[ "Apache-2.0" ]
145
2017-11-19T17:21:23.000Z
2022-02-17T08:39:01.000Z
218.900545
9,924
0.905778
[ [ [ "# 卷积神经网络示例与各层可视化", "_____no_output_____" ] ], [ [ "import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n%matplotlib inline \nprint (\"当前TensorFlow版本为 [%s]\" % (tf.__version__))\nprint (\"所有包载入完毕\")", "当前TensorFlow版本为 [1.3.0]\n所有包载入完毕\n" ] ], [ [ "## 载入 MNIST", "_____no_output_____" ] ], [ [ "mnist = input_data.read_data_sets('data/', one_hot=True)\ntrainimg = mnist.train.images\ntrainlabel = mnist.train.labels\ntestimg = mnist.test.images\ntestlabel = mnist.test.labels\nprint (\"MNIST ready\")", "Extracting data/train-images-idx3-ubyte.gz\nExtracting data/train-labels-idx1-ubyte.gz\nExtracting data/t10k-images-idx3-ubyte.gz\nExtracting data/t10k-labels-idx1-ubyte.gz\nMNIST ready\n" ] ], [ [ "## 定义模型", "_____no_output_____" ] ], [ [ "# NETWORK TOPOLOGIES\nn_input = 784\nn_channel = 64 \nn_classes = 10 \n\n# INPUTS AND OUTPUTS\nx = tf.placeholder(\"float\", [None, n_input])\ny = tf.placeholder(\"float\", [None, n_classes])\n \n# NETWORK PARAMETERS\nstddev = 0.1\nweights = {\n 'c1': tf.Variable(tf.random_normal([7, 7, 1, n_channel], stddev=stddev)),\n 'd1': tf.Variable(tf.random_normal([14*14*64, n_classes], stddev=stddev))\n}\nbiases = {\n 'c1': tf.Variable(tf.random_normal([n_channel], stddev=stddev)),\n 'd1': tf.Variable(tf.random_normal([n_classes], stddev=stddev))\n}\nprint (\"NETWORK READY\")", "NETWORK READY\n" ] ], [ [ "## 定义图结构", "_____no_output_____" ] ], [ [ "# MODEL\ndef CNN(_x, _w, _b):\n # RESHAPE\n _x_r = tf.reshape(_x, shape=[-1, 28, 28, 1])\n # CONVOLUTION\n _conv1 = tf.nn.conv2d(_x_r, _w['c1'], strides=[1, 1, 1, 1], padding='SAME')\n # ADD BIAS\n _conv2 = tf.nn.bias_add(_conv1, _b['c1'])\n # RELU\n _conv3 = tf.nn.relu(_conv2)\n # MAX-POOL\n _pool = tf.nn.max_pool(_conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n # VECTORIZE\n _dense = tf.reshape(_pool, [-1, _w['d1'].get_shape().as_list()[0]])\n # DENSE\n _logit = tf.add(tf.matmul(_dense, _w['d1']), _b['d1'])\n _out = {\n 'x_r': _x_r, 'conv1': _conv1, 'conv2': _conv2, 'conv3': _conv3\n , 'pool': _pool, 'dense': _dense, 'logit': _logit\n }\n return _out\n\n# PREDICTION\ncnnout = CNN(x, weights, biases)\n\n# LOSS AND OPTIMIZER\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels=y, logits=cnnout['logit']))\noptm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost) \ncorr = tf.equal(tf.argmax(cnnout['logit'], 1), tf.argmax(y, 1)) \naccr = tf.reduce_mean(tf.cast(corr, \"float\"))\n\n# INITIALIZER\ninit = tf.global_variables_initializer()\nprint (\"FUNCTIONS READY\")", "FUNCTIONS READY\n" ] ], [ [ "## 存储", "_____no_output_____" ] ], [ [ "savedir = \"nets/cnn_mnist_simple/\"\nsaver = tf.train.Saver(max_to_keep=3)\nsave_step = 4\nif not os.path.exists(savedir):\n os.makedirs(savedir)\nprint (\"SAVER READY\")", "SAVER READY\n" ] ], [ [ "## 运行", "_____no_output_____" ] ], [ [ "# PARAMETERS\ntraining_epochs = 20\nbatch_size = 100\ndisplay_step = 4\n# LAUNCH THE GRAPH\nsess = tf.Session()\nsess.run(init)\n# OPTIMIZE\nfor epoch in range(training_epochs):\n avg_cost = 0.\n total_batch = int(mnist.train.num_examples/batch_size)\n # ITERATION\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n feeds = {x: batch_xs, y: batch_ys}\n sess.run(optm, feed_dict=feeds)\n avg_cost += sess.run(cost, feed_dict=feeds)\n avg_cost = avg_cost / total_batch\n # DISPLAY\n if (epoch+1) % display_step == 0:\n print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch+1, training_epochs, avg_cost))\n feeds = {x: batch_xs, y: batch_ys}\n train_acc = sess.run(accr, feed_dict=feeds)\n print (\"TRAIN ACCURACY: %.3f\" % (train_acc))\n feeds = {x: mnist.test.images, y: mnist.test.labels}\n test_acc = sess.run(accr, feed_dict=feeds)\n print (\"TEST ACCURACY: %.3f\" % (test_acc))\n # SAVE\n if (epoch+1) % save_step == 0:\n savename = savedir+\"net-\"+str(epoch+1)+\".ckpt\"\n saver.save(sess, savename)\n print (\"[%s] SAVED.\" % (savename))\nprint (\"OPTIMIZATION FINISHED\")", "Epoch: 004/020 cost: 0.035408186\nTRAIN ACCURACY: 0.980\nTEST ACCURACY: 0.986\n[nets/cnn_mnist_simple/net-4.ckpt] SAVED.\nEpoch: 008/020 cost: 0.014208857\nTRAIN ACCURACY: 0.990\nTEST ACCURACY: 0.987\n[nets/cnn_mnist_simple/net-8.ckpt] SAVED.\nEpoch: 012/020 cost: 0.006352575\nTRAIN ACCURACY: 1.000\nTEST ACCURACY: 0.987\n[nets/cnn_mnist_simple/net-12.ckpt] SAVED.\nEpoch: 016/020 cost: 0.003182677\nTRAIN ACCURACY: 1.000\nTEST ACCURACY: 0.987\n[nets/cnn_mnist_simple/net-16.ckpt] SAVED.\nEpoch: 020/020 cost: 0.001347903\nTRAIN ACCURACY: 1.000\nTEST ACCURACY: 0.987\n[nets/cnn_mnist_simple/net-20.ckpt] SAVED.\nOPTIMIZATION FINISHED\n" ] ], [ [ "## 恢复", "_____no_output_____" ] ], [ [ "do_restore = 0\nif do_restore == 1:\n sess = tf.Session()\n epoch = 20\n savename = savedir+\"net-\"+str(epoch)+\".ckpt\"\n saver.restore(sess, savename)\n print (\"NETWORK RESTORED\")\nelse:\n print (\"DO NOTHING\")", "DO NOTHING\n" ] ], [ [ "## CNN如何工作", "_____no_output_____" ] ], [ [ "input_r = sess.run(cnnout['x_r'], feed_dict={x: trainimg[0:1, :]})\nconv1 = sess.run(cnnout['conv1'], feed_dict={x: trainimg[0:1, :]})\nconv2 = sess.run(cnnout['conv2'], feed_dict={x: trainimg[0:1, :]})\nconv3 = sess.run(cnnout['conv3'], feed_dict={x: trainimg[0:1, :]})\npool = sess.run(cnnout['pool'], feed_dict={x: trainimg[0:1, :]})\ndense = sess.run(cnnout['dense'], feed_dict={x: trainimg[0:1, :]})\nout = sess.run(cnnout['logit'], feed_dict={x: trainimg[0:1, :]}) ", "_____no_output_____" ] ], [ [ "## 输入", "_____no_output_____" ] ], [ [ "print (\"Size of 'input_r' is %s\" % (input_r.shape,))\nlabel = np.argmax(trainlabel[0, :])\nprint (\"Label is %d\" % (label))\n\n# PLOT\nplt.matshow(input_r[0, :, :, 0], cmap=plt.get_cmap('gray'))\nplt.title(\"Label of this image is \" + str(label) + \"\")\nplt.colorbar()\nplt.show()", "Size of 'input_r' is (1, 28, 28, 1)\nLabel is 7\n" ] ], [ [ "# CONV 卷积层", "_____no_output_____" ] ], [ [ "print (\"SIZE OF 'CONV1' IS %s\" % (conv1.shape,))\nfor i in range(3):\n plt.matshow(conv1[0, :, :, i], cmap=plt.get_cmap('gray'))\n plt.title(str(i) + \"th conv1\")\n plt.colorbar()\n plt.show()", "SIZE OF 'CONV1' IS (1, 28, 28, 64)\n" ] ], [ [ "## CONV + BIAS", "_____no_output_____" ] ], [ [ "print (\"SIZE OF 'CONV2' IS %s\" % (conv2.shape,))\nfor i in range(3):\n plt.matshow(conv2[0, :, :, i], cmap=plt.get_cmap('gray'))\n plt.title(str(i) + \"th conv2\")\n plt.colorbar()\n plt.show()", "SIZE OF 'CONV2' IS (1, 28, 28, 64)\n" ] ], [ [ "## CONV + BIAS + RELU", "_____no_output_____" ] ], [ [ "print (\"SIZE OF 'CONV3' IS %s\" % (conv3.shape,))\nfor i in range(3):\n plt.matshow(conv3[0, :, :, i], cmap=plt.get_cmap('gray'))\n plt.title(str(i) + \"th conv3\")\n plt.colorbar()\n plt.show()", "SIZE OF 'CONV3' IS (1, 28, 28, 64)\n" ] ], [ [ "## POOL", "_____no_output_____" ] ], [ [ "print (\"SIZE OF 'POOL' IS %s\" % (pool.shape,))\nfor i in range(3):\n plt.matshow(pool[0, :, :, i], cmap=plt.get_cmap('gray'))\n plt.title(str(i) + \"th pool\")\n plt.colorbar()\n plt.show()", "SIZE OF 'POOL' IS (1, 14, 14, 64)\n" ] ], [ [ "## DENSE", "_____no_output_____" ] ], [ [ "print (\"SIZE OF 'DENSE' IS %s\" % (dense.shape,))\nprint (\"SIZE OF 'OUT' IS %s\" % (out.shape,))\nplt.matshow(out, cmap=plt.get_cmap('gray'))\nplt.title(\"OUT\")\nplt.colorbar()\nplt.show()", "SIZE OF 'DENSE' IS (1, 12544)\nSIZE OF 'OUT' IS (1, 10)\n" ] ], [ [ "## CONVOLUTION FILTER 卷积核", "_____no_output_____" ] ], [ [ "wc1 = sess.run(weights['c1'])\nprint (\"SIZE OF 'WC1' IS %s\" % (wc1.shape,))\nfor i in range(3):\n plt.matshow(wc1[:, :, 0, i], cmap=plt.get_cmap('gray'))\n plt.title(str(i) + \"th conv filter\")\n plt.colorbar()\n plt.show()", "SIZE OF 'WC1' IS (7, 7, 1, 64)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4af9d0eebd1f8b8189a5811c42352ee2b7a2f5e3
31,771
ipynb
Jupyter Notebook
python_1 snow16.ipynb
baicha12/snow-fox
7c72ec193acd8c1b4280420c7755697e059eef41
[ "Apache-2.0" ]
null
null
null
python_1 snow16.ipynb
baicha12/snow-fox
7c72ec193acd8c1b4280420c7755697e059eef41
[ "Apache-2.0" ]
null
null
null
python_1 snow16.ipynb
baicha12/snow-fox
7c72ec193acd8c1b4280420c7755697e059eef41
[ "Apache-2.0" ]
null
null
null
151.290476
25,684
0.869724
[ [ [ "Python语言进阶", "_____no_output_____" ] ], [ [ "\"\"\"\n查找 - 顺序查找和二分查找\n算法:解决问题的方法(步骤)\n评价一个算法的好坏主要指标:渐进时间复杂度和空间复杂度,通常一个算法很难到时间复杂度和空间复杂度都很低(因为时间和空间是不可调和 的矛盾)\n表示渐进时间复杂度通常用大o标记\no(c):常量时间复杂度 - 哈希存储/布隆过滤器\no(log_2 n):对数时间复杂度 - 折半查找\no(n):线性时间复杂度 - 顺序查找\no(n * log_2 n):对数线性时间复杂度 - 高级排序算法(归并算法,快速排序)\no(n ** 2):平方时间复杂度 - 简单排序算法(冒泡排序。选择排序。插入排序 )\no(n ** 3): 立方时间复杂度 - Floyd算法 / 矩阵乘法运算\n也称为多项式时间复杂度\no(2 ** n):几何级数时间复杂度 - 汉诺塔\no(3 ** n):几何级数时间复杂度\n也称为指数时间复杂度\no(n!):阶乘时间复杂度 \n\"\"\"\nfrom math import log2,factorial\nfrom matplotlib import pyplot\n\nimport numpy\n\ndef seq_searth(items:list,elem) -> int:\n \"\"\"顺序查找\"\"\"\n start,end = 0,len(items) - 1\n while start <= end:\n mid = (start + end)// 2\n if elem > items[mid]:\n start = mid + 1\n elif elem < items[mid]:\n end = mid - 1\n else :\n return mid\n return -1\n\n\ndef main():\n \"\"\"主函数(程序入口)\"\"\"\n num = 6\n styles = ['r-.','g-*','b-o','y-x','c-^','m-+','k-d']\n \n legends = ['对数', '线性', '线性对数', '平方', '立方', '几何级数', '阶乘']\n x_data = [x for x in range(1, num + 1)]\n y_data1 = [log2(y) for y in range(1,num + 1)]\n y_data2 = [y for y in range(1,num + 1)]\n y_data3 = [y * log2(y) for y in range(1,num + 1)]\n y_data4 = [y ** 2 for y in range(1,num + 1)]\n y_data5 = [y ** 3 for y in range(1,num + 1)]\n y_data6 = [3 ** y for y in range(1,num + 1)]\n y_data7 = [factorial(y) for y in range(1,num + 1) ]\n y_datas = [y_data1,y_data2,y_data3,y_data4,y_data5,y_data6,y_data7]\n for index, y_data in enumerate(y_datas):\n \n pyplot.plot(x_data,y_data,styles[index])\n pyplot.legend(legends)\n pyplot.xticks(numpy.arange(1,7,step=1))\n pyplot.yticks(numpy.arange(0,751,step=50))\n pyplot.show()\n \n \nif __name__ =='__main__':\n main()", "_____no_output_____" ], [ "\"\"\"\n查找 - 顺序查找和二分查找\n算法:解决问题的方法(步骤)\n评价一个算法的好坏主要有两个指标:渐近时间复杂度和渐近空间复杂度,通常一个算法很难做到时间复杂度和空间复杂度都很低(因为时间和空间是不可调和的矛盾)\n表示渐近时间复杂度通常使用大O标记\nO(c):常量时间复杂度 - 哈希存储 / 布隆过滤器\nO(log_2 n):对数时间复杂度 - 折半查找\nO(n):线性时间复杂度 - 顺序查找\nO(n * log_2 n):- 对数线性时间复杂度 - 高级排序算法(归并排序、快速排序)\nO(n ** 2):平方时间复杂度 - 简单排序算法(冒泡排序、选择排序、插入排序)\nO(n ** 3):立方时间复杂度 - Floyd算法 / 矩阵乘法运算\n也称为多项式时间复杂度\nO(2 ** n):几何级数时间复杂度 - 汉诺塔\nO(3 ** n):几何级数时间复杂度\n也称为指数时间复杂度\nO(n!):阶乘时间复杂度 - 旅行经销商问题 - NP\n\"\"\"\nfrom math import log2, factorial\nfrom matplotlib import pyplot\n\nimport numpy\n\n\ndef seq_search(items: list, elem) -> int:\n \"\"\"顺序查找\"\"\"\n for index, item in enumerate(items):\n if elem == item:\n return index\n return -1\n\n\ndef bin_search(items, elem):\n \"\"\"二分查找\"\"\"\n start, end = 0, len(items) - 1\n while start <= end:\n mid = (start + end) // 2\n if elem > items[mid]:\n start = mid + 1\n elif elem < items[mid]:\n end = mid - 1\n else:\n return mid\n return -1\n\n\ndef main():\n \"\"\"主函数(程序入口)\"\"\"\n num = 6\n styles = ['r-.', 'g-*', 'b-o', 'y-x', 'c-^', 'm-+', 'k-d']\n legends = ['对数', '线性', '线性对数', '平方', '立方', '几何级数', '阶乘']\n x_data = [x for x in range(1, num + 1)]\n y_data1 = [log2(y) for y in range(1, num + 1)]\n y_data2 = [y for y in range(1, num + 1)]\n y_data3 = [y * log2(y) for y in range(1, num + 1)]\n y_data4 = [y ** 2 for y in range(1, num + 1)]\n y_data5 = [y ** 3 for y in range(1, num + 1)]\n y_data6 = [3 ** y for y in range(1, num + 1)]\n y_data7 = [factorial(y) for y in range(1, num + 1)]\n y_datas = [y_data1, y_data2, y_data3, y_data4, y_data5, y_data6, y_data7]\n for index, y_data in enumerate(y_datas):\n pyplot.plot(x_data, y_data, styles[index])\n pyplot.legend(legends)\n pyplot.xticks(numpy.arange(1, 7, step=1))\n pyplot.yticks(numpy.arange(0, 751, step=50))\n pyplot.show()\n\n\nif __name__ == '__main__':\n main()", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
4af9d117a0b94366182aaf339c83cfacee414e0e
51,930
ipynb
Jupyter Notebook
dlnd_tv_script_generation-master/dlnd_tv_script_generation-master/dlnd_tv_script_generation.ipynb
oarb-projects/deep_learning_projects
5ab313576c341611dae4ffe7dbfb1d4f62e23bf4
[ "MIT" ]
1
2019-05-30T17:09:35.000Z
2019-05-30T17:09:35.000Z
dlnd_tv_script_generation-master/dlnd_tv_script_generation-master/dlnd_tv_script_generation.ipynb
oarb-projects/deep_learning_projects
5ab313576c341611dae4ffe7dbfb1d4f62e23bf4
[ "MIT" ]
null
null
null
dlnd_tv_script_generation-master/dlnd_tv_script_generation-master/dlnd_tv_script_generation.ipynb
oarb-projects/deep_learning_projects
5ab313576c341611dae4ffe7dbfb1d4f62e23bf4
[ "MIT" ]
null
null
null
48.127896
1,880
0.611708
[ [ [ "# TV Script Generation\nIn this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at [Moe's Tavern](https://simpsonswiki.com/wiki/Moe's_Tavern).\n## Get the Data\nThe data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like \"Moe's Cavern\", \"Flaming Moe's\", \"Uncle Moe's Family Feed-Bag\", etc..", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\n\ndata_dir = './data/simpsons/moes_tavern_lines.txt'\ntext = helper.load_data(data_dir)\n# Ignore notice, since we don't use it for analysing the data\ntext = text[81:]", "_____no_output_____" ] ], [ [ "## Explore the Data\nPlay around with `view_sentence_range` to view different parts of the data.", "_____no_output_____" ] ], [ [ "view_sentence_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\nscenes = text.split('\\n\\n')\nprint('Number of scenes: {}'.format(len(scenes)))\nsentence_count_scene = [scene.count('\\n') for scene in scenes]\nprint('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))\n\nsentences = [sentence for scene in scenes for sentence in scene.split('\\n')]\nprint('Number of lines: {}'.format(len(sentences)))\nword_count_sentence = [len(sentence.split()) for sentence in sentences]\nprint('Average number of words in each line: {}'.format(np.average(word_count_sentence)))\n\nprint()\nprint('The sentences {} to {}:'.format(*view_sentence_range))\nprint('\\n'.join(text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))", "Dataset Stats\nRoughly the number of unique words: 11492\nNumber of scenes: 262\nAverage number of sentences in each scene: 15.251908396946565\nNumber of lines: 4258\nAverage number of words in each line: 11.50164396430249\n\nThe sentences 0 to 10:\n\nMoe_Szyslak: (INTO PHONE) Moe's Tavern. Where the elite meet to drink.\nBart_Simpson: Eh, yeah, hello, is Mike there? Last name, Rotch.\nMoe_Szyslak: (INTO PHONE) Hold on, I'll check. (TO BARFLIES) Mike Rotch. Mike Rotch. Hey, has anybody seen Mike Rotch, lately?\nMoe_Szyslak: (INTO PHONE) Listen you little puke. One of these days I'm gonna catch you, and I'm gonna carve my name on your back with an ice pick.\nMoe_Szyslak: What's the matter Homer? You're not your normal effervescent self.\nHomer_Simpson: I got my problems, Moe. Give me another one.\nMoe_Szyslak: Homer, hey, you should not drink to forget your problems.\nBarney_Gumble: Yeah, you should only drink to enhance your social skills.\n\n" ] ], [ [ "## Implement Preprocessing Functions\nThe first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:\n- Lookup Table\n- Tokenize Punctuation\n\n### Lookup Table\nTo create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:\n- Dictionary to go from the words to an id, we'll call `vocab_to_int`\n- Dictionary to go from the id to word, we'll call `int_to_vocab`\n\nReturn these dictionaries in the following tuple `(vocab_to_int, int_to_vocab)`", "_____no_output_____" ] ], [ [ "import numpy as np\nimport problem_unittests as tests\n\ndef create_lookup_tables(text):\n \"\"\"\n Create lookup tables for vocabulary\n :param text: The text of tv scripts split into words\n :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n \"\"\"\n # TODO: Implement Function\n vocab_to_int = {w:i for i, w in enumerate(set(text))}\n int_to_vocab = {i:w for i, w in enumerate(set(text))}\n return vocab_to_int, int_to_vocab\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_create_lookup_tables(create_lookup_tables)", "Tests Passed\n" ] ], [ [ "### Tokenize Punctuation\nWe'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word \"bye\" and \"bye!\".\n\nImplement the function `token_lookup` to return a dict that will be used to tokenize symbols like \"!\" into \"||Exclamation_Mark||\". Create a dictionary for the following symbols where the symbol is the key and value is the token:\n- Period ( . )\n- Comma ( , )\n- Quotation Mark ( \" )\n- Semicolon ( ; )\n- Exclamation mark ( ! )\n- Question mark ( ? )\n- Left Parentheses ( ( )\n- Right Parentheses ( ) )\n- Dash ( -- )\n- Return ( \\n )\n\nThis dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token \"dash\", try using something like \"||dash||\".", "_____no_output_____" ] ], [ [ "def token_lookup():\n \"\"\"\n Generate a dict to turn punctuation into a token.\n :return: Tokenize dictionary where the key is the punctuation and the value is the token\n \"\"\"\n return {\n '.': '||Period||',\n ',': '||Comma||',\n '\"': '||Quotation_Mark||',\n ';': '||Semicolon||',\n '!': '||Exclamation_mark||',\n '?': '||Question_mark||',\n '(': '||Left_Parentheses||',\n ')': '||Right_Parentheses||',\n '--': '||Dash||',\n \"\\n\": '||Return||'\n }\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_tokenize(token_lookup)", "Tests Passed\n" ] ], [ [ "## Preprocess all the data and save it\nRunning the code cell below will preprocess all the data and save it to file.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Preprocess Training, Validation, and Testing Data\nhelper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)", "_____no_output_____" ] ], [ [ "# Check Point\nThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport numpy as np\nimport problem_unittests as tests\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()", "_____no_output_____" ] ], [ [ "## Build the Neural Network\nYou'll build the components necessary to build a RNN by implementing the following functions below:\n- get_inputs\n- get_init_cell\n- get_embed\n- build_rnn\n- build_nn\n- get_batches\n\n### Check the Version of TensorFlow and Access to GPU", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom distutils.version import LooseVersion\nimport warnings\nimport tensorflow as tf\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))", "TensorFlow Version: 1.2.1\n" ] ], [ [ "### Input\nImplement the `get_inputs()` function to create TF Placeholders for the Neural Network. It should create the following placeholders:\n- Input text placeholder named \"input\" using the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) `name` parameter.\n- Targets placeholder\n- Learning Rate placeholder\n\nReturn the placeholders in the following the tuple `(Input, Targets, LearingRate)`", "_____no_output_____" ] ], [ [ "def get_inputs():\n \"\"\"\n Create TF Placeholders for input, targets, and learning rate.\n :return: Tuple (input, targets, learning rate)\n \"\"\"\n # TODO: Implement Function\n inputs = tf.placeholder(dtype=tf.int32, shape=[None, None], name='input')\n targets = tf.placeholder(dtype=tf.int32, shape=[None, None], name='targets')\n learning_rate = tf.placeholder(dtype=tf.float32, name='learning_rate')\n return inputs, targets, learning_rate\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_inputs(get_inputs)", "Tests Passed\n" ] ], [ [ "### Build RNN Cell and Initialize\nStack one or more [`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell) in a [`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell).\n- The Rnn size should be set using `rnn_size`\n- Initalize Cell State using the MultiRNNCell's [`zero_state()`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell#zero_state) function\n - Apply the name \"initial_state\" to the initial state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\n\nReturn the cell and initial state in the following tuple `(Cell, InitialState)`", "_____no_output_____" ] ], [ [ "def get_init_cell(batch_size, rnn_size, keep_prob=0.8, layers=3):\n \"\"\"\n Create an RNN Cell and initialize it.\n :param batch_size: Size of batches\n :param rnn_size: Size of RNNs\n :return: Tuple (cell, initialize state)\n \"\"\"\n cell = tf.contrib.rnn.BasicLSTMCell(rnn_size)\n cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)\n multi = tf.contrib.rnn.MultiRNNCell([cell] * layers)\n init_state = multi.zero_state(batch_size, tf.float32)\n init_state = tf.identity(init_state, 'initial_state')\n return multi, init_state\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_init_cell(get_init_cell)", "_____no_output_____" ] ], [ [ "### Word Embedding\nApply embedding to `input_data` using TensorFlow. Return the embedded sequence.", "_____no_output_____" ] ], [ [ "def get_embed(input_data, vocab_size, embed_dim):\n \"\"\"\n Create embedding for <input_data>.\n :param input_data: TF placeholder for text input.\n :param vocab_size: Number of words in vocabulary.\n :param embed_dim: Number of embedding dimensions\n :return: Embedded input.\n \"\"\"\n embeddings = tf.Variable(tf.random_uniform((vocab_size, embed_dim), -1, 1))\n embed = tf.nn.embedding_lookup(embeddings, input_data)\n return embed\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_embed(get_embed)", "Tests Passed\n" ] ], [ [ "### Build RNN\nYou created a RNN Cell in the `get_init_cell()` function. Time to use the cell to create a RNN.\n- Build the RNN using the [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn)\n - Apply the name \"final_state\" to the final state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\n\nReturn the outputs and final_state state in the following tuple `(Outputs, FinalState)` ", "_____no_output_____" ] ], [ [ "def build_rnn(cell, inputs):\n \"\"\"\n Create a RNN using a RNN Cell\n :param cell: RNN Cell\n :param inputs: Input text data\n :return: Tuple (Outputs, Final State)\n \"\"\"\n outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)\n final_state = tf.identity(final_state, 'final_state')\n return outputs, final_state\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_build_rnn(build_rnn)", "Tests Passed\n" ] ], [ [ "### Build the Neural Network\nApply the functions you implemented above to:\n- Apply embedding to `input_data` using your `get_embed(input_data, vocab_size, embed_dim)` function.\n- Build RNN using `cell` and your `build_rnn(cell, inputs)` function.\n- Apply a fully connected layer with a linear activation and `vocab_size` as the number of outputs.\n\nReturn the logits and final state in the following tuple (Logits, FinalState) ", "_____no_output_____" ] ], [ [ "def build_nn(cell, rnn_size, input_data, vocab_size):\n \"\"\"\n Build part of the neural network\n :param cell: RNN cell\n :param rnn_size: Size of rnns\n :param input_data: Input data\n :param vocab_size: Vocabulary size\n :return: Tuple (Logits, FinalState)\n \"\"\"\n embed = get_embed(input_data, vocab_size, rnn_size)\n outputs, final_state = build_rnn(cell, embed)\n logits = tf.contrib.layers.fully_connected(outputs, vocab_size, activation_fn=None)\n return logits, final_state\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_build_nn(build_nn)", "Tests Passed\n" ] ], [ [ "### Batches\nImplement `get_batches` to create batches of input and targets using `int_text`. The batches should be a Numpy array with the shape `(number of batches, 2, batch size, sequence length)`. Each batch contains two elements:\n- The first element is a single batch of **input** with the shape `[batch size, sequence length]`\n- The second element is a single batch of **targets** with the shape `[batch size, sequence length]`\n\nIf you can't fill the last batch with enough data, drop the last batch.\n\nFor exmple, `get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 2, 3)` would return a Numpy array of the following:\n```\n[\n # First Batch\n [\n # Batch of Input\n [[ 1 2 3], [ 7 8 9]],\n # Batch of targets\n [[ 2 3 4], [ 8 9 10]]\n ],\n \n # Second Batch\n [\n # Batch of Input\n [[ 4 5 6], [10 11 12]],\n # Batch of targets\n [[ 5 6 7], [11 12 13]]\n ]\n]\n```", "_____no_output_____" ] ], [ [ "def get_batches(int_text, batch_size, seq_length):\n \"\"\"\n Return batches of input and target\n :param int_text: Text with the words replaced by their ids\n :param batch_size: The size of batch\n :param seq_length: The length of sequence\n :return: Batches as a Numpy array\n \"\"\"\n # TODO: Implement Function\n n_batches = len(int_text) // (batch_size * seq_length)\n result = []\n for i in range(n_batches):\n inputs = []\n targets = []\n for j in range(batch_size):\n idx = i * seq_length + j * seq_length\n inputs.append(int_text[idx:idx + seq_length])\n targets.append(int_text[idx + 1:idx + seq_length + 1])\n result.append([inputs, targets])\n result=np.array(result)\n print(result.shape)\n print(result[1])\n print(n_batches)\n print(batch_size)\n print(seq_length)\n # (number of batches, 2, batch size, sequence length).\n return np.array(result)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_batches(get_batches)", "(7, 2, 128, 5)\n[[[ 5 6 7 8 9]\n [ 10 11 12 13 14]\n [ 15 16 17 18 19]\n ..., \n [630 631 632 633 634]\n [635 636 637 638 639]\n [640 641 642 643 644]]\n\n [[ 6 7 8 9 10]\n [ 11 12 13 14 15]\n [ 16 17 18 19 20]\n ..., \n [631 632 633 634 635]\n [636 637 638 639 640]\n [641 642 643 644 645]]]\n7\n128\n5\nTests Passed\n" ] ], [ [ "## Neural Network Training\n### Hyperparameters\nTune the following parameters:\n\n- Set `num_epochs` to the number of epochs.\n- Set `batch_size` to the batch size.\n- Set `rnn_size` to the size of the RNNs.\n- Set `seq_length` to the length of sequence.\n- Set `learning_rate` to the learning rate.\n- Set `show_every_n_batches` to the number of batches the neural network should print progress.", "_____no_output_____" ] ], [ [ "# Number of Epochs\nnum_epochs = 100\n# Batch Size\nbatch_size = 128\n# RNN Size\nrnn_size = 256\n# Sequence Length\nseq_length = 25\n# Learning Rate\nlearning_rate = 0.01\n# Show stats for every n number of batches\nshow_every_n_batches = 50\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nsave_dir = './save'", "_____no_output_____" ] ], [ [ "### Build the Graph\nBuild the graph using the neural network you implemented.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom tensorflow.contrib import seq2seq\n\ntrain_graph = tf.Graph()\nwith train_graph.as_default():\n vocab_size = len(int_to_vocab)\n input_text, targets, lr = get_inputs()\n input_data_shape = tf.shape(input_text)\n cell, initial_state = get_init_cell(input_data_shape[0], rnn_size)\n logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size)\n\n # Probabilities for generating words\n probs = tf.nn.softmax(logits, name='probs')\n\n # Loss function\n cost = seq2seq.sequence_loss(\n logits,\n targets,\n tf.ones([input_data_shape[0], input_data_shape[1]]))\n\n # Optimizer\n optimizer = tf.train.AdamOptimizer(lr)\n\n # Gradient Clipping\n gradients = optimizer.compute_gradients(cost)\n capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients]\n train_op = optimizer.apply_gradients(capped_gradients)", "_____no_output_____" ] ], [ [ "## Train\nTrain the neural network on the preprocessed data. If you have a hard time getting a good loss, check the [forms](https://discussions.udacity.com/) to see if anyone is having the same problem.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nbatches = get_batches(int_text, batch_size, seq_length)\n\nwith tf.Session(graph=train_graph) as sess:\n sess.run(tf.global_variables_initializer())\n\n for epoch_i in range(num_epochs):\n state = sess.run(initial_state, {input_text: batches[0][0]})\n\n for batch_i, (x, y) in enumerate(batches):\n feed = {\n input_text: x,\n targets: y,\n initial_state: state,\n lr: learning_rate}\n train_loss, state, _ = sess.run([cost, final_state, train_op], feed)\n\n # Show every <show_every_n_batches> batches\n if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0:\n print('Epoch {:>3} Batch {:>4}/{} train_loss = {:.3f}'.format(\n epoch_i,\n batch_i,\n len(batches),\n train_loss))\n\n # Save Model\n saver = tf.train.Saver()\n saver.save(sess, save_dir)\n print('Model Trained and Saved')", "Epoch 0 Batch 0/21 train_loss = 8.821\nEpoch 2 Batch 8/21 train_loss = 5.283\nEpoch 4 Batch 16/21 train_loss = 5.190\nEpoch 7 Batch 3/21 train_loss = 5.122\nEpoch 9 Batch 11/21 train_loss = 4.646\nEpoch 11 Batch 19/21 train_loss = 4.008\nEpoch 14 Batch 6/21 train_loss = 3.073\nEpoch 16 Batch 14/21 train_loss = 2.163\nEpoch 19 Batch 1/21 train_loss = 1.541\nEpoch 21 Batch 9/21 train_loss = 0.902\nEpoch 23 Batch 17/21 train_loss = 0.574\nEpoch 26 Batch 4/21 train_loss = 0.363\nEpoch 28 Batch 12/21 train_loss = 0.257\nEpoch 30 Batch 20/21 train_loss = 0.206\nEpoch 33 Batch 7/21 train_loss = 0.141\nEpoch 35 Batch 15/21 train_loss = 0.128\nEpoch 38 Batch 2/21 train_loss = 0.113\nEpoch 40 Batch 10/21 train_loss = 0.091\nEpoch 42 Batch 18/21 train_loss = 0.085\nEpoch 45 Batch 5/21 train_loss = 0.081\nEpoch 47 Batch 13/21 train_loss = 0.068\nEpoch 50 Batch 0/21 train_loss = 0.075\nEpoch 52 Batch 8/21 train_loss = 0.057\nEpoch 54 Batch 16/21 train_loss = 0.065\nEpoch 57 Batch 3/21 train_loss = 0.059\nEpoch 59 Batch 11/21 train_loss = 0.050\nEpoch 61 Batch 19/21 train_loss = 0.061\nEpoch 64 Batch 6/21 train_loss = 0.051\nEpoch 66 Batch 14/21 train_loss = 0.053\nEpoch 69 Batch 1/21 train_loss = 0.057\nEpoch 71 Batch 9/21 train_loss = 0.052\nEpoch 73 Batch 17/21 train_loss = 0.051\nEpoch 76 Batch 4/21 train_loss = 0.054\nEpoch 78 Batch 12/21 train_loss = 0.050\nEpoch 80 Batch 20/21 train_loss = 0.054\nEpoch 83 Batch 7/21 train_loss = 0.042\nEpoch 85 Batch 15/21 train_loss = 0.047\nEpoch 88 Batch 2/21 train_loss = 0.049\nEpoch 90 Batch 10/21 train_loss = 0.051\nEpoch 92 Batch 18/21 train_loss = 0.050\nEpoch 95 Batch 5/21 train_loss = 0.051\nEpoch 97 Batch 13/21 train_loss = 0.053\nModel Trained and Saved\n" ] ], [ [ "## Save Parameters\nSave `seq_length` and `save_dir` for generating a new TV script.", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Save parameters for checkpoint\nhelper.save_params((seq_length, save_dir))", "_____no_output_____" ] ], [ [ "# Checkpoint", "_____no_output_____" ] ], [ [ "\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport helper\nimport problem_unittests as tests\n\n_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\nseq_length, load_dir = helper.load_params()", "_____no_output_____" ] ], [ [ "## Implement Generate Functions\n### Get Tensors\nGet tensors from `loaded_graph` using the function [`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name). Get the tensors using the following names:\n- \"input:0\"\n- \"initial_state:0\"\n- \"final_state:0\"\n- \"probs:0\"\n\nReturn the tensors in the following tuple `(InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)` ", "_____no_output_____" ] ], [ [ "def get_tensors(loaded_graph):\n \"\"\"\n Get input, initial state, final state, and probabilities tensor from <loaded_graph>\n :param loaded_graph: TensorFlow graph loaded from file\n :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)\n \"\"\"\n inputs = loaded_graph.get_tensor_by_name('input:0')\n init_state = loaded_graph.get_tensor_by_name('initial_state:0')\n final_state = loaded_graph.get_tensor_by_name('final_state:0')\n probs = loaded_graph.get_tensor_by_name('probs:0')\n return inputs, init_state, final_state, probs\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_get_tensors(get_tensors)", "Tests Passed\n" ] ], [ [ "### Choose Word\nImplement the `pick_word()` function to select the next word using `probabilities`.", "_____no_output_____" ] ], [ [ "def pick_word(probabilities, int_to_vocab):\n \"\"\"\n Pick the next word in the generated text\n :param probabilities: Probabilites of the next word\n :param int_to_vocab: Dictionary of word ids as the keys and words as the values\n :return: String of the predicted word\n \"\"\"\n # TODO: Implement Function\n return int_to_vocab[np.argmax(probabilities)]\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_pick_word(pick_word)", "Tests Passed\n" ] ], [ [ "## Generate TV Script\nThis will generate the TV script for you. Set `gen_length` to the length of TV script you want to generate.", "_____no_output_____" ] ], [ [ "gen_length = 200\n# homer_simpson, moe_szyslak, or Barney_Gumble\nprime_word = 'moe_szyslak'\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nloaded_graph = tf.Graph()\nwith tf.Session(graph=loaded_graph) as sess:\n # Load saved model\n loader = tf.train.import_meta_graph(load_dir + '.meta')\n loader.restore(sess, load_dir)\n\n # Get Tensors from loaded model\n input_text, initial_state, final_state, probs = get_tensors(loaded_graph)\n\n # Sentences generation setup\n gen_sentences = [prime_word + ':']\n prev_state = sess.run(initial_state, {input_text: np.array([[1]])})\n\n # Generate sentences\n for n in range(gen_length):\n # Dynamic Input\n dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]\n dyn_seq_length = len(dyn_input[0])\n\n # Get Prediction\n probabilities, prev_state = sess.run(\n [probs, final_state],\n {input_text: dyn_input, initial_state: prev_state})\n \n pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)\n\n gen_sentences.append(pred_word)\n \n # Remove tokens\n tv_script = ' '.join(gen_sentences)\n for key, token in token_dict.items():\n ending = ' ' if key in ['\\n', '(', '\"'] else ''\n tv_script = tv_script.replace(' ' + token.lower(), key)\n tv_script = tv_script.replace('\\n ', '\\n')\n tv_script = tv_script.replace('( ', '(')\n \n print(tv_script)", "moe_szyslak:(into phone) moe's tavern. where the elite in your nice. you're little bart... we laughing) that your, you know, twenty-five\" yeah? i don't that right. do you ya to drink?\ncollette: try lighting it. cuz to smithers good right? that's bucket and the\" flaming moe. is made a my plant and a couple of over.\nfootball_announcer:) poison(take folk are, no. mcstagger?\nlisa_simpson: well, that's right. what? one that my?\nmoe_szyslak: you're crank make away moron.\nmoe_szyslak: i like another one. gumbel. but i need\" yeah, but i got behind...\nbart_simpson:(to are good, a with we're worry, we're example...\njust about with once i did you got studio problems. hold! thank you.\nc. _montgomery_burns: that whoa!\nlittle_man: moe's warmly? hold the flaming moe. now(into phone) yeah, freshened going in the letter. business is bet that you'll\n" ] ], [ [ "# The TV Script is Nonsensical\nIt's ok if the TV script doesn't make any sense. We trained on less than a megabyte of text. In order to get good results, you'll have to use a smaller vocabulary or get more data. Luckly there's more data! As we mentioned in the begging of this project, this is a subset of [another dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data). We didn't have you train on all the data, because that would take too long. However, you are free to train your neural network on all the data. After you complete the project, of course.\n# Submitting This Project\nWhen submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_tv_script_generation.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4af9f456ba97041523f54234c02b8c0bcd80a386
24,782
ipynb
Jupyter Notebook
lessons/Recommendations/1_Intro_to_Recommendations/3_Measuring Similarity.ipynb
aauss/DSND_Term2
ff1ff8edc208652c29bfc25f18c610a02dc9d299
[ "MIT" ]
null
null
null
lessons/Recommendations/1_Intro_to_Recommendations/3_Measuring Similarity.ipynb
aauss/DSND_Term2
ff1ff8edc208652c29bfc25f18c610a02dc9d299
[ "MIT" ]
null
null
null
lessons/Recommendations/1_Intro_to_Recommendations/3_Measuring Similarity.ipynb
aauss/DSND_Term2
ff1ff8edc208652c29bfc25f18c610a02dc9d299
[ "MIT" ]
null
null
null
40.165316
481
0.57687
[ [ [ "### How to Find Your Neighbor?\n\nIn neighborhood based collaborative filtering, it is incredibly important to be able to identify an individual's neighbors. Let's look at a small dataset in order to understand, how we can use different metrics to identify close neighbors.", "_____no_output_____" ] ], [ [ "%load_ext lab_black", "_____no_output_____" ], [ "from itertools import product\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import spearmanr, kendalltau\nimport matplotlib.pyplot as plt\nimport tests as t\nimport helper as h\n\n%matplotlib inline\n\nplay_data = pd.DataFrame(\n {\n \"x1\": [-3, -2, -1, 0, 1, 2, 3],\n \"x2\": [9, 4, 1, 0, 1, 4, 9],\n \"x3\": [1, 2, 3, 4, 5, 6, 7],\n \"x4\": [2, 5, 15, 27, 28, 30, 31],\n }\n)\n\n# create play data dataframe\nplay_data = play_data[[\"x1\", \"x2\", \"x3\", \"x4\"]]", "_____no_output_____" ] ], [ [ "### Measures of Similarity\n\nThe first metrics we will look at have similar characteristics:\n\n1. Pearson's Correlation Coefficient\n2. Spearman's Correlation Coefficient\n3. Kendall's Tau\n\nLet's take a look at each of these individually.\n\n### Pearson's Correlation\n\nFirst, **Pearson's correlation coefficient** is a measure related to the strength and direction of a **linear** relationship. \n\nIf we have two vectors **x** and **y**, we can compare their individual elements in the following way to calculate Pearson's correlation coefficient:\n\n$$CORR(\\textbf{x}, \\textbf{y}) = \\frac{\\sum\\limits_{i=1}^{n}(x_i - \\bar{x})(y_i - \\bar{y})}{\\sqrt{\\sum\\limits_{i=1}^{n}(x_i-\\bar{x})^2}\\sqrt{\\sum\\limits_{i=1}^{n}(y_i-\\bar{y})^2}} $$\n\nwhere \n\n$$\\bar{x} = \\frac{1}{n}\\sum\\limits_{i=1}^{n}x_i$$\n\n1. Write a function that takes in two vectors and returns the Pearson correlation coefficient. You can then compare your answer to the built in function in numpy by using the assert statements in the following cell.", "_____no_output_____" ] ], [ [ "def pearson_corr(x, y):\n \"\"\"\n INPUT\n x - an array of matching length to array y\n y - an array of matching length to array x\n OUTPUT\n corr - the pearson correlation coefficient for comparing x and y\n \"\"\"\n numerator = (x - np.mean(x)) @ (y - np.mean(y))\n denominator = np.sqrt(np.sum((x - np.mean(x)) ** 2)) * np.sqrt(\n np.sum((y - np.mean(y)) ** 2)\n )\n corr = numerator / denominator\n\n return corr", "_____no_output_____" ], [ "# This cell will test your function against the built in numpy function\nassert (\n pearson_corr(play_data[\"x1\"], play_data[\"x2\"])\n == np.corrcoef(play_data[\"x1\"], play_data[\"x2\"])[0][1]\n), \"Oops! The correlation between the first two columns should be 0, but your function returned {}.\".format(\n pearson_corr(play_data[\"x1\"], play_data[\"x2\"])\n)\nassert (\n round(pearson_corr(play_data[\"x1\"], play_data[\"x3\"]), 2)\n == np.corrcoef(play_data[\"x1\"], play_data[\"x3\"])[0][1]\n), \"Oops! The correlation between the first and third columns should be {}, but your function returned {}.\".format(\n np.corrcoef(play_data[\"x1\"], play_data[\"x3\"])[0][1],\n pearson_corr(play_data[\"x1\"], play_data[\"x3\"]),\n)\nassert round(pearson_corr(play_data[\"x3\"], play_data[\"x4\"]), 2) == round(\n np.corrcoef(play_data[\"x3\"], play_data[\"x4\"])[0][1], 2\n), \"Oops! The correlation between the first and third columns should be {}, but your function returned {}.\".format(\n np.corrcoef(play_data[\"x3\"], play_data[\"x4\"])[0][1],\n pearson_corr(play_data[\"x3\"], play_data[\"x4\"]),\n)\nprint(\n \"If this is all you see, it looks like you are all set! Nice job coding up Pearson's correlation coefficient!\"\n)", "If this is all you see, it looks like you are all set! Nice job coding up Pearson's correlation coefficient!\n" ] ], [ [ "`2.` Now that you have computed **Pearson's correlation coefficient**, use the below dictionary to identify statements that are true about **this** measure.", "_____no_output_____" ] ], [ [ "a = True\nb = False\nc = \"We can't be sure.\"\n\n\npearson_dct = {\n \"If when x increases, y always increases, Pearson's correlation will be always be 1.\": False, # Letter here,\n \"If when x increases by 1, y always increases by 3, Pearson's correlation will always be 1.\": True, # Letter here,\n \"If when x increases by 1, y always decreases by 5, Pearson's correlation will always be -1.\": True, # Letter here,\n \"If when x increases by 1, y increases by 3 times x, Pearson's correlation will always be 1.\": False, # Letter here\n}\n\nt.sim_2_sol(pearson_dct)", "That's right! Pearson's correlation relates to a linear relationship. The second and third cases are examples of perfect linear relationships, where we would receive values of 1 and -1. Only having an increase or decrease that are directly related will not lead to a Pearson's correlation coefficient of 1 or -1. You can see this by testing out your function using the examples above without using assert statements.\n" ] ], [ [ "### Spearman's Correlation\n\nNow, let's look at **Spearman's correlation coefficient**. Spearman's correlation is what is known as a [non-parametric](https://en.wikipedia.org/wiki/Nonparametric_statistics) statistic, which is a statistic who's distribution doesn't depend parameters (statistics that follow normal distributions or binomial distributions are examples of parametric statistics). \n\nFrequently non-parametric statistics are based on the ranks of data rather than the original values collected. This happens to be the case with Spearman's correlation coefficient, which is calculated similarly to Pearson's correlation. However, instead of using the raw data, we use the rank of each value.\n\nYou can quickly change from the raw data to the ranks using the **.rank()** method as shown here:", "_____no_output_____" ] ], [ [ "print(\n \"The ranked values for the variable x1 are: {}\".format(\n np.array(play_data[\"x1\"].rank())\n )\n)\nprint(\n \"The raw data values for the variable x1 are: {}\".format(np.array(play_data[\"x1\"]))\n)", "The ranked values for the variable x1 are: [1. 2. 3. 4. 5. 6. 7.]\nThe raw data values for the variable x1 are: [-3 -2 -1 0 1 2 3]\n" ] ], [ [ "If we map each of our data to ranked data values as shown above:\n\n$$\\textbf{x} \\rightarrow \\textbf{x}^{r}$$\n$$\\textbf{y} \\rightarrow \\textbf{y}^{r}$$\n\nHere, we let the **r** indicate these are ranked values (this is not raising any value to the power of r). Then we compute Spearman's correlation coefficient as:\n\n$$SCORR(\\textbf{x}, \\textbf{y}) = \\frac{\\sum\\limits_{i=1}^{n}(x^{r}_i - \\bar{x}^{r})(y^{r}_i - \\bar{y}^{r})}{\\sqrt{\\sum\\limits_{i=1}^{n}(x^{r}_i-\\bar{x}^{r})^2}\\sqrt{\\sum\\limits_{i=1}^{n}(y^{r}_i-\\bar{y}^{r})^2}} $$\n\nwhere \n\n$$\\bar{x}^r = \\frac{1}{n}\\sum\\limits_{i=1}^{n}x^r_i$$\n\n`3.` Write a function that takes in two vectors and returns the Spearman correlation coefficient. You can then compare your answer to the built in function in scipy stats by using the assert statements in the following cell.", "_____no_output_____" ] ], [ [ "def corr_spearman(x, y):\n \"\"\"\n INPUT\n x - an array of matching length to array y\n y - an array of matching length to array x\n OUTPUT\n corr - the spearman correlation coefficient for comparing x and y\n \"\"\"\n x = x.rank()\n y = y.rank()\n numerator = (x - np.mean(x)) @ (y - np.mean(y))\n denominator = np.sqrt(np.sum((x - np.mean(x)) ** 2)) * np.sqrt(\n np.sum((y - np.mean(y)) ** 2)\n )\n corr = numerator / denominator\n return corr", "_____no_output_____" ], [ "# This cell will test your function against the built in scipy function\nassert (\n corr_spearman(play_data[\"x1\"], play_data[\"x2\"])\n == spearmanr(play_data[\"x1\"], play_data[\"x2\"])[0]\n), \"Oops! The correlation between the first two columns should be 0, but your function returned {}.\".format(\n compute_corr(play_data[\"x1\"], play_data[\"x2\"])\n)\nassert (\n round(corr_spearman(play_data[\"x1\"], play_data[\"x3\"]), 2)\n == spearmanr(play_data[\"x1\"], play_data[\"x3\"])[0]\n), \"Oops! The correlation between the first and third columns should be {}, but your function returned {}.\".format(\n np.corrcoef(play_data[\"x1\"], play_data[\"x3\"])[0][1],\n compute_corr(play_data[\"x1\"], play_data[\"x3\"]),\n)\nassert round(corr_spearman(play_data[\"x3\"], play_data[\"x4\"]), 2) == round(\n spearmanr(play_data[\"x3\"], play_data[\"x4\"])[0], 2\n), \"Oops! The correlation between the first and third columns should be {}, but your function returned {}.\".format(\n np.corrcoef(play_data[\"x3\"], play_data[\"x4\"])[0][1],\n compute_corr(play_data[\"x3\"], play_data[\"x4\"]),\n)\nprint(\n \"If this is all you see, it looks like you are all set! Nice job coding up Spearman's correlation coefficient!\"\n)", "If this is all you see, it looks like you are all set! Nice job coding up Spearman's correlation coefficient!\n" ], [ "a = True\nb = False\nc = \"We can't be sure.\"\n\n\nspearman_dct = {\n \"If when x increases, y always increases, Spearman's correlation will be always be 1.\": a, # Letter here,\n \"If when x increases by 1, y always increases by 3, Pearson's correlation will always be 1.\": a, # Letter here,\n \"If when x increases by 1, y always decreases by 5, Pearson's correlation will always be -1.\": a, # Letter here,\n \"If when x increases by 1, y increases by 3 times x, Pearson's correlation will always be 1.\": a, # Letter here\n}\n\nt.sim_4_sol(spearman_dct)", "That's right! Unlike Pearson's correlation, Spearman's correlation can have perfect relationships (1 or -1 values) that aren't linear relationships. You will notice that neither Spearman or Pearson correlation values suggest a relation when there are quadratic relationships.\n" ] ], [ [ "### Kendall's Tau\n\nKendall's tau is quite similar to Spearman's correlation coefficient. Both of these measures are nonparametric measures of a relationship. Specifically both Spearman and Kendall's coefficients are calculated based on ranking data and not the raw data. \n\nSimilar to both of the previous measures, Kendall's Tau is always between -1 and 1, where -1 suggests a strong, negative relationship between two variables and 1 suggests a strong, positive relationship between two variables.\n\nThough Spearman's and Kendall's measures are very similar, there are statistical advantages to choosing Kendall's measure in that Kendall's Tau has smaller variability when using larger sample sizes. However Spearman's measure is more computationally efficient, as Kendall's Tau is O(n^2) and Spearman's correlation is O(nLog(n)). You can find more on this topic in [this thread](https://www.researchgate.net/post/Does_Spearmans_rho_have_any_advantage_over_Kendalls_tau).\n\nLet's take a closer look at exactly how this measure is calculated. Again, we want to map our data to ranks:\n\n$$\\textbf{x} \\rightarrow \\textbf{x}^{r}$$\n$$\\textbf{y} \\rightarrow \\textbf{y}^{r}$$\n\nThen we calculate Kendall's Tau as:\n\n$$TAU(\\textbf{x}, \\textbf{y}) = \\frac{2}{n(n -1)}\\sum_{i < j}sgn(x^r_i - x^r_j)sgn(y^r_i - y^r_j)$$\n\nWhere $sgn$ takes the the sign associated with the difference in the ranked values. An alternative way to write \n\n$$sgn(x^r_i - x^r_j)$$ \n\nis in the following way:\n\n$$\n \\begin{cases} \n -1 & x^r_i < x^r_j \\\\\n 0 & x^r_i = x^r_j \\\\\n 1 & x^r_i > x^r_j \n \\end{cases}\n$$\n\nTherefore the possible results of \n\n$$sgn(x^r_i - x^r_j)sgn(y^r_i - y^r_j)$$\n\nare only 1, -1, or 0, which are summed to give an idea of the propotion of times the ranks of **x** and **y** are pointed in the right direction.\n\n`5.` Write a function that takes in two vectors and returns Kendall's Tau. You can then compare your answer to the built in function in scipy stats by using the assert statements in the following cell.", "_____no_output_____" ] ], [ [ "def kendalls_tau(x, y):\n \"\"\"\n INPUT\n x - an array of matching length to array y\n y - an array of matching length to array x\n OUTPUT\n tau - the kendall's tau for comparing x and y\n \"\"\"\n x = x.rank()\n y = y.rank()\n\n normalization = 2 / (len(x) * (len(x) - 1))\n indeces = filter(lambda x: x[0] < x[1], product(range(len(x)), range(len(y))))\n indeces = list(map(list, zip(*indeces)))\n indeces_i = indeces[0]\n indeces_j = indeces[1]\n\n tau = np.sum(\n np.sign(x.iloc[indeces_i].values - x.iloc[indeces_j].values)\n * np.sign(y.iloc[indeces_i].values - y.iloc[indeces_j].values)\n )\n\n return tau * normalization", "_____no_output_____" ], [ "%%timeit\nkendalls_tau(play_data[\"x1\"], play_data[\"x2\"])", "327 µs ± 1.11 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" ], [ "# This cell will test your function against the built in scipy function\nassert (\n kendalls_tau(play_data[\"x1\"], play_data[\"x2\"])\n == kendalltau(play_data[\"x1\"], play_data[\"x2\"])[0]\n), \"Oops! The correlation between the first two columns should be 0, but your function returned {}.\".format(\n kendalls_tau(play_data[\"x1\"], play_data[\"x2\"])\n)\nassert (\n round(kendalls_tau(play_data[\"x1\"], play_data[\"x3\"]), 2)\n == kendalltau(play_data[\"x1\"], play_data[\"x3\"])[0]\n), \"Oops! The correlation between the first and third columns should be {}, but your function returned {}.\".format(\n kendalltau(play_data[\"x1\"], play_data[\"x3\"])[0][1],\n kendalls_tau(play_data[\"x1\"], play_data[\"x3\"]),\n)\nassert round(kendalls_tau(play_data[\"x3\"], play_data[\"x4\"]), 2) == round(\n kendalltau(play_data[\"x3\"], play_data[\"x4\"])[0], 2\n), \"Oops! The correlation between the first and third columns should be {}, but your function returned {}.\".format(\n kendalltau(play_data[\"x3\"], play_data[\"x4\"])[0][1],\n kendalls_tau(play_data[\"x3\"], play_data[\"x4\"]),\n)\nprint(\n \"If this is all you see, it looks like you are all set! Nice job coding up Kendall's Tau!\"\n)", "If this is all you see, it looks like you are all set! Nice job coding up Kendall's Tau!\n" ] ], [ [ "`6.` Use your functions (and/or your knowledge of each of the above coefficients) to accurately identify each of the below statements as True or False. **Note:** There may be some rounding differences due to the way numbers are stored, so it is recommended that you consider comparisons to 4 or fewer decimal places.", "_____no_output_____" ] ], [ [ "a = True\nb = False\nc = \"We can't be sure.\"\n\n\ncorr_comp_dct = {\n \"For all columns of play_data, Spearman and Kendall's measures match.\": a, # Letter here,\n \"For all columns of play_data, Spearman and Pearson's measures match.\": b, # Letter here,\n \"For all columns of play_data, Pearson and Kendall's measures match.\": b, # Letter here\n}\n\nt.sim_6_sol(corr_comp_dct)", "That's right! Pearson does not match the other two measures, as it looks specifically for linear relationships. However, Spearman and Kenall's measures are exactly the same to one another in the cases related to play_data.\n" ] ], [ [ "### Distance Measures\n\nEach of the above measures are considered measures of correlation. Similarly, there are distance measures (of which there are many). [This is a great article](http://dataaspirant.com/2015/04/11/five-most-popular-similarity-measures-implementation-in-python/) on some popular distance metrics. In this notebook, we will be looking specifically at two of these measures. \n\n1. Euclidean Distance\n2. Manhattan Distance\n\nDifferent than the three measures you built functions for, these two measures take on values between 0 and potentially infinity. Measures that are closer to 0 imply that two vectors are more similar to one another. The larger these values become, the more dissimilar two vectors are to one another.\n\nChoosing one of these two `distance` metrics vs. one of the three `similarity` above is often a matter of personal preference, audience, and data specificities. You will see in a bit a case where one of these measures (euclidean or manhattan distance) is optimal to using Pearson's correlation coefficient.\n\n### Euclidean Distance\n\nEuclidean distance can also just be considered as straight-line distance between two vectors.\n\nFor two vectors **x** and **y**, we can compute this as:\n\n$$ EUC(\\textbf{x}, \\textbf{y}) = \\sqrt{\\sum\\limits_{i=1}^{n}(x_i - y_i)^2}$$\n\n### Manhattan Distance\n\nDifferent from euclidean distance, Manhattan distance is a 'manhattan block' distance from one vector to another. Therefore, you can imagine this distance as a way to compute the distance between two points when you are not able to go through buildings.\n\nSpecifically, this distance is computed as:\n\n$$ MANHATTAN(\\textbf{x}, \\textbf{y}) = \\sqrt{\\sum\\limits_{i=1}^{n}|x_i - y_i|}$$\n\nUsing each of the above, write a function for each to take two vectors and compute the euclidean and manhattan distances.\n\n\n<img src=\"images/distances.png\">\n\nYou can see in the above image, the **blue** line gives the **Manhattan** distance, while the **green** line gives the **Euclidean** distance between two points.\n\n`7.` Use the below cell to complete a function for each distance metric. Then test your functions against the built in values using the below.", "_____no_output_____" ] ], [ [ "def eucl_dist(x, y):\n \"\"\"\n INPUT\n x - an array of matching length to array y\n y - an array of matching length to array x\n OUTPUT\n euc - the euclidean distance between x and y\n \"\"\"\n return np.sqrt(np.sum((x - y) ** 2))\n\n\ndef manhat_dist(x, y):\n \"\"\"\n INPUT\n x - an array of matching length to array y\n y - an array of matching length to array x\n OUTPUT\n manhat - the manhattan distance between x and y\n \"\"\"\n return np.sum(np.abs(x - y))", "_____no_output_____" ], [ "# Test your functions\nassert h.test_eucl(play_data[\"x1\"], play_data[\"x2\"]) == eucl_dist(\n play_data[\"x1\"], play_data[\"x2\"]\n)\nassert h.test_eucl(play_data[\"x2\"], play_data[\"x3\"]) == eucl_dist(\n play_data[\"x2\"], play_data[\"x3\"]\n)\nassert h.test_manhat(play_data[\"x1\"], play_data[\"x2\"]) == manhat_dist(\n play_data[\"x1\"], play_data[\"x2\"]\n)\nassert h.test_manhat(play_data[\"x2\"], play_data[\"x3\"]) == manhat_dist(\n play_data[\"x2\"], play_data[\"x3\"]\n)", "_____no_output_____" ] ], [ [ "### Final Note\n\nIt is worth noting that two vectors could be similar by metrics like the three at the top of the notebook, while being incredibly, incredibly different by measures like these final two. Again, understanding your specific situation will assist in understanding whether your metric is approporate.", "_____no_output_____" ] ] ]
[ "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", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4afa0859fa39b989c4b247e4db2790439cda366a
40,162
ipynb
Jupyter Notebook
notebooks/reactivex.io/A Decision Tree of Observable Operators. Part I - Creation.ipynb
yutiansut/RxPY
c3bbba77f9ebd7706c949141725e220096deabd4
[ "ECL-2.0", "Apache-2.0" ]
1
2018-11-16T09:07:13.000Z
2018-11-16T09:07:13.000Z
notebooks/reactivex.io/A Decision Tree of Observable Operators. Part I - Creation.ipynb
yutiansut/RxPY
c3bbba77f9ebd7706c949141725e220096deabd4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
notebooks/reactivex.io/A Decision Tree of Observable Operators. Part I - Creation.ipynb
yutiansut/RxPY
c3bbba77f9ebd7706c949141725e220096deabd4
[ "ECL-2.0", "Apache-2.0" ]
1
2020-05-08T08:23:08.000Z
2020-05-08T08:23:08.000Z
34.414739
337
0.509113
[ [ [ "%run startup.py", "_____no_output_____" ], [ "%%javascript\n$.getScript('./assets/js/ipython_notebook_toc.js')", "_____no_output_____" ] ], [ [ "# A Decision Tree of Observable Operators\n\n## Part 1: NEW Observables.\n\n> source: http://reactivex.io/documentation/operators.html#tree. \n> (transcribed to RxPY 1.5.7, Py2.7 / 2016-12, Gunther Klessinger, [axiros](http://www.axiros.com)) \n\n**This tree can help you find the ReactiveX Observable operator you’re looking for.** \n\n<h2 id=\"tocheading\">Table of Contents</h2>\n<div id=\"toc\"></div>\n\n## Usage\n\nThere are no configured behind the scenes imports or code except [`startup.py`](./edit/startup.py), which defines output helper functions, mainly:\n\n- `rst, reset_start_time`: resets a global timer, in order to have use cases starting from 0.\n- `subs(observable)`: subscribes to an observable, printing notifications with time, thread, value\n\n\nAll other code is explicitly given in the notebook. \nSince all initialisiation of tools is in the first cell, you always have to run the first cell after ipython kernel restarts. \n**All other cells are autonmous.**\n\nIn the use case functions, in contrast to the official examples we simply use **`rand`** quite often (mapped to `randint(0, 100)`), to demonstrate when/how often observable sequences are generated and when their result is buffered for various subscribers. \n*When in doubt then run the cell again, you might have been \"lucky\" and got the same random.*\n\n### RxJS\nThe (bold printed) operator functions are linked to the [official documentation](http://reactivex.io/documentation/operators.html#tree) and created roughly analogous to the **RxJS** examples. The rest of the TOC lines links to anchors within the notebooks. \n\n### Output\nWhen the output is not in marble format we display it like so:\n\n```\nnew subscription on stream 276507289 \n\n 3.4 M [next] 1.4: {'answer': 42}\n 3.5 T1 [cmpl] 1.6: fin\n \n```\nwhere the lines are syncronously `print`ed as they happen. \"M\" and \"T1\" would be thread names (\"M\" is main thread). \nFor each use case in `reset_start_time()` (alias `rst`), a global timer is set to 0 and we show the offset to it, in *milliseconds* & with one decimal value and also the offset to the start of stream subscription. In the example 3.4, 3.5 are millis since global counter reset, while 1.4, 1.6 are offsets to start of subscription.\n", "_____no_output_____" ], [ "# I want to create a **NEW** Observable...", "_____no_output_____" ], [ "## ... that emits a particular item: **[just](http://reactivex.io/documentation/operators/just.html) **", "_____no_output_____" ] ], [ [ "reset_start_time(O.just)\nstream = O.just({'answer': rand()})\ndisposable = subs(stream)\nsleep(0.5)\ndisposable = subs(stream) # same answer\n# all stream ops work, its a real stream:\ndisposable = subs(stream.map(lambda x: x.get('answer', 0) * 2))", "\n\n========== return_value ==========\n\nmodule rx.linq.observable.returnvalue\n@extensionclassmethod(Observable, alias=\"just\")\ndef return_value(cls, value, scheduler=None):\n Returns an observable sequence that contains a single element,\n using the specified scheduler to send out observer messages.\n There is an alias called 'just'.\n\n example\n res = rx.Observable.return(42)\n res = rx.Observable.return(42, rx.Scheduler.timeout)\n\n Keyword arguments:\n value -- Single element in the resulting observable sequence.\n scheduler -- [Optional] Scheduler to send the single element on. If\n not specified, defaults to Scheduler.immediate.\n\n Returns an observable sequence containing the single specified\n element.\n--------------------------------------------------------------------------------\n\n 1.8 M New subscription on stream 273460685\n 2.8 M [next] 0.9: {'answer': 66}\n 3.3 M [cmpl] 1.5: fin\n\n 504.5 M New subscription on stream 273460685\n 505.0 M [next] 0.3: {'answer': 66}\n 505.1 M [cmpl] 0.4: fin\n\n 505.5 M New subscription on stream 272024237\n 506.3 M [next] 0.7: 132\n 506.8 M [cmpl] 1.1: fin\n" ] ], [ [ "## ..that was returned from a function *called at subscribe-time*: **[start](http://reactivex.io/documentation/operators/start.html)**", "_____no_output_____" ] ], [ [ "print('There is a little API difference to RxJS, see Remarks:\\n')\nrst(O.start)\n\ndef f():\n log('function called')\n return rand()\n\nstream = O.start(func=f)\nd = subs(stream)\nd = subs(stream)\n\nheader(\"Exceptions are handled correctly (an observable should never except):\")\n\ndef breaking_f(): \n return 1 / 0\n\nstream = O.start(func=breaking_f)\nd = subs(stream)\nd = subs(stream)\n\n\n\n# startasync: only in python3 and possibly here(?) http://www.tornadoweb.org/en/stable/concurrent.html#tornado.concurrent.Future\n#stream = O.start_async(f)\n#d = subs(stream)\n", "There is a little API difference to RxJS, see Remarks:\n\n\n\n========== start ==========\n\nmodule rx.linq.observable.start\n@extensionclassmethod(Observable)\ndef start(cls, func, scheduler=None):\n Invokes the specified function asynchronously on the specified\n scheduler, surfacing the result through an observable sequence.\n\n Example:\n res = rx.Observable.start(lambda: pprint('hello'))\n res = rx.Observable.start(lambda: pprint('hello'), rx.Scheduler.timeout)\n\n Keyword arguments:\n func -- {Function} Function to run asynchronously.\n scheduler -- {Scheduler} [Optional] Scheduler to run the function on. If\n not specified, defaults to Scheduler.timeout.\n\n Returns {Observable} An observable sequence exposing the function's\n result value, or an exception.\n\n Remarks:\n The function is called immediately, not during the subscription of the\n resulting sequence. Multiple subscriptions to the resulting sequence can\n observe the function's result.\n--------------------------------------------------------------------------------\n\n 2.7 T4 function called 3.2 M New subscription on stream 274466149\n\n 3.7 M [next] 0.4: 43\n 3.8 M [cmpl] 0.5: fin\n\n 4.7 M New subscription on stream 274466149\n 5.1 M [next] 0.2: 43\n 5.3 M [cmpl] 0.4: fin\n\n\n========== Exceptions are handled correctly (an observable should never except): ==========\n\n\n 6.9 M New subscription on stream 274466197\n 7.5 M [err ] 0.5: integer division or modulo by zero\n\n 8.4 M New subscription on stream 274466197\n 8.9 M [err ] 0.3: integer division or modulo by zero\n" ] ], [ [ "## ..that was returned from an Action, Callable, Runnable, or something of that sort, called at subscribe-time: **[from](http://reactivex.io/documentation/operators/from.html)**", "_____no_output_____" ] ], [ [ "rst(O.from_iterable)\ndef f():\n log('function called')\n return rand()\n# aliases: O.from_, O.from_list\n# 1.: From a tuple:\nstream = O.from_iterable((1,2,rand()))\nd = subs(stream)\n# d = subs(stream) # same result\n\n# 2. from a generator\ngen = (rand() for j in range(3))\nstream = O.from_iterable(gen)\nd = subs(stream)\n\n", "\n\n========== from_iterable ==========\n\nmodule rx.linq.observable.fromiterable\n@extensionclassmethod(Observable, alias=[\"from_\", \"from_list\"])\ndef from_iterable(cls, iterable, scheduler=None):\n Converts an array to an observable sequence, using an optional\n scheduler to enumerate the array.\n\n 1 - res = rx.Observable.from_iterable([1,2,3])\n 2 - res = rx.Observable.from_iterable([1,2,3], rx.Scheduler.timeout)\n\n Keyword arguments:\n :param Observable cls: Observable class\n :param Scheduler scheduler: [Optional] Scheduler to run the\n enumeration of the input sequence on.\n\n :returns: The observable sequence whose elements are pulled from the\n given iterable sequence.\n :rtype: Observable\n--------------------------------------------------------------------------------\n\n 3.3 M New subscription on stream 274466081\n 3.8 M [next] 0.4: 1\n 4.1 M [next] 0.7: 2\n 4.6 M [next] 1.1: 95\n 4.8 M [cmpl] 1.4: fin\n\n 5.4 M New subscription on stream 274466125\n 5.6 M [next] 0.2: 29\n 6.0 M [next] 0.6: 29\n 6.2 M [next] 0.8: 15\n 6.3 M [cmpl] 0.9: fin\n" ], [ "rst(O.from_callback)\n# in my words: In the on_next of the subscriber you'll have the original arguments,\n# potentially objects, e.g. user original http requests.\n# i.e. you could merge those with the result stream of a backend call to\n# a webservice or db and send the request.response back to the user then.\n\ndef g(f, a, b):\n f(a, b)\n log('called f')\nstream = O.from_callback(lambda a, b, f: g(f, a, b))('fu', 'bar')\nd = subs(stream.delay(200))\n# d = subs(stream.delay(200)) # does NOT work\n", "\n\n========== from_callback ==========\n\nmodule rx.linq.observable.fromcallback\n@extensionclassmethod(Observable)\ndef from_callback(cls, func, mapper=None):\n Converts a callback function to an observable sequence.\n\n Keyword arguments:\n func -- {Function} Function with a callback as the last parameter to\n convert to an Observable sequence.\n mapper -- {Function} [Optional] A mapper which takes the arguments\n from the callback to produce a single item to yield on next.\n\n Returns {Function} A function, when executed with the required\n parameters minus the callback, produces an Observable sequence with a\n single value of the arguments to the callback as a list.\n--------------------------------------------------------------------------------\n\n 4.6 M New subscription on stream 272024249\n 5.9 M called f\n" ] ], [ [ "## ...after a specified delay: **[timer](http://reactivex.io/documentation/operators/timer.html)**", "_____no_output_____" ] ], [ [ "rst()\n# start a stream of 0, 1, 2, .. after 200 ms, with a delay of 100 ms:\nstream = O.timer(200, 100).time_interval()\\\n .map(lambda x: 'val:%s dt:%s' % (x.value, x.interval))\\\n .take(3)\nd = subs(stream, name='observer1')\n# intermix directly with another one\nd = subs(stream, name='observer2')", "\n 0.8 M New subscription on stream 274470005\n\n 3.4 M New subscription on stream 274470005\n" ] ], [ [ "## ...that emits a sequence of items repeatedly: **[repeat](http://reactivex.io/documentation/operators/repeat.html) **", "_____no_output_____" ] ], [ [ "rst(O.repeat)\n# repeat is over *values*, not function calls. Use generate or create for function calls!\nsubs(O.repeat({'rand': time.time()}, 3))\n\nheader('do while:')\nl = []\ndef condition(x):\n l.append(1)\n return True if len(l) < 2 else False\nstream = O.just(42).do_while(condition)\nd = subs(stream)\n\n", "\n\n========== repeat ==========\n\nmodule rx.linq.observable.repeat\n@extensionclassmethod(Observable)\ndef repeat(cls, value=None, repeat_count=None, scheduler=None):\n Generates an observable sequence that repeats the given element the\n specified number of times, using the specified scheduler to send out\n observer messages.\n\n 1 - res = rx.Observable.repeat(42)\n 2 - res = rx.Observable.repeat(42, 4)\n 3 - res = rx.Observable.repeat(42, 4, Rx.Scheduler.timeout)\n 4 - res = rx.Observable.repeat(42, None, Rx.Scheduler.timeout)\n\n Keyword arguments:\n value -- Element to repeat.\n repeat_count -- [Optional] Number of times to repeat the element. If not\n specified, repeats indefinitely.\n scheduler -- Scheduler to run the producer loop on. If not specified,\n defaults to ImmediateScheduler.\n\n Returns an observable sequence that repeats the given element the\n specified number of times.\n--------------------------------------------------------------------------------\n\n 2.0 M New subscription on stream 274473961\n 2.9 M [next] 0.9: {'rand': 1482335562.344726}\n 4.5 M [next] 2.4: {'rand': 1482335562.344726}\n 5.1 M [next] 3.0: {'rand': 1482335562.344726}\n 5.2 M [cmpl] 3.1: fin\n\n\n========== do while: ==========\n\n\n 6.8 M New subscription on stream 273460681\n 7.5 M [next] 0.5: 42\n 8.7 M [next] 1.7: 42\n 9.2 M [cmpl] 2.2: fin\n" ] ], [ [ "## ...from scratch, with custom logic and cleanup (calling a function again and again): **[create](http://reactivex.io/documentation/operators/create.html) **", "_____no_output_____" ] ], [ [ "rx = O.create\nrst(rx)\n\ndef f(obs):\n # this function is called for every observer\n obs.on_next(rand())\n obs.on_next(rand())\n obs.on_completed()\n def cleanup():\n log('cleaning up...')\n return cleanup\nstream = O.create(f).delay(200) # the delay causes the cleanup called before the subs gets the vals\nd = subs(stream)\nd = subs(stream)\n\n\n\n\nsleep(0.5)\nrst(title='Exceptions are handled nicely')\nl = []\ndef excepting_f(obs):\n for i in range(3):\n l.append(1)\n obs.on_next('%s %s (observer hash: %s)' % (i, 1. / (3 - len(l)), hash(obs) ))\n obs.on_completed()\n\nstream = O.create(excepting_f)\nd = subs(stream)\nd = subs(stream)\n\n\n\n\nrst(title='Feature or Bug?')\nprint('(where are the first two values?)')\nl = []\ndef excepting_f(obs):\n for i in range(3):\n l.append(1)\n obs.on_next('%s %s (observer hash: %s)' % (i, 1. / (3 - len(l)), hash(obs) ))\n obs.on_completed()\n\nstream = O.create(excepting_f).delay(100)\nd = subs(stream)\nd = subs(stream)\n# I think its an (amazing) feature, preventing to process functions results of later(!) failing functions\n", "\n\n========== create ==========\n\nmodule rx.linq.observable.create\n@extensionclassmethod(Observable, alias=\"create\")\ndef create(cls, subscribe):\n n.a.\n--------------------------------------------------------------------------------\n\n 2.4 M New subscription on stream 273454757\n 3.9 M cleaning up...\n\n 4.5 M New subscription on stream 273454757\n 5.8 M cleaning up...\n 131.3 T6 [next] 202.3: ['fu', 'bar']\n 131.7 T6 [cmpl] 202.7: fin\n 142.0 T7 [next] 202.4: val:0 dt:0:00:00.202066 (observer1)\n 144.0 T8 [next] 201.8: val:0 dt:0:00:00.201505 (observer2)\n 208.2 T9 [next] 205.7: 59\n 208.8 T9 [next] 206.3: 68\n 209.2 T9 [cmpl] 206.7: fin\n 209.6 T10 [next] 204.9: 84\n 210.0 T10 [next] 205.3: 79\n 210.2 T10 [cmpl] 205.4: fin\n 246.3 T12 [next] 304.1: val:1 dt:0:00:00.102253 (observer2)\n 247.0 T11 [next] 307.4: val:1 dt:0:00:00.104979 (observer1)\n 345.7 T14 [next] 406.1: val:2 dt:0:00:00.098724 (observer1)\n 346.0 T14 [cmpl] 406.4: fin (observer1)\n 348.3 T13 [next] 406.2: val:2 dt:0:00:00.102073 (observer2)\n 348.5 T13 [cmpl] 406.3: fin (observer2)\n" ], [ "rx = O.generate\nrst(rx)\n\"\"\"The basic form of generate takes four parameters:\n\nthe first item to emit\na function to test an item to determine whether to emit it (true) or terminate the Observable (false)\na function to generate the next item to test and emit based on the value of the previous item\na function to transform items before emitting them\n\"\"\"\ndef generator_based_on_previous(x): return x + 1.1\ndef doubler(x): return 2 * x\nd = subs(rx(0, lambda x: x < 4, generator_based_on_previous, doubler))", "\n\n========== generate ==========\n\nmodule rx.linq.observable.generate\n@extensionclassmethod(Observable)\ndef generate(cls, initial_state, condition, iterate, result_mapper, scheduler=None):\n Generates an observable sequence by running a state-driven loop\n producing the sequence's elements, using the specified scheduler to\n send out observer messages.\n\n 1 - res = rx.Observable.generate(0,\n lambda x: x < 10,\n lambda x: x + 1,\n lambda x: x)\n 2 - res = rx.Observable.generate(0,\n lambda x: x < 10,\n lambda x: x + 1,\n lambda x: x,\n Rx.Scheduler.timeout)\n\n Keyword arguments:\n initial_state -- Initial state.\n condition -- Condition to terminate generation (upon returning False).\n iterate -- Iteration step function.\n result_mapper -- Selector function for results produced in the\n sequence.\n scheduler -- [Optional] Scheduler on which to run the generator loop.\n If not provided, defaults to CurrentThreadScheduler.\n\n Returns the generated sequence.\n--------------------------------------------------------------------------------\n\n 4.8 M New subscription on stream 274475993\n 5.7 M [next] 0.7: 0\n 6.4 M [next] 1.4: 2.2\n 6.6 M [next] 1.6: 4.4\n 7.1 M [next] 2.1: 6.6\n 7.3 M [cmpl] 2.3: fin\n" ], [ "rx = O.generate_with_relative_time\nrst(rx)\nstream = rx(1, lambda x: x < 4, lambda x: x + 1, lambda x: x, lambda t: 100)\nd = subs(stream)\n", "\n\n========== generate_with_relative_time ==========\n\nmodule rx.linq.observable.generatewithrelativetime\n@extensionclassmethod(Observable)\ndef generate_with_relative_time(cls, initial_state, condition, iterate,\n Generates an observable sequence by iterating a state from an\n initial state until the condition fails.\n\n res = source.generate_with_relative_time(0,\n lambda x: True,\n lambda x: x + 1,\n lambda x: x,\n lambda x: 500)\n\n initial_state -- Initial state.\n condition -- Condition to terminate generation (upon returning false).\n iterate -- Iteration step function.\n result_mapper -- Selector function for results produced in the\n sequence.\n time_mapper -- Time mapper function to control the speed of values\n being produced each iteration, returning integer values denoting\n milliseconds.\n scheduler -- [Optional] Scheduler on which to run the generator loop.\n If not specified, the timeout scheduler is used.\n\n Returns the generated sequence.\n--------------------------------------------------------------------------------\n\n 4.7 M New subscription on stream 274475933\n" ] ], [ [ "## ...for each observer that subscribes OR according to a condition at subscription time: **[defer / if_then](http://reactivex.io/documentation/operators/defer.html) **", "_____no_output_____" ] ], [ [ "rst(O.defer)\n# plural! (unique per subscription)\nstreams = O.defer(lambda: O.just(rand()))\nd = subs(streams)\nd = subs(streams) # gets other values - created by subscription!", "\n\n========== defer ==========\n\nmodule rx.linq.observable.defer\n@extensionclassmethod(Observable)\ndef defer(cls, observable_factory):\n Returns an observable sequence that invokes the specified factory\n function whenever a new observer subscribes.\n\n Example:\n 1 - res = rx.Observable.defer(lambda: rx.Observable.from_([1,2,3]))\n\n Keyword arguments:\n :param types.FunctionType observable_factory: Observable factory function\n to invoke for each observer that subscribes to the resulting sequence.\n\n :returns: An observable sequence whose observers trigger an invocation\n of the given observable factory function.\n :rtype: Observable\n--------------------------------------------------------------------------------\n\n 2.7 M New subscription on stream 274475969\n 3.4 M [next] 0.6: 38\n 3.5 M [cmpl] 0.7: fin\n\n 4.4 M New subscription on stream 274475969\n 4.9 M [next] 0.4: 77\n 5.2 M [cmpl] 0.7: fin\n" ], [ "# evaluating a condition at subscription time in order to decide which of two streams to take.\nrst(O.if_then)\ncond = True\ndef should_run():\n return cond\nstreams = O.if_then(should_run, O.return_value(43), O.return_value(56))\nd = subs(streams)\n\nlog('condition will now evaluate falsy:')\ncond = False\nstreams = O.if_then(should_run, O.return_value(43), O.return_value(rand()))\nd = subs(streams)\nd = subs(streams)", "\n\n========== if_then ==========\n\nmodule rx.linq.observable.ifthen\n@extensionclassmethod(Observable)\ndef if_then(cls, condition, then_source, else_source=None, scheduler=None):\n Determines whether an observable collection contains values.\n\n Example:\n 1 - res = rx.Observable.if(condition, obs1)\n 2 - res = rx.Observable.if(condition, obs1, obs2)\n 3 - res = rx.Observable.if(condition, obs1, scheduler=scheduler)\n\n Keyword parameters:\n condition -- {Function} The condition which determines if the\n then_source or else_source will be run.\n then_source -- {Observable} The observable sequence or Promise that\n will be run if the condition function returns true.\n else_source -- {Observable} [Optional] The observable sequence or\n Promise that will be run if the condition function returns False.\n If this is not provided, it defaults to rx.Observable.empty\n scheduler -- [Optional] Scheduler to use.\n\n Returns an observable {Observable} sequence which is either the\n then_source or else_source.\n--------------------------------------------------------------------------------\n\n 3.3 M New subscription on stream 274480673\n 3.6 M [next] 0.2: 43\n 3.8 M [cmpl] 0.5: fin\n 4.0 M condition will now evaluate falsy:\n\n 4.4 M New subscription on stream 274480817\n 4.6 M [next] 0.2: 52\n 4.7 M [cmpl] 0.3: fin\n\n 5.2 M New subscription on stream 274480817\n 5.6 M [next] 0.2: 52\n 5.8 M [cmpl] 0.4: fin\n" ] ], [ [ "## ...that emits a sequence of integers: **[range](http://reactivex.io/documentation/operators/range.html) **", "_____no_output_____" ] ], [ [ "rst(O.range)\nd = subs(O.range(0, 3))", "\n\n========== range ==========\n\nmodule rx.linq.observable.range\n@extensionclassmethod(Observable)\ndef range(cls, start, count, scheduler=None):\n Generates an observable sequence of integral numbers within a\n specified range, using the specified scheduler to send out observer\n messages.\n\n 1 - res = Rx.Observable.range(0, 10)\n 2 - res = Rx.Observable.range(0, 10, rx.Scheduler.timeout)\n\n Keyword arguments:\n start -- The value of the first integer in the sequence.\n count -- The number of sequential integers to generate.\n scheduler -- [Optional] Scheduler to run the generator loop on. If not\n specified, defaults to Scheduler.current_thread.\n\n Returns an observable sequence that contains a range of sequential\n integral numbers.\n--------------------------------------------------------------------------------\n\n 2.9 M New subscription on stream 274475905\n 3.7 M [next] 0.4: 0\n 4.3 M [next] 1.0: 1\n 4.6 M [next] 1.3: 2\n 4.9 M [cmpl] 1.6: fin\n" ] ], [ [ "### ...at particular intervals of time: **[interval](http://reactivex.io/documentation/operators/interval.html) **\n\n(you can `.publish()` it to get an easy \"hot\" observable)", "_____no_output_____" ] ], [ [ "rst(O.interval)\nd = subs(O.interval(100).time_interval()\\\n .map(lambda x, v: '%(interval)s %(value)s' \\\n % ItemGetter(x)).take(3))", "\n\n========== interval ==========\n\nmodule rx.linq.observable.interval\n@extensionclassmethod(Observable)\ndef interval(cls, period, scheduler=None):\n Returns an observable sequence that produces a value after each\n period.\n\n Example:\n 1 - res = rx.Observable.interval(1000)\n 2 - res = rx.Observable.interval(1000, rx.Scheduler.timeout)\n\n Keyword arguments:\n period -- Period for producing the values in the resulting sequence\n (specified as an integer denoting milliseconds).\n scheduler -- [Optional] Scheduler to run the timer on. If not specified,\n rx.Scheduler.timeout is used.\n\n Returns an observable sequence that produces a value after each period.\n--------------------------------------------------------------------------------\n\n 1.2 M New subscription (14365) on stream 276610125\n 102.3 T8 [next] 100.9: 0:00:00.100623 0 -> 14365\n 208.2 T9 [next] 206.9: 0:00:00.105960 1 -> 14365\n 310.8 T10 [next] 309.5: 0:00:00.102625 2 -> 14365\n 311.1 T10 [cmpl] 309.8: fin -> 14365\n" ] ], [ [ "### ...after a specified delay (see timer)", "_____no_output_____" ], [ "## ...that completes without emitting items: **[empty](http://reactivex.io/documentation/operators/empty-never-throw.html) **", "_____no_output_____" ] ], [ [ "rst(O.empty)\nd = subs(O.empty())", "\n\n========== empty ==========\n\nmodule rx.linq.observable.empty\n@extensionclassmethod(Observable)\ndef empty(cls, scheduler=None):\n Returns an empty observable sequence, using the specified scheduler\n to send out the single OnCompleted message.\n\n 1 - res = rx.Observable.empty()\n 2 - res = rx.Observable.empty(rx.Scheduler.timeout)\n\n scheduler -- Scheduler to send the termination call on.\n\n Returns an observable sequence with no elements.\n--------------------------------------------------------------------------------\n\n 2.9 M New subscription on stream 273460593\n 3.2 M [cmpl] 0.2: fin\n" ] ], [ [ "## ...that does nothing at all: **[never](http://reactivex.io/documentation/operators/empty-never-throw.html) **", "_____no_output_____" ] ], [ [ "rst(O.never)\nd = subs(O.never())", "\n\n========== never ==========\n\n 0.7 T18 [next] 104.4: 0 -1.0 (observer hash: 274473797)\n 1.1 T18 [next] 104.8: 1 -0.5 (observer hash: 274473797)module rx.linq.observable.never\n@extensionclassmethod(Observable)\ndef never(cls):\n Returns a non-terminating observable sequence, which can be used to\n denote an infinite duration (e.g. when using reactive joins).\n\n Returns an observable sequence whose observers will never get called.\n--------------------------------------------------------------------------------\n\n 2.0 T18 [next] 105.7: 2 -0.333333333333 (observer hash: 274473797)\n\n 2.1 T18 [cmpl] 105.9: fin 2.7 M New subscription on stream 274473849\n\n" ] ], [ [ "## ...that excepts: **[throw](http://reactivex.io/documentation/operators/empty-never-throw.html) **", "_____no_output_____" ] ], [ [ "rst(O.on_error)\nd = subs(O.on_error(ZeroDivisionError))", "\n\n========== throw ==========\n\nmodule rx.linq.observable.throw\n@extensionclassmethod(Observable, alias=\"throw_exception\")\ndef on_error(cls, exception, scheduler=None):\n Returns an observable sequence that terminates with an exception,\n using the specified scheduler to send out the single OnError message.\n\n 1 - res = rx.Observable.throw(Exception('Error'))\n 2 - res = rx.Observable.throw(Exception('Error'),\n rx.Scheduler.timeout)\n\n Keyword arguments:\n exception -- An object used for the sequence's termination.\n scheduler -- Scheduler to send the exceptional termination call on. If\n not specified, defaults to ImmediateScheduler.\n\n Returns the observable sequence that terminates exceptionally with the\n specified exception object.\n--------------------------------------------------------------------------------\n\n 1.8 M New subscription (23467) on stream 276521733\n 2.0 M [err ] 0.2: <type 'exceptions.ZeroDivisionError'> -> 23467\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", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4afa09ae7a16f344f08824ff490819ef5b2c6a38
269,191
ipynb
Jupyter Notebook
extern/face_expression/face_expression/third_party/face_mesh_mediapipe/playground.ipynb
wangxihao/rgbd-kinect-pose
03180723c99759ba2500bcd42b5fe7a1d26eb507
[ "MIT" ]
1
2022-02-07T06:12:26.000Z
2022-02-07T06:12:26.000Z
extern/face_expression/face_expression/third_party/face_mesh_mediapipe/playground.ipynb
wangxihao/rgbd-kinect-pose
03180723c99759ba2500bcd42b5fe7a1d26eb507
[ "MIT" ]
null
null
null
extern/face_expression/face_expression/third_party/face_mesh_mediapipe/playground.ipynb
wangxihao/rgbd-kinect-pose
03180723c99759ba2500bcd42b5fe7a1d26eb507
[ "MIT" ]
null
null
null
712.145503
55,368
0.951934
[ [ [ "%load_ext autoreload\n%autoreload 2", "_____no_output_____" ], [ "# ffmpeg -y -i ../../tmp/karim.MOV ../../tmp/karim/frame_%06d.jpg\n# ffmpeg -y -framerate 25 -i ../../tmp/karim_result/frame_%06d.jpg -c:v libx264 -vf fps=25 -pix_fmt yuv420p ../../tmp/karim_result.mp4", "_____no_output_____" ], [ "import numpy as np\nimport csv\nimport tensorflow as tf\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nimport os\nimport shutil\nimport glob\nfrom tqdm import tqdm\n\nfrom face_mesh_mediapipe import FaceMeshMediaPipe", "_____no_output_____" ], [ "anchors_path = \"./models/face_anchors.csv\"\ndetection_model_path = \"./models/face_detection_front.tflite\"\nlandmark_model_path = \"./models/face_landmark.tflite\"\n\nfacemesh_model = FaceMeshMediaPipe(anchors_path, detection_model_path, landmark_model_path)", "_____no_output_____" ], [ "frame_dir = \"../../tmp/karim\"\nresult_dir = \"../../tmp/karim_result\"\nframe_names = sorted(os.listdir(frame_dir))[::50]\n\nshutil.rmtree(result_dir, ignore_errors=True)\nos.makedirs(result_dir, exist_ok=True)\n\nfor frame_name in tqdm(frame_names):\n frame_path = os.path.join(frame_dir, frame_name)\n \n image = cv2.cvtColor(cv2.imread(frame_path), cv2.COLOR_BGR2RGB)\n keypoints_3d, keypoints_3d_normed = facemesh_model(image)\n if keypoints_3d is None:\n keypoints_3d = np.zeros((468, 3))\n \n canvas = image.copy()\n for point in keypoints_3d[:, :2]:\n x, y = int(point[0]), int(point[1])\n canvas = cv2.circle(canvas, (x, y), 2, (0, 0, 255), -1)\n \n print(keypoints_3d[:, 2].min(), keypoints_3d[:, 2].max(), keypoints_3d[:, 2].mean())\n plt.imshow(canvas)\n plt.show()\n \n # save\n cv2.imwrite(os.path.join(result_dir, frame_name), cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))", "\r 0%| | 0/5 [00:00<?, ?it/s]" ], [ "# image = cv2.cvtColor(cv2.imread(\"./images/olya.png\"), cv2.COLOR_BGR2RGB)\n# image = cv2.cvtColor(cv2.imread(\"./images/olya_rot.jpg\"), cv2.COLOR_BGR2RGB)\nimage = cv2.cvtColor(cv2.imread(\"./images/olya_rot_sq.jpg\"), cv2.COLOR_BGR2RGB)\n\nkeypoints_2d = facemesh_model(image)\n\n# plt.imshow(image_pad)\nplt.imshow(image)\nplt.scatter(keypoints_2d[:, 0], keypoints_2d[:, 1])", "_____no_output_____" ], [ "!cat /proc/cpuinfo | grep 'model name' | uniq", "_____no_output_____" ], [ "\n\nplt.imshow(image_pad)\nplt.scatter(keypoints_2d_transformed[:, 0], keypoints_2d_transformed[:, 1])", "_____no_output_____" ], [ "pad", "_____no_output_____" ], [ "keypoints_2d.shape, transformation_matrix_inv.shape", "_____no_output_____" ], [ "cv2.warpPerspective(\n image_norm, transformation_matrix, tuple(self.landmark_input_shape)\n )", "_____no_output_____" ], [ "import time", "_____no_output_____" ], [ "start_time = time.time()", "_____no_output_____" ], [ "elapsed_time = time.time() - start_time", "_____no_output_____" ], [ "elapsed_time", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4afa19c8fe4cdc537e81b6dcf8d8986c56eb62f2
61,095
ipynb
Jupyter Notebook
pandas/intro_to_pandas.ipynb
kirbiyik/human-learning
2ff9aed3b441c9db30c5487cdabfff404f0ca5a5
[ "MIT" ]
1
2018-08-06T12:33:40.000Z
2018-08-06T12:33:40.000Z
pandas/intro_to_pandas.ipynb
kirbiyik/human-learning
2ff9aed3b441c9db30c5487cdabfff404f0ca5a5
[ "MIT" ]
null
null
null
pandas/intro_to_pandas.ipynb
kirbiyik/human-learning
2ff9aed3b441c9db30c5487cdabfff404f0ca5a5
[ "MIT" ]
null
null
null
32.584
8,708
0.50505
[ [ [ "#### Copyright 2017 Google LLC.", "_____no_output_____" ] ], [ [ "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "# Quick Introduction to pandas", "_____no_output_____" ], [ "**Learning Objectives:**\n * Gain an introduction to the `DataFrame` and `Series` data structures of the *pandas* library\n * Access and manipulate data within a `DataFrame` and `Series`\n * Import CSV data into a *pandas* `DataFrame`\n * Reindex a `DataFrame` to shuffle data", "_____no_output_____" ], [ "[*pandas*](http://pandas.pydata.org/) is a column-oriented data analysis API. It's a great tool for handling and analyzing input data, and many ML frameworks support *pandas* data structures as inputs.\nAlthough a comprehensive introduction to the *pandas* API would span many pages, the core concepts are fairly straightforward, and we'll present them below. For a more complete reference, the [*pandas* docs site](http://pandas.pydata.org/pandas-docs/stable/index.html) contains extensive documentation and many tutorials.", "_____no_output_____" ], [ "## Basic Concepts\n\nThe following line imports the *pandas* API and prints the API version:", "_____no_output_____" ] ], [ [ "import pandas as pd\npd.__version__", "_____no_output_____" ] ], [ [ "The primary data structures in *pandas* are implemented as two classes:\n\n * **`DataFrame`**, which you can imagine as a relational data table, with rows and named columns.\n * **`Series`**, which is a single column. A `DataFrame` contains one or more `Series` and a name for each `Series`.\n\nThe data frame is a commonly used abstraction for data manipulation. Similar implementations exist in [Spark](https://spark.apache.org/) and [R](https://www.r-project.org/about.html).", "_____no_output_____" ], [ "One way to create a `Series` is to construct a `Series` object. For example:", "_____no_output_____" ] ], [ [ "pd.Series(['San Francisco', 'San Jose', 'Sacramento'])", "_____no_output_____" ] ], [ [ "`DataFrame` objects can be created by passing a `dict` mapping `string` column names to their respective `Series`. If the `Series` don't match in length, missing values are filled with special [NA/NaN](http://pandas.pydata.org/pandas-docs/stable/missing_data.html) values. Example:", "_____no_output_____" ] ], [ [ "city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento'])\npopulation = pd.Series([852469, 1015785, 485199])\n\npd.DataFrame({ 'City name': city_names, 'Population': population })", "_____no_output_____" ] ], [ [ "But most of the time, you load an entire file into a `DataFrame`. The following example loads a file with California housing data. Run the following cell to load the data and create feature definitions:", "_____no_output_____" ] ], [ [ "california_housing_dataframe = pd.read_csv(\"https://storage.googleapis.com/mledu-datasets/california_housing_train.csv\", sep=\",\")\ncalifornia_housing_dataframe.describe()", "_____no_output_____" ] ], [ [ "The example above used `DataFrame.describe` to show interesting statistics about a `DataFrame`. Another useful function is `DataFrame.head`, which displays the first few records of a `DataFrame`:", "_____no_output_____" ] ], [ [ "california_housing_dataframe.head()", "_____no_output_____" ] ], [ [ "Another powerful feature of *pandas* is graphing. For example, `DataFrame.hist` lets you quickly study the distribution of values in a column:", "_____no_output_____" ] ], [ [ "california_housing_dataframe.hist('housing_median_age')", "_____no_output_____" ] ], [ [ "## Accessing Data\n\nYou can access `DataFrame` data using familiar Python dict/list operations:", "_____no_output_____" ] ], [ [ "cities = pd.DataFrame({ 'City name': city_names, 'Population': population })\nprint(type(cities['City name']))\ncities['City name']", "<class 'pandas.core.series.Series'>\n" ], [ "print(type(cities['City name'][1]))\ncities['City name'][1]", "<class 'str'>\n" ], [ "print(type(cities[0:2]))\ncities[0:2]", "<class 'pandas.core.frame.DataFrame'>\n" ] ], [ [ "In addition, *pandas* provides an extremely rich API for advanced [indexing and selection](http://pandas.pydata.org/pandas-docs/stable/indexing.html) that is too extensive to be covered here.", "_____no_output_____" ], [ "## Manipulating Data\n\nYou may apply Python's basic arithmetic operations to `Series`. For example:", "_____no_output_____" ] ], [ [ "population / 1000.", "_____no_output_____" ] ], [ [ "[NumPy](http://www.numpy.org/) is a popular toolkit for scientific computing. *pandas* `Series` can be used as arguments to most NumPy functions:", "_____no_output_____" ] ], [ [ "import numpy as np\n\nnp.log(population)", "_____no_output_____" ] ], [ [ "For more complex single-column transformations, you can use `Series.apply`. Like the Python [map function](https://docs.python.org/2/library/functions.html#map), \n`Series.apply` accepts as an argument a [lambda function](https://docs.python.org/2/tutorial/controlflow.html#lambda-expressions), which is applied to each value.\n\nThe example below creates a new `Series` that indicates whether `population` is over one million:", "_____no_output_____" ] ], [ [ "population.apply(lambda val: val > 1000000)", "_____no_output_____" ] ], [ [ "\nModifying `DataFrames` is also straightforward. For example, the following code adds two `Series` to an existing `DataFrame`:", "_____no_output_____" ] ], [ [ "cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92])\ncities['Population density'] = cities['Population'] / cities['Area square miles']\ncities", "_____no_output_____" ] ], [ [ "## Exercise #1\n\nModify the `cities` table by adding a new boolean column that is True if and only if *both* of the following are True:\n\n * The city is named after a saint.\n * The city has an area greater than 50 square miles.\n\n**Note:** Boolean `Series` are combined using the bitwise, rather than the traditional boolean, operators. For example, when performing *logical and*, use `&` instead of `and`.\n\n**Hint:** \"San\" in Spanish means \"saint.\"", "_____no_output_____" ] ], [ [ "cities['check'] = cities['City name'].apply(lambda x: x[:3]=='San') & \\\n cities['Area square miles'].apply(lambda x: x > 50)\ncities\n", "_____no_output_____" ] ], [ [ "### Solution\n\nClick below for a solution.", "_____no_output_____" ] ], [ [ "cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San'))\ncities", "_____no_output_____" ] ], [ [ "## Indexes\nBoth `Series` and `DataFrame` objects also define an `index` property that assigns an identifier value to each `Series` item or `DataFrame` row. \n\nBy default, at construction, *pandas* assigns index values that reflect the ordering of the source data. Once created, the index values are stable; that is, they do not change when data is reordered.", "_____no_output_____" ] ], [ [ "city_names.index", "_____no_output_____" ], [ "cities.index", "_____no_output_____" ] ], [ [ "Call `DataFrame.reindex` to manually reorder the rows. For example, the following has the same effect as sorting by city name:", "_____no_output_____" ] ], [ [ "cities.reindex([2, 0, 1])", "_____no_output_____" ] ], [ [ "Reindexing is a great way to shuffle (randomize) a `DataFrame`. In the example below, we take the index, which is array-like, and pass it to NumPy's `random.permutation` function, which shuffles its values in place. Calling `reindex` with this shuffled array causes the `DataFrame` rows to be shuffled in the same way.\nTry running the following cell multiple times!", "_____no_output_____" ] ], [ [ "cities.reindex(np.random.permutation(cities.index))", "_____no_output_____" ] ], [ [ "For more information, see the [Index documentation](http://pandas.pydata.org/pandas-docs/stable/indexing.html#index-objects).", "_____no_output_____" ], [ "## Exercise #2\n\nThe `reindex` method allows index values that are not in the original `DataFrame`'s index values. Try it and see what happens if you use such values! Why do you think this is allowed?", "_____no_output_____" ] ], [ [ "cities.reindex([2, -1, 8])", "_____no_output_____" ] ], [ [ "### Solution\n\nClick below for the solution.", "_____no_output_____" ], [ "If your `reindex` input array includes values not in the original `DataFrame` index values, `reindex` will add new rows for these \"missing\" indices and populate all corresponding columns with `NaN` values:", "_____no_output_____" ] ], [ [ "cities.reindex([0, 4, 5, 2])", "_____no_output_____" ] ], [ [ "This behavior is desirable because indexes are often strings pulled from the actual data (see the [*pandas* reindex\ndocumentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html) for an example\nin which the index values are browser names).\n\nIn this case, allowing \"missing\" indices makes it easy to reindex using an external list, as you don't have to worry about\nsanitizing the input.", "_____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" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4afa1b9c60b82a374760b11b4c4503597e51ad4f
526,718
ipynb
Jupyter Notebook
notebooks/intro_deep_learning/3.2_feature_extraction.ipynb
ronaldobernardi/special_topics_class
ca79453c2962bcb66f7d80b80b42e3dbc71ab624
[ "Apache-2.0" ]
null
null
null
notebooks/intro_deep_learning/3.2_feature_extraction.ipynb
ronaldobernardi/special_topics_class
ca79453c2962bcb66f7d80b80b42e3dbc71ab624
[ "Apache-2.0" ]
null
null
null
notebooks/intro_deep_learning/3.2_feature_extraction.ipynb
ronaldobernardi/special_topics_class
ca79453c2962bcb66f7d80b80b42e3dbc71ab624
[ "Apache-2.0" ]
null
null
null
633.836342
150,460
0.942928
[ [ [ "## Special Topics - Introduction to Deep Learning\n\n#### Prof. Thomas da Silva Paula", "_____no_output_____" ], [ "### Feature extraction example\n\n* Using Keras\n* Using VGG-16", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg16 import preprocess_input\n\nplt.rcParams['figure.figsize'] = [15, 5]", "_____no_output_____" ] ], [ [ "## Creating the model", "_____no_output_____" ] ], [ [ "model = VGG16(weights='imagenet', include_top=False, pooling='avg', input_shape=(224, 224, 3))", "WARNING:tensorflow:From /home/thomas/.envs/py3/lib/python3.6/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" ], [ "model.summary()", "_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) (None, 224, 224, 3) 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n_________________________________________________________________\nglobal_average_pooling2d_1 ( (None, 512) 0 \n=================================================================\nTotal params: 14,714,688\nTrainable params: 14,714,688\nNon-trainable params: 0\n_________________________________________________________________\n" ] ], [ [ "### Feature extraction example", "_____no_output_____" ] ], [ [ "img_path = '../../sample_images/sneakers.png'\nimg = image.load_img(img_path, target_size=(224, 224))\nplt.imshow(img)", "_____no_output_____" ] ], [ [ "We need to prepare the image using the same preprocessing steps used to train the model. Fortunetly, Keras has methods to help us out.", "_____no_output_____" ] ], [ [ "x = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx = preprocess_input(x)\n\nfeatures = model.predict(x)", "_____no_output_____" ] ], [ [ "Checking shape and type", "_____no_output_____" ] ], [ [ "print(features.shape, features.dtype)", "(1, 512) float32\n" ] ], [ [ "Printing features", "_____no_output_____" ] ], [ [ "from pprint import pprint", "_____no_output_____" ], [ "pprint(features)", "array([[0.0000000e+00, 6.0639971e-01, 1.2241087e+00, 0.0000000e+00,\n 7.6285583e-01, 9.3353331e-01, 4.7094667e-01, 0.0000000e+00,\n 0.0000000e+00, 1.9924963e+01, 1.4466014e+00, 0.0000000e+00,\n 1.2180121e+00, 0.0000000e+00, 0.0000000e+00, 1.6389935e+01,\n 1.7182510e-01, 2.0266817e+00, 0.0000000e+00, 6.7011623e+00,\n 0.0000000e+00, 2.8219001e+00, 1.4962605e-01, 2.9597852e+00,\n 0.0000000e+00, 2.5504065e-01, 1.6535183e+00, 3.8728275e+00,\n 0.0000000e+00, 6.0658491e-01, 0.0000000e+00, 0.0000000e+00,\n 3.1740711e+00, 3.3034900e-01, 0.0000000e+00, 2.9369137e-01,\n 0.0000000e+00, 8.2455468e-01, 1.0085965e-01, 0.0000000e+00,\n 3.1839323e+00, 1.7112944e+01, 7.4131870e-01, 9.6320772e-01,\n 5.1401488e-02, 4.0519438e+00, 6.6801023e+00, 1.3918856e+01,\n 4.2468858e+00, 8.6180413e-01, 3.4711781e+00, 5.6451054e+00,\n 1.0152748e+01, 1.5829812e+00, 0.0000000e+00, 3.6567924e+00,\n 5.9682503e+00, 6.8307206e-02, 7.6533681e-01, 1.1373340e+00,\n 0.0000000e+00, 4.6766024e+00, 3.4389660e-01, 0.0000000e+00,\n 0.0000000e+00, 2.8509095e+00, 5.4107890e+00, 4.1712832e+00,\n 0.0000000e+00, 0.0000000e+00, 0.0000000e+00, 3.5100007e+00,\n 1.7826376e+00, 0.0000000e+00, 4.2363667e-01, 1.2573874e+00,\n 0.0000000e+00, 5.4925001e-01, 5.1038927e-01, 0.0000000e+00,\n 0.0000000e+00, 1.9681660e+00, 3.9911082e+00, 7.7583280e+00,\n 0.0000000e+00, 3.2026155e+00, 1.8421052e-01, 0.0000000e+00,\n 3.1603971e+00, 0.0000000e+00, 0.0000000e+00, 8.0792093e-01,\n 0.0000000e+00, 1.5015146e+00, 9.9417818e-01, 3.5476735e+00,\n 9.3484182e+00, 5.9968624e+00, 4.1852822e+00, 5.0409989e+00,\n 0.0000000e+00, 2.2600448e-01, 9.0468031e-01, 3.8086047e+00,\n 2.3084729e+00, 7.2678800e+00, 3.5115275e+00, 5.8744888e+00,\n 1.0973458e+00, 0.0000000e+00, 7.5800734e+00, 0.0000000e+00,\n 6.0689438e-02, 7.7620158e+00, 8.9861536e+00, 0.0000000e+00,\n 0.0000000e+00, 5.2750681e-02, 9.8333973e-01, 5.3532486e+00,\n 0.0000000e+00, 1.0118096e-01, 0.0000000e+00, 2.0302844e+00,\n 2.3888661e-02, 3.8600059e+00, 1.4952109e+00, 0.0000000e+00,\n 0.0000000e+00, 0.0000000e+00, 8.5608406e+00, 1.2772584e+00,\n 1.7895372e-01, 7.0525080e-01, 2.6633108e-01, 0.0000000e+00,\n 4.8621111e-03, 1.1644270e+00, 0.0000000e+00, 0.0000000e+00,\n 1.3830398e+00, 0.0000000e+00, 3.0868123e+00, 3.4960195e-01,\n 0.0000000e+00, 5.3148443e-01, 1.1543876e+00, 6.2833017e-01,\n 1.9572034e-01, 4.0440583e-01, 0.0000000e+00, 1.3848369e-02,\n 4.2901959e+00, 2.7746127e+00, 6.4910488e+00, 4.2896543e+00,\n 3.2535267e+00, 3.7667041e+00, 0.0000000e+00, 1.3855765e+00,\n 3.7794963e-01, 8.7390721e-01, 9.5273100e-04, 1.7330166e+00,\n 2.7492123e+00, 9.5099099e-02, 0.0000000e+00, 0.0000000e+00,\n 3.1991954e+00, 4.2179906e-01, 0.0000000e+00, 3.0341831e-01,\n 1.3751034e+00, 5.8014266e-02, 1.2764181e+00, 1.8332418e+00,\n 4.0166874e+00, 0.0000000e+00, 3.0639354e-02, 0.0000000e+00,\n 2.7350874e+00, 0.0000000e+00, 1.3663791e+00, 0.0000000e+00,\n 0.0000000e+00, 0.0000000e+00, 0.0000000e+00, 1.5727199e+01,\n 6.1683697e-01, 0.0000000e+00, 2.7622107e-01, 0.0000000e+00,\n 1.0622245e+00, 3.2499888e+00, 7.7441716e-01, 7.3620749e-01,\n 4.0563583e+00, 7.6700372e-01, 0.0000000e+00, 0.0000000e+00,\n 1.2429050e+00, 2.8824704e+00, 1.2450428e+00, 0.0000000e+00,\n 0.0000000e+00, 2.0109965e-01, 1.7575039e+00, 1.1525856e+00,\n 0.0000000e+00, 1.3648750e+00, 1.2368112e-01, 0.0000000e+00,\n 1.7943878e+01, 0.0000000e+00, 6.9198102e-01, 1.1463230e+00,\n 7.5900249e+00, 4.6471265e-01, 0.0000000e+00, 1.5500344e+00,\n 0.0000000e+00, 6.9660587e+00, 2.0524640e+00, 2.9294425e-01,\n 6.8241644e-01, 1.1975509e-01, 1.1623051e+01, 1.7103174e-01,\n 2.8538866e+00, 2.1006519e+01, 9.5785532e+00, 4.5588794e+00,\n 0.0000000e+00, 5.4989128e+00, 1.8180843e-01, 2.2199357e-01,\n 7.8265256e-01, 2.7023268e-01, 0.0000000e+00, 0.0000000e+00,\n 3.9854568e-01, 3.0859394e+00, 5.5339098e-01, 3.9899385e+00,\n 2.6405315e+00, 0.0000000e+00, 3.6027203e+00, 3.0631280e+00,\n 2.3215309e-02, 1.9656858e+00, 0.0000000e+00, 1.3941557e+00,\n 5.7986307e+00, 2.5126606e-02, 0.0000000e+00, 1.6741629e+01,\n 4.0332675e+00, 5.1216025e+00, 2.6294374e-01, 0.0000000e+00,\n 4.9078774e+00, 5.2612290e+00, 9.1952533e-01, 9.4617033e+00,\n 2.5089841e+00, 1.6953151e-01, 8.2220507e-01, 6.0607070e-01,\n 3.3987924e-01, 1.6613331e+00, 0.0000000e+00, 5.8456486e-01,\n 2.0231924e+00, 7.1400501e-02, 0.0000000e+00, 0.0000000e+00,\n 1.7029678e+01, 0.0000000e+00, 7.1875963e+00, 9.4987088e-01,\n 0.0000000e+00, 6.9178562e-03, 0.0000000e+00, 0.0000000e+00,\n 6.2889528e-01, 3.2174380e+00, 1.2482121e+00, 1.0348332e+00,\n 0.0000000e+00, 2.0301718e-01, 0.0000000e+00, 0.0000000e+00,\n 2.9498944e+00, 5.6052808e-02, 6.3248215e+00, 9.3721193e-01,\n 3.6421690e+00, 0.0000000e+00, 2.5078487e+00, 7.5288811e+00,\n 4.4202790e-01, 0.0000000e+00, 0.0000000e+00, 0.0000000e+00,\n 2.6355631e+00, 1.0174786e-01, 5.6112319e-01, 1.4125812e+00,\n 2.9811339e+00, 2.4328477e+00, 1.0202549e+01, 0.0000000e+00,\n 5.0174135e-01, 0.0000000e+00, 0.0000000e+00, 2.7816236e+00,\n 9.6029062e+00, 5.0358548e+00, 5.4653263e-01, 2.2321814e-01,\n 4.6542373e+00, 1.0893087e+00, 0.0000000e+00, 4.7360268e-01,\n 0.0000000e+00, 0.0000000e+00, 3.9081810e+00, 6.6521525e+00,\n 1.3338111e-02, 0.0000000e+00, 0.0000000e+00, 2.1264437e+01,\n 7.2513809e+00, 5.2197137e+00, 0.0000000e+00, 3.2378185e-01,\n 7.2049708e+00, 5.7740736e-01, 1.4835763e-01, 1.0768124e+00,\n 4.6431742e+00, 2.0954745e+00, 2.2171197e+00, 1.4055867e+01,\n 8.1094236e+00, 1.3173168e+00, 3.9258797e+00, 2.0781214e+00,\n 0.0000000e+00, 0.0000000e+00, 6.4449221e-01, 0.0000000e+00,\n 4.0574012e+00, 4.6038949e-01, 6.6758925e-01, 2.8937740e+00,\n 5.2857609e+00, 2.6400657e+00, 5.6880999e-01, 1.1582577e-01,\n 0.0000000e+00, 7.2397094e+00, 0.0000000e+00, 1.6024054e+01,\n 2.1562919e-02, 5.0674522e-01, 4.0202222e+00, 1.4506702e+00,\n 5.8873248e+00, 6.8255477e+00, 2.2649479e+00, 1.6367894e+00,\n 0.0000000e+00, 0.0000000e+00, 7.5681415e+00, 1.3856899e+00,\n 0.0000000e+00, 7.2371274e-01, 1.4682100e+00, 6.7663832e+00,\n 6.2488565e+00, 2.1448509e-01, 2.6589281e+01, 0.0000000e+00,\n 0.0000000e+00, 3.0029449e-01, 0.0000000e+00, 3.4467232e+00,\n 1.2806034e+00, 0.0000000e+00, 2.0046573e+00, 0.0000000e+00,\n 1.9980489e-01, 2.9395647e+00, 0.0000000e+00, 1.5444681e+01,\n 0.0000000e+00, 5.8159156e+00, 1.2933959e+01, 0.0000000e+00,\n 0.0000000e+00, 0.0000000e+00, 1.6282202e+01, 0.0000000e+00,\n 2.7624838e+00, 0.0000000e+00, 1.3572938e+00, 1.8366561e+00,\n 1.7282879e+00, 8.0646478e-02, 2.6995873e-01, 0.0000000e+00,\n 1.7787983e+00, 0.0000000e+00, 0.0000000e+00, 4.4069581e+00,\n 6.4076238e+00, 8.6866125e-02, 6.7630806e+00, 2.5095391e-01,\n 0.0000000e+00, 2.4959038e-01, 0.0000000e+00, 4.8371693e-01,\n 0.0000000e+00, 4.6878153e-01, 6.6461571e-02, 0.0000000e+00,\n 5.4713521e+00, 0.0000000e+00, 2.4058197e+00, 3.4866059e+00,\n 1.8472975e-01, 0.0000000e+00, 2.4313451e-01, 5.0157251e+00,\n 1.2789822e+00, 0.0000000e+00, 1.6035285e+00, 2.2510340e+00,\n 8.9369220e-01, 3.0000477e+00, 3.0935798e-02, 0.0000000e+00,\n 1.2571865e+00, 0.0000000e+00, 0.0000000e+00, 0.0000000e+00,\n 3.3102953e+00, 0.0000000e+00, 3.5232392e-01, 0.0000000e+00,\n 7.0495355e-01, 0.0000000e+00, 4.1747136e+00, 1.6505204e-02,\n 4.8895655e+00, 2.2380338e+00, 3.4364548e-01, 3.9933858e+00,\n 6.4775264e-01, 0.0000000e+00, 2.0082436e+00, 1.5756164e+00,\n 5.4484472e+00, 1.0164651e+00, 0.0000000e+00, 1.4484224e+00,\n 1.4954364e+00, 1.8046621e+01, 2.4233634e+00, 1.2490170e+00,\n 6.9416904e+00, 0.0000000e+00, 5.9719439e+00, 0.0000000e+00,\n 4.4643328e-01, 3.7314403e-01, 1.9094412e+00, 1.2094363e+00,\n 2.1741641e+00, 2.6312020e+00, 2.4712007e+00, 1.0500855e+00,\n 5.8901715e+00, 2.0934145e+00, 1.6178520e-01, 8.3829861e+00,\n 3.9705017e+00, 7.5351233e+00, 0.0000000e+00, 7.8685933e-01,\n 0.0000000e+00, 7.1193404e-02, 5.6495223e+00, 8.2938833e+00,\n 0.0000000e+00, 3.3879831e+00, 1.2994294e+00, 0.0000000e+00,\n 2.6675999e-01, 1.0888713e-01, 1.1178662e+00, 1.0197920e+01,\n 9.9095657e-02, 3.3304745e-01, 1.7063299e-01, 4.9174721e-03,\n 4.6413312e+00, 0.0000000e+00, 4.6589878e-01, 0.0000000e+00]],\n dtype=float32)\n" ], [ "print(features)", "[[0.0000000e+00 6.0639971e-01 1.2241087e+00 0.0000000e+00 7.6285583e-01\n 9.3353331e-01 4.7094667e-01 0.0000000e+00 0.0000000e+00 1.9924963e+01\n 1.4466014e+00 0.0000000e+00 1.2180121e+00 0.0000000e+00 0.0000000e+00\n 1.6389935e+01 1.7182510e-01 2.0266817e+00 0.0000000e+00 6.7011623e+00\n 0.0000000e+00 2.8219001e+00 1.4962605e-01 2.9597852e+00 0.0000000e+00\n 2.5504065e-01 1.6535183e+00 3.8728275e+00 0.0000000e+00 6.0658491e-01\n 0.0000000e+00 0.0000000e+00 3.1740711e+00 3.3034900e-01 0.0000000e+00\n 2.9369137e-01 0.0000000e+00 8.2455468e-01 1.0085965e-01 0.0000000e+00\n 3.1839323e+00 1.7112944e+01 7.4131870e-01 9.6320772e-01 5.1401488e-02\n 4.0519438e+00 6.6801023e+00 1.3918856e+01 4.2468858e+00 8.6180413e-01\n 3.4711781e+00 5.6451054e+00 1.0152748e+01 1.5829812e+00 0.0000000e+00\n 3.6567924e+00 5.9682503e+00 6.8307206e-02 7.6533681e-01 1.1373340e+00\n 0.0000000e+00 4.6766024e+00 3.4389660e-01 0.0000000e+00 0.0000000e+00\n 2.8509095e+00 5.4107890e+00 4.1712832e+00 0.0000000e+00 0.0000000e+00\n 0.0000000e+00 3.5100007e+00 1.7826376e+00 0.0000000e+00 4.2363667e-01\n 1.2573874e+00 0.0000000e+00 5.4925001e-01 5.1038927e-01 0.0000000e+00\n 0.0000000e+00 1.9681660e+00 3.9911082e+00 7.7583280e+00 0.0000000e+00\n 3.2026155e+00 1.8421052e-01 0.0000000e+00 3.1603971e+00 0.0000000e+00\n 0.0000000e+00 8.0792093e-01 0.0000000e+00 1.5015146e+00 9.9417818e-01\n 3.5476735e+00 9.3484182e+00 5.9968624e+00 4.1852822e+00 5.0409989e+00\n 0.0000000e+00 2.2600448e-01 9.0468031e-01 3.8086047e+00 2.3084729e+00\n 7.2678800e+00 3.5115275e+00 5.8744888e+00 1.0973458e+00 0.0000000e+00\n 7.5800734e+00 0.0000000e+00 6.0689438e-02 7.7620158e+00 8.9861536e+00\n 0.0000000e+00 0.0000000e+00 5.2750681e-02 9.8333973e-01 5.3532486e+00\n 0.0000000e+00 1.0118096e-01 0.0000000e+00 2.0302844e+00 2.3888661e-02\n 3.8600059e+00 1.4952109e+00 0.0000000e+00 0.0000000e+00 0.0000000e+00\n 8.5608406e+00 1.2772584e+00 1.7895372e-01 7.0525080e-01 2.6633108e-01\n 0.0000000e+00 4.8621111e-03 1.1644270e+00 0.0000000e+00 0.0000000e+00\n 1.3830398e+00 0.0000000e+00 3.0868123e+00 3.4960195e-01 0.0000000e+00\n 5.3148443e-01 1.1543876e+00 6.2833017e-01 1.9572034e-01 4.0440583e-01\n 0.0000000e+00 1.3848369e-02 4.2901959e+00 2.7746127e+00 6.4910488e+00\n 4.2896543e+00 3.2535267e+00 3.7667041e+00 0.0000000e+00 1.3855765e+00\n 3.7794963e-01 8.7390721e-01 9.5273100e-04 1.7330166e+00 2.7492123e+00\n 9.5099099e-02 0.0000000e+00 0.0000000e+00 3.1991954e+00 4.2179906e-01\n 0.0000000e+00 3.0341831e-01 1.3751034e+00 5.8014266e-02 1.2764181e+00\n 1.8332418e+00 4.0166874e+00 0.0000000e+00 3.0639354e-02 0.0000000e+00\n 2.7350874e+00 0.0000000e+00 1.3663791e+00 0.0000000e+00 0.0000000e+00\n 0.0000000e+00 0.0000000e+00 1.5727199e+01 6.1683697e-01 0.0000000e+00\n 2.7622107e-01 0.0000000e+00 1.0622245e+00 3.2499888e+00 7.7441716e-01\n 7.3620749e-01 4.0563583e+00 7.6700372e-01 0.0000000e+00 0.0000000e+00\n 1.2429050e+00 2.8824704e+00 1.2450428e+00 0.0000000e+00 0.0000000e+00\n 2.0109965e-01 1.7575039e+00 1.1525856e+00 0.0000000e+00 1.3648750e+00\n 1.2368112e-01 0.0000000e+00 1.7943878e+01 0.0000000e+00 6.9198102e-01\n 1.1463230e+00 7.5900249e+00 4.6471265e-01 0.0000000e+00 1.5500344e+00\n 0.0000000e+00 6.9660587e+00 2.0524640e+00 2.9294425e-01 6.8241644e-01\n 1.1975509e-01 1.1623051e+01 1.7103174e-01 2.8538866e+00 2.1006519e+01\n 9.5785532e+00 4.5588794e+00 0.0000000e+00 5.4989128e+00 1.8180843e-01\n 2.2199357e-01 7.8265256e-01 2.7023268e-01 0.0000000e+00 0.0000000e+00\n 3.9854568e-01 3.0859394e+00 5.5339098e-01 3.9899385e+00 2.6405315e+00\n 0.0000000e+00 3.6027203e+00 3.0631280e+00 2.3215309e-02 1.9656858e+00\n 0.0000000e+00 1.3941557e+00 5.7986307e+00 2.5126606e-02 0.0000000e+00\n 1.6741629e+01 4.0332675e+00 5.1216025e+00 2.6294374e-01 0.0000000e+00\n 4.9078774e+00 5.2612290e+00 9.1952533e-01 9.4617033e+00 2.5089841e+00\n 1.6953151e-01 8.2220507e-01 6.0607070e-01 3.3987924e-01 1.6613331e+00\n 0.0000000e+00 5.8456486e-01 2.0231924e+00 7.1400501e-02 0.0000000e+00\n 0.0000000e+00 1.7029678e+01 0.0000000e+00 7.1875963e+00 9.4987088e-01\n 0.0000000e+00 6.9178562e-03 0.0000000e+00 0.0000000e+00 6.2889528e-01\n 3.2174380e+00 1.2482121e+00 1.0348332e+00 0.0000000e+00 2.0301718e-01\n 0.0000000e+00 0.0000000e+00 2.9498944e+00 5.6052808e-02 6.3248215e+00\n 9.3721193e-01 3.6421690e+00 0.0000000e+00 2.5078487e+00 7.5288811e+00\n 4.4202790e-01 0.0000000e+00 0.0000000e+00 0.0000000e+00 2.6355631e+00\n 1.0174786e-01 5.6112319e-01 1.4125812e+00 2.9811339e+00 2.4328477e+00\n 1.0202549e+01 0.0000000e+00 5.0174135e-01 0.0000000e+00 0.0000000e+00\n 2.7816236e+00 9.6029062e+00 5.0358548e+00 5.4653263e-01 2.2321814e-01\n 4.6542373e+00 1.0893087e+00 0.0000000e+00 4.7360268e-01 0.0000000e+00\n 0.0000000e+00 3.9081810e+00 6.6521525e+00 1.3338111e-02 0.0000000e+00\n 0.0000000e+00 2.1264437e+01 7.2513809e+00 5.2197137e+00 0.0000000e+00\n 3.2378185e-01 7.2049708e+00 5.7740736e-01 1.4835763e-01 1.0768124e+00\n 4.6431742e+00 2.0954745e+00 2.2171197e+00 1.4055867e+01 8.1094236e+00\n 1.3173168e+00 3.9258797e+00 2.0781214e+00 0.0000000e+00 0.0000000e+00\n 6.4449221e-01 0.0000000e+00 4.0574012e+00 4.6038949e-01 6.6758925e-01\n 2.8937740e+00 5.2857609e+00 2.6400657e+00 5.6880999e-01 1.1582577e-01\n 0.0000000e+00 7.2397094e+00 0.0000000e+00 1.6024054e+01 2.1562919e-02\n 5.0674522e-01 4.0202222e+00 1.4506702e+00 5.8873248e+00 6.8255477e+00\n 2.2649479e+00 1.6367894e+00 0.0000000e+00 0.0000000e+00 7.5681415e+00\n 1.3856899e+00 0.0000000e+00 7.2371274e-01 1.4682100e+00 6.7663832e+00\n 6.2488565e+00 2.1448509e-01 2.6589281e+01 0.0000000e+00 0.0000000e+00\n 3.0029449e-01 0.0000000e+00 3.4467232e+00 1.2806034e+00 0.0000000e+00\n 2.0046573e+00 0.0000000e+00 1.9980489e-01 2.9395647e+00 0.0000000e+00\n 1.5444681e+01 0.0000000e+00 5.8159156e+00 1.2933959e+01 0.0000000e+00\n 0.0000000e+00 0.0000000e+00 1.6282202e+01 0.0000000e+00 2.7624838e+00\n 0.0000000e+00 1.3572938e+00 1.8366561e+00 1.7282879e+00 8.0646478e-02\n 2.6995873e-01 0.0000000e+00 1.7787983e+00 0.0000000e+00 0.0000000e+00\n 4.4069581e+00 6.4076238e+00 8.6866125e-02 6.7630806e+00 2.5095391e-01\n 0.0000000e+00 2.4959038e-01 0.0000000e+00 4.8371693e-01 0.0000000e+00\n 4.6878153e-01 6.6461571e-02 0.0000000e+00 5.4713521e+00 0.0000000e+00\n 2.4058197e+00 3.4866059e+00 1.8472975e-01 0.0000000e+00 2.4313451e-01\n 5.0157251e+00 1.2789822e+00 0.0000000e+00 1.6035285e+00 2.2510340e+00\n 8.9369220e-01 3.0000477e+00 3.0935798e-02 0.0000000e+00 1.2571865e+00\n 0.0000000e+00 0.0000000e+00 0.0000000e+00 3.3102953e+00 0.0000000e+00\n 3.5232392e-01 0.0000000e+00 7.0495355e-01 0.0000000e+00 4.1747136e+00\n 1.6505204e-02 4.8895655e+00 2.2380338e+00 3.4364548e-01 3.9933858e+00\n 6.4775264e-01 0.0000000e+00 2.0082436e+00 1.5756164e+00 5.4484472e+00\n 1.0164651e+00 0.0000000e+00 1.4484224e+00 1.4954364e+00 1.8046621e+01\n 2.4233634e+00 1.2490170e+00 6.9416904e+00 0.0000000e+00 5.9719439e+00\n 0.0000000e+00 4.4643328e-01 3.7314403e-01 1.9094412e+00 1.2094363e+00\n 2.1741641e+00 2.6312020e+00 2.4712007e+00 1.0500855e+00 5.8901715e+00\n 2.0934145e+00 1.6178520e-01 8.3829861e+00 3.9705017e+00 7.5351233e+00\n 0.0000000e+00 7.8685933e-01 0.0000000e+00 7.1193404e-02 5.6495223e+00\n 8.2938833e+00 0.0000000e+00 3.3879831e+00 1.2994294e+00 0.0000000e+00\n 2.6675999e-01 1.0888713e-01 1.1178662e+00 1.0197920e+01 9.9095657e-02\n 3.3304745e-01 1.7063299e-01 4.9174721e-03 4.6413312e+00 0.0000000e+00\n 4.6589878e-01 0.0000000e+00]]\n" ] ], [ [ "### Features can be used for comparison", "_____no_output_____" ] ], [ [ "def load_and_extract_features(img_path):\n # Loading rgba to show the image properly\n img = image.load_img(img_path, color_mode='rgba')\n plt.imshow(img)\n \n # Loading rgb with expected input size\n img = image.load_img(img_path, target_size=(224, 224))\n \n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n\n features = model.predict(x)\n \n return features", "_____no_output_____" ], [ "features_tshirt1 = load_and_extract_features('../../sample_images/tshirt.png')", "_____no_output_____" ], [ "features_tshirt2 = load_and_extract_features('../../sample_images/tshirt2.png')", "_____no_output_____" ], [ "features_pug = load_and_extract_features('../../sample_images/pug.png')", "_____no_output_____" ], [ "features_pug2 = load_and_extract_features('../../sample_images/pug2.png')", "_____no_output_____" ], [ "features_sneakers = load_and_extract_features('../../sample_images/sneakers.png')", "_____no_output_____" ] ], [ [ "### Computing distance between features\nWe can then compute the distance between these features and see whether given images are more similar to each other", "_____no_output_____" ], [ "#### T-shirt 1 vs Pug 1", "_____no_output_____" ] ], [ [ "from scipy.spatial.distance import cosine", "_____no_output_____" ], [ "distance = cosine(features_tshirt1, features_pug)\nprint(distance)", "0.8084378838539124\n" ] ], [ [ "#### T-shirt 2 vs Pug 2", "_____no_output_____" ] ], [ [ "distance = cosine(features_tshirt2, features_pug2)\nprint(distance)", "0.7392519414424896\n" ] ], [ [ "#### Pug 1 vs Sneakers", "_____no_output_____" ] ], [ [ "distance = cosine(features_pug, features_sneakers)\nprint(distance)", "0.7406953275203705\n" ] ], [ [ "#### T-shirt 1 vs T-shirt 2", "_____no_output_____" ] ], [ [ "distance = cosine(features_tshirt1, features_tshirt2)\nprint(distance)", "0.27799564599990845\n" ] ], [ [ "#### Pug 1 vs Pug 2", "_____no_output_____" ] ], [ [ "distance = cosine(features_pug, features_pug2)\nprint(distance)", "0.13096392154693604\n" ], [ "distance = cosine(features_pug, features_pug)\nprint(distance)", "0.0\n" ] ], [ [ "### We can also use features to train classifiers\nWe'll see how it works in the assignment :)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4afa3375aac224bac823b8e8dbda5c33d1e9e63e
261,609
ipynb
Jupyter Notebook
big-market-sales-prediction.ipynb
Nithishnj23/nj
cafa71a016e553c705e66e47f87515d0099039de
[ "MIT" ]
null
null
null
big-market-sales-prediction.ipynb
Nithishnj23/nj
cafa71a016e553c705e66e47f87515d0099039de
[ "MIT" ]
null
null
null
big-market-sales-prediction.ipynb
Nithishnj23/nj
cafa71a016e553c705e66e47f87515d0099039de
[ "MIT" ]
null
null
null
82.396535
28,432
0.790791
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nsns.set_style('whitegrid')\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "df = pd.read_csv('../input/bigmarket/bigmarket.csv')\ndf.head()", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 8523 entries, 0 to 8522\nData columns (total 12 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Item_Identifier 8523 non-null object \n 1 Item_Weight 7060 non-null float64\n 2 Item_Fat_Content 8523 non-null object \n 3 Item_Visibility 8523 non-null float64\n 4 Item_Type 8523 non-null object \n 5 Item_MRP 8523 non-null float64\n 6 Outlet_Identifier 8523 non-null object \n 7 Outlet_Establishment_Year 8523 non-null int64 \n 8 Outlet_Size 6113 non-null object \n 9 Outlet_Location_Type 8523 non-null object \n 10 Outlet_Type 8523 non-null object \n 11 Item_Outlet_Sales 8523 non-null float64\ndtypes: float64(4), int64(1), object(7)\nmemory usage: 799.2+ KB\n" ] ], [ [ "**# checking for missing values****", "_____no_output_____" ] ], [ [ "df.isnull().sum()", "_____no_output_____" ] ], [ [ "Handling Missing Values\n\nMEAN -> AVERAGE\nMODE -> MORE REPEATED VALUE", "_____no_output_____" ] ], [ [ "df['Item_Weight'].mean()", "_____no_output_____" ] ], [ [ "# filling missing values in \"Item-Weight\" with MEAN VALUE", "_____no_output_____" ] ], [ [ "df['Item_Weight'].fillna(df['Item_Weight'].mean(), inplace=True)", "_____no_output_____" ], [ "# Mode of \"Outlet_Size\" column\ndf['Outlet_Size'].mode()", "_____no_output_____" ], [ "# filling the missing values in \"Outlet_Size\" column with Mode\nmode_of_Outlet_size = df.pivot_table(values='Outlet_Size', columns='Outlet_Type', aggfunc=(lambda x: x.mode()[0]))", "_____no_output_____" ], [ "print(mode_of_Outlet_size)", "Outlet_Type Grocery Store Supermarket Type1 Supermarket Type2 \\\nOutlet_Size Small Small Medium \n\nOutlet_Type Supermarket Type3 \nOutlet_Size Medium \n" ], [ "miss_values = df['Outlet_Size'].isnull()\nprint(miss_values)", "0 False\n1 False\n2 False\n3 True\n4 False\n ... \n8518 False\n8519 True\n8520 False\n8521 False\n8522 False\nName: Outlet_Size, Length: 8523, dtype: bool\n" ], [ "df.loc[miss_values, 'Outlet_Size'] = df.loc[miss_values, 'Outlet_Type'].apply(lambda x:mode_of_Outlet_size[x])\n#checking for missing values\ndf.isnull().sum()", "_____no_output_____" ] ], [ [ "**Data Analysis**", "_____no_output_____" ] ], [ [ "df.describe()", "_____no_output_____" ] ], [ [ "**# Item_Weight distribution**\n", "_____no_output_____" ] ], [ [ "\nplt.figure(figsize=(6,6))\nsns.distplot(df['Item_Weight'])\nplt.show()", "_____no_output_____" ] ], [ [ "**# Item Visibility distribution**", "_____no_output_____" ] ], [ [ "\nplt.figure(figsize=(6,6))\nsns.distplot(df['Item_Visibility'])\nplt.show()", "_____no_output_____" ] ], [ [ "**# Item MRP distribution**", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(6,6))\nsns.distplot(df['Item_MRP'])\nplt.show()", "_____no_output_____" ] ], [ [ "# Item_Outlet_Sales distribution", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(6,6))\nsns.distplot(df['Item_Outlet_Sales'])\nplt.show()", "_____no_output_____" ] ], [ [ "**# Outlet_Establishment_Year column**", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(6,6))\nsns.countplot(x='Outlet_Establishment_Year', data=df)\nplt.show()", "_____no_output_____" ] ], [ [ "**# Item_Fat_Content column**", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(6,6))\nsns.countplot(x='Item_Fat_Content', data=df)\nplt.show()", "_____no_output_____" ] ], [ [ "**# Item_Type column**", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(30,6))\nsns.countplot(x='Item_Type', data=df)\nplt.show()", "_____no_output_____" ] ], [ [ "**# Outlet_Size column**", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(6,6))\nsns.countplot(x='Outlet_Size', data=df)\nplt.show()", "_____no_output_____" ] ], [ [ "**Data Pre=Processing**", "_____no_output_____" ] ], [ [ "df.head()", "_____no_output_____" ], [ "df['Item_Fat_Content'].value_counts()", "_____no_output_____" ], [ "df.replace({'Item_Fat_Content':{'low fat':'Low Fat', 'LF':'Low Fat', 'reg':'Regular'}},inplace=True)", "_____no_output_____" ], [ "df['Item_Fat_Content'].value_counts()", "_____no_output_____" ] ], [ [ "**Label Encoding**", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import LabelEncoder", "_____no_output_____" ], [ "encoder = LabelEncoder()", "_____no_output_____" ], [ "df['Item_Identifier'] = encoder.fit_transform(df['Item_Identifier'])\n\ndf['Item_Fat_Content'] = encoder.fit_transform(df['Item_Fat_Content'])\n\ndf['Item_Type'] = encoder.fit_transform(df['Item_Type'])\n\ndf['Outlet_Identifier'] = encoder.fit_transform(df['Outlet_Identifier'])\n\ndf['Outlet_Size'] = encoder.fit_transform(df['Outlet_Size'])\n\ndf['Outlet_Location_Type'] = encoder.fit_transform(df['Outlet_Location_Type'])\n\ndf['Outlet_Type'] = encoder.fit_transform(df['Outlet_Type'])", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "**Splitting features and Target**", "_____no_output_____" ] ], [ [ "X = df.iloc[:,:-1].values\ny = df.iloc[:,-1].values", "_____no_output_____" ], [ "print(X)", "[[1.560e+02 9.300e+00 0.000e+00 ... 1.000e+00 0.000e+00 1.000e+00]\n [8.000e+00 5.920e+00 1.000e+00 ... 1.000e+00 2.000e+00 2.000e+00]\n [6.620e+02 1.750e+01 0.000e+00 ... 1.000e+00 0.000e+00 1.000e+00]\n ...\n [1.357e+03 1.060e+01 0.000e+00 ... 2.000e+00 1.000e+00 1.000e+00]\n [6.810e+02 7.210e+00 1.000e+00 ... 1.000e+00 2.000e+00 2.000e+00]\n [5.000e+01 1.480e+01 0.000e+00 ... 2.000e+00 0.000e+00 1.000e+00]]\n" ], [ "print(y)", "[3735.138 443.4228 2097.27 ... 1193.1136 1845.5976 765.67 ]\n" ] ], [ [ "**Splitting into Train Test Split**", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=0)", "_____no_output_____" ], [ "print(X.shape, X_train.shape, X_test.shape)", "(8523, 11) (6818, 11) (1705, 11)\n" ] ], [ [ "**Training Algortihm**", "_____no_output_____" ] ], [ [ "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense", "_____no_output_____" ], [ "model = Sequential()\n\nmodel.add(Dense(20, activation='relu'))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dense(5, activation='relu'))\n\nmodel.add(Dense(1)) # output layer\n\nmodel.compile(optimizer='rmsprop', loss='mse')", "2022-04-28 11:03:11.854496: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.\n" ], [ "model.fit(x = X_train, y = y_train, epochs=50)", "2022-04-28 11:03:12.164429: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2)\n" ], [ "model.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ndense (Dense) (None, 20) 240 \n_________________________________________________________________\ndense_1 (Dense) (None, 10) 210 \n_________________________________________________________________\ndense_2 (Dense) (None, 5) 55 \n_________________________________________________________________\ndense_3 (Dense) (None, 1) 6 \n=================================================================\nTotal params: 511\nTrainable params: 511\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "loss_df = pd.DataFrame(model.history.history)", "_____no_output_____" ], [ "loss_df", "_____no_output_____" ], [ "loss_df.plot()", "_____no_output_____" ] ], [ [ "**Model Evaluation**", "_____no_output_____" ] ], [ [ "\ntest_eval = model.evaluate(X_test, y_test, verbose=0)\nprint(test_eval)", "1591096.25\n" ] ], [ [ "**# model evaluation on train set**", "_____no_output_____" ] ], [ [ "train_eval = model.evaluate(X_train, y_train, verbose=0)\nprint(train_eval)", "1596897.75\n" ] ], [ [ "**# Checking difference between train_eval and test_eval**", "_____no_output_____" ] ], [ [ "model_diff = train_eval - test_eval\nprint(model_diff)", "5801.5\n" ] ], [ [ "**# Train prediction on test data**", "_____no_output_____" ] ], [ [ "train_prediction = model.predict(X_train)", "_____no_output_____" ] ], [ [ "**# Test prediction on test data**", "_____no_output_____" ] ], [ [ "test_prediction = model.predict(X_test)", "_____no_output_____" ], [ "print(train_prediction)", "[[2647.918 ]\n [ 673.0176 ]\n [ 670.96826]\n ...\n [ 805.0281 ]\n [1562.1196 ]\n [2929.8635 ]]\n" ], [ "print(test_prediction)", "[[2104.4558 ]\n [1590.8557 ]\n [1024.7468 ]\n ...\n [3670.7898 ]\n [ 195.01709]\n [4680.941 ]]\n" ] ], [ [ "**# R Squared : R-squared measures the strength of the relationship between your model and the dependent variable on a convenient 0 –**", "_____no_output_____" ] ], [ [ "from sklearn.metrics import r2_score\nr2_train = r2_score(y_train, train_prediction)", "_____no_output_____" ], [ "print('R squared value of train data:', r2_train)", "R squared value of train data: 0.45086162528405027\n" ], [ "r2_test = r2_score(y_test, test_prediction)", "_____no_output_____" ], [ "print('R squared value of test data:',r2_test)", "R squared value of test data: 0.4563809007260504\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", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4afa4042f8e5380e6df32508f8aece4719cdc621
182,488
ipynb
Jupyter Notebook
examples/__CLProgram_scratch.ipynb
bcwarner/physics-sim
5a0be30e573212c53b9a435ffacdea09c6addbfc
[ "MIT" ]
2
2021-03-26T06:20:20.000Z
2022-01-23T01:19:35.000Z
examples/__CLProgram_scratch.ipynb
bcwarner/physics-sim
5a0be30e573212c53b9a435ffacdea09c6addbfc
[ "MIT" ]
null
null
null
examples/__CLProgram_scratch.ipynb
bcwarner/physics-sim
5a0be30e573212c53b9a435ffacdea09c6addbfc
[ "MIT" ]
2
2020-10-27T19:12:35.000Z
2022-01-23T01:19:40.000Z
491.881402
24,340
0.943136
[ [ [ "import phys\nimport phys.newton\nimport phys.light\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nclass ScatterDeleteStep2(phys.Step):\n def __init__(self, n, A):\n self.n = n\n self.A = A\n self.built = False\n \n def run(self, sim):\n if self.built != True:\n skip = phys.CLInput(name=\"photon_check\", type=\"obj_action\", code=\"if type(obj) != phys.light.PhotonObject:\\n \\t\\t continue\")\n d0, d1, d2 = tuple([phys.CLInput(name=\"d\" + str(x), type=\"obj\", obj_attr=\"dr[\" + str(x) + \"]\") for x in range(0, 3)])\n rand = phys.CLInput(name=\"rand\", type=\"obj_def\", obj_def=\"np.random.random()\")\n A_, n_ = phys.CLInput(name=\"A\", type=\"const\", const_value=str(self.n)), phys.CLInput(name=\"n\", type=\"const\", const_value=str(self.A))\n pht = phys.CLInput(name=\"pht\", type=\"obj_track\", obj_track=\"obj\")\n res = phys.CLOutput(name=\"res\", ctype=\"int\")\n kernel = \"\"\"\n int gid = get_global_id(0);\n double norm = sqrt(pow(d0[gid], 2) + pow(d1[gid], 2) + pow(d2[gid], 2));\n double pcoll = A * n * norm;\n if (pcoll >= rand[gid]){\n // Mark for removal.\n res[gid] = 1;\n } else {\n res[gid] = 0;\n }\n \"\"\"\n \n self.prog = phys.CLProgram(sim, \"test\", kernel)\n self.prog.prep_metadata = [skip, d0, d1, d2, rand, pht, A_, n_]\n self.prog.output_metadata = [res]\n self.prog.build_kernel()\n self.built = True\n \n out = self.prog.run()\n for idx, x in enumerate(out[\"res\"]):\n if x == 1:\n sim.remove_obj(self.prog.pht[idx])\n\ndef new_sim(step, n):\n sim = phys.Simulation({\"cl_on\": True})\n sim.add_objs(phys.light.generate_photons_from_E(np.linspace(phys.Measurement(5e-19, \"J**1\"), phys.Measurement(1e-18, \"J**1\"), 1000)))\n sim.exit = lambda cond: len(cond.objects) == 0\n sim.add_step(0, phys.UpdateTimeStep(lambda s: phys.Measurement(np.double(0.001), \"s**1\")))\n sim.add_step(1, phys.newton.NewtonianKinematicsStep())\n A = np.double(0.001)\n n = np.double(0.001)\n sim.add_step(2, step(n, A))\n sim.add_step(3, phys.light.ScatterMeasureStep(None, True))\n return sim", "_____no_output_____" ], [ "orig, new = [], []\nns = np.floor(10 ** np.linspace(2, 5, 9))\nfor i in ns:\n print(\"Testing old \" + str(i))\n o = new_sim(phys.light.ScatterDeleteStepReference, int(i))\n o.start()\n o.join()\n orig.append(o.run_time)\n plt.plot(o.ts, [x[1] for x in o.steps[3].data], label=\"n\")\n plt.ylabel(\"Photons\")\n plt.xlabel(\"Time (s)\")\n plt.title(\"Photon Count vs. Time (s) w/ old, N = \" + str(i))\n plt.show()\n \n \n print(\"Testing new \" + str(i))\n n = new_sim(ScatterDeleteStep2, int(i))\n n.start()\n n.join()\n new.append(n.run_time)", "Testing old 100.0\n" ], [ "plt.plot(ns, new, label=\"New\")\nplt.plot(ns, orig, label=\"Original\")\nplt.legend()\nplt.xlabel(\"$N_\\gamma$\")\nplt.ylabel(\"Time (s)\")\nplt.title(\"$N_\\gamma$ vs. Time\")\nplt.show()", "_____no_output_____" ], [ "o.ts[0].size", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code" ] ]
4afa40476ad35180b3587f901cfd09f3a318ae3e
6,662
ipynb
Jupyter Notebook
tutorial/A4 - Additional Resources.ipynb
ghPRao/practice-bokeh
86f2f1a49ab3a3c35d30700920db20a222f3b4be
[ "BSD-3-Clause" ]
null
null
null
tutorial/A4 - Additional Resources.ipynb
ghPRao/practice-bokeh
86f2f1a49ab3a3c35d30700920db20a222f3b4be
[ "BSD-3-Clause" ]
null
null
null
tutorial/A4 - Additional Resources.ipynb
ghPRao/practice-bokeh
86f2f1a49ab3a3c35d30700920db20a222f3b4be
[ "BSD-3-Clause" ]
null
null
null
35.248677
423
0.594116
[ [ [ "<table style=\"float:left; border:none\">\n <tr style=\"border:none\">\n <td style=\"border:none\">\n <a href=\"https://bokeh.org/\"> \n <img \n src=\"assets/bokeh-transparent.png\" \n style=\"width:50px\"\n >\n </a> \n </td>\n <td style=\"border:none\">\n <h1>Bokeh Tutorial</h1>\n </td>\n </tr>\n</table>\n<div style=\"float:right;\"><h2>A4. Additional resources</h2></div>", "_____no_output_____" ], [ "# Additional resources\n\nThere are lots of things we haven't had time to tell you about. In general to learn more about bokeh, the following resources will hopefully be helpful:\n\n", "_____no_output_____" ], [ "## Doumentation\n\n##### Main Page - https://bokeh.org \n\nThe main front page, with links to many other resources\n\n---\n\n##### Documentation - https://docs.bokeh.org/en/latest \n\nThe documentation toplevel page\n\n---\n\n##### User's Guide - https://docs.bokeh.org/en/latest/docs/user_guide.html\n\nThe user's guide has many top-oriented subsections, for example \"Plotting with Basic Glyphs\", \"Configuring Plot Tools\", or \"Adding Interactions\". Each user's guide section typically example code and corresponding live plots that demonstrate how to accomplish various tasks. \n\n---\n\n##### Gallery - https://docs.bokeh.org/en/latest/docs/gallery.html\n\nOne of the best ways to learn is to find an existing example similar to what you want, and to study it and then use it as a starting place. Starting from a known working example can often save time and effort when getting started by allowing you to make small, incremental changes and observing the outcome. The Bokeh docs have a large thumbnail gallery that links to live plots and apps with corresponding code. \n\n\n---\n\n##### Reference Guide - https://docs.bokeh.org/en/latest/docs/reference.html\n\nIf you are already familiar with Bokeh and have questions about specific details of the obejcts you are already using, the reference guide is a good resource for finding information. The reference guide is automatically generated from the project source code and is a complete resources for all bokeh models and their properties. \n\n---\n\n\n\n##### Issue tracker - https://github.com/bokeh/bokeh/issues\n\nThe GitHub issue tracker is the place to go to submit ***bug reports*** and ***feature requests***. It it NOT the right place for general support questions (see the *General Community Support* links below).\n\n", "_____no_output_____" ], [ "## Example apps and Scripts\n\nIn addition to all the live gallery examples, Bokeh has many additional scripts and apps that can be instructive to study and emulate. \n\n##### Examples folder - https://github.com/bokeh/bokeh/tree/master/examples/\n\nThe `examples` directory has many subfolders dedicated to different kinds of topics. Some of the highlights are:\n\n* `app` - example Bokeh apps, run with \"`bokeh serve`\"\n* `howto` - some examples arranged around specific topics such as layout or notebook comms\n* `models` - examples that demonstrate the low-level `bokeh.models` API\n* `plotting` - a large collections of examples using the `bokeh.plotting` interface\n* `webgl` - some examples demonstrating WebGL usage\n\n---\n\n", "_____no_output_____" ], [ "## General Commnity Support\n\nBokeh has a large and growing community. The best place to go for general support questions (either to ask, or to answer!) is https://discourse.bokeh.org\n\n", "_____no_output_____" ], [ "## Contributor Resources\n\nBokeh has a small but growing developer community. We are always looking to have new contributors. Below are some resources for people involved in working on Bokeh itself.\n\n##### Source code - https://github.com/bokeh/bokeh\n\nGo here to clone the GitHub repo (in order to contribute or get the examples), or to submit issues to the issue tracker \n\n---\n\n##### Issue tracker - https://github.com/bokeh/bokeh/issues\n\nThe GitHub issue tracker is the place to go to submit ***bug reports*** and ***feature requests***. For general support questions, see the *General Community Support* links above.\n\n---\n\n#### Developer's Guide - https://bokeh.pydata.org/en/latest/docs/dev_guide.html\n\nIf you are interesting in becoming a contributor to Bokeh, the developer's guide is the place to start. It has information about getting a development environment set up, the library architecture, writing and running tests, \n\n---\n\n#### Dev Channel in Discourse - https://discourse.bokeh.org/c/development\n\nCome here for assistance with any questions about developing Bokeh itself. \n", "_____no_output_____" ], [ "# Next Section", "_____no_output_____" ], [ "This is the last section of the appendices.\n\nTo go back to the overview, click [here](00%20-%20Introduction%20and%20Setup.ipynb).", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4afa5c200ee771b285148cbe0efdb2421cd05cbd
4,734
ipynb
Jupyter Notebook
orbital_mechanics.ipynb
carlisavannah/astr-119-session-15
4228b0b1afa0e3ec77326774784fdb6bfaed06a4
[ "MIT" ]
null
null
null
orbital_mechanics.ipynb
carlisavannah/astr-119-session-15
4228b0b1afa0e3ec77326774784fdb6bfaed06a4
[ "MIT" ]
null
null
null
orbital_mechanics.ipynb
carlisavannah/astr-119-session-15
4228b0b1afa0e3ec77326774784fdb6bfaed06a4
[ "MIT" ]
null
null
null
24.78534
210
0.489649
[ [ [ "# Create a simple solar system model", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom collections import namedtuple", "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/font_manager.py:229: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.\n 'Matplotlib is building the font cache using fc-list. '\n" ] ], [ [ "## Define a planet class", "_____no_output_____" ] ], [ [ "class planet():\n \"A planet in our solar system\"\n def _init__(self,semimajor,eccentricity):\n self.x = np.zeros(2) #x and y position\n self.v = np.zeros(2) #x and y velocity\n self.a_g = np.zeros(2) #x and y acceleration\n self.t = 0.0 #current time\n self.dt = 0.0 #current timestep\n self.a = semimajor #semimajor axis of the orbit\n self.e = eccentricity #eccentricity of the orbit\n self.istep = 0 #current integer timestep1\n self.name = \"\" #name for the planet", "_____no_output_____" ] ], [ [ "## Define a dictionary with some constants", "_____no_output_____" ] ], [ [ "solar_system = {\"M_sun\":1.0, \"G\":39.4784176043574320}", "_____no_output_____" ] ], [ [ "## Define some functions for setting circlular velocity, and acceleration", "_____no_output_____" ] ], [ [ "def SolarCircularVelocity(p):\n \n G = solar_system[\"G\"]\n M = solar_system[\"M_sun\"]\n r = ( p.x[0]**2 + p.x[1]**2 )**0.5\n \n #return the circular velocity\n return (G*M/r)**0.5", "_____no_output_____" ] ], [ [ "## Write a function to compute the gravitational acceleration on each planet from the Sun", "_____no_output_____" ] ], [ [ "def SolargravitationalAcceleration(p):\n \n G = solar_system[\"G\"]\n M = solar_system[\"M_sun\"]\n r = ( p.x[0]**2 + p.x[1]**2 )**0.5\n \n #acceleration in AU/yr/yr\n a_grav = -1.0*G*M/r**2\n \n #find the angle at this position\n if(p.x[0]==0.0):\n if(p.x[1]>0.0):\n theta = 0.5*np.pi\n else:\n theta = 1.5*np.pi\n else:\n theta = np.arctan2(p.x[1],p.x[0])\n \n #set the x and y components of the velocity\n #p.a_g[0] = a_grav * np.cos(theta)\n #p.a_g[1] = a_grav * np.sin(theta)\n return a_grav*np.cos(theta), a_grav*np.sin(theta)", "_____no_output_____" ] ], [ [ "## Compute the timestep", "_____no_output_____" ] ], [ [ "def calc_dt(p):\n \n #integration tolerance\n ETA_TIME_STEP = 0.0004\n \n #compute timestep\n eta = EtA_TIME_STEP\n v = (p.v[0]**2 + p.v[1]**2)**0.5\n a = (p.a_g[0]**2 + p.a_g[1]**2)**0.5\n dt = eta * np.fmin(1./np.fabs(v),1./np.fabs(a)**0.5)\n \n return dt", "_____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" ] ]
4afa5c73b58fb85164845bea2ba45220630c4671
5,266
ipynb
Jupyter Notebook
2-1.TextCNN/TextCNN.ipynb
hw-nav/nlp-tutorial
e58f5120c56069067b6d89767318a0d937659ef1
[ "MIT" ]
11,037
2019-01-02T13:52:43.000Z
2022-03-31T23:41:12.000Z
2-1.TextCNN/TextCNN.ipynb
hw-nav/nlp-tutorial
e58f5120c56069067b6d89767318a0d937659ef1
[ "MIT" ]
62
2019-02-02T17:20:10.000Z
2022-03-08T05:26:47.000Z
2-1.TextCNN/TextCNN.ipynb
hw-nav/nlp-tutorial
e58f5120c56069067b6d89767318a0d937659ef1
[ "MIT" ]
3,093
2019-02-02T16:12:08.000Z
2022-03-31T05:00:11.000Z
45.008547
158
0.501709
[ [ [ "# code by Tae Hwan Jung @graykode\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nclass TextCNN(nn.Module):\n def __init__(self):\n super(TextCNN, self).__init__()\n self.num_filters_total = num_filters * len(filter_sizes)\n self.W = nn.Embedding(vocab_size, embedding_size)\n self.Weight = nn.Linear(self.num_filters_total, num_classes, bias=False)\n self.Bias = nn.Parameter(torch.ones([num_classes]))\n self.filter_list = nn.ModuleList([nn.Conv2d(1, num_filters, (size, embedding_size)) for size in filter_sizes])\n\n def forward(self, X):\n embedded_chars = self.W(X) # [batch_size, sequence_length, sequence_length]\n embedded_chars = embedded_chars.unsqueeze(1) # add channel(=1) [batch, channel(=1), sequence_length, embedding_size]\n\n pooled_outputs = []\n for i, conv in enumerate(self.filter_list):\n # conv : [input_channel(=1), output_channel(=3), (filter_height, filter_width), bias_option]\n h = F.relu(conv(embedded_chars))\n # mp : ((filter_height, filter_width))\n mp = nn.MaxPool2d((sequence_length - filter_sizes[i] + 1, 1))\n # pooled : [batch_size(=6), output_height(=1), output_width(=1), output_channel(=3)]\n pooled = mp(h).permute(0, 3, 2, 1)\n pooled_outputs.append(pooled)\n\n h_pool = torch.cat(pooled_outputs, len(filter_sizes)) # [batch_size(=6), output_height(=1), output_width(=1), output_channel(=3) * 3]\n h_pool_flat = torch.reshape(h_pool, [-1, self.num_filters_total]) # [batch_size(=6), output_height * output_width * (output_channel * 3)]\n model = self.Weight(h_pool_flat) + self.Bias # [batch_size, num_classes]\n return model\n\nif __name__ == '__main__':\n embedding_size = 2 # embedding size\n sequence_length = 3 # sequence length\n num_classes = 2 # number of classes\n filter_sizes = [2, 2, 2] # n-gram windows\n num_filters = 3 # number of filters\n\n # 3 words sentences (=sequence_length is 3)\n sentences = [\"i love you\", \"he loves me\", \"she likes baseball\", \"i hate you\", \"sorry for that\", \"this is awful\"]\n labels = [1, 1, 1, 0, 0, 0] # 1 is good, 0 is not good.\n\n word_list = \" \".join(sentences).split()\n word_list = list(set(word_list))\n word_dict = {w: i for i, w in enumerate(word_list)}\n vocab_size = len(word_dict)\n\n model = TextCNN()\n\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.Adam(model.parameters(), lr=0.001)\n\n inputs = torch.LongTensor([np.asarray([word_dict[n] for n in sen.split()]) for sen in sentences])\n targets = torch.LongTensor([out for out in labels]) # To using Torch Softmax Loss function\n\n # Training\n for epoch in range(5000):\n optimizer.zero_grad()\n output = model(inputs)\n\n # output : [batch_size, num_classes], target_batch : [batch_size] (LongTensor, not one-hot)\n loss = criterion(output, targets)\n if (epoch + 1) % 1000 == 0:\n print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss))\n\n loss.backward()\n optimizer.step()\n\n # Test\n test_text = 'sorry hate you'\n tests = [np.asarray([word_dict[n] for n in test_text.split()])]\n test_batch = torch.LongTensor(tests)\n\n # Predict\n predict = model(test_batch).data.max(1, keepdim=True)[1]\n if predict[0][0] == 0:\n print(test_text,\"is Bad Mean...\")\n else:\n print(test_text,\"is Good Mean!!\")", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
4afa5ca48ac013f4e6db865e4aaaf15e6d8867f3
65,211
ipynb
Jupyter Notebook
code/1_basic_GAN/multi-gpu_cosmogan_train.ipynb
vmos1/cosmogan_pytorch
75d3d4f652a92d45d823a051b750b35d802e2317
[ "BSD-3-Clause-LBNL" ]
1
2020-10-19T18:52:50.000Z
2020-10-19T18:52:50.000Z
code/1_basic_GAN/multi-gpu_cosmogan_train.ipynb
vmos1/cosmogan_pytorch
75d3d4f652a92d45d823a051b750b35d802e2317
[ "BSD-3-Clause-LBNL" ]
1
2020-11-13T22:35:02.000Z
2020-11-14T02:00:44.000Z
code/1_basic_GAN/multi-gpu_cosmogan_train.ipynb
vmos1/cosmogan_pytorch
75d3d4f652a92d45d823a051b750b35d802e2317
[ "BSD-3-Clause-LBNL" ]
null
null
null
44.787775
1,211
0.5001
[ [ [ "# Testing cosmogan\nAug 25, 2020\n\nBorrowing pieces of code from : \n\n- https://github.com/pytorch/tutorials/blob/11569e0db3599ac214b03e01956c2971b02c64ce/beginner_source/dcgan_faces_tutorial.py\n- https://github.com/exalearn/epiCorvid/tree/master/cGAN", "_____no_output_____" ] ], [ [ "import os\nimport random\nimport logging\nimport sys\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nfrom torchsummary import summary\nfrom torch.utils.data import DataLoader, TensorDataset\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import HTML\n\nimport argparse\nimport time\nfrom datetime import datetime\nimport glob\nimport pickle\nimport yaml\nimport collections\n\n\nimport torch.distributed as dist\nimport socket", "_____no_output_____" ], [ "%matplotlib widget", "_____no_output_____" ] ], [ [ "## Modules", "_____no_output_____" ] ], [ [ "def try_barrier():\n \"\"\"Attempt a barrier but ignore any exceptions\"\"\"\n print('BAR %d'%rank)\n\n try:\n dist.barrier()\n except:\n pass\n\ndef _get_sync_file():\n \"\"\"Logic for naming sync file using slurm env variables\"\"\"\n #sync_file_dir = '%s/pytorch-sync-files' % os.environ['SCRATCH']\n sync_file_dir = '/global/homes/b/balewski/prjs/tmp/local-sync-files'\n os.makedirs(sync_file_dir, exist_ok=True)\n sync_file = 'file://%s/pytorch_sync.%s.%s' % (\n sync_file_dir, os.environ['SLURM_JOB_ID'], os.environ['SLURM_STEP_ID'])\n return sync_file\n\n", "_____no_output_____" ], [ "def f_load_config(config_file):\n with open(config_file) as f:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n return config\n\n### Transformation functions for image pixel values\ndef f_transform(x):\n return 2.*x/(x + 4.) - 1.\n\ndef f_invtransform(s):\n return 4.*(1. + s)/(1. - s)\n", "_____no_output_____" ], [ "# custom weights initialization called on netG and netD\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0)\n\n# Generator Code\nclass View(nn.Module):\n def __init__(self, shape):\n super(View, self).__init__()\n self.shape = shape\n\n def forward(self, x):\n return x.view(*self.shape)\n\nclass Generator(nn.Module):\n def __init__(self, gdict):\n super(Generator, self).__init__()\n\n ## Define new variables from dict\n keys=['ngpu','nz','nc','ngf','kernel_size','stride','g_padding']\n ngpu, nz,nc,ngf,kernel_size,stride,g_padding=list(collections.OrderedDict({key:gdict[key] for key in keys}).values())\n\n self.main = nn.Sequential(\n # nn.ConvTranspose2d(in_channels, out_channels, kernel_size,stride,padding,output_padding,groups,bias, Dilation,padding_mode)\n nn.Linear(nz,nc*ngf*8*8*8),# 32768\n nn.BatchNorm2d(nc,eps=1e-05, momentum=0.9, affine=True),\n nn.ReLU(inplace=True),\n View(shape=[-1,ngf*8,8,8]),\n nn.ConvTranspose2d(ngf * 8, ngf * 4, kernel_size, stride, g_padding, output_padding=1, bias=False),\n nn.BatchNorm2d(ngf*4,eps=1e-05, momentum=0.9, affine=True),\n nn.ReLU(inplace=True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d( ngf * 4, ngf * 2, kernel_size, stride, g_padding, 1, bias=False),\n nn.BatchNorm2d(ngf*2,eps=1e-05, momentum=0.9, affine=True),\n nn.ReLU(inplace=True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d( ngf * 2, ngf, kernel_size, stride, g_padding, 1, bias=False),\n nn.BatchNorm2d(ngf,eps=1e-05, momentum=0.9, affine=True),\n nn.ReLU(inplace=True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d( ngf, nc, kernel_size, stride,g_padding, 1, bias=False),\n nn.Tanh()\n )\n \n def forward(self, ip):\n return self.main(ip)\n\nclass Discriminator(nn.Module):\n def __init__(self, gdict):\n super(Discriminator, self).__init__()\n \n ## Define new variables from dict\n keys=['ngpu','nz','nc','ndf','kernel_size','stride','d_padding']\n ngpu, nz,nc,ndf,kernel_size,stride,d_padding=list(collections.OrderedDict({key:gdict[key] for key in keys}).values()) \n\n self.main = nn.Sequential(\n # input is (nc) x 64 x 64\n # nn.Conv2d(in_channels, out_channels, kernel_size,stride,padding,output_padding,groups,bias, Dilation,padding_mode)\n nn.Conv2d(nc, ndf,kernel_size, stride, d_padding, bias=True),\n nn.BatchNorm2d(ndf,eps=1e-05, momentum=0.9, affine=True),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf) x 32 x 32\n nn.Conv2d(ndf, ndf * 2, kernel_size, stride, d_padding, bias=True),\n nn.BatchNorm2d(ndf * 2,eps=1e-05, momentum=0.9, affine=True),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*2) x 16 x 16\n nn.Conv2d(ndf * 2, ndf * 4, kernel_size, stride, d_padding, bias=True),\n nn.BatchNorm2d(ndf * 4,eps=1e-05, momentum=0.9, affine=True),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*4) x 8 x 8\n nn.Conv2d(ndf * 4, ndf * 8, kernel_size, stride, d_padding, bias=True),\n nn.BatchNorm2d(ndf * 8,eps=1e-05, momentum=0.9, affine=True),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*8) x 4 x 4\n nn.Flatten(),\n nn.Linear(nc*ndf*8*8*8, 1)\n# nn.Sigmoid()\n )\n\n def forward(self, ip):\n return self.main(ip)\n", "_____no_output_____" ], [ "def f_gen_images(gdict,netG,optimizerG,ip_fname,op_loc,op_strg='inf_img_',op_size=500):\n '''Generate images for best saved models\n Arguments: gdict, netG, optimizerG, \n ip_fname: name of input file\n op_strg: [string name for output file]\n op_size: Number of images to generate\n '''\n\n nz,device=gdict['nz'],gdict['device']\n\n try:\n if torch.cuda.is_available(): checkpoint=torch.load(ip_fname)\n else: checkpoint=torch.load(ip_fname,map_location=torch.device('cpu'))\n except Exception as e:\n print(e)\n print(\"skipping generation of images for \",ip_fname)\n return\n \n ## Load checkpoint\n if gdict['multi-gpu']:\n netG.module.load_state_dict(checkpoint['G_state'])\n else:\n netG.load_state_dict(checkpoint['G_state'])\n \n ## Load other stuff\n iters=checkpoint['iters']\n epoch=checkpoint['epoch']\n optimizerG.load_state_dict(checkpoint['optimizerG_state_dict'])\n \n # Generate batch of latent vectors\n noise = torch.randn(op_size, 1, 1, nz, device=device)\n # Generate fake image batch with G\n netG.eval() ## This is required before running inference\n gen = netG(noise)\n gen_images=gen.detach().cpu().numpy()[:,:,:,:]\n print(gen_images.shape)\n \n op_fname='%s_epoch-%s_step-%s.npy'%(op_strg,epoch,iters)\n\n np.save(op_loc+op_fname,gen_images)\n\n print(\"Image saved in \",op_fname)\n \ndef f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc):\n ''' Checkpoint model '''\n \n if gdict['multi-gpu']: ## Dataparallel\n torch.save({'epoch':epoch,'iters':iters,'best_chi1':best_chi1,'best_chi2':best_chi2,\n 'G_state':netG.module.state_dict(),'D_state':netD.module.state_dict(),'optimizerG_state_dict':optimizerG.state_dict(),\n 'optimizerD_state_dict':optimizerD.state_dict()}, save_loc) \n else :\n torch.save({'epoch':epoch,'iters':iters,'best_chi1':best_chi1,'best_chi2':best_chi2,\n 'G_state':netG.state_dict(),'D_state':netD.state_dict(),'optimizerG_state_dict':optimizerG.state_dict(),\n 'optimizerD_state_dict':optimizerD.state_dict()}, save_loc)\n \ndef f_load_checkpoint(ip_fname,netG,netD,optimizerG,optimizerD,gdict):\n ''' Load saved checkpoint\n Also loads step, epoch, best_chi1, best_chi2'''\n \n try:\n checkpoint=torch.load(ip_fname)\n except Exception as e:\n print(e)\n print(\"skipping generation of images for \",ip_fname)\n raise SystemError\n \n ## Load checkpoint\n if gdict['multi-gpu']:\n netG.module.load_state_dict(checkpoint['G_state'])\n netD.module.load_state_dict(checkpoint['D_state'])\n else:\n netG.load_state_dict(checkpoint['G_state'])\n netD.load_state_dict(checkpoint['D_state'])\n \n optimizerD.load_state_dict(checkpoint['optimizerD_state_dict'])\n optimizerG.load_state_dict(checkpoint['optimizerG_state_dict'])\n \n iters=checkpoint['iters']\n epoch=checkpoint['epoch']\n best_chi1=checkpoint['best_chi1']\n best_chi2=checkpoint['best_chi2']\n\n netG.train()\n netD.train()\n \n return iters,epoch,best_chi1,best_chi2", "_____no_output_____" ], [ "####################\n### Pytorch code ###\n####################\n\ndef f_torch_radial_profile(img, center=(None,None)):\n ''' Module to compute radial profile of a 2D image \n Bincount causes issues with backprop, so not using this code\n '''\n \n y,x=torch.meshgrid(torch.arange(0,img.shape[0]),torch.arange(0,img.shape[1])) # Get a grid of x and y values\n if center[0]==None and center[1]==None:\n center = torch.Tensor([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0]) # compute centers\n\n # get radial values of every pair of points\n r = torch.sqrt((x - center[0])**2 + (y - center[1])**2)\n r= r.int()\n \n# print(r.shape,img.shape)\n # Compute histogram of r values\n tbin=torch.bincount(torch.reshape(r,(-1,)),weights=torch.reshape(img,(-1,)).type(torch.DoubleTensor))\n nr = torch.bincount(torch.reshape(r,(-1,)))\n radialprofile = tbin / nr\n \n return radialprofile[1:-1]\n\n\ndef f_torch_get_azimuthalAverage_with_batch(image, center=None): ### Not used in this code.\n \"\"\"\n Calculate the azimuthally averaged radial profile. Only use if you need to combine batches\n\n image - The 2D image\n center - The [x,y] pixel coordinates used as the center. The default is \n None, which then uses the center of the image (including \n fracitonal pixels).\n source: https://www.astrobetter.com/blog/2010/03/03/fourier-transforms-of-images-in-python/\n \"\"\"\n \n batch, channel, height, width = image.shape\n # Create a grid of points with x and y coordinates\n y, x = np.indices([height,width])\n\n if not center:\n center = np.array([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0])\n\n # Get the radial coordinate for every grid point. Array has the shape of image\n r = torch.tensor(np.hypot(x - center[0], y - center[1]))\n\n # Get sorted radii\n ind = torch.argsort(torch.reshape(r, (batch, channel,-1)))\n r_sorted = torch.gather(torch.reshape(r, (batch, channel, -1,)),2, ind)\n i_sorted = torch.gather(torch.reshape(image, (batch, channel, -1,)),2, ind)\n\n # Get the integer part of the radii (bin size = 1)\n r_int=r_sorted.to(torch.int32)\n\n # Find all pixels that fall within each radial bin.\n deltar = r_int[:,:,1:] - r_int[:,:,:-1] # Assumes all radii represented\n rind = torch.reshape(torch.where(deltar)[2], (batch, -1)) # location of changes in radius\n rind=torch.unsqueeze(rind,1)\n nr = (rind[:,:,1:] - rind[:,:,:-1]).type(torch.float) # number of radius bin\n\n # Cumulative sum to figure out sums for each radius bin\n\n csum = torch.cumsum(i_sorted, axis=-1)\n# print(csum.shape,rind.shape,nr.shape)\n\n tbin = torch.gather(csum, 2, rind[:,:,1:]) - torch.gather(csum, 2, rind[:,:,:-1])\n radial_prof = tbin / nr\n\n return radial_prof\n\n\ndef f_get_rad(img):\n ''' Get the radial tensor for use in f_torch_get_azimuthalAverage '''\n \n height,width=img.shape[-2:]\n # Create a grid of points with x and y coordinates\n y, x = np.indices([height,width])\n \n center=[]\n if not center:\n center = np.array([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0])\n\n # Get the radial coordinate for every grid point. Array has the shape of image\n r = torch.tensor(np.hypot(x - center[0], y - center[1]))\n \n # Get sorted radii\n ind = torch.argsort(torch.reshape(r, (-1,)))\n \n return r.detach(),ind.detach()\n\n\ndef f_torch_get_azimuthalAverage(image,r,ind):\n \"\"\"\n Calculate the azimuthally averaged radial profile.\n\n image - The 2D image\n center - The [x,y] pixel coordinates used as the center. The default is \n None, which then uses the center of the image (including \n fracitonal pixels).\n source: https://www.astrobetter.com/blog/2010/03/03/fourier-transforms-of-images-in-python/\n \"\"\"\n \n# height, width = image.shape\n# # Create a grid of points with x and y coordinates\n# y, x = np.indices([height,width])\n\n# if not center:\n# center = np.array([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0])\n\n# # Get the radial coordinate for every grid point. Array has the shape of image\n# r = torch.tensor(np.hypot(x - center[0], y - center[1]))\n\n# # Get sorted radii\n# ind = torch.argsort(torch.reshape(r, (-1,)))\n\n r_sorted = torch.gather(torch.reshape(r, ( -1,)),0, ind)\n i_sorted = torch.gather(torch.reshape(image, ( -1,)),0, ind)\n \n # Get the integer part of the radii (bin size = 1)\n r_int=r_sorted.to(torch.int32)\n\n # Find all pixels that fall within each radial bin.\n deltar = r_int[1:] - r_int[:-1] # Assumes all radii represented\n rind = torch.reshape(torch.where(deltar)[0], (-1,)) # location of changes in radius\n nr = (rind[1:] - rind[:-1]).type(torch.float) # number of radius bin\n\n # Cumulative sum to figure out sums for each radius bin\n \n csum = torch.cumsum(i_sorted, axis=-1)\n tbin = torch.gather(csum, 0, rind[1:]) - torch.gather(csum, 0, rind[:-1])\n radial_prof = tbin / nr\n\n return radial_prof\n\ndef f_torch_fftshift(real, imag):\n for dim in range(0, len(real.size())):\n real = torch.roll(real, dims=dim, shifts=real.size(dim)//2)\n imag = torch.roll(imag, dims=dim, shifts=imag.size(dim)//2)\n return real, imag\n\ndef f_torch_compute_spectrum(arr,r,ind):\n \n GLOBAL_MEAN=1.0\n arr=(arr-GLOBAL_MEAN)/(GLOBAL_MEAN)\n y1=torch.rfft(arr,signal_ndim=2,onesided=False)\n real,imag=f_torch_fftshift(y1[:,:,0],y1[:,:,1]) ## last index is real/imag part\n y2=real**2+imag**2 ## Absolute value of each complex number\n \n# print(y2.shape)\n z1=f_torch_get_azimuthalAverage(y2,r,ind) ## Compute radial profile\n \n return z1\n\ndef f_torch_compute_batch_spectrum(arr,r,ind):\n \n batch_pk=torch.stack([f_torch_compute_spectrum(i,r,ind) for i in arr])\n \n return batch_pk\n\ndef f_torch_image_spectrum(x,num_channels,r,ind):\n '''\n Data has to be in the form (batch,channel,x,y)\n '''\n mean=[[] for i in range(num_channels)] \n sdev=[[] for i in range(num_channels)] \n\n for i in range(num_channels):\n arr=x[:,i,:,:]\n batch_pk=f_torch_compute_batch_spectrum(arr,r,ind)\n mean[i]=torch.mean(batch_pk,axis=0)\n# sdev[i]=torch.std(batch_pk,axis=0)/np.sqrt(batch_pk.shape[0])\n# sdev[i]=torch.std(batch_pk,axis=0)\n sdev[i]=torch.var(batch_pk,axis=0)\n \n mean=torch.stack(mean)\n sdev=torch.stack(sdev)\n \n return mean,sdev\n\ndef f_compute_hist(data,bins):\n \n try: \n hist_data=torch.histc(data,bins=bins)\n ## A kind of normalization of histograms: divide by total sum\n hist_data=(hist_data*bins)/torch.sum(hist_data)\n except Exception as e:\n print(e)\n hist_data=torch.zeros(bins)\n\n return hist_data\n\n### Losses \ndef loss_spectrum(spec_mean,spec_mean_ref,spec_std,spec_std_ref,image_size,lambda1):\n ''' Loss function for the spectrum : mean + variance \n Log(sum( batch value - expect value) ^ 2 )) '''\n \n idx=int(image_size/2) ### For the spectrum, use only N/2 indices for loss calc.\n ### Warning: the first index is the channel number.For multiple channels, you are averaging over them, which is fine.\n \n spec_mean=torch.log(torch.mean(torch.pow(spec_mean[:,:idx]-spec_mean_ref[:,:idx],2)))\n spec_sdev=torch.log(torch.mean(torch.pow(spec_std[:,:idx]-spec_std_ref[:,:idx],2)))\n \n lambda1=lambda1;\n lambda2=lambda1;\n ans=lambda1*spec_mean+lambda2*spec_sdev\n \n if torch.isnan(spec_sdev).any(): print(\"spec loss with nan\",ans)\n \n return ans\n \ndef loss_hist(hist_sample,hist_ref):\n \n lambda1=1.0\n return lambda1*torch.log(torch.mean(torch.pow(hist_sample-hist_ref,2)))\n", "_____no_output_____" ], [ "# def f_size(ip):\n# p=2;s=2\n# # return (ip + 2 * 0 - 1 * (p-1) -1 )/ s + 1\n\n# return (ip-1)*s - 2 * p + 1 *(5-1)+ 1 + 1\n\n# f_size(128)", "_____no_output_____" ], [ "# logging.basicConfig(filename=save_dir+'/log.log',filemode='w',format='%(name)s - %(levelname)s - %(message)s')", "_____no_output_____" ] ], [ [ "## Main code", "_____no_output_____" ] ], [ [ "def f_train_loop(dataloader,metrics_df,gdict):\n ''' Train single epoch '''\n \n ## Define new variables from dict\n keys=['image_size','start_epoch','epochs','iters','best_chi1','best_chi2','save_dir','device','flip_prob','nz','batchsize','bns']\n image_size,start_epoch,epochs,iters,best_chi1,best_chi2,save_dir,device,flip_prob,nz,batchsize,bns=list(collections.OrderedDict({key:gdict[key] for key in keys}).values())\n \n for epoch in range(start_epoch,epochs):\n t_epoch_start=time.time()\n for count, data in enumerate(dataloader, 0):\n \n ####### Train GAN ########\n netG.train(); netD.train(); ### Need to add these after inference and before training\n\n tme1=time.time()\n ### Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n netD.zero_grad()\n\n real_cpu = data[0].to(device)\n b_size = real_cpu.size(0)\n real_label = torch.full((b_size,), 1, device=device)\n fake_label = torch.full((b_size,), 0, device=device)\n g_label = torch.full((b_size,), 1, device=device) ## No flipping for Generator labels\n # Flip labels with probability flip_prob\n for idx in np.random.choice(np.arange(b_size),size=int(np.ceil(b_size*flip_prob))):\n real_label[idx]=0; fake_label[idx]=1\n\n # Generate fake image batch with G\n noise = torch.randn(b_size, 1, 1, nz, device=device)\n fake = netG(noise) \n\n # Forward pass real batch through D\n output = netD(real_cpu).view(-1)\n errD_real = criterion(output, real_label)\n errD_real.backward()\n D_x = output.mean().item()\n\n # Forward pass real batch through D\n output = netD(fake.detach()).view(-1)\n errD_fake = criterion(output, fake_label)\n errD_fake.backward()\n D_G_z1 = output.mean().item()\n errD = errD_real + errD_fake\n optimizerD.step()\n\n ###Update G network: maximize log(D(G(z)))\n netG.zero_grad()\n output = netD(fake).view(-1)\n errG_adv = criterion(output, g_label)\n # Histogram pixel intensity loss\n hist_gen=f_compute_hist(fake,bins=bns)\n hist_loss=loss_hist(hist_gen,hist_val.to(device))\n\n # Add spectral loss\n mean,sdev=f_torch_image_spectrum(f_invtransform(fake),1,r.to(device),ind.to(device))\n spec_loss=loss_spectrum(mean,mean_spec_val.to(device),sdev,sdev_spec_val.to(device),image_size,gdict['lambda1'])\n \n if gdict['spec_loss_flag']: errG=errG_adv+spec_loss\n else: errG=errG_adv\n\n if torch.isnan(errG).any():\n logging.info(errG)\n raise SystemError\n \n # Calculate gradients for G\n errG.backward()\n D_G_z2 = output.mean().item()\n optimizerG.step()\n\n tme2=time.time()\n\n ####### Store metrics ########\n # Output training stats\n if count % gdict['checkpoint_size'] == 0:\n logging.info('[%d/%d][%d/%d]\\tLoss_D: %.4f\\tLoss_adv: %.4f\\tLoss_G: %.4f\\tD(x): %.4f\\tD(G(z)): %.4f / %.4f'\n % (epoch, epochs, count, len(dataloader), errD.item(), errG_adv.item(),errG.item(), D_x, D_G_z1, D_G_z2)),\n logging.info(\"Spec loss: %s,\\t hist loss: %s\"%(spec_loss.item(),hist_loss.item())),\n logging.info(\"Training time for step %s : %s\"%(iters, tme2-tme1))\n\n # Save metrics\n cols=['step','epoch','Dreal','Dfake','Dfull','G_adv','G_full','spec_loss','hist_loss','D(x)','D_G_z1','D_G_z2','time']\n vals=[iters,epoch,errD_real.item(),errD_fake.item(),errD.item(),errG_adv.item(),errG.item(),spec_loss.item(),hist_loss.item(),D_x,D_G_z1,D_G_z2,tme2-tme1]\n for col,val in zip(cols,vals): metrics_df.loc[iters,col]=val\n\n ### Checkpoint the best model\n checkpoint=True\n iters += 1 ### Model has been updated, so update iters before saving metrics and model.\n\n ### Compute validation metrics for updated model\n netG.eval()\n with torch.no_grad():\n #fake = netG(fixed_noise).detach().cpu()\n fake = netG(fixed_noise)\n hist_gen=f_compute_hist(fake,bins=bns)\n hist_chi=loss_hist(hist_gen,hist_val.to(device))\n mean,sdev=f_torch_image_spectrum(f_invtransform(fake),1,r.to(device),ind.to(device))\n spec_chi=loss_spectrum(mean,mean_spec_val.to(device),sdev,sdev_spec_val.to(device),image_size,gdict['lambda1']) \n # Storing chi for next step\n for col,val in zip(['spec_chi','hist_chi'],[spec_chi.item(),hist_chi.item()]): metrics_df.loc[iters,col]=val \n\n # Checkpoint model for continuing run\n if count == len(dataloader)-1: ## Check point at last step of epoch\n f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_last.tar') \n\n if (checkpoint and (epoch > 1)): # Choose best models by metric\n if hist_chi< best_chi1:\n f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_best_hist.tar')\n best_chi1=hist_chi.item()\n logging.info(\"Saving best hist model at epoch %s, step %s.\"%(epoch,iters))\n\n if spec_chi< best_chi2:\n f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_best_spec.tar')\n best_chi2=spec_chi.item()\n logging.info(\"Saving best spec model at epoch %s, step %s\"%(epoch,iters))\n \n if iters in gdict['save_steps_list']:\n f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_{0}.tar'.format(iters))\n logging.info(\"Saving given-step at epoch %s, step %s.\"%(epoch,iters))\n \n # Save G's output on fixed_noise\n if ((iters % gdict['checkpoint_size'] == 0) or ((epoch == epochs-1) and (count == len(dataloader)-1))):\n netG.eval()\n with torch.no_grad():\n fake = netG(fixed_noise).detach().cpu()\n img_arr=np.array(fake[:,:,:,:])\n fname='gen_img_epoch-%s_step-%s'%(epoch,iters)\n np.save(save_dir+'/images/'+fname,img_arr)\n \n t_epoch_end=time.time()\n logging.info(\"Time taken for epoch %s: %s\"%(epoch,t_epoch_end-t_epoch_start))\n # Save Metrics to file after each epoch\n metrics_df.to_pickle(save_dir+'/df_metrics.pkle')\n \n logging.info(\"best chis: {0}, {1}\".format(best_chi1,best_chi2))", "_____no_output_____" ], [ "def f_init_gdict(gdict,config_dict):\n ''' Initialize the global dictionary gdict with values in config file'''\n keys1=['workers','nc','nz','ngf','ndf','beta1','kernel_size','stride','g_padding','d_padding','flip_prob']\n keys2=['image_size','checkpoint_size','num_imgs','ip_fname','op_loc']\n for key in keys1: gdict[key]=config_dict['training'][key]\n for key in keys2: gdict[key]=config_dict['data'][key]", "_____no_output_____" ], [ "device='cuda'\n\nif device=='cuda':\n rank = int(os.environ['SLURM_PROCID'])\n world_size = int(os.environ['SLURM_NTASKS'])\n locRank=int(os.environ['SLURM_LOCALID'])\nelse:\n rank=0; world_size = 1; locRank=0 \n\nhost=socket.gethostname()\nverb=rank==0\nprint('M:myRank=',rank,'world_size =',world_size,'verb=',verb,host,'locRank=',locRank )\nmasterIP=os.getenv('MASTER_ADDR')\nif masterIP==None:\n assert device=='cuda' # must speciffy MASTER_ADDR\n sync_file = _get_sync_file()\n if verb: print('use sync_file =',sync_file)\nelse:\n sync_file='env://'\n masterPort=os.getenv('MASTER_PORT')\n if verb: print('use masterIP',masterIP,masterPort)\n assert masterPort!=None\n\nif verb:\n print('imported PyTorch ver:',torch.__version__)\n\ndist.init_process_group(backend='nccl', init_method=sync_file, world_size=world_size, rank=rank)\nprint(\"M:after dist.init_process_group\")\n\ninp_dim=280\nfc_dim=20\nout_dim=10\n\nepochs=15\nbatch_size=16*1024//world_size # local batch size\nsteps=16\nnum_eve=steps*batch_size\nlearning_rate = 0.02\n\nnum_cpus=5 # to load the data in parallel , -c10 locks 5 phys cores\n\n# Initialize model \ntorch.manual_seed(0)\n", "M:myRank= 0 world_size = 1 verb= True cgpu17 locRank= 0\n" ], [ "model = JanModel(inp_dim,fc_dim,out_dim)\nif device=='cuda':\n torch.cuda.set_device(locRank)\n model.cuda(locRank)\n\n# define loss function\nloss_fn = nn.MSELoss().cuda(locRank)\n\n# Initialize optimizer\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n# Wrap the model\n# This reproduces the model onto the GPU for the process.\nif device=='cuda':\n model = nn.parallel.DistributedDataParallel(model, device_ids=[locRank])\n \n# - - - - DATA PERP - - - - -\nif verb: print('\\nM: generate data and train, num_eve=',num_eve)\nX,Y=create_dataset(num_eve,inp_dim,out_dim)\n\nif verb: print('\\nCreate torch-Dataset instance')\ntrainDst=JanDataset(X,Y)\n\nif verb: print('\\nCreate torch-DataLoader instance & test it, num_cpus=',num_cpus)\ntrainLdr = DataLoader(trainDst, batch_size=batch_size, shuffle=True, num_workers=num_cpus,pin_memory=True)\n# - - - - DATA READY - - - - - \n# Note, intentionally I do not use torch.utils.data.distributed.DistributedSampler(..)\n# because I want to controll manually what data will be sent to which GPU - here data are generated on CPU matched to GPU\n\nif verb:\n print('\\n print one batch of training data ')\n xx, yy = next(iter(trainLdr))\n print('test_dataLoader: X:',xx.shape,'Y:',yy.shape)\n print('Y[:,]',yy[:,0])\n\n print('\\n= = = = Prepare for the treaining = = =\\n')\n print('\\n\\nM: torchsummary.summary(model):'); print(model)\n\ninp_size=(inp_dim,) # input_size=(channels, H, W)) if CNN is first\nif device=='cuda':\n model=model.to(device) # re-cast model on device, data will be cast later", "_____no_output_____" ] ], [ [ "## Start", "_____no_output_____" ] ], [ [ "if __name__==\"__main__\":\n torch.backends.cudnn.benchmark=True\n# torch.autograd.set_detect_anomaly(True)\n\n t0=time.time()\n #################################\n# args=f_parse_args()\n # Manually add args ( different for jupyter notebook)\n args=argparse.Namespace()\n args.config='1_main_code/config_128.yaml'\n args.ngpu=1\n args.batchsize=128\n args.spec_loss_flag=True\n args.checkpoint_size=50\n args.epochs=10\n args.learn_rate=0.0002\n args.mode='fresh'\n# args.mode='continue'\n# args.ip_fldr='/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/20201211_093818_nb_test/'\n args.run_suffix='nb_test'\n args.deterministic=False\n args.seed='234373'\n args.lambda1=0.1\n args.save_steps_list=[5,10]\n\n ### Set up ###\n config_file=args.config\n config_dict=f_load_config(config_file)\n\n # Initilize variables \n gdict={}\n f_init_gdict(gdict,config_dict)\n \n ## Add args variables to gdict\n for key in ['ngpu','batchsize','mode','spec_loss_flag','epochs','learn_rate','lambda1','save_steps_list']:\n gdict[key]=vars(args)[key]\n \n ###### Set up directories #######\n if gdict['mode']=='fresh':\n # Create prefix for foldername \n fldr_name=datetime.now().strftime('%Y%m%d_%H%M%S') ## time format\n gdict['save_dir']=gdict['op_loc']+fldr_name+'_'+args.run_suffix\n \n if not os.path.exists(gdict['save_dir']):\n os.makedirs(gdict['save_dir']+'/models')\n os.makedirs(gdict['save_dir']+'/images')\n \n elif gdict['mode']=='continue': ## For checkpointed runs\n gdict['save_dir']=args.ip_fldr\n ### Read loss data\n with open (gdict['save_dir']+'df_metrics.pkle','rb') as f:\n metrics_dict=pickle.load(f) \n\n# ### Write all logging.info statements to stdout and log file (different for jpt notebooks)\n# logfile=gdict['save_dir']+'/log.log'\n# logging.basicConfig(level=logging.DEBUG, filename=logfile, filemode=\"a+\", format=\"%(asctime)-15s %(levelname)-8s %(message)s\")\n \n# Lg = logging.getLogger()\n# Lg.setLevel(logging.DEBUG)\n# lg_handler_file = logging.FileHandler(logfile)\n# lg_handler_stdout = logging.StreamHandler(sys.stdout)\n# Lg.addHandler(lg_handler_file)\n# Lg.addHandler(lg_handler_stdout)\n \n# logging.info('Args: {0}'.format(args))\n# logging.info(config_dict)\n# logging.info('Start: %s'%(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))\n# if gdict['spec_loss_flag']: logging.info(\"Using Spectral loss\")\n\n ### Override (different for jpt notebooks)\n gdict['num_imgs']=2000\n \n ## Special declarations\n gdict['bns']=50\n gdict['device']=torch.device(\"cuda\" if (torch.cuda.is_available() and gdict['ngpu'] > 0) else \"cpu\")\n gdict['ngpu']=torch.cuda.device_count()\n \n gdict['multi-gpu']=True if (gdict['device'].type == 'cuda') and (gdict['ngpu'] > 1) else False \n print(gdict)\n \n ### Initialize random seed\n if args.seed=='random': manualSeed = np.random.randint(1, 10000)\n else: manualSeed=int(args.seed)\n logging.info(\"Seed:{0}\".format(manualSeed))\n random.seed(manualSeed)\n np.random.seed(manualSeed)\n torch.manual_seed(manualSeed)\n torch.cuda.manual_seed_all(manualSeed)\n logging.info('Device:{0}'.format(gdict['device']))\n \n if args.deterministic: \n logging.info(\"Running with deterministic sequence. Performance will be slower\")\n torch.backends.cudnn.deterministic=True\n# torch.backends.cudnn.enabled = False\n torch.backends.cudnn.benchmark = False\n \n #################################\n ####### Read data and precompute ######\n img=np.load(gdict['ip_fname'],mmap_mode='r')[:gdict['num_imgs']].transpose(0,1,2,3)\n t_img=torch.from_numpy(img)\n print(\"%s, %s\"%(img.shape,t_img.shape))\n\n dataset=TensorDataset(t_img)\n dataloader=DataLoader(dataset,batch_size=gdict['batchsize'],shuffle=True,num_workers=0,drop_last=True)\n\n # Precompute metrics with validation data for computing losses\n with torch.no_grad():\n val_img=np.load(gdict['ip_fname'])[-3000:].transpose(0,1,2,3)\n t_val_img=torch.from_numpy(val_img).to(gdict['device'])\n\n # Precompute radial coordinates\n r,ind=f_get_rad(img)\n r=r.to(gdict['device']); ind=ind.to(gdict['device'])\n # Stored mean and std of spectrum for full input data once\n mean_spec_val,sdev_spec_val=f_torch_image_spectrum(f_invtransform(t_val_img),1,r,ind)\n hist_val=f_compute_hist(t_val_img,bins=gdict['bns'])\n del val_img; del t_val_img; del img; del t_img\n\n #################################\n ###### Build Networks ###\n # Define Models\n print(\"Building GAN networks\")\n # Create Generator\n netG = Generator(gdict).to(gdict['device'])\n netG.apply(weights_init)\n# print(netG)\n summary(netG,(1,1,64))\n # Create Discriminator\n netD = Discriminator(gdict).to(gdict['device'])\n netD.apply(weights_init)\n# print(netD)\n summary(netD,(1,128,128))\n \n print(\"Number of GPUs used %s\"%(gdict['ngpu']))\n if (gdict['multi-gpu']):\n netG = nn.DataParallel(netG, list(range(gdict['ngpu'])))\n netD = nn.DataParallel(netD, list(range(gdict['ngpu'])))\n \n #### Initialize networks ####\n # criterion = nn.BCELoss()\n criterion = nn.BCEWithLogitsLoss()\n \n if gdict['mode']=='fresh':\n optimizerD = optim.Adam(netD.parameters(), lr=gdict['learn_rate'], betas=(gdict['beta1'], 0.999),eps=1e-7)\n optimizerG = optim.Adam(netG.parameters(), lr=gdict['learn_rate'], betas=(gdict['beta1'], 0.999),eps=1e-7)\n ### Initialize variables \n iters,start_epoch,best_chi1,best_chi2=0,0,1e10,1e10 \n \n ### Load network weights for continuing run\n elif gdict['mode']=='continue':\n iters,start_epoch,best_chi1,best_chi2=f_load_checkpoint(gdict['save_dir']+'/models/checkpoint_last.tar',netG,netD,optimizerG,optimizerD,gdict) \n logging.info(\"Continuing existing run. Loading checkpoint with epoch {0} and step {1}\".format(start_epoch,iters))\n start_epoch+=1 ## Start with the next epoch \n\n ## Add to gdict\n for key,val in zip(['best_chi1','best_chi2','iters','start_epoch'],[best_chi1,best_chi2,iters,start_epoch]): gdict[key]=val\n print(gdict)\n \n fixed_noise = torch.randn(gdict['batchsize'], 1, 1, gdict['nz'], device=gdict['device']) #Latent vectors to view G progress \n ", "{'workers': 2, 'nc': 1, 'nz': 64, 'ngf': 64, 'ndf': 64, 'beta1': 0.5, 'kernel_size': 5, 'stride': 2, 'g_padding': 2, 'd_padding': 2, 'flip_prob': 0.01, 'image_size': 128, 'checkpoint_size': 10, 'num_imgs': 200, 'ip_fname': '/global/cfs/cdirs/m3363/vayyar/cosmogan_data/raw_data/128_square/dataset_2_smoothing_200k/norm_1_train_val.npy', 'op_loc': '/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/', 'ngpu': 1, 'batchsize': 128, 'mode': 'fresh', 'spec_loss_flag': True, 'epochs': 10, 'learn_rate': 0.0002, 'lambda1': 0.1, 'save_steps_list': [5, 10], 'save_dir': '/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/20210115_095009_nb_test', 'bns': 50, 'device': device(type='cuda'), 'multi-gpu': False}\n(200, 1, 128, 128), torch.Size([200, 1, 128, 128])\nBuilding GAN networks\n----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Linear-1 [-1, 1, 1, 32768] 2,129,920\n BatchNorm2d-2 [-1, 1, 1, 32768] 2\n ReLU-3 [-1, 1, 1, 32768] 0\n View-4 [-1, 512, 8, 8] 0\n ConvTranspose2d-5 [-1, 256, 16, 16] 3,276,800\n BatchNorm2d-6 [-1, 256, 16, 16] 512\n ReLU-7 [-1, 256, 16, 16] 0\n ConvTranspose2d-8 [-1, 128, 32, 32] 819,200\n BatchNorm2d-9 [-1, 128, 32, 32] 256\n ReLU-10 [-1, 128, 32, 32] 0\n ConvTranspose2d-11 [-1, 64, 64, 64] 204,800\n BatchNorm2d-12 [-1, 64, 64, 64] 128\n ReLU-13 [-1, 64, 64, 64] 0\n ConvTranspose2d-14 [-1, 1, 128, 128] 1,600\n Tanh-15 [-1, 1, 128, 128] 0\n================================================================\nTotal params: 6,433,218\nTrainable params: 6,433,218\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.00\nForward/backward pass size (MB): 11.75\nParams size (MB): 24.54\nEstimated Total Size (MB): 36.29\n----------------------------------------------------------------\n----------------------------------------------------------------\n Layer (type) Output Shape Param #\n================================================================\n Conv2d-1 [-1, 64, 64, 64] 1,664\n BatchNorm2d-2 [-1, 64, 64, 64] 128\n LeakyReLU-3 [-1, 64, 64, 64] 0\n Conv2d-4 [-1, 128, 32, 32] 204,928\n BatchNorm2d-5 [-1, 128, 32, 32] 256\n LeakyReLU-6 [-1, 128, 32, 32] 0\n Conv2d-7 [-1, 256, 16, 16] 819,456\n BatchNorm2d-8 [-1, 256, 16, 16] 512\n LeakyReLU-9 [-1, 256, 16, 16] 0\n Conv2d-10 [-1, 512, 8, 8] 3,277,312\n BatchNorm2d-11 [-1, 512, 8, 8] 1,024\n LeakyReLU-12 [-1, 512, 8, 8] 0\n Flatten-13 [-1, 32768] 0\n Linear-14 [-1, 1] 32,769\n================================================================\nTotal params: 4,338,049\nTrainable params: 4,338,049\nNon-trainable params: 0\n----------------------------------------------------------------\nInput size (MB): 0.06\nForward/backward pass size (MB): 11.50\nParams size (MB): 16.55\nEstimated Total Size (MB): 28.11\n----------------------------------------------------------------\nNumber of GPUs used 1\n{'workers': 2, 'nc': 1, 'nz': 64, 'ngf': 64, 'ndf': 64, 'beta1': 0.5, 'kernel_size': 5, 'stride': 2, 'g_padding': 2, 'd_padding': 2, 'flip_prob': 0.01, 'image_size': 128, 'checkpoint_size': 10, 'num_imgs': 200, 'ip_fname': '/global/cfs/cdirs/m3363/vayyar/cosmogan_data/raw_data/128_square/dataset_2_smoothing_200k/norm_1_train_val.npy', 'op_loc': '/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/', 'ngpu': 1, 'batchsize': 128, 'mode': 'fresh', 'spec_loss_flag': True, 'epochs': 10, 'learn_rate': 0.0002, 'lambda1': 0.1, 'save_steps_list': [5, 10], 'save_dir': '/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/20210115_095009_nb_test', 'bns': 50, 'device': device(type='cuda'), 'multi-gpu': False, 'best_chi1': 10000000000.0, 'best_chi2': 10000000000.0, 'iters': 0, 'start_epoch': 0}\n" ], [ "if __name__==\"__main__\":\n ################################# \n ### Set up metrics dataframe\n cols=['step','epoch','Dreal','Dfake','Dfull','G_adv','G_full','spec_loss','hist_loss','spec_chi','hist_chi','D(x)','D_G_z1','D_G_z2','time']\n # size=int(len(dataloader) * epochs)+1\n metrics_df=pd.DataFrame(columns=cols)\n \n #################################\n ########## Train loop and save metrics and images ######\n print(\"Starting Training Loop...\")\n f_train_loop(dataloader,metrics_df,gdict)\n \n ## Generate images for best saved models ######\n op_loc=gdict['save_dir']+'/images/'\n ip_fname=gdict['save_dir']+'/models/checkpoint_best_spec.tar'\n f_gen_images(gdict,netG,optimizerG,ip_fname,op_loc,op_strg='best_spec',op_size=200)\n \n ip_fname=gdict['save_dir']+'/models/checkpoint_best_hist.tar'\n f_gen_images(gdict,netG,optimizerG,ip_fname,op_loc,op_strg='best_hist',op_size=200)\n \n tf=time.time()\n print(\"Total time %s\"%(tf-t0))\n print('End: %s'%(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))\n ", "Starting Training Loop...\n(200, 128, 128)\nImage saved in best_spec_epoch-2_step-3.npy\n(200, 128, 128)\nImage saved in best_hist_epoch-9_step-10.npy\nTotal time 18.619718313217163\nEnd: 2021-01-15 09:50:27\n" ], [ "# metrics_df.plot('step','time')\nmetrics_df", "_____no_output_____" ], [ "gdict", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4afa83e29a15cfb4a694fa9cd275e53729af8b3f
290,418
ipynb
Jupyter Notebook
notebooks/Programming Exercise 1 - Linear Regression.ipynb
Realtyxxx/Coursera-Machine-Learning
1d384c69341a4d48a74c543282b039381b702407
[ "MIT" ]
1
2020-06-13T15:23:46.000Z
2020-06-13T15:23:46.000Z
notebooks/Programming Exercise 1 - Linear Regression.ipynb
Realtyxxx/Coursera-Machine-Learning
1d384c69341a4d48a74c543282b039381b702407
[ "MIT" ]
null
null
null
notebooks/Programming Exercise 1 - Linear Regression.ipynb
Realtyxxx/Coursera-Machine-Learning
1d384c69341a4d48a74c543282b039381b702407
[ "MIT" ]
null
null
null
791.3297
215,789
0.93885
[ [ [ "## Programming Exercise 1 - Linear Regression\n\n- [warmUpExercise](#warmUpExercise)\n- [Linear regression with one variable](#Linear-regression-with-one-variable)\n- [Gradient Descent](#Gradient-Descent)", "_____no_output_____" ] ], [ [ "# %load ../../standard_import.txt\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.linear_model import LinearRegression\nfrom mpl_toolkits.mplot3d import axes3d\n\npd.set_option('display.notebook_repr_html', False)\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', 150)\npd.set_option('display.max_seq_items', None)\n \n#%config InlineBackend.figure_formats = {'pdf',}\n%matplotlib inline \n\nimport seaborn as sns\nsns.set_context('notebook')\nsns.set_style('white')", "_____no_output_____" ] ], [ [ "#### warmUpExercise", "_____no_output_____" ] ], [ [ "def warmUpExercise():\n return(np.identity(5))", "_____no_output_____" ], [ "warmUpExercise()", "_____no_output_____" ] ], [ [ "### Linear regression with one variable", "_____no_output_____" ] ], [ [ "data = np.loadtxt('data/ex1data1.txt', delimiter=',')\n\nX = np.c_[np.ones(data.shape[0]),data[:,0]]\ny = np.c_[data[:,1]]", "_____no_output_____" ], [ "plt.scatter(X[:,1], y, s=30, c='r', marker='x', linewidths=1)\nplt.xlim(4,24)\nplt.xlabel('Population of City in 10,000s')\nplt.ylabel('Profit in $10,000s');", "_____no_output_____" ] ], [ [ "#### Gradient Descent", "_____no_output_____" ] ], [ [ "def computeCost(X, y, theta=[[0],[0]]):\n m = y.size\n J = 0\n \n h = X.dot(theta)\n \n J = 1/(2*m)*np.sum(np.square(h-y))\n \n return(J)", "_____no_output_____" ], [ "computeCost(X,y)", "_____no_output_____" ], [ "def gradientDescent(X, y, theta=[[0],[0]], alpha=0.01, num_iters=1500):\n m = y.size\n J_history = np.zeros(num_iters)\n \n for iter in np.arange(num_iters):\n h = X.dot(theta)\n theta = theta - alpha*(1/m)*(X.T.dot(h-y))\n J_history[iter] = computeCost(X, y, theta)\n return(theta, J_history)", "_____no_output_____" ], [ "# theta for minimized cost J\ntheta , Cost_J = gradientDescent(X, y)\nprint('theta: ',theta.ravel())\n\nplt.plot(Cost_J)\nplt.ylabel('Cost J')\nplt.xlabel('Iterations');", "theta: [-3.63029144 1.16636235]\n" ], [ "xx = np.arange(5,23)\nyy = theta[0]+theta[1]*xx\n\n# Plot gradient descent\nplt.scatter(X[:,1], y, s=30, c='r', marker='x', linewidths=1)\nplt.plot(xx,yy, label='Linear regression (Gradient descent)')\n\n# Compare with Scikit-learn Linear regression \nregr = LinearRegression()\nregr.fit(X[:,1].reshape(-1,1), y.ravel())\nplt.plot(xx, regr.intercept_+regr.coef_*xx, label='Linear regression (Scikit-learn GLM)')\n\nplt.xlim(4,24)\nplt.xlabel('Population of City in 10,000s')\nplt.ylabel('Profit in $10,000s')\nplt.legend(loc=4);", "_____no_output_____" ], [ "# Predict profit for a city with population of 35000 and 70000\nprint(theta.T.dot([1, 3.5])*10000)\nprint(theta.T.dot([1, 7])*10000)", "[ 4519.7678677]\n[ 45342.45012945]\n" ], [ "# Create grid coordinates for plotting\nB0 = np.linspace(-10, 10, 50)\nB1 = np.linspace(-1, 4, 50)\nxx, yy = np.meshgrid(B0, B1, indexing='xy')\nZ = np.zeros((B0.size,B1.size))\n\n# Calculate Z-values (Cost) based on grid of coefficients\nfor (i,j),v in np.ndenumerate(Z):\n Z[i,j] = computeCost(X,y, theta=[[xx[i,j]], [yy[i,j]]])\n\nfig = plt.figure(figsize=(15,6))\nax1 = fig.add_subplot(121)\nax2 = fig.add_subplot(122, projection='3d')\n\n# Left plot\nCS = ax1.contour(xx, yy, Z, np.logspace(-2, 3, 20), cmap=plt.cm.jet)\nax1.scatter(theta[0],theta[1], c='r')\n\n# Right plot\nax2.plot_surface(xx, yy, Z, rstride=1, cstride=1, alpha=0.6, cmap=plt.cm.jet)\nax2.set_zlabel('Cost')\nax2.set_zlim(Z.min(),Z.max())\nax2.view_init(elev=15, azim=230)\n\n# settings common to both plots\nfor ax in fig.axes:\n ax.set_xlabel(r'$\\theta_0$', fontsize=17)\n ax.set_ylabel(r'$\\theta_1$', fontsize=17)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
4afa89faf88680a6afef847af273d28954410fd1
6,345
ipynb
Jupyter Notebook
examples/basic_usage.ipynb
pjhartout/fastwlk
deb78923c9a8450099c26bac09da94ae87892d0d
[ "BSD-3-Clause" ]
null
null
null
examples/basic_usage.ipynb
pjhartout/fastwlk
deb78923c9a8450099c26bac09da94ae87892d0d
[ "BSD-3-Clause" ]
7
2022-03-21T08:46:44.000Z
2022-03-25T16:20:48.000Z
examples/basic_usage.ipynb
pjhartout/fastwlk
deb78923c9a8450099c26bac09da94ae87892d0d
[ "BSD-3-Clause" ]
null
null
null
29.929245
143
0.527817
[ [ [ "import pickle\n\nfrom pyprojroot import here\n\nfrom fastwlk.kernel import WeisfeilerLehmanKernel\n", "_____no_output_____" ], [ "# Let's first load some graphs from a pickle file\nwith open(here() / \"data/graphs.pkl\", \"rb\") as f:\n graphs = pickle.load(f)", "_____no_output_____" ], [ "wl_kernel = WeisfeilerLehmanKernel(\n n_jobs=6, n_iter=4, node_label=\"residue\", biased=True, verbose=True\n)\n# Returns self-similarity kernel matrix\nKX = wl_kernel.compute_gram_matrix(graphs)\n\n# Returns similarity kernel matrix between two different graph distributions\nKXY = wl_kernel.compute_gram_matrix(graphs[:30], graphs[30:])", "Compute hashes of X: 100%|██████████| 100/100 [00:01<00:00, 89.14it/s]\nCompute dot products: 100%|██████████| 6/6 [00:00<00:00, 14.07it/s]\nCompute hashes of X: 100%|██████████| 30/30 [00:00<00:00, 131.39it/s]\nCompute hashes of Y: 100%|██████████| 70/70 [00:00<00:00, 128.51it/s]\nCompute dot products: 100%|██████████| 6/6 [00:00<00:00, 21.28it/s]\n" ], [ "print(KX.shape)\nprint(KXY.shape)", "(100, 100)\n(30, 70)\n" ], [ "# It's also possible to get an unbiased version of the kernel matrix, avoiding comparing X_i to itself, saving even more computations.\n# This can be useful when evaluating unbiased estimates of the maximum mean discrepancy and other similarity measures in RKHS.\n\nwl_kernel_unbiased = WeisfeilerLehmanKernel(\n n_jobs=6, n_iter=4, node_label=\"residue\", biased=False, verbose=True,\n )\n# Returns unbiased self-similarity kernel matrix\nKX_unbiased = wl_kernel_unbiased.compute_gram_matrix(graphs)\n\nwl_kernel_biased = WeisfeilerLehmanKernel(\n n_jobs=6, n_iter=4, node_label=\"residue\", biased=True, verbose=True,\n)\n# Returns biased self-similarity kernel matrix\nKX_biased = wl_kernel_biased.compute_gram_matrix(graphs)", "Compute hashes of X: 100%|██████████| 100/100 [00:00<00:00, 133.04it/s]\nCompute dot products: 100%|██████████| 6/6 [00:00<00:00, 18.19it/s]\nCompute hashes of X: 100%|██████████| 100/100 [00:00<00:00, 132.52it/s]\nCompute dot products: 100%|██████████| 6/6 [00:00<00:00, 16.30it/s]\n" ], [ "print(\"Unbiased kernel matrix:\")\nprint(KX_unbiased)\nprint(\"Full kernel matrix:\")\nprint(KX_biased)", "Unbiased kernel matrix:\n[[ 0 5062 5009 ... 6347 7039 15688]\n [ 5062 0 9726 ... 13401 16818 34219]\n [ 5009 9726 0 ... 12198 15083 31149]\n ...\n [ 6347 13401 12198 ... 0 17613 43219]\n [ 7039 16818 15083 ... 17613 0 42820]\n [15688 34219 31149 ... 43219 42820 0]]\nFull kernel matrix:\n[[ 3608 5062 5009 ... 6347 7039 15688]\n [ 5062 14532 9726 ... 13401 16818 34219]\n [ 5009 9726 13649 ... 12198 15083 31149]\n ...\n [ 6347 13401 12198 ... 19780 17613 43219]\n [ 7039 16818 15083 ... 17613 28336 42820]\n [ 15688 34219 31149 ... 43219 42820 130398]]\n" ], [ "# If for whatever reason you are comparing the same graphs multiple times \n# but with a different kernel config, you can precompute the hashes and set\n# the precomputed flag to True.\n\nwl_kernel = WeisfeilerLehmanKernel(\n n_jobs=6, precomputed=True, n_iter=4, node_label=\"residue\", biased=True, verbose=True,\n)\n\nhashes = [wl_kernel.compute_wl_hashes(graph) for graph in graphs]\n\n\nwl_kernel.compute_gram_matrix(hashes)", "Compute dot products: 100%|██████████| 6/6 [00:00<00:00, 9.76it/s]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4afabe91ff592627634e7c6905511ba5c8bd96b6
1,161
ipynb
Jupyter Notebook
notebooks/Untitled.ipynb
bollwyvl/es6-widget-example
0d9d93a8fe663600c2e3627e310a9f99b34af1e3
[ "BSD-3-Clause" ]
null
null
null
notebooks/Untitled.ipynb
bollwyvl/es6-widget-example
0d9d93a8fe663600c2e3627e310a9f99b34af1e3
[ "BSD-3-Clause" ]
null
null
null
notebooks/Untitled.ipynb
bollwyvl/es6-widget-example
0d9d93a8fe663600c2e3627e310a9f99b34af1e3
[ "BSD-3-Clause" ]
null
null
null
16.826087
62
0.517657
[ [ [ "from es6widgetexample.es6examplewidget import ES6Example", "_____no_output_____" ], [ "from ipywidgets import Text", "_____no_output_____" ], [ "ex = ES6Example(foo=Text(value=\"Bar\"))\nex", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
4afac29fa08f986cc70e4b780486803d5362defe
30,522
ipynb
Jupyter Notebook
BEL to Natural Language.ipynb
djinnome/pybel-notebooks
424324f12abb2e842f6a6a16ab51dc98a241c505
[ "Apache-2.0" ]
2
2019-11-14T01:26:27.000Z
2021-09-08T04:24:05.000Z
BEL to Natural Language.ipynb
djinnome/pybel-notebooks
424324f12abb2e842f6a6a16ab51dc98a241c505
[ "Apache-2.0" ]
17
2016-10-21T10:50:48.000Z
2022-01-17T18:59:45.000Z
BEL to Natural Language.ipynb
djinnome/pybel-notebooks
424324f12abb2e842f6a6a16ab51dc98a241c505
[ "Apache-2.0" ]
4
2017-06-30T17:16:46.000Z
2020-04-05T02:22:50.000Z
50.87
9,907
0.524966
[ [ [ "# BEL to Natural Language\n\n**Author:** [Charles Tapley Hoyt](https://github.com/cthoyt/)\n\n**Estimated Run Time:** 5 seconds\n\nThis notebook shows how the PyBEL-INDRA integration can be used to turn a BEL graph into natural language. Special thanks to John Bachman and Ben Gyori for all of their efforts in making this possible.\n\nTo view the interactive Javascript output in this notebook, open in the [Jupyter NBViewer](http://nbviewer.jupyter.org/github/pybel/pybel-notebooks/blob/master/BEL%20to%20Natural%20Language.ipynb).", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import sys\nimport time\n\nimport indra\nimport indra.util.get_version\nimport ndex2\nimport pybel\n\nfrom indra.assemblers.english_assembler import EnglishAssembler\nfrom indra.sources.bel.bel_api import process_pybel_graph\n\nfrom pybel.examples import sialic_acid_graph\nfrom pybel_tools.visualization import to_jupyter", "_____no_output_____" ] ], [ [ "## Environment", "_____no_output_____" ] ], [ [ "print(sys.version)", "3.6.3 (default, Oct 9 2017, 09:47:56) \n[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)]\n" ], [ "print(time.asctime())", "Thu Mar 15 13:55:44 2018\n" ] ], [ [ "## Dependencies", "_____no_output_____" ] ], [ [ "pybel.utils.get_version()", "_____no_output_____" ], [ "indra.util.get_version.get_version()", "_____no_output_____" ] ], [ [ "# Data\n\nThe [Sialic Acid graph](http://pybel.readthedocs.io/en/latest/examples.html#pybel.examples.sialic_acid_example.pybel.examples.sialic_acid_graph) is used as an example.", "_____no_output_____" ] ], [ [ "to_jupyter(sialic_acid_graph)", "_____no_output_____" ] ], [ [ "# Conversion\n\nThe PyBEL BELGraph instance is converted to INDRA statments with the function [`process_pybel_graph`](http://indra.readthedocs.io/en/latest/modules/sources/bel/index.html#indra.sources.bel.bel_api.process_pybel_graph). It returns an instance of [`PybelProcessor`](`http://indra.readthedocs.io/en/latest/modules/sources/bel/index.html#module-indra.sources.bel.pybel_processor`), which stores the INDRA statments.", "_____no_output_____" ] ], [ [ "pbp = process_pybel_graph(sialic_acid_graph)", "INFO: [2018-03-15 13:55:44] indra/pybel_processor - Unable to get identifier information for node: a(CHEBI:\"sialic acid\")\nINFO: [2018-03-15 13:55:44] indra/pybel_processor - Unable to get identifier information for node: a(CHEBI:\"sialic acid\")\n" ] ], [ [ "A list of INDRA statements is extracted from the BEL graph and stored in the field [`PybelProcessor.statements`](http://indra.readthedocs.io/en/latest/modules/sources/bel/index.html#indra.sources.bel.pybel_processor.PybelProcessor.statements). Note that INDRA is built to consider mechanistic information, and therefore excludes most associative relationships.", "_____no_output_____" ] ], [ [ "stmts = pbp.statements\nstmts", "_____no_output_____" ] ], [ [ "The list of INDRA statements is converted to plain english using the [`EnglishAssembler`](http://indra.readthedocs.io/en/latest/modules/assemblers/english_assembler.html#indra.assemblers.english_assembler.EnglishAssembler).", "_____no_output_____" ] ], [ [ "asm = EnglishAssembler(stmts)\nprint(asm.make_model(), sep='\\n')", "Active CD33 leads to the phosphorylation of CD33. Active phosphorylated CD33 activates PTPN6. Active phosphorylated CD33 activates PTPN11. Active PTPN6 inhibits SYK. Active PTPN11 inhibits SYK. Active SYK activates TREM2. Active SYK activates TYROBP.\n" ] ], [ [ "# Conclusion\n\nWhile knowledge assembly is indeed difficult and precarious, the true scientific task is to use them to generate mechanistic hypotheses. By far, the most common way is for a scientist to use their intution and choose an explanatory subgraph or pathway. This notebook has demonstrated that after this has been done, the results can be serialized to english prose in a precise manner.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4afacd7da34e6c7936049e8c703c6a1022ff28f3
17,502
ipynb
Jupyter Notebook
notebooks/protocol_examples.ipynb
gvashishtha/seldon-core
425431b90a99576a6dfeb65927bca41e740fca0f
[ "Apache-2.0" ]
4
2019-08-29T19:36:55.000Z
2021-12-20T00:37:08.000Z
notebooks/protocol_examples.ipynb
gvashishtha/seldon-core
425431b90a99576a6dfeb65927bca41e740fca0f
[ "Apache-2.0" ]
153
2020-02-03T10:48:40.000Z
2021-08-02T10:31:51.000Z
notebooks/protocol_examples.ipynb
YikSanChan/seldon-core
1b94454c137e41ce6e38a320667d140352805cc7
[ "Apache-2.0" ]
3
2019-10-27T17:56:52.000Z
2021-02-21T17:06:03.000Z
26.967643
551
0.517027
[ [ [ "# Basic Examples with Different Protocols\n\n## Prerequisites\n\n * A kubernetes cluster with kubectl configured\n * curl\n * grpcurl\n * pygmentize\n \n## Examples\n\n * [Seldon Protocol](#Seldon-Protocol-Model)\n * [Tensorflow Protocol](#Tensorflow-Protocol-Model)\n * [KFServing V2 Protocol](#KFServing-V2-Protocol-Model)\n \n\n## Setup Seldon Core\n\nUse the setup notebook to [Setup Cluster](https://docs.seldon.io/projects/seldon-core/en/latest/examples/seldon_core_setup.html) to setup Seldon Core with an ingress - either Ambassador or Istio.\n\nThen port-forward to that ingress on localhost:8003 in a separate terminal either with:\n\n * Ambassador: `kubectl port-forward $(kubectl get pods -n seldon -l app.kubernetes.io/name=ambassador -o jsonpath='{.items[0].metadata.name}') -n seldon 8003:8080`\n * Istio: `kubectl port-forward $(kubectl get pods -l istio=ingressgateway -n istio-system -o jsonpath='{.items[0].metadata.name}') -n istio-system 8003:80`", "_____no_output_____" ] ], [ [ "!kubectl create namespace seldon", "Error from server (AlreadyExists): namespaces \"seldon\" already exists\r\n" ], [ "!kubectl config set-context $(kubectl config current-context) --namespace=seldon", "Context \"kind-kind\" modified.\r\n" ], [ "import json\nimport time", "_____no_output_____" ], [ "from IPython.core.magic import register_line_cell_magic\n\n@register_line_cell_magic\ndef writetemplate(line, cell):\n with open(line, 'w') as f:\n f.write(cell.format(**globals()))", "_____no_output_____" ], [ "VERSION=!cat ../version.txt\nVERSION=VERSION[0]\nVERSION", "_____no_output_____" ] ], [ [ "## Seldon Protocol Model", "_____no_output_____" ], [ "We will deploy a REST model that uses the SELDON Protocol namely by specifying the attribute `protocol: seldon`", "_____no_output_____" ] ], [ [ "%%writetemplate resources/model_seldon.yaml\napiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: example-seldon\nspec:\n protocol: seldon\n predictors:\n - componentSpecs:\n - spec:\n containers:\n - image: seldonio/mock_classifier:{VERSION}\n name: classifier\n graph:\n name: classifier\n type: MODEL\n name: model\n replicas: 1", "_____no_output_____" ], [ "!kubectl apply -f resources/model_seldon.yaml", "seldondeployment.machinelearning.seldon.io/example-seldon created\r\n" ], [ "!kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example-seldon -o jsonpath='{.items[0].metadata.name}')", "Waiting for deployment \"example-seldon-model-0-classifier\" rollout to finish: 0 of 1 updated replicas are available...\ndeployment \"example-seldon-model-0-classifier\" successfully rolled out\n" ], [ "for i in range(60):\n state=!kubectl get sdep example-seldon -o jsonpath='{.status.state}'\n state=state[0]\n print(state)\n if state==\"Available\":\n break\n time.sleep(1)\nassert(state==\"Available\")", "Available\n" ], [ "X=!curl -s -d '{\"data\": {\"ndarray\":[[1.0, 2.0, 5.0]]}}' \\\n -X POST http://localhost:8003/seldon/seldon/example-seldon/api/v1.0/predictions \\\n -H \"Content-Type: application/json\"\nd=json.loads(X[0])\nprint(d)\nassert(d[\"data\"][\"ndarray\"][0][0] > 0.4)", "{'data': {'names': ['proba'], 'ndarray': [[0.43782349911420193]]}, 'meta': {'requestPath': {'classifier': 'seldonio/mock_classifier:1.6.0-dev'}}}\n" ], [ "X=!cd ../executor/proto && grpcurl -d '{\"data\":{\"ndarray\":[[1.0,2.0,5.0]]}}' \\\n -rpc-header seldon:example-seldon -rpc-header namespace:seldon \\\n -plaintext \\\n -proto ./prediction.proto 0.0.0.0:8003 seldon.protos.Seldon/Predict\nd=json.loads(\"\".join(X))\nprint(d)\nassert(d[\"data\"][\"ndarray\"][0][0] > 0.4)", "{'meta': {'requestPath': {'classifier': 'seldonio/mock_classifier:1.6.0-dev'}}, 'data': {'names': ['proba'], 'ndarray': [[0.43782349911420193]]}}\n" ], [ "!kubectl delete -f resources/model_seldon.yaml", "seldondeployment.machinelearning.seldon.io \"example-seldon\" deleted\r\n" ] ], [ [ "## Tensorflow Protocol Model\nWe will deploy a model that uses the TENSORLFOW Protocol namely by specifying the attribute `protocol: tensorflow`", "_____no_output_____" ] ], [ [ "%%writefile resources/model_tfserving.yaml\napiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: example-tfserving\nspec:\n protocol: tensorflow\n predictors:\n - componentSpecs:\n - spec:\n containers:\n - args: \n - --port=8500\n - --rest_api_port=8501\n - --model_name=halfplustwo\n - --model_base_path=gs://seldon-models/tfserving/half_plus_two\n image: tensorflow/serving\n name: halfplustwo\n ports:\n - containerPort: 8501\n name: http\n protocol: TCP\n - containerPort: 8500\n name: grpc\n protocol: TCP\n graph:\n name: halfplustwo\n type: MODEL\n endpoint:\n httpPort: 8501\n grpcPort: 8500\n name: model\n replicas: 1", "Overwriting resources/model_tfserving.yaml\n" ], [ "!kubectl apply -f resources/model_tfserving.yaml", "seldondeployment.machinelearning.seldon.io/example-tfserving created\r\n" ], [ "!kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=example-tfserving \\\n -o jsonpath='{.items[0].metadata.name}')", "deployment \"example-tfserving-model-0-halfplustwo\" successfully rolled out\r\n" ], [ "for i in range(60):\n state=!kubectl get sdep example-tfserving -o jsonpath='{.status.state}'\n state=state[0]\n print(state)\n if state==\"Available\":\n break\n time.sleep(1)\nassert(state==\"Available\")", "Available\n" ], [ "X=!curl -s -d '{\"instances\": [1.0, 2.0, 5.0]}' \\\n -X POST http://localhost:8003/seldon/seldon/example-tfserving/v1/models/halfplustwo/:predict \\\n -H \"Content-Type: application/json\"\nd=json.loads(\"\".join(X))\nprint(d)\nassert(d[\"predictions\"][0] == 2.5)", "{'predictions': [2.5, 3.0, 4.5]}\n" ], [ "X=!cd ../executor/proto && grpcurl \\\n -d '{\"model_spec\":{\"name\":\"halfplustwo\"},\"inputs\":{\"x\":{\"dtype\": 1, \"tensor_shape\": {\"dim\":[{\"size\": 3}]}, \"floatVal\" : [1.0, 2.0, 3.0]}}}' \\\n -rpc-header seldon:example-tfserving -rpc-header namespace:seldon \\\n -plaintext -proto ./prediction_service.proto \\\n 0.0.0.0:8003 tensorflow.serving.PredictionService/Predict\nd=json.loads(\"\".join(X))\nprint(d)\nassert(d[\"outputs\"][\"x\"][\"floatVal\"][0] == 2.5)", "{'outputs': {'x': {'dtype': 'DT_FLOAT', 'tensorShape': {'dim': [{'size': '3'}]}, 'floatVal': [2.5, 3, 3.5]}}, 'modelSpec': {'name': 'halfplustwo', 'version': '123', 'signatureName': 'serving_default'}}\n" ], [ "!kubectl delete -f resources/model_tfserving.yaml", "seldondeployment.machinelearning.seldon.io \"example-tfserving\" deleted\r\n" ] ], [ [ "## KFServing V2 Protocol Model", "_____no_output_____" ], [ "We will deploy a REST model that uses the KFServing V2 Protocol namely by specifying the attribute `protocol: kfserving`", "_____no_output_____" ] ], [ [ "%%writefile resources/model_v2.yaml\napiVersion: machinelearning.seldon.io/v1alpha2\nkind: SeldonDeployment\nmetadata:\n name: triton\nspec:\n protocol: kfserving\n predictors:\n - graph:\n children: []\n implementation: TRITON_SERVER\n modelUri: gs://seldon-models/trtis/simple-model\n name: simple\n name: simple\n replicas: 1", "Overwriting resources/model_v2.yaml\n" ], [ "!kubectl apply -f resources/model_v2.yaml", "seldondeployment.machinelearning.seldon.io/triton created\r\n" ], [ "!kubectl rollout status deploy/$(kubectl get deploy -l seldon-deployment-id=triton -o jsonpath='{.items[0].metadata.name}')", "Waiting for deployment \"triton-simple-0-simple\" rollout to finish: 0 of 1 updated replicas are available...\ndeployment \"triton-simple-0-simple\" successfully rolled out\n" ], [ "for i in range(60):\n state=!kubectl get sdep triton -o jsonpath='{.status.state}'\n state=state[0]\n print(state)\n if state==\"Available\":\n break\n time.sleep(1)\nassert(state==\"Available\")", "Available\n" ], [ "X=!curl -s -d '{\"inputs\":[{\"name\":\"INPUT0\",\"data\":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],\"datatype\":\"INT32\",\"shape\":[1,16]},{\"name\":\"INPUT1\",\"data\":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],\"datatype\":\"INT32\",\"shape\":[1,16]}]}' \\\n -X POST http://0.0.0.0:8003/seldon/seldon/triton/v2/models/simple/infer \\\n -H \"Content-Type: application/json\"\nd=json.loads(X[0])\nprint(d)\nassert(d[\"outputs\"][0][\"data\"][0]==2)", "{'model_name': 'simple', 'model_version': '1', 'outputs': [{'name': 'OUTPUT0', 'datatype': 'INT32', 'shape': [1, 16], 'data': [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32]}, {'name': 'OUTPUT1', 'datatype': 'INT32', 'shape': [1, 16], 'data': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}]}\n" ], [ "X=!cd ../executor/api/grpc/kfserving/inference && \\\n grpcurl -d '{\"model_name\":\"simple\",\"inputs\":[{\"name\":\"INPUT0\",\"contents\":{\"int_contents\":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]},\"datatype\":\"INT32\",\"shape\":[1,16]},{\"name\":\"INPUT1\",\"contents\":{\"int_contents\":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]},\"datatype\":\"INT32\",\"shape\":[1,16]}]}' \\\n -plaintext -proto ./grpc_service.proto \\\n -rpc-header seldon:triton -rpc-header namespace:seldon \\\n 0.0.0.0:8003 inference.GRPCInferenceService/ModelInfer\nX=\"\".join(X)\nprint(X)", "{ \"modelName\": \"simple\", \"modelVersion\": \"1\", \"outputs\": [ { \"name\": \"OUTPUT0\", \"datatype\": \"INT32\", \"shape\": [ \"1\", \"16\" ] }, { \"name\": \"OUTPUT1\", \"datatype\": \"INT32\", \"shape\": [ \"1\", \"16\" ] } ], \"rawOutputContents\": [ \"AgAAAAQAAAAGAAAACAAAAAoAAAAMAAAADgAAABAAAAASAAAAFAAAABYAAAAYAAAAGgAAABwAAAAeAAAAIAAAAA==\", \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==\" ]}\n" ], [ "!kubectl delete -f resources/model_v2.yaml", "seldondeployment.machinelearning.seldon.io \"triton\" deleted\r\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
4afadd4c072885a11e6cf8217a119a365ba50647
30,980
ipynb
Jupyter Notebook
Datascience_With_Python/Machine Learning/Videos/Solar Radiation Prediction/solar_radiation_prediction.ipynb
vishnupriya129/winter-of-contributing
8632c74d0c2d55bb4fddee9d6faac30159f376e1
[ "MIT" ]
1,078
2021-09-05T09:44:33.000Z
2022-03-27T01:16:02.000Z
Datascience_With_Python/Machine Learning/Videos/Solar Radiation Prediction/solar_radiation_prediction.ipynb
vishnupriya129/winter-of-contributing
8632c74d0c2d55bb4fddee9d6faac30159f376e1
[ "MIT" ]
6,845
2021-09-05T12:49:50.000Z
2022-03-12T16:41:13.000Z
Datascience_With_Python/Machine Learning/Videos/Solar Radiation Prediction/solar_radiation_prediction.ipynb
vishnupriya129/winter-of-contributing
8632c74d0c2d55bb4fddee9d6faac30159f376e1
[ "MIT" ]
2,629
2021-09-03T04:53:16.000Z
2022-03-20T17:45:00.000Z
29.645933
284
0.405713
[ [ [ "# Introduction:\n- The dataset contains such columns as: \"wind direction\", \"wind speed\", \"humidity\" and temperature. The response parameter that is to be predicted is: \"Solar_radiation\". It contains measurements for the past 4 months and you have to predict the level of solar radiation.", "_____no_output_____" ], [ "Importing the libraries", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression,ElasticNet\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error", "_____no_output_____" ], [ "df=pd.read_csv(\"SolarPrediction.csv\")", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.tail()", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df.columns", "_____no_output_____" ], [ "df.var()", "_____no_output_____" ], [ "df.corr()", "_____no_output_____" ], [ "df.describe()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 32686 entries, 0 to 32685\nData columns (total 11 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 UNIXTime 32686 non-null int64 \n 1 Data 32686 non-null object \n 2 Time 32686 non-null object \n 3 Radiation 32686 non-null float64\n 4 Temperature 32686 non-null int64 \n 5 Pressure 32686 non-null float64\n 6 Humidity 32686 non-null int64 \n 7 WindDirection(Degrees) 32686 non-null float64\n 8 Speed 32686 non-null float64\n 9 TimeSunRise 32686 non-null object \n 10 TimeSunSet 32686 non-null object \ndtypes: float64(4), int64(3), object(4)\nmemory usage: 2.7+ MB\n" ], [ "df.isnull().sum()", "_____no_output_____" ], [ "X=df.drop(['Data','Time','TimeSunRise','TimeSunSet','Radiation'],axis=1)\ny=df['Radiation']", "_____no_output_____" ], [ "X_train, X_, y_train, y_ = train_test_split(X, y, test_size=0.30, random_state=101)", "_____no_output_____" ], [ "X_val, X_test, y_val, y_test = train_test_split(X_, y_, test_size=0.30, random_state=101)", "_____no_output_____" ], [ "scaler=StandardScaler()", "_____no_output_____" ], [ "X_train=scaler.fit_transform(X_train)\nX_val=scaler.fit_transform(X_val)\nX_test=scaler.transform(X_test)", "_____no_output_____" ], [ "linear_model=LinearRegression()\nlinear_model.fit(X_train,y_train)", "_____no_output_____" ], [ "ElasticNet_model=ElasticNet()\nElasticNet_model.fit(X_train,y_train)", "_____no_output_____" ], [ "RandomForest_model=RandomForestRegressor()\nRandomForest_model.fit(X_train,y_train)", "_____no_output_____" ], [ "GradientBoosting_model=GradientBoostingRegressor()\nGradientBoosting_model.fit(X_train,y_train)", "_____no_output_____" ], [ "def report(model):\n preds = model.predict(X_val)\n MAE= mean_absolute_error(preds,y_val)\n MSE=mean_squared_error(preds,y_val)\n RMSE=np.sqrt(MSE)\n print('Mean Absolute Error: '+str(MAE))\n print('Root Mean Squared Error: '+str(RMSE))\n print(\"Test Score:\" + str(model.score(X_val,y_val)))\n", "_____no_output_____" ], [ "print('Linear Regression')\nreport(linear_model)", "Linear Regression\nMean Absolute Error: 151.83085509171417\nRoot Mean Squared Error: 202.82795349983735\nTest Score:0.5962180492362541\n" ], [ "print('ElasticNet')\nreport(ElasticNet_model)", "ElasticNet\nMean Absolute Error: 169.19653552557784\nRoot Mean Squared Error: 224.53381334474494\nTest Score:0.5051714046420267\n" ], [ "print('Random Forest Regressor')\nreport(RandomForest_model)", "Random Forest Regressor\nMean Absolute Error: 73.44051643356644\nRoot Mean Squared Error: 134.4739149638744\nTest Score:0.8225126594840884\n" ], [ "print('Gradient Boosting Regressor')\nreport(GradientBoosting_model)", "Gradient Boosting Regressor\nMean Absolute Error: 102.96356720688891\nRoot Mean Squared Error: 161.88824996858267\nTest Score:0.7427698084863579\n" ] ], [ [ "# Conclusion\n- Since RandomForestRegressor performed better than the rest of the models taken for evaluation, we will proceed further with the RandomForestRegressor mode", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4afaf3b1f70cfffa4babc7e8ff878e227dae6979
596,817
ipynb
Jupyter Notebook
[IMPL]_Spectral_Biclustering.ipynb
AlxndrMlk/ML_misc
52bbffb4552d944bf9e3af350e9a7837ebe29adc
[ "MIT" ]
null
null
null
[IMPL]_Spectral_Biclustering.ipynb
AlxndrMlk/ML_misc
52bbffb4552d944bf9e3af350e9a7837ebe29adc
[ "MIT" ]
null
null
null
[IMPL]_Spectral_Biclustering.ipynb
AlxndrMlk/ML_misc
52bbffb4552d944bf9e3af350e9a7837ebe29adc
[ "MIT" ]
null
null
null
2,539.646809
210,332
0.964788
[ [ [ "import numpy as np\nfrom matplotlib import pyplot as plt\n\nimport pandas as pd\n\nfrom sklearn.datasets import make_checkerboard\nfrom sklearn.datasets import samples_generator as sg\nfrom sklearn.cluster.bicluster import SpectralBiclustering\nfrom sklearn.metrics import consensus_score", "_____no_output_____" ] ], [ [ "# Spectral Biclustering\nBased on: https://scikit-learn.org/stable/auto_examples/bicluster/plot_spectral_biclustering.html", "_____no_output_____" ] ], [ [ "# Generate synthetic data\nn_clusters = (4, 4)\n\ndata, rows, columns = make_checkerboard(\n shape=(300, 300), n_clusters=n_clusters, noise=10,\n shuffle=False, random_state=42)", "_____no_output_____" ], [ "# pd.DataFrame(data)", "_____no_output_____" ], [ "# Visualize the generated data\nplt.matshow(data, cmap=plt.cm.Purples)\nplt.title(\"Original dataset\")\nplt.show()", "_____no_output_____" ], [ "# Shuffle the data\ndata, row_idx, col_idx = sg._shuffle(data, random_state=0)", "_____no_output_____" ], [ "# Visualize shuffled data\nplt.matshow(data, cmap=plt.cm.Purples)\nplt.title(\"Shuffled dataset\")\nplt.show()", "_____no_output_____" ], [ "# Initialize and fit the model\nmodel = SpectralBiclustering(n_clusters=n_clusters, method='log',\n random_state=42)\nmodel.fit(data)", "_____no_output_____" ], [ "# Compute consensus score\nscore = consensus_score(model.biclusters_,\n (rows[:, row_idx], columns[:, col_idx]))\n\nprint(f\"Consensus score: {score:.1f}\")", "Consensus score: 1.0\n" ], [ "fit_data = data[np.argsort(model.row_labels_)]\nfit_data = fit_data[:, np.argsort(model.column_labels_)]", "_____no_output_____" ], [ "# Plot the data after clustering\nplt.matshow(fit_data, cmap=plt.cm.Purples)\nplt.title(\"After biclustering; rearranged to show biclusters\")\nplt.show()", "_____no_output_____" ], [ "plt.matshow(np.outer(np.sort(model.row_labels_) + 1,\n np.sort(model.column_labels_) + 1),\n cmap=plt.cm.Purples)\nplt.title(\"Checkerboard structure of rearranged data\")\n\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4afb050b2f55bba634e6d2ceae5f6c560f76b070
50,432
ipynb
Jupyter Notebook
BCNcode/0_vibratioon_signal/1250/CNN/CNN_1250-012-512-y.ipynb
Decaili98/BCN-code-2022
ab0ce085cb29fbf12b6d773861953cb2cef23e20
[ "MulanPSL-1.0" ]
null
null
null
BCNcode/0_vibratioon_signal/1250/CNN/CNN_1250-012-512-y.ipynb
Decaili98/BCN-code-2022
ab0ce085cb29fbf12b6d773861953cb2cef23e20
[ "MulanPSL-1.0" ]
null
null
null
BCNcode/0_vibratioon_signal/1250/CNN/CNN_1250-012-512-y.ipynb
Decaili98/BCN-code-2022
ab0ce085cb29fbf12b6d773861953cb2cef23e20
[ "MulanPSL-1.0" ]
null
null
null
107.991435
16,324
0.78361
[ [ [ "from tensorflow import keras\nfrom tensorflow.keras import *\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.regularizers import l2#正则化L2\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd", "_____no_output_____" ], [ "# 12-0.2\n# 13-2.4\n# 18-12.14\nimport pandas as pd\nimport numpy as np\nnormal = np.loadtxt(r'F:\\张老师课题学习内容\\code\\数据集\\试验数据(包括压力脉动和振动)\\2013.9.12-未发生缠绕前\\2013-9.12振动\\2013-9-12振动-1250rmin-mat\\1250rnormalviby.txt', delimiter=',')\nchanrao = np.loadtxt(r'F:\\张老师课题学习内容\\code\\数据集\\试验数据(包括压力脉动和振动)\\2013.9.17-发生缠绕后\\振动\\9-18上午振动1250rmin-mat\\1250r_chanraoviby.txt', delimiter=',')\nprint(normal.shape,chanrao.shape,\"***************************************************\")\ndata_normal=normal[0:2] #提取前两行\ndata_chanrao=chanrao[0:2] #提取前两行\nprint(data_normal.shape,data_chanrao.shape)\nprint(data_normal,\"\\r\\n\",data_chanrao,\"***************************************************\")\ndata_normal=data_normal.reshape(1,-1)\ndata_chanrao=data_chanrao.reshape(1,-1)\nprint(data_normal.shape,data_chanrao.shape)\nprint(data_normal,\"\\r\\n\",data_chanrao,\"***************************************************\")", "(22, 32768) (20, 32768) ***************************************************\n(2, 32768) (2, 32768)\n[[-1.2078 0.66425 -0.18073 ... 0.33287 0.56707 -1.317 ]\n [ 1.3834 1.2339 -0.79308 ... -0.83606 -0.42435 -0.51437]] \r\n [[-1.2913 4.8747 -1.6471 ... -5.559 -1.4744 -1.6646 ]\n [ 0.15349 1.4305 3.1625 ... -6.8379 -1.5389 0.55019]] ***************************************************\n(1, 65536) (1, 65536)\n[[-1.2078 0.66425 -0.18073 ... -0.83606 -0.42435 -0.51437]] \r\n [[-1.2913 4.8747 -1.6471 ... -6.8379 -1.5389 0.55019]] ***************************************************\n" ], [ "#水泵的两种故障类型信号normal正常,chanrao故障\ndata_normal=data_normal.reshape(-1, 512)#(65536,1)-(128, 515)\ndata_chanrao=data_chanrao.reshape(-1,512)\nprint(data_normal.shape,data_chanrao.shape)\n", "(128, 512) (128, 512)\n" ], [ "import numpy as np\ndef yuchuli(data,label):#(4:1)(51:13)\n #打乱数据顺序\n np.random.shuffle(data)\n train = data[0:102,:]\n test = data[102:128,:]\n label_train = np.array([label for i in range(0,102)])\n label_test =np.array([label for i in range(0,26)])\n return train,test ,label_train ,label_test\ndef stackkk(a,b,c,d,e,f,g,h):\n aa = np.vstack((a, e))\n bb = np.vstack((b, f))\n cc = np.hstack((c, g))\n dd = np.hstack((d, h))\n return aa,bb,cc,dd\nx_tra0,x_tes0,y_tra0,y_tes0 = yuchuli(data_normal,0)\nx_tra1,x_tes1,y_tra1,y_tes1 = yuchuli(data_chanrao,1)\ntr1,te1,yr1,ye1=stackkk(x_tra0,x_tes0,y_tra0,y_tes0 ,x_tra1,x_tes1,y_tra1,y_tes1)\n\nx_train=tr1\nx_test=te1\ny_train = yr1\ny_test = ye1\n\n#打乱数据\nstate = np.random.get_state()\nnp.random.shuffle(x_train)\nnp.random.set_state(state)\nnp.random.shuffle(y_train)\n\nstate = np.random.get_state()\nnp.random.shuffle(x_test)\nnp.random.set_state(state)\nnp.random.shuffle(y_test)\n\n\n#对训练集和测试集标准化\ndef ZscoreNormalization(x):\n \"\"\"Z-score normaliaztion\"\"\"\n x = (x - np.mean(x)) / np.std(x)\n return x\nx_train=ZscoreNormalization(x_train)\nx_test=ZscoreNormalization(x_test)\n# print(x_test[0])\n\n\n#转化为一维序列\nx_train = x_train.reshape(-1,512,1)\nx_test = x_test.reshape(-1,512,1)\nprint(x_train.shape,x_test.shape)\n\ndef to_one_hot(labels,dimension=2):\n results = np.zeros((len(labels),dimension))\n for i,label in enumerate(labels):\n results[i,label] = 1\n return results\none_hot_train_labels = to_one_hot(y_train)\none_hot_test_labels = to_one_hot(y_test)\n", "(204, 512, 1) (52, 512, 1)\n" ], [ "x = layers.Input(shape=[512,1,1])\n#普通卷积层\nconv1 = layers.Conv2D(filters=16, kernel_size=(2, 1), activation='relu',padding='valid',name='conv1')(x)\n#池化层\nPOOL1 = MaxPooling2D((2,1))(conv1)\n#普通卷积层\nconv2 = layers.Conv2D(filters=32, kernel_size=(2, 1), activation='relu',padding='valid',name='conv2')(POOL1)\n#池化层\nPOOL2 = MaxPooling2D((2,1))(conv2)\n#Dropout层\nDropout=layers.Dropout(0.1)(POOL2 )\nFlatten=layers.Flatten()(Dropout)\n#全连接层\nDense1=layers.Dense(50, activation='relu')(Flatten)\nDense2=layers.Dense(2, activation='softmax')(Dense1)\nmodel = keras.Model(x, Dense2) \nmodel.summary() ", "Model: \"model\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 512, 1, 1)] 0 \n_________________________________________________________________\nconv1 (Conv2D) (None, 511, 1, 16) 48 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 255, 1, 16) 0 \n_________________________________________________________________\nconv2 (Conv2D) (None, 254, 1, 32) 1056 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 127, 1, 32) 0 \n_________________________________________________________________\ndropout (Dropout) (None, 127, 1, 32) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 4064) 0 \n_________________________________________________________________\ndense (Dense) (None, 50) 203250 \n_________________________________________________________________\ndense_1 (Dense) (None, 2) 102 \n=================================================================\nTotal params: 204,456\nTrainable params: 204,456\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "\n#定义优化\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',metrics=['accuracy']) ", "_____no_output_____" ], [ "import time\ntime_begin = time.time()\nhistory = model.fit(x_train,one_hot_train_labels,\n validation_split=0.1,\n epochs=50,batch_size=10,\n shuffle=True)\ntime_end = time.time()\ntime = time_end - time_begin\nprint('time:', time)", "Epoch 1/50\n19/19 [==============================] - 2s 55ms/step - loss: 0.7115 - accuracy: 0.4461 - val_loss: 0.5042 - val_accuracy: 0.5714\nEpoch 2/50\n19/19 [==============================] - 0s 7ms/step - loss: 0.4017 - accuracy: 0.8103 - val_loss: 0.2843 - val_accuracy: 1.0000\nEpoch 3/50\n19/19 [==============================] - 0s 6ms/step - loss: 0.1712 - accuracy: 0.9870 - val_loss: 0.0645 - val_accuracy: 1.0000\nEpoch 4/50\n19/19 [==============================] - 0s 7ms/step - loss: 0.0367 - accuracy: 1.0000 - val_loss: 0.0209 - val_accuracy: 1.0000\nEpoch 5/50\n19/19 [==============================] - 0s 6ms/step - loss: 0.0100 - accuracy: 1.0000 - val_loss: 0.0096 - val_accuracy: 1.0000\nEpoch 6/50\n19/19 [==============================] - 0s 9ms/step - loss: 0.0052 - accuracy: 1.0000 - val_loss: 0.0047 - val_accuracy: 1.0000\nEpoch 7/50\n19/19 [==============================] - 0s 8ms/step - loss: 0.0027 - accuracy: 1.0000 - val_loss: 0.0035 - val_accuracy: 1.0000\nEpoch 8/50\n19/19 [==============================] - 0s 7ms/step - loss: 0.0017 - accuracy: 1.0000 - val_loss: 0.0027 - val_accuracy: 1.0000\nEpoch 9/50\n19/19 [==============================] - 0s 7ms/step - loss: 0.0014 - accuracy: 1.0000 - val_loss: 0.0021 - val_accuracy: 1.0000\nEpoch 10/50\n19/19 [==============================] - 0s 6ms/step - loss: 0.0011 - accuracy: 1.0000 - val_loss: 0.0017 - val_accuracy: 1.0000\nEpoch 11/50\n19/19 [==============================] - 0s 7ms/step - loss: 8.1093e-04 - accuracy: 1.0000 - val_loss: 0.0015 - val_accuracy: 1.0000\nEpoch 12/50\n19/19 [==============================] - 0s 7ms/step - loss: 8.1193e-04 - accuracy: 1.0000 - val_loss: 0.0013 - val_accuracy: 1.0000\nEpoch 13/50\n19/19 [==============================] - 0s 8ms/step - loss: 6.5521e-04 - accuracy: 1.0000 - val_loss: 0.0011 - val_accuracy: 1.0000\nEpoch 14/50\n19/19 [==============================] - 0s 6ms/step - loss: 5.9818e-04 - accuracy: 1.0000 - val_loss: 9.1820e-04 - val_accuracy: 1.0000\nEpoch 15/50\n19/19 [==============================] - 0s 6ms/step - loss: 4.3598e-04 - accuracy: 1.0000 - val_loss: 8.3457e-04 - val_accuracy: 1.0000\nEpoch 16/50\n19/19 [==============================] - ETA: 0s - loss: 4.1611e-04 - accuracy: 1.00 - 0s 7ms/step - loss: 4.1046e-04 - accuracy: 1.0000 - val_loss: 7.1305e-04 - val_accuracy: 1.0000\nEpoch 17/50\n19/19 [==============================] - 0s 6ms/step - loss: 3.9825e-04 - accuracy: 1.0000 - val_loss: 6.4924e-04 - val_accuracy: 1.0000\nEpoch 18/50\n19/19 [==============================] - 0s 6ms/step - loss: 3.0200e-04 - accuracy: 1.0000 - val_loss: 5.6917e-04 - val_accuracy: 1.0000\nEpoch 19/50\n19/19 [==============================] - 0s 6ms/step - loss: 2.6285e-04 - accuracy: 1.0000 - val_loss: 5.0667e-04 - val_accuracy: 1.0000\nEpoch 20/50\n19/19 [==============================] - 0s 6ms/step - loss: 2.5610e-04 - accuracy: 1.0000 - val_loss: 4.7883e-04 - val_accuracy: 1.0000\nEpoch 21/50\n19/19 [==============================] - 0s 6ms/step - loss: 2.7510e-04 - accuracy: 1.0000 - val_loss: 4.4633e-04 - val_accuracy: 1.0000\nEpoch 22/50\n19/19 [==============================] - 0s 6ms/step - loss: 1.8611e-04 - accuracy: 1.0000 - val_loss: 3.8946e-04 - val_accuracy: 1.0000\nEpoch 23/50\n19/19 [==============================] - 0s 6ms/step - loss: 1.6716e-04 - accuracy: 1.0000 - val_loss: 3.4663e-04 - val_accuracy: 1.0000\nEpoch 24/50\n19/19 [==============================] - 0s 6ms/step - loss: 1.7220e-04 - accuracy: 1.0000 - val_loss: 3.3536e-04 - val_accuracy: 1.0000\nEpoch 25/50\n19/19 [==============================] - 0s 8ms/step - loss: 1.4986e-04 - accuracy: 1.0000 - val_loss: 3.0928e-04 - val_accuracy: 1.0000\nEpoch 26/50\n19/19 [==============================] - 0s 6ms/step - loss: 1.4477e-04 - accuracy: 1.0000 - val_loss: 2.8932e-04 - val_accuracy: 1.0000\nEpoch 27/50\n19/19 [==============================] - 0s 6ms/step - loss: 1.1541e-04 - accuracy: 1.0000 - val_loss: 2.6308e-04 - val_accuracy: 1.0000\nEpoch 28/50\n19/19 [==============================] - 0s 6ms/step - loss: 1.1087e-04 - accuracy: 1.0000 - val_loss: 2.5061e-04 - val_accuracy: 1.0000\nEpoch 29/50\n19/19 [==============================] - 0s 6ms/step - loss: 1.0422e-04 - accuracy: 1.0000 - val_loss: 2.3885e-04 - val_accuracy: 1.0000\nEpoch 30/50\n19/19 [==============================] - 0s 6ms/step - loss: 9.8308e-05 - accuracy: 1.0000 - val_loss: 2.3615e-04 - val_accuracy: 1.0000\nEpoch 31/50\n19/19 [==============================] - 0s 5ms/step - loss: 8.6089e-05 - accuracy: 1.0000 - val_loss: 2.0884e-04 - val_accuracy: 1.0000\nEpoch 32/50\n19/19 [==============================] - 0s 6ms/step - loss: 8.8994e-05 - accuracy: 1.0000 - val_loss: 1.9688e-04 - val_accuracy: 1.0000\nEpoch 33/50\n19/19 [==============================] - 0s 6ms/step - loss: 8.4027e-05 - accuracy: 1.0000 - val_loss: 1.8595e-04 - val_accuracy: 1.0000\nEpoch 34/50\n19/19 [==============================] - 0s 6ms/step - loss: 7.0698e-05 - accuracy: 1.0000 - val_loss: 1.8541e-04 - val_accuracy: 1.0000\nEpoch 35/50\n19/19 [==============================] - 0s 6ms/step - loss: 6.5979e-05 - accuracy: 1.0000 - val_loss: 1.6956e-04 - val_accuracy: 1.0000\nEpoch 36/50\n19/19 [==============================] - 0s 6ms/step - loss: 5.9412e-05 - accuracy: 1.0000 - val_loss: 1.5691e-04 - val_accuracy: 1.0000\nEpoch 37/50\n19/19 [==============================] - 0s 6ms/step - loss: 6.8760e-05 - accuracy: 1.0000 - val_loss: 1.6483e-04 - val_accuracy: 1.0000\nEpoch 38/50\n19/19 [==============================] - 0s 6ms/step - loss: 6.4120e-05 - accuracy: 1.0000 - val_loss: 1.4810e-04 - val_accuracy: 1.0000\nEpoch 39/50\n19/19 [==============================] - 0s 6ms/step - loss: 5.4538e-05 - accuracy: 1.0000 - val_loss: 1.3474e-04 - val_accuracy: 1.0000\nEpoch 40/50\n19/19 [==============================] - 0s 6ms/step - loss: 5.1633e-05 - accuracy: 1.0000 - val_loss: 1.2510e-04 - val_accuracy: 1.0000\nEpoch 41/50\n19/19 [==============================] - 0s 6ms/step - loss: 4.7422e-05 - accuracy: 1.0000 - val_loss: 1.1827e-04 - val_accuracy: 1.0000\nEpoch 42/50\n19/19 [==============================] - 0s 6ms/step - loss: 5.0794e-05 - accuracy: 1.0000 - val_loss: 1.2261e-04 - val_accuracy: 1.0000\nEpoch 43/50\n19/19 [==============================] - 0s 6ms/step - loss: 4.8068e-05 - accuracy: 1.0000 - val_loss: 1.2094e-04 - val_accuracy: 1.0000\nEpoch 44/50\n19/19 [==============================] - 0s 6ms/step - loss: 4.5887e-05 - accuracy: 1.0000 - val_loss: 1.1383e-04 - val_accuracy: 1.0000\nEpoch 45/50\n19/19 [==============================] - 0s 6ms/step - loss: 4.3190e-05 - accuracy: 1.0000 - val_loss: 1.0683e-04 - val_accuracy: 1.0000\nEpoch 46/50\n19/19 [==============================] - 0s 6ms/step - loss: 3.7583e-05 - accuracy: 1.0000 - val_loss: 1.0013e-04 - val_accuracy: 1.0000\nEpoch 47/50\n19/19 [==============================] - 0s 7ms/step - loss: 3.5037e-05 - accuracy: 1.0000 - val_loss: 9.7038e-05 - val_accuracy: 1.0000\nEpoch 48/50\n19/19 [==============================] - 0s 6ms/step - loss: 3.1917e-05 - accuracy: 1.0000 - val_loss: 9.2204e-05 - val_accuracy: 1.0000\nEpoch 49/50\n19/19 [==============================] - 0s 6ms/step - loss: 3.4232e-05 - accuracy: 1.0000 - val_loss: 8.7596e-05 - val_accuracy: 1.0000\nEpoch 50/50\n19/19 [==============================] - 0s 6ms/step - loss: 3.1118e-05 - accuracy: 1.0000 - val_loss: 8.9842e-05 - val_accuracy: 1.0000\ntime: 7.821579933166504\n" ], [ "import time\ntime_begin = time.time()\nscore = model.evaluate(x_test,one_hot_test_labels, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n \ntime_end = time.time()\ntime = time_end - time_begin\nprint('time:', time)", "Test loss: 0.00022774016542825848\nTest accuracy: 1.0\ntime: 0.050037384033203125\n" ], [ "#绘制acc-loss曲线\nimport matplotlib.pyplot as plt\n\nplt.plot(history.history['loss'],color='r')\nplt.plot(history.history['val_loss'],color='g')\nplt.plot(history.history['accuracy'],color='b')\nplt.plot(history.history['val_accuracy'],color='k')\nplt.title('model loss and acc')\nplt.ylabel('Accuracy')\nplt.xlabel('epoch')\nplt.legend(['train_loss', 'test_loss','train_acc', 'test_acc'], loc='center right')\n# plt.legend(['train_loss','train_acc'], loc='upper left')\n#plt.savefig('1.png')\nplt.show()", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\n\nplt.plot(history.history['loss'],color='r')\nplt.plot(history.history['accuracy'],color='b')\nplt.title('model loss and sccuracy ')\nplt.ylabel('loss/sccuracy')\nplt.xlabel('epoch')\nplt.legend(['train_loss', 'train_sccuracy'], loc='center right')\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4afb14d5dbd6c5409a19652c1fed4ddec3d61c83
775,582
ipynb
Jupyter Notebook
examples/phenology-uc2/Phenology.ipynb
soxofaan/openeo-processes
12565abd810c4cac84c9fccaf00d0fd873b88af0
[ "Apache-2.0" ]
null
null
null
examples/phenology-uc2/Phenology.ipynb
soxofaan/openeo-processes
12565abd810c4cac84c9fccaf00d0fd873b88af0
[ "Apache-2.0" ]
null
null
null
examples/phenology-uc2/Phenology.ipynb
soxofaan/openeo-processes
12565abd810c4cac84c9fccaf00d0fd873b88af0
[ "Apache-2.0" ]
null
null
null
487.48083
264,012
0.937887
[ [ [ "# OpenEO Use Case 2: Multi–source phenology toolbox\nUse case implemented by VITO.\n\n## Official description\nThis use case concentrates on data fusion tools, time-series generation and phenological\nmetrics using Sentinel-2 data. It will be tested on several back-end platforms by pilot users from\nthe Action against Hunger and the International Centre for Integrated Mountain Development.\nThe here tested processes depend on the availability of orthorectified Sentinel-2 surface re-\nflectance data including per pixel quality masks.\n\n## Overview\n\nIn this use case, the goal is to derive phenology information from Sentinel-2 time series data.\nIn this case, phenology is defined by:\n- Start of season, a date and the corresponding value of the biophysical indicator\n- The maximum value of the growing curve for the indicator\n- End of season, a date and the corresponding value of the biophysical indicator\n\nMultiple biophysical indicators exist. But in this use case, the enhanced vegitation index (EVI) is used.\n\nWe start by importing the necessary packages, and defining an area of interest.\nDuring the algorithm development phase, we work on a limited study field, so that we can use\nthe direct execution capabilities of OpenEO to receive feedback on the implemented changes.\n", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib.pyplot as plt \nfrom rasterio.plot import show, show_hist\nimport rasterio\n\nfrom shapely.geometry import Polygon\n\nfrom openeo import ImageCollection\n\nimport openeo\nimport logging\nimport os\nfrom pathlib import Path\nimport json\n\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\n\nimport scipy.signal\n\n#enable logging in requests library\nfrom openeo.rest.imagecollectionclient import ImageCollectionClient\n\nstart = \"2018-05-01\"\nend = \"2018-10-01\"\n\ndate = \"2018-08-17\"\n\nparcels = gpd.read_file('potato_field.geojson')\nparcels.plot()\npolygon = parcels.geometry[0]\n\nminx,miny,maxx,maxy = polygon.bounds\n\n#enlarge bounds, to also have some data outside of our parcel\n#minx -= 0.001\n#miny -= 0.001\n#maxx+=0.001\n#maxy+=0.001\npolygon.bounds\n", "_____no_output_____" ] ], [ [ "Connect to the OpenEO backend, and create a Sentinel-2 datacube containing 10M reflectance bands.\n\nWe do not yet specify a time range, this allows us to play around with different time ranges later on.\n", "_____no_output_____" ] ], [ [ "session = openeo.session(\"nobody\", \"http://openeo.vgt.vito.be/openeo/0.4.0\")\n\n#retrieve the list of available collections\ncollections = session.list_collections()\ns2_radiometry = session.imagecollection(\"CGS_SENTINEL2_RADIOMETRY_V102_001\") \\\n .filter_bbox(west=minx,east=maxx,north=maxy,south=miny,crs=\"EPSG:4326\")\n", "_____no_output_____" ] ], [ [ "## Preprocessing step 1: EVI computation\nCreate an EVI data cube, based on reflectance bands. \nThe formula for the EVI index can be expressed using plain Python.\n\nThe bands retrieved from the backend are unscaled reflectance values with a valid\nrange between 0 and 10000. \n", "_____no_output_____" ] ], [ [ "\nB02 = s2_radiometry.band('2')\nB04 = s2_radiometry.band('4')\nB08 = s2_radiometry.band('8')\n\nevi_cube_nodate = (2.5 * (B08 - B04)) / ((B08 + 6.0 * B04 - 7.5 * B02) + 10000.0*1.0)\n\nevi_cube = evi_cube_nodate.filter_temporal(start,end)\n\n#write graph to json, as example\ndef write_graph(graph, filename): \n with open(filename, 'w') as outfile: \n json.dump(graph, outfile,indent=4)\nwrite_graph(evi_cube.graph,\"evi_cube.json\")", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-block alert-success\">\nNo actual processing has occurred until now, we have just been building a workflow consisting of multiple steps. In OpenEO, this workflow is representation is called a process graph. This allows your workflow to be exchanged between multiple systems.\n\nThe figure below shows this in a graphical representation. \n\n![EVI Process graph](https://open-eo.github.io/openeo-api/img/pg-example.png \"Process graph\")\n</div>\n", "_____no_output_____" ] ], [ [ "def show_image(cube,cmap='RdYlGn'):\n %time cube.filter_temporal(date,date).download(\"temp%s.tiff\"%date,format='GTIFF')\n with rasterio.open(\"temp%s.tiff\"%date) as src:\n band_temp = src.read(1)\n fig, (ax) = plt.subplots(1,1, figsize=(7,7))\n show(band_temp,ax=ax,cmap=cmap,vmin=0,vmax=1)\nshow_image(evi_cube_nodate)", "CPU times: user 7.86 ms, sys: 2.69 ms, total: 10.5 ms\nWall time: 4.06 s\n" ] ], [ [ "### Preprocessing step 2: Cloud masking\nIn Sen2cor sceneclassification these values are relevant for phenology:\n- 4: vegetated\n- 5: not-vegetated\nEverything else is cloud, snow, water, shadow ...\n\nIn OpenEO, the mask function will mask every value that is set to True.\n", "_____no_output_____" ] ], [ [ "s2_sceneclassification = session.imagecollection(\"S2_FAPAR_SCENECLASSIFICATION_V102_PYRAMID\") \\\n .filter_bbox(west=minx,east=maxx,north=maxy,south=miny,crs=\"EPSG:4326\")\n\nmask = s2_sceneclassification.band('classification')\n\nmask = (mask != 4) & (mask !=5)\nmask\n", "_____no_output_____" ] ], [ [ "Masks produced by sen2cor still include a lot of unwanted clouds and shadow. This problem usually occurs in the proximity of detected clouds, so we try to extend our mask. To do that, we use a bit of fuzzy logic: blur the binary mask using a gaussian so that our mask gives us an indication of how close to a cloud we are.\n\nBy adjusting the window size, we can play around with how far from the detected clouds we want to extend our mask.\nA 30 pixel kernel applied to a 10M resolution image will cover a 300m area. ", "_____no_output_____" ] ], [ [ "def makekernel(iwindowsize): \n kernel_vect = scipy.signal.windows.gaussian(iwindowsize, std = iwindowsize/4.0, sym=True)\n kernel = np.outer(kernel_vect, kernel_vect)\n kernel = kernel / kernel.sum() \n return kernel \n \nplt.imshow(makekernel(31))", "_____no_output_____" ] ], [ [ "Use the apply_kernel OpenEO process:\nhttps://open-eo.github.io/openeo-api/v/0.4.0/processreference/#apply_kernel", "_____no_output_____" ] ], [ [ "fuzzy_mask = mask.apply_kernel(makekernel(29))\nmask_extended = fuzzy_mask > 0.1", "_____no_output_____" ], [ "write_graph(mask_extended.graph,\"mask.json\")", "_____no_output_____" ] ], [ [ "To evaluate our masking code, we download some reference images:\n", "_____no_output_____" ] ], [ [ "mask_for_date = mask_extended.filter_temporal(date,date)", "_____no_output_____" ], [ "%time fuzzy_mask.filter_temporal(date,date).download(\"mask%s.tiff\"%date,format='GTIFF')\n#s2_sceneclassification.filter_temporal(date,date).download(\"scf%s.tiff\"%date,format='GTIFF')\n%time evi_cube_nodate.filter_temporal(date,date).download(\"unmasked%s.tiff\"%date,format='GTIFF')\n%time evi_cube_nodate.filter_temporal(date,date).mask(rastermask=mask_for_date,replacement=np.nan).download(\"masked%s.tiff\"%date,format='GTIFF')", "CPU times: user 14.4 ms, sys: 3.66 ms, total: 18 ms\nWall time: 12.6 s\nCPU times: user 8.89 ms, sys: 1.08 ms, total: 9.97 ms\nWall time: 2.39 s\nCPU times: user 14.6 ms, sys: 2.99 ms, total: 17.6 ms\nWall time: 9.79 s\n" ], [ "with rasterio.open(\"unmasked%s.tiff\"%date) as src:\n band_unmasked = src.read(1)\n\nwith rasterio.open(\"masked%s.tiff\"%date) as src:\n band_masked = src.read(1)\n \nwith rasterio.open(\"mask%s.tiff\"%date) as src:\n band_mask = src.read(1)", "_____no_output_____" ], [ "fig, (axr, axg,axb) = plt.subplots(1,3, figsize=(14,14))\n\nshow(band_unmasked,ax=axr,cmap='RdYlGn',vmin=0,vmax=1)\nshow(band_masked,ax=axg,cmap='RdYlGn',vmin=0,vmax=1)\nshow(band_mask,ax=axb,cmap='coolwarm',vmin=0.0,vmax=0.8)\n", "_____no_output_____" ] ], [ [ "We can look under the hood of OpenEO, to look at the process graph that is used to encode our workflow:", "_____no_output_____" ] ], [ [ "evi_cube_masked = evi_cube.mask(rastermask=mask_extended.filter_temporal(start,end),replacement=np.nan)", "_____no_output_____" ] ], [ [ "#### Creating a viewing service\n\nOpenEO allows us to turn a datacube into a WMTS viewing service:\n", "_____no_output_____" ] ], [ [ "service = evi_cube_masked.tiled_viewing_service(type='WMTS',style={'colormap':'RdYlGn'})\nprint(service)", "{'url': 'http://openeo.vgt.vito.be/openeo/services/5269f809-d234-46c3-a13f-1c733c9da575/service/wmts'}\n" ] ], [ [ "Extract an unsmoothed timeseries, this allows us to evaluate the intermediate result.\nFor further analysis, smoothing will be needed.\n", "_____no_output_____" ] ], [ [ "%time\ntimeseries_raw_dc = evi_cube.polygonal_mean_timeseries(polygon)\ntimeseries_raw = pd.Series(timeseries_raw_dc.execute(),name=\"evi_raw\")\n#timeseries are provided as an array, because of bands, so unpack\ntimeseries_raw = timeseries_raw.apply(pd.Series)\ntimeseries_raw.columns = [\"evi_raw\"]\ntimeseries_raw.head(15)", "CPU times: user 4 µs, sys: 8 µs, total: 12 µs\nWall time: 29.1 µs\n" ], [ "timeseries_masked_dc = evi_cube_masked.polygonal_mean_timeseries(polygon)\n%time timeseries_masked = pd.Series(timeseries_masked_dc.execute())\ntimeseries_masked = timeseries_masked.apply(pd.Series)\ntimeseries_masked.columns = [\"evi_masked\"]\ntimeseries_masked.head(15)", "CPU times: user 7.83 ms, sys: 675 µs, total: 8.5 ms\nWall time: 28.5 s\n" ] ], [ [ "Now we can plot both the cloudmasked and unmasked values. Do note that the 'unmasked' layer already has some basic cloud filtering in place based on medium and high probability clouds.", "_____no_output_____" ] ], [ [ "all_timeseries = timeseries_raw.join(timeseries_masked).dropna(how='all')\nall_timeseries.index = pd.to_datetime(all_timeseries.index)\nall_timeseries.plot(figsize=(14,7))\nall_timeseries.head(15)", "_____no_output_____" ] ], [ [ "In the plot, we can see that cloud masking seems to reduce some of the variation that is found in the original raw timeseries.", "_____no_output_____" ], [ "## Preprocessing step 3: Time series smoothing\n\nCloud masking has reduced the noise in our signal, but it is clearly not perfect. This is due to the limitations of the pixel based cloud masking algorithm, which still leaves a lot of undetected bad pixels in our data.\n\nA commonly used approach is to apply a smoothing on the timeseries. \nHere we suggest to use a 'Savitzky-Golay' filter, which we first try out locally on the aggregated timeseries, before applying to the pixels through the OpenEO API.", "_____no_output_____" ] ], [ [ "timeseries_masked.index = pd.to_datetime(timeseries_masked.index)\ntimeseries_masked.interpolate(axis=0).plot(figsize=(14,7))", "_____no_output_____" ] ], [ [ "Run the filter with different parameters to assess the effect.", "_____no_output_____" ] ], [ [ "from scipy.signal import savgol_filter\nsmooth_ts = pd.DataFrame(timeseries_masked.dropna())\n#smooth_ts['smooth_5'] = savgol_filter(smooth_ts.evi_masked, 5, 1)\nsmooth_ts['smooth_5_poly'] = savgol_filter(smooth_ts.evi_masked, 5, 2)\n#smooth_ts['smooth_9'] = savgol_filter(smooth_ts.evi_masked, 9, 1)\nsmooth_ts['smooth_9_poly'] = savgol_filter(smooth_ts.evi_masked, 9, 2)\nsmooth_ts.plot(figsize=(14,7))\n", "_____no_output_____" ] ], [ [ "### Using a UDF for pixel based smoothing\nThe end result should be a phenology map, so we need to apply our smoothing method on the pixel values.\nWe use a 'user defined function' (UDF) to apply custom Python code to a datacube containging time series per pixel.\n\nThe code for our UDF function is contained in a separate file, and shown below:", "_____no_output_____" ] ], [ [ "def get_resource(relative_path):\n \n return str(Path( relative_path))\ndef load_udf(relative_path):\n import json\n with open(get_resource(relative_path), 'r+') as f:\n return f.read()\n\nsmoothing_udf = load_udf('udf/smooth_savitzky_golay.py')\nprint(smoothing_udf)", "# -*- coding: utf-8 -*-\n# Uncomment the import only for coding support\n#from openeo_udf.api.base import SpatialExtent, RasterCollectionTile, FeatureCollectionTile, UdfData\n\n__license__ = \"Apache License, Version 2.0\"\n\n\ndef rct_savitzky_golay(udf_data):\n from scipy.signal import savgol_filter\n import pandas as pd\n # Iterate over each tile\n for tile in udf_data.raster_collection_tiles:\n timeseries_array = tile.data\n #TODO: savitzky golay implementation assumes regularly spaced samples!\n\n #first we ensure that there are no nodata values in our input, as this will cause everything to become nodata.\n array_2d = timeseries_array.reshape((timeseries_array.shape[0], timeseries_array.shape[1] * timeseries_array.shape[2]))\n\n df = pd.DataFrame(array_2d)\n #df.fillna(method='ffill', axis=0, inplace=True)\n df.interpolate(inplace=True,axis=0)\n filled=df.as_matrix().reshape(timeseries_array.shape)\n\n #now apply savitzky golay on filled data\n smoothed_array = savgol_filter(filled, 5, 2,axis=0)\n #print(smoothed_array)\n tile.set_data(smoothed_array)\n\n\n# This function call is the entry point for the UDF.\n# The caller will provide all required data in the **data** object.\nrct_savitzky_golay(data)\n\n" ] ], [ [ "Now we apply our udf to the temporal dimension of the datacube. Use the code block below to display the api documentation.", "_____no_output_____" ] ], [ [ "?evi_cube_masked.apply_dimension", "_____no_output_____" ], [ "smoothed_evi = evi_cube_masked.apply_dimension(smoothing_udf,runtime='Python')\ntimeseries_smooth = smoothed_evi.polygonal_mean_timeseries(polygon)\n\nwrite_graph(timeseries_smooth.graph,\"timeseries_udf.json\")\nts_savgol = pd.Series(timeseries_smooth.execute()).apply(pd.Series)\nts_savgol.head(10)", "_____no_output_____" ], [ "ts_savgol.dropna(inplace=True)\nts_savgol.index = pd.to_datetime(ts_savgol.index)\nts_savgol.head(10)", "_____no_output_____" ], [ "all_timeseries['savgol_udf'] =ts_savgol\nall_timeseries.plot(figsize=(14,7))\nall_timeseries.head()", "_____no_output_____" ] ], [ [ "This plot shows the result of applying smoothing per pixel. The noise in the timeseries seems to be reduced, but we do still need to validate if this is correct!\n\n### To be continued...", "_____no_output_____" ] ], [ [ "#smoothed_evi.filter_temporal(date,date).download(\"smoothed%s.tiff\"%date,format='GTIFF')\nshow_image(smoothed_evi)", "CPU times: user 15.9 ms, sys: 5.63 ms, total: 21.5 ms\nWall time: 2min 16s\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]
4afb15d2163afed2c4265245a7c5aef3c6648b53
294,804
ipynb
Jupyter Notebook
ICL_Getting_started_with_TensorFlow_2/Week 5 Capstone_Project End to End SVHN Dataset.ipynb
pacificblue/Coursera
9639dcdf7686407d9604a7428c21ab98b26aa50c
[ "BSD-2-Clause" ]
null
null
null
ICL_Getting_started_with_TensorFlow_2/Week 5 Capstone_Project End to End SVHN Dataset.ipynb
pacificblue/Coursera
9639dcdf7686407d9604a7428c21ab98b26aa50c
[ "BSD-2-Clause" ]
null
null
null
ICL_Getting_started_with_TensorFlow_2/Week 5 Capstone_Project End to End SVHN Dataset.ipynb
pacificblue/Coursera
9639dcdf7686407d9604a7428c21ab98b26aa50c
[ "BSD-2-Clause" ]
null
null
null
286.217476
69,096
0.901212
[ [ [ "# Capstone Project\n## Image classifier for the SVHN dataset\n### Instructions\n\nIn this notebook, you will create a neural network that classifies real-world images digits. You will use concepts from throughout this course in building, training, testing, validating and saving your Tensorflow classifier model.\n\nThis project is peer-assessed. Within this notebook you will find instructions in each section for how to complete the project. Pay close attention to the instructions as the peer review will be carried out according to a grading rubric that checks key parts of the project instructions. Feel free to add extra cells into the notebook as required.\n\n### How to submit\n\nWhen you have completed the Capstone project notebook, you will submit a pdf of the notebook for peer review. First ensure that the notebook has been fully executed from beginning to end, and all of the cell outputs are visible. This is important, as the grading rubric depends on the reviewer being able to view the outputs of your notebook. Save the notebook as a pdf (File -> Download as -> PDF via LaTeX). You should then submit this pdf for review.\n\n### Let's get started!\n\nWe'll start by running some imports, and loading the dataset. For this project you are free to make further imports throughout the notebook as you wish. ", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np", "_____no_output_____" ] ], [ [ "![SVHN overview image](data/svhn_examples.jpg)\nFor the capstone project, you will use the [SVHN dataset](http://ufldl.stanford.edu/housenumbers/). This is an image dataset of over 600,000 digit images in all, and is a harder dataset than MNIST as the numbers appear in the context of natural scene images. SVHN is obtained from house numbers in Google Street View images. \n\n* Y. Netzer, T. Wang, A. Coates, A. Bissacco, B. Wu and A. Y. Ng. \"Reading Digits in Natural Images with Unsupervised Feature Learning\". NIPS Workshop on Deep Learning and Unsupervised Feature Learning, 2011.\n\nYour goal is to develop an end-to-end workflow for building, training, validating, evaluating and saving a neural network that classifies a real-world image into one of ten classes.", "_____no_output_____" ] ], [ [ "# Run this cell to load the dataset\n\ntrain = loadmat('data/train_32x32.mat')\ntest = loadmat('data/test_32x32.mat')", "_____no_output_____" ] ], [ [ "Both `train` and `test` are dictionaries with keys `X` and `y` for the input images and labels respectively.", "_____no_output_____" ], [ "## 1. Inspect and preprocess the dataset\n* Extract the training and testing images and labels separately from the train and test dictionaries loaded for you.\n* Select a random sample of images and corresponding labels from the dataset (at least 10), and display them in a figure.\n* Convert the training and test images to grayscale by taking the average across all colour channels for each pixel. _Hint: retain the channel dimension, which will now have size 1._\n* Select a random sample of the grayscale images and corresponding labels from the dataset (at least 10), and display them in a figure.", "_____no_output_____" ] ], [ [ "x_train = train['X']\ny_train = train['y']\nx_test = test['X']\ny_test = test['y']\nx_train.shape, y_train.shape, x_test.shape, y_test.shape", "_____no_output_____" ], [ "x_train = np.transpose(x_train, (3, 0, 1, 2))\nx_test = np.transpose(x_test, (3, 0, 1, 2))\nx_train.shape, x_test.shape", "_____no_output_____" ], [ "fig=plt.figure(figsize=(12,6))\ncolumns = 5\nrows = 2\nfor id in range(1, columns*rows +1):\n train_set = True if np.random.randint(2) == 1 else False\n if train_set:\n n = np.random.randint(x_train.shape[0])\n ax = fig.add_subplot(rows, columns, id)\n ax.title.set_text(f\"Img-{id}, label={y_train[n][0]}\")\n ax.imshow(x_train[n])\n else:\n n = np.random.randint(x_test.shape[0])\n ax = fig.add_subplot(rows, columns, id)\n ax.title.set_text(f\"Img-{id}, label={y_test[n][0]}\")\n ax.imshow(x_test[n])\n \nplt.show()", "_____no_output_____" ], [ "x_train = np.mean(x_train, axis=3) / 255\nx_test = np.mean(x_test, axis=3) / 255", "_____no_output_____" ], [ "fig=plt.figure(figsize=(12,6))\ncolumns = 5\nrows = 2\nfor id in range(1, columns*rows +1):\n train_set = True if np.random.randint(2) == 1 else False\n if train_set:\n n = np.random.randint(x_train.shape[0])\n ax = fig.add_subplot(rows, columns, id)\n ax.title.set_text(f\"Img-{id}, label={y_train[n][0]}\")\n ax.imshow(x_train[n], cmap='gray')\n else:\n n = np.random.randint(x_test.shape[0])\n ax = fig.add_subplot(rows, columns, id)\n ax.title.set_text(f\"Img-{id}, label={y_test[n][0]}\")\n ax.imshow(x_test[n], cmap='gray')\n \nplt.show()", "_____no_output_____" ], [ "x_train = x_train.reshape(x_train.shape + (1,))\nx_test = x_test.reshape(x_test.shape + (1,))\nx_train.shape, x_test.shape", "_____no_output_____" ], [ "y_train= y_train.reshape(y_train.shape[0])\ny_train= y_train-1\ny_train[0:10]", "_____no_output_____" ], [ "y_test= y_test.reshape(y_test.shape[0])\ny_test= y_test-1\ny_test[0:10]", "_____no_output_____" ], [ "y_train = tf.keras.utils.to_categorical(y_train)\ny_test = tf.keras.utils.to_categorical(y_test)", "_____no_output_____" ], [ "y_train.shape, y_test.shape", "_____no_output_____" ] ], [ [ "## 2. MLP neural network classifier\n* Build an MLP classifier model using the Sequential API. Your model should use only Flatten and Dense layers, with the final layer having a 10-way softmax output. \n* You should design and build the model yourself. Feel free to experiment with different MLP architectures. _Hint: to achieve a reasonable accuracy you won't need to use more than 4 or 5 layers._\n* Print out the model summary (using the summary() method)\n* Compile and train the model (we recommend a maximum of 30 epochs), making use of both training and validation sets during the training run. \n* Your model should track at least one appropriate metric, and use at least two callbacks during training, one of which should be a ModelCheckpoint callback.\n* As a guide, you should aim to achieve a final categorical cross entropy training loss of less than 1.0 (the validation loss might be higher).\n* Plot the learning curves for loss vs epoch and accuracy vs epoch for both training and validation sets.\n* Compute and display the loss and accuracy of the trained model on the test set.", "_____no_output_____" ] ], [ [ "from tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Activation", "_____no_output_____" ], [ "def get_model(input_shape):\n \"\"\"\n This function should build a Sequential model according to the above specification. Ensure the \n weights are initialised by providing the input_shape argument in the first layer, given by the\n function argument.\n Your function should return the model.\n \"\"\"\n model = Sequential()\n model.add(keras.Input(shape=input_shape))\n model.add(Flatten())\n model.add(Dense(units=1024,activation='relu'))\n model.add(Dense(units=256,activation='relu'))\n model.add(Dense(units=128,activation='relu'))\n model.add(Dense(units=64,activation='relu'))\n model.add(Dense(units=32,activation='relu'))\n model.add(Dense(10, activation='softmax'))\n \n model.compile(loss='categorical_crossentropy',\n optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),\n metrics=['accuracy'])\n \n return model\n\nmodel = get_model(x_train[0].shape)\nmodel.summary()", "Model: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nflatten (Flatten) (None, 1024) 0 \n_________________________________________________________________\ndense (Dense) (None, 1024) 1049600 \n_________________________________________________________________\ndense_1 (Dense) (None, 256) 262400 \n_________________________________________________________________\ndense_2 (Dense) (None, 128) 32896 \n_________________________________________________________________\ndense_3 (Dense) (None, 64) 8256 \n_________________________________________________________________\ndense_4 (Dense) (None, 32) 2080 \n_________________________________________________________________\ndense_5 (Dense) (None, 10) 330 \n=================================================================\nTotal params: 1,355,562\nTrainable params: 1,355,562\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=5)\n\ncheckpoint_path = \"checkpoints_best_only/checkpoint\"\ncheckpoint_best_only = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n save_freq='epoch',\n save_weights_only=True,\n save_best_only=True,\n monitor='val_accuracy',\n verbose=1)\ncallbacks = [checkpoint_best_only, early_stopping]", "_____no_output_____" ], [ "history = model.fit(x_train,y_train, validation_split=0.15, epochs=60, verbose=1, callbacks=callbacks)", "Train on 62268 samples, validate on 10989 samples\nEpoch 1/60\n62208/62268 [============================>.] - ETA: 0s - loss: 2.1469 - accuracy: 0.2195\nEpoch 00001: val_accuracy improved from -inf to 0.27609, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 109s 2ms/sample - loss: 2.1467 - accuracy: 0.2196 - val_loss: 1.9780 - val_accuracy: 0.2761\nEpoch 2/60\n62208/62268 [============================>.] - ETA: 0s - loss: 1.5968 - accuracy: 0.4392\nEpoch 00002: val_accuracy improved from 0.27609 to 0.49559, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 106s 2ms/sample - loss: 1.5965 - accuracy: 0.4393 - val_loss: 1.4592 - val_accuracy: 0.4956\nEpoch 3/60\n62240/62268 [============================>.] - ETA: 0s - loss: 1.2903 - accuracy: 0.5709\nEpoch 00003: val_accuracy improved from 0.49559 to 0.57776, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 108s 2ms/sample - loss: 1.2902 - accuracy: 0.5709 - val_loss: 1.2659 - val_accuracy: 0.5778\nEpoch 4/60\n62208/62268 [============================>.] - ETA: 0s - loss: 1.1602 - accuracy: 0.6259\nEpoch 00004: val_accuracy improved from 0.57776 to 0.60151, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 107s 2ms/sample - loss: 1.1603 - accuracy: 0.6258 - val_loss: 1.2082 - val_accuracy: 0.6015\nEpoch 5/60\n62176/62268 [============================>.] - ETA: 0s - loss: 1.0987 - accuracy: 0.6480\nEpoch 00005: val_accuracy improved from 0.60151 to 0.62845, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 107s 2ms/sample - loss: 1.0987 - accuracy: 0.6481 - val_loss: 1.1584 - val_accuracy: 0.6284\nEpoch 6/60\n62240/62268 [============================>.] - ETA: 0s - loss: 1.0489 - accuracy: 0.6650\nEpoch 00006: val_accuracy improved from 0.62845 to 0.66667, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 107s 2ms/sample - loss: 1.0488 - accuracy: 0.6650 - val_loss: 1.0426 - val_accuracy: 0.6667\nEpoch 7/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.9993 - accuracy: 0.6831\nEpoch 00007: val_accuracy improved from 0.66667 to 0.68541, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 107s 2ms/sample - loss: 0.9994 - accuracy: 0.6830 - val_loss: 0.9804 - val_accuracy: 0.6854\nEpoch 8/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.9567 - accuracy: 0.6957\nEpoch 00008: val_accuracy improved from 0.68541 to 0.70015, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 107s 2ms/sample - loss: 0.9568 - accuracy: 0.6957 - val_loss: 0.9408 - val_accuracy: 0.7002\nEpoch 9/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.9209 - accuracy: 0.7078\nEpoch 00009: val_accuracy improved from 0.70015 to 0.71262, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 103s 2ms/sample - loss: 0.9210 - accuracy: 0.7078 - val_loss: 0.9031 - val_accuracy: 0.7126\nEpoch 10/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.8911 - accuracy: 0.7190\nEpoch 00010: val_accuracy did not improve from 0.71262\n62268/62268 [==============================] - 104s 2ms/sample - loss: 0.8913 - accuracy: 0.7190 - val_loss: 0.9519 - val_accuracy: 0.6978\nEpoch 11/60\n62176/62268 [============================>.] - ETA: 0s - loss: 0.8667 - accuracy: 0.7255\nEpoch 00011: val_accuracy improved from 0.71262 to 0.71353, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 104s 2ms/sample - loss: 0.8668 - accuracy: 0.7255 - val_loss: 0.8874 - val_accuracy: 0.7135\nEpoch 12/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.8404 - accuracy: 0.7337\nEpoch 00012: val_accuracy did not improve from 0.71353\n62268/62268 [==============================] - 104s 2ms/sample - loss: 0.8405 - accuracy: 0.7337 - val_loss: 0.9043 - val_accuracy: 0.7110\nEpoch 13/60\n62176/62268 [============================>.] - ETA: 0s - loss: 0.8264 - accuracy: 0.7398\nEpoch 00013: val_accuracy improved from 0.71353 to 0.73446, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 104s 2ms/sample - loss: 0.8264 - accuracy: 0.7398 - val_loss: 0.8430 - val_accuracy: 0.7345\nEpoch 14/60\n62176/62268 [============================>.] - ETA: 0s - loss: 0.8162 - accuracy: 0.7418\nEpoch 00014: val_accuracy improved from 0.73446 to 0.73537, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.8162 - accuracy: 0.7418 - val_loss: 0.8371 - val_accuracy: 0.7354\nEpoch 15/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7924 - accuracy: 0.7492\nEpoch 00015: val_accuracy did not improve from 0.73537\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.7925 - accuracy: 0.7492 - val_loss: 0.9439 - val_accuracy: 0.6943\nEpoch 16/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.7879 - accuracy: 0.7503\nEpoch 00016: val_accuracy improved from 0.73537 to 0.74101, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.7878 - accuracy: 0.7503 - val_loss: 0.8258 - val_accuracy: 0.7410\nEpoch 17/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7739 - accuracy: 0.7544\nEpoch 00017: val_accuracy did not improve from 0.74101\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7738 - accuracy: 0.7544 - val_loss: 0.8742 - val_accuracy: 0.7266\nEpoch 18/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7679 - accuracy: 0.7563\nEpoch 00018: val_accuracy improved from 0.74101 to 0.74584, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7679 - accuracy: 0.7562 - val_loss: 0.8000 - val_accuracy: 0.7458\nEpoch 19/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7571 - accuracy: 0.7614\nEpoch 00019: val_accuracy did not improve from 0.74584\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7571 - accuracy: 0.7614 - val_loss: 0.8229 - val_accuracy: 0.7401\nEpoch 20/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.7429 - accuracy: 0.7652\nEpoch 00020: val_accuracy did not improve from 0.74584\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7432 - accuracy: 0.7652 - val_loss: 0.8082 - val_accuracy: 0.7451\nEpoch 21/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7423 - accuracy: 0.7648\nEpoch 00021: val_accuracy improved from 0.74584 to 0.74602, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.7424 - accuracy: 0.7647 - val_loss: 0.8142 - val_accuracy: 0.7460\nEpoch 22/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.7328 - accuracy: 0.7656\nEpoch 00022: val_accuracy improved from 0.74602 to 0.75466, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7327 - accuracy: 0.7656 - val_loss: 0.7928 - val_accuracy: 0.7547\nEpoch 23/60\n62176/62268 [============================>.] - ETA: 0s - loss: 0.7231 - accuracy: 0.7693\nEpoch 00023: val_accuracy improved from 0.75466 to 0.76031, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7232 - accuracy: 0.7693 - val_loss: 0.7738 - val_accuracy: 0.7603\nEpoch 24/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.7176 - accuracy: 0.7710\nEpoch 00024: val_accuracy did not improve from 0.76031\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7174 - accuracy: 0.7711 - val_loss: 0.7792 - val_accuracy: 0.7568\nEpoch 25/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7090 - accuracy: 0.7762\nEpoch 00025: val_accuracy did not improve from 0.76031\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7089 - accuracy: 0.7762 - val_loss: 0.8293 - val_accuracy: 0.7425\nEpoch 26/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.7093 - accuracy: 0.7735\nEpoch 00026: val_accuracy did not improve from 0.76031\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.7094 - accuracy: 0.7735 - val_loss: 0.8872 - val_accuracy: 0.7238\nEpoch 27/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7006 - accuracy: 0.7775\nEpoch 00027: val_accuracy did not improve from 0.76031\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.7006 - accuracy: 0.7775 - val_loss: 0.7994 - val_accuracy: 0.7535\nEpoch 28/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.6930 - accuracy: 0.7800\nEpoch 00028: val_accuracy improved from 0.76031 to 0.76176, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.6931 - accuracy: 0.7800 - val_loss: 0.7706 - val_accuracy: 0.7618\nEpoch 29/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.6878 - accuracy: 0.7808\nEpoch 00029: val_accuracy improved from 0.76176 to 0.76649, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.6878 - accuracy: 0.7808 - val_loss: 0.7627 - val_accuracy: 0.7665\nEpoch 30/60\n62176/62268 [============================>.] - ETA: 0s - loss: 0.6838 - accuracy: 0.7822\nEpoch 00030: val_accuracy did not improve from 0.76649\n62268/62268 [==============================] - 104s 2ms/sample - loss: 0.6838 - accuracy: 0.7823 - val_loss: 0.8255 - val_accuracy: 0.7471\nEpoch 31/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.6827 - accuracy: 0.7826\nEpoch 00031: val_accuracy did not improve from 0.76649\n62268/62268 [==============================] - 102s 2ms/sample - loss: 0.6826 - accuracy: 0.7827 - val_loss: 0.7790 - val_accuracy: 0.7607\nEpoch 32/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.6764 - accuracy: 0.7840\nEpoch 00032: val_accuracy improved from 0.76649 to 0.76877, saving model to checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 104s 2ms/sample - loss: 0.6763 - accuracy: 0.7839 - val_loss: 0.7692 - val_accuracy: 0.7688\nEpoch 33/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.6689 - accuracy: 0.7864\nEpoch 00033: val_accuracy did not improve from 0.76877\n62268/62268 [==============================] - 103s 2ms/sample - loss: 0.6691 - accuracy: 0.7864 - val_loss: 0.7930 - val_accuracy: 0.7583\nEpoch 34/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.6648 - accuracy: 0.7860\nEpoch 00034: val_accuracy did not improve from 0.76877\n62268/62268 [==============================] - 100s 2ms/sample - loss: 0.6648 - accuracy: 0.7860 - val_loss: 0.7779 - val_accuracy: 0.7629\nEpoch 35/60\n62208/62268 [============================>.] - ETA: 0s - loss: 0.6643 - accuracy: 0.7867\nEpoch 00035: val_accuracy did not improve from 0.76877\n62268/62268 [==============================] - 99s 2ms/sample - loss: 0.6643 - accuracy: 0.7866 - val_loss: 0.8628 - val_accuracy: 0.7385\nEpoch 36/60\n62176/62268 [============================>.] - ETA: 0s - loss: 0.6555 - accuracy: 0.7896\nEpoch 00036: val_accuracy did not improve from 0.76877\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.6555 - accuracy: 0.7896 - val_loss: 0.7814 - val_accuracy: 0.7611\nEpoch 37/60\n62240/62268 [============================>.] - ETA: 0s - loss: 0.6488 - accuracy: 0.7928\nEpoch 00037: val_accuracy did not improve from 0.76877\n62268/62268 [==============================] - 98s 2ms/sample - loss: 0.6488 - accuracy: 0.7928 - val_loss: 0.8517 - val_accuracy: 0.7471\n" ], [ "try:\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\nexcept KeyError:\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\nplt.title('Accuracy vs. epochs')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Training', 'Validation'], loc='lower right')\nplt.show() ", "_____no_output_____" ], [ "plt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Loss vs. epochs')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Training', 'Validation'], loc='upper right')\nplt.show() ", "_____no_output_____" ], [ "test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)\nprint(\"Test loss: {:.3f}\\nTest accuracy: {:.2f}%\".format(test_loss, 100 * test_acc))", "Test loss: 0.955\nTest accuracy: 72.27%\n" ] ], [ [ "## 3. CNN neural network classifier\n* Build a CNN classifier model using the Sequential API. Your model should use the Conv2D, MaxPool2D, BatchNormalization, Flatten, Dense and Dropout layers. The final layer should again have a 10-way softmax output. \n* You should design and build the model yourself. Feel free to experiment with different CNN architectures. _Hint: to achieve a reasonable accuracy you won't need to use more than 2 or 3 convolutional layers and 2 fully connected layers.)_\n* The CNN model should use fewer trainable parameters than your MLP model.\n* Compile and train the model (we recommend a maximum of 30 epochs), making use of both training and validation sets during the training run.\n* Your model should track at least one appropriate metric, and use at least two callbacks during training, one of which should be a ModelCheckpoint callback.\n* You should aim to beat the MLP model performance with fewer parameters!\n* Plot the learning curves for loss vs epoch and accuracy vs epoch for both training and validation sets.\n* Compute and display the loss and accuracy of the trained model on the test set.", "_____no_output_____" ] ], [ [ "from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, BatchNormalization", "_____no_output_____" ], [ "def get_cnn_model(input_shape):\n \"\"\"\n This function should build a Sequential model according to the above specification. Ensure the \n weights are initialised by providing the input_shape argument in the first layer, given by the\n function argument.\n Your function should return the model.\n \"\"\"\n model = Sequential([\n Conv2D(name=\"conv_1\", filters=32, kernel_size=(3,3), activation='relu', padding='SAME', input_shape=input_shape),\n MaxPooling2D(name=\"pool_1\", pool_size=(2,2)),\n Conv2D(name=\"conv_2\", filters=16, kernel_size=(3,3), activation='relu', padding='SAME'),\n MaxPooling2D(name=\"pool_2\", pool_size=(4,4)),\n Flatten(name=\"flatten\"),\n Dense(name=\"dense_1\", units=32, activation='relu'),\n Dense(name=\"dense_2\", units=10, activation='softmax')\n ])\n \n model.compile(loss='categorical_crossentropy',\n optimizer=\"adam\",\n metrics=['accuracy'])\n \n return model\n \n\ncnn_model = get_cnn_model(x_train[0].shape)\ncnn_model.summary()", "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv_1 (Conv2D) (None, 32, 32, 32) 320 \n_________________________________________________________________\npool_1 (MaxPooling2D) (None, 16, 16, 32) 0 \n_________________________________________________________________\nconv_2 (Conv2D) (None, 16, 16, 16) 4624 \n_________________________________________________________________\npool_2 (MaxPooling2D) (None, 4, 4, 16) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 256) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 32) 8224 \n_________________________________________________________________\ndense_2 (Dense) (None, 10) 330 \n=================================================================\nTotal params: 13,498\nTrainable params: 13,498\nNon-trainable params: 0\n_________________________________________________________________\n" ], [ "early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=5)\n\ncnn_checkpoint_path = \"cnn_checkpoints_best_only/checkpoint\"\ncnn_checkpoint_best_only = tf.keras.callbacks.ModelCheckpoint(filepath=cnn_checkpoint_path,\n save_freq='epoch',\n save_weights_only=True,\n save_best_only=True,\n monitor='val_accuracy',\n verbose=1)\ncallbacks = [cnn_checkpoint_best_only, early_stopping]\n\ncnn_history = cnn_model.fit(x_train, y_train, epochs=15, validation_split=0.15, callbacks=callbacks, verbose=1)", "Train on 62268 samples, validate on 10989 samples\nEpoch 1/15\n62240/62268 [============================>.] - ETA: 0s - loss: 1.3598 - accuracy: 0.5474\nEpoch 00001: val_accuracy improved from -inf to 0.75758, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 254s 4ms/sample - loss: 1.3595 - accuracy: 0.5475 - val_loss: 0.8246 - val_accuracy: 0.7576\nEpoch 2/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.7463 - accuracy: 0.7809\nEpoch 00002: val_accuracy improved from 0.75758 to 0.80435, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 250s 4ms/sample - loss: 0.7463 - accuracy: 0.7809 - val_loss: 0.6905 - val_accuracy: 0.8043\nEpoch 3/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.6497 - accuracy: 0.8119\nEpoch 00003: val_accuracy improved from 0.80435 to 0.81836, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 248s 4ms/sample - loss: 0.6497 - accuracy: 0.8120 - val_loss: 0.6278 - val_accuracy: 0.8184\nEpoch 4/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.6025 - accuracy: 0.8250\nEpoch 00004: val_accuracy improved from 0.81836 to 0.82710, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 260s 4ms/sample - loss: 0.6025 - accuracy: 0.8250 - val_loss: 0.5989 - val_accuracy: 0.8271\nEpoch 5/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.5707 - accuracy: 0.8337\nEpoch 00005: val_accuracy improved from 0.82710 to 0.82765, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 248s 4ms/sample - loss: 0.5706 - accuracy: 0.8337 - val_loss: 0.5870 - val_accuracy: 0.8276\nEpoch 6/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.5430 - accuracy: 0.8411\nEpoch 00006: val_accuracy improved from 0.82765 to 0.83629, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 248s 4ms/sample - loss: 0.5432 - accuracy: 0.8411 - val_loss: 0.5640 - val_accuracy: 0.8363\nEpoch 7/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.5251 - accuracy: 0.8468\nEpoch 00007: val_accuracy improved from 0.83629 to 0.84503, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 247s 4ms/sample - loss: 0.5252 - accuracy: 0.8468 - val_loss: 0.5388 - val_accuracy: 0.8450\nEpoch 8/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.5070 - accuracy: 0.8521\nEpoch 00008: val_accuracy did not improve from 0.84503\n62268/62268 [==============================] - 246s 4ms/sample - loss: 0.5070 - accuracy: 0.8520 - val_loss: 0.5473 - val_accuracy: 0.8391\nEpoch 9/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.4906 - accuracy: 0.8546\nEpoch 00009: val_accuracy improved from 0.84503 to 0.84876, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 248s 4ms/sample - loss: 0.4905 - accuracy: 0.8546 - val_loss: 0.5156 - val_accuracy: 0.8488\nEpoch 10/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.4767 - accuracy: 0.8587\nEpoch 00010: val_accuracy did not improve from 0.84876\n62268/62268 [==============================] - 271s 4ms/sample - loss: 0.4766 - accuracy: 0.8587 - val_loss: 0.5247 - val_accuracy: 0.8449\nEpoch 11/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.4634 - accuracy: 0.8628\nEpoch 00011: val_accuracy improved from 0.84876 to 0.85340, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 250s 4ms/sample - loss: 0.4635 - accuracy: 0.8627 - val_loss: 0.4986 - val_accuracy: 0.8534\nEpoch 12/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.4548 - accuracy: 0.8651\nEpoch 00012: val_accuracy did not improve from 0.85340\n62268/62268 [==============================] - 249s 4ms/sample - loss: 0.4548 - accuracy: 0.8650 - val_loss: 0.5007 - val_accuracy: 0.8502\nEpoch 13/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.4452 - accuracy: 0.8676\nEpoch 00013: val_accuracy improved from 0.85340 to 0.85777, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 249s 4ms/sample - loss: 0.4451 - accuracy: 0.8676 - val_loss: 0.4852 - val_accuracy: 0.8578\nEpoch 14/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.4361 - accuracy: 0.8698\nEpoch 00014: val_accuracy did not improve from 0.85777\n62268/62268 [==============================] - 246s 4ms/sample - loss: 0.4361 - accuracy: 0.8698 - val_loss: 0.4853 - val_accuracy: 0.8573\nEpoch 15/15\n62240/62268 [============================>.] - ETA: 0s - loss: 0.4293 - accuracy: 0.8711\nEpoch 00015: val_accuracy improved from 0.85777 to 0.85922, saving model to cnn_checkpoints_best_only/checkpoint\n62268/62268 [==============================] - 266s 4ms/sample - loss: 0.4292 - accuracy: 0.8712 - val_loss: 0.4754 - val_accuracy: 0.8592\n" ], [ "try:\n plt.plot(cnn_history.history['accuracy'])\n plt.plot(cnn_history.history['val_accuracy'])\nexcept KeyError:\n plt.plot(cnn_.history['acc'])\n plt.plot(cnn_.history['val_acc'])\nplt.title('Accuracy vs. epochs')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Training', 'Validation'], loc='lower right')\nplt.show() ", "_____no_output_____" ], [ "plt.plot(cnn_history.history['loss'])\nplt.plot(cnn_history.history['val_loss'])\nplt.title('Loss vs. epochs')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Training', 'Validation'], loc='upper right')\nplt.show() ", "_____no_output_____" ], [ "cnn_test_loss, cnn_test_acc = cnn_model.evaluate(x_test, y_test, verbose=0)\nprint(\"Test loss: {:.3f}\\nTest accuracy: {:.2f}%\".format(cnn_test_loss, 100 * cnn_test_acc))", "Test loss: 0.496\nTest accuracy: 85.79%\n" ] ], [ [ "## 4. Get model predictions\n* Load the best weights for the MLP and CNN models that you saved during the training run.\n* Randomly select 5 images and corresponding labels from the test set and display the images with their labels.\n* Alongside the image and label, show each model’s predictive distribution as a bar chart, and the final model prediction given by the label with maximum probability.", "_____no_output_____" ] ], [ [ "model.load_weights(checkpoint_path)\ncnn_model.load_weights(cnn_checkpoint_path)", "_____no_output_____" ], [ "num_test_images = x_test.shape[0]\n\nrandom_inx = np.random.choice(num_test_images, 5)\nrandom_test_images = x_test[random_inx, ...]\nrandom_test_labels = y_test[random_inx, ...]\n\npredictions = model.predict(random_test_images)\ncnn_predictions = cnn_model.predict(random_test_images)\n\nfig, axes = plt.subplots(5, 2, figsize=(16, 12))\nfig.subplots_adjust(hspace=0.4, wspace=-0.2)\n\nfor i, (cnn_prediction, prediction, image, label) in enumerate(zip(cnn_predictions, predictions, random_test_images, random_test_labels)):\n axes[i, 0].imshow(np.squeeze(image))\n axes[i, 0].get_xaxis().set_visible(False)\n axes[i, 0].get_yaxis().set_visible(False)\n axes[i, 0].text(10., -1.5, f'Digit {label}')\n axes[i, 1].bar(np.arange(len(cnn_prediction))+1, cnn_prediction, color=\"green\")\n axes[i, 1].bar(np.arange(len(prediction))+1, prediction)\n axes[i, 1].set_xticks(np.arange(len(prediction))+1)\n axes[i, 1].set_title(f\"Model prediction: {np.argmax(prediction)+1}, CNN Model prediction: {np.argmax(cnn_prediction)+1}\")\n \nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4afb2b3e5f7ed2532c2610e5e17429e6a3e8979e
22,669
ipynb
Jupyter Notebook
Programming Assignment: Building and serialising K.ipynb
ABHIJATSARARI/data_engineering
b22a6d3761815e0f589e8507e980616acdfffc1e
[ "MIT" ]
null
null
null
Programming Assignment: Building and serialising K.ipynb
ABHIJATSARARI/data_engineering
b22a6d3761815e0f589e8507e980616acdfffc1e
[ "MIT" ]
null
null
null
Programming Assignment: Building and serialising K.ipynb
ABHIJATSARARI/data_engineering
b22a6d3761815e0f589e8507e980616acdfffc1e
[ "MIT" ]
null
null
null
96.876068
6,305
0.615069
[ [ [ "# Keras exercise\n\nIn this exercise you will be creating a Keras model by loading a data set, preprocessing input data, building a Sequential Keras model and compiling the model with a training configuration. Afterwards, you train your model on the training data and evaluate it on the test set. To finish this exercise, you will past the accuracy of your model to the Coursera grader.\n\nThis notebook is tested in IBM Watson Studio under python 3.6\n\n## Data\n\nFor this exercise we will use the Reuters newswire dataset. This dataset consists of 11,228 newswires from the Reuters news agency. Each wire is encoded as a sequence of word indexes, just as in the IMDB data we encountered in lecture 5 of this series. Moreover, each wire is categorised into one of 46 topics, which will serve as our label. This dataset is available through the Keras API.\n\n## Goal\n\nWe want to create a Multi-layer perceptron (MLP) using Keras which we can train to classify news items into the specified 46 topics.\n\n## Instructions\n\nWe start by installing and importing everything we need for this exercise:", "_____no_output_____" ] ], [ [ "!pip install tensorflow==2.2.0rc0", "\u001b[31mERROR: Could not find a version that satisfies the requirement tensorflow==2.2.0rc0 (from versions: 2.2.0rc1, 2.2.0rc2, 2.2.0rc3, 2.2.0rc4, 2.2.0, 2.2.1, 2.2.2, 2.2.3, 2.3.0rc0, 2.3.0rc1, 2.3.0rc2, 2.3.0, 2.3.1, 2.3.2, 2.3.3, 2.3.4, 2.4.0rc0, 2.4.0rc1, 2.4.0rc2, 2.4.0rc3, 2.4.0rc4, 2.4.0, 2.4.1, 2.4.2, 2.4.3, 2.4.4, 2.5.0rc0, 2.5.0rc1, 2.5.0rc2, 2.5.0rc3, 2.5.0, 2.5.1, 2.5.2, 2.6.0rc0, 2.6.0rc1, 2.6.0rc2, 2.6.0, 2.6.1, 2.6.2, 2.7.0rc0, 2.7.0rc1, 2.7.0, 2.8.0rc0)\u001b[0m\r\n\u001b[31mERROR: No matching distribution found for tensorflow==2.2.0rc0\u001b[0m\r\n" ], [ "!pip install --upgrade tensorflow", "Requirement already satisfied: tensorflow in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (2.7.0)\nRequirement already satisfied: numpy>=1.14.5 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (1.19.2)\nRequirement already satisfied: keras<2.8,>=2.7.0rc0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (2.7.0)\nRequirement already satisfied: protobuf>=3.9.2 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (3.11.2)\nRequirement already satisfied: h5py>=2.9.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (2.10.0)\nRequirement already satisfied: libclang>=9.0.1 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (12.0.0)\nRequirement already satisfied: keras-preprocessing>=1.1.1 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (1.1.2)\nRequirement already satisfied: opt-einsum>=2.3.2 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (3.1.0)\nRequirement already satisfied: tensorflow-io-gcs-filesystem>=0.21.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (0.23.1)\nRequirement already satisfied: tensorboard~=2.6 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (2.7.0)\nRequirement already satisfied: absl-py>=0.4.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (0.10.0)\nRequirement already satisfied: google-pasta>=0.1.1 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (0.2.0)\nRequirement already satisfied: wheel<1.0,>=0.32.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (0.35.1)\nRequirement already satisfied: grpcio<2.0,>=1.24.3 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (1.35.0)\nRequirement already satisfied: wrapt>=1.11.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (1.12.1)\nRequirement already satisfied: gast<0.5.0,>=0.2.1 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (0.3.3)\nRequirement already satisfied: tensorflow-estimator<2.8,~=2.7.0rc0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (2.7.0)\nRequirement already satisfied: typing-extensions>=3.6.6 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (3.7.4.3)\nRequirement already satisfied: flatbuffers<3.0,>=1.12 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (2.0)\nRequirement already satisfied: termcolor>=1.1.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (1.1.0)\nRequirement already satisfied: six>=1.12.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (1.15.0)\nRequirement already satisfied: astunparse>=1.6.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorflow) (1.6.3)\nRequirement already satisfied: setuptools in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from protobuf>=3.9.2->tensorflow) (52.0.0.post20211006)\nRequirement already satisfied: requests<3,>=2.21.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow) (2.25.1)\nRequirement already satisfied: markdown>=2.6.8 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow) (3.1.1)\nRequirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow) (0.6.1)\nRequirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow) (1.6.0)\nRequirement already satisfied: google-auth<3,>=1.6.3 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow) (1.23.0)\nRequirement already satisfied: werkzeug>=0.11.15 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow) (2.0.1)\nRequirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow) (0.4.4)\nRequirement already satisfied: rsa<5,>=3.1.4 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow) (4.7.2)\nRequirement already satisfied: cachetools<5.0,>=2.0.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow) (4.2.2)\nRequirement already satisfied: pyasn1-modules>=0.2.1 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow) (0.2.8)\nRequirement already satisfied: requests-oauthlib>=0.7.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow) (1.3.0)\nRequirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow) (0.4.8)\nRequirement already satisfied: idna<3,>=2.5 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2.8)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (1.26.6)\nRequirement already satisfied: chardet<5,>=3.0.2 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2021.10.8)\nRequirement already satisfied: oauthlib>=3.0.0 in /opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow) (3.1.1)\n" ], [ "import tensorflow as tf\nif not tf.__version__ == '2.2.0-rc0':\n print(tf.__version__)\n raise ValueError('please upgrade to TensorFlow 2.2.0-rc0, or restart your Kernel (Kernel->Restart & Clear Output)')", "2.7.0\n" ] ], [ [ "IMPORTANT! => Please restart the kernel by clicking on \"Kernel\"->\"Restart and Clear Outout\" and wait until all output disapears. Then your changes are beeing picked up\n\nAs you can see, we use Keras' Sequential model with only two types of layers: Dense and Dropout. We also specify a random seed to make our results reproducible. Next, we load the Reuters data set:", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.utils import to_categorical\nseed = 1337\nnp.random.seed(seed)\nfrom tensorflow.keras.datasets import reuters\n\nmax_words = 1000\n(x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=max_words,\n test_split=0.2,\n seed=seed)\nnum_classes = np.max(y_train) + 1 # 46 topics", "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/reuters.npz\n2113536/2110848 [==============================] - 0s 0us/step\n2121728/2110848 [==============================] - 0s 0us/step\n" ] ], [ [ "Note that we cap the maximum number of words in a news item to 1000 by specifying the *num_words* key word. Also, 20% of the data will be test data and we ensure reproducibility by setting our random seed.\n\nOur training features are still simply sequences of indexes and we need to further preprocess them, so that we can plug them into a *Dense* layer. For this we use a *Tokenizer* from Keras' text preprocessing module. This tokenizer will take an index sequence and map it to a vector of length *max_words=1000*. Each of the 1000 vector positions corresponds to one of the words in our newswire corpus. The output of the tokenizer has a 1 at the i-th position of the vector, if the word corresponding to i is in the description of the newswire, and 0 otherwise. Even if this word appears multiple times, we still just put a 1 into our vector, i.e. our tokenizer is binary. We use this tokenizer to transform both train and test features:", "_____no_output_____" ] ], [ [ "from tensorflow.keras.preprocessing.text import Tokenizer\n\ntokenizer = Tokenizer(num_words=max_words)\nx_train = tokenizer.sequences_to_matrix(x_train, mode='binary')\nx_test = tokenizer.sequences_to_matrix(x_test, mode='binary')", "_____no_output_____" ] ], [ [ "## 1. Exercise part: label encoding\n\nUse to_categorical, as we did in the lectures, to transform both *y_train* and *y_test* into one-hot encoded vectors of length *num_classes*:", "_____no_output_____" ] ], [ [ "y_train = to_categorical(y_train, num_classes=num_classes)\ny_test = to_categorical(y_test, num_classes=num_classes)", "_____no_output_____" ] ], [ [ "## 2. Exercise part: model definition\n\nNext, initialise a Keras *Sequential* model and add three layers to it:\n\n Layer: Add a *Dense* layer with in input_shape=(max_words,), 512 output units and \"relu\" activation.\n Layer: Add a *Dropout* layer with dropout rate of 50%.\n Layer: Add a *Dense* layer with num_classes output units and \"softmax\" activation.", "_____no_output_____" ] ], [ [ "model = Sequential() # Instantiate sequential model\nmodel.add(Dense(512, activation='relu', input_shape = (max_words,))) # Add first layer. Make sure to specify input shape\nmodel.add(Dropout(0.5)) # Add second layer\nmodel.add(Dense(num_classes, activation='softmax')) # Add third layer", "2022-01-19 08:11:49.315068: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /opt/ibm/dsdriver/lib:/opt/oracle/lib:/opt/conda/envs/Python-3.8-main/lib/python3.8/site-packages/tensorflow\n2022-01-19 08:11:49.315068: W tensorflow/stream_executor/cuda/cuda_driver.cc:269] failed call to cuInit: UNKNOWN ERROR (303)\n" ] ], [ [ "## 3. Exercise part: model compilation\n\nAs the next step, we need to compile our Keras model with a training configuration. Compile your model with \"categorical_crossentropy\" as loss function, \"adam\" as optimizer and specify \"accuracy\" as evaluation metric. NOTE: In case you get an error regarding h5py, just restart the kernel and start from scratch", "_____no_output_____" ] ], [ [ "model.compile(loss=\"categorical_crossentropy\", optimizer='adam', metrics=['accuracy'])\n", "_____no_output_____" ] ], [ [ "## 4. Exercise part: model training and evaluation\n\nNext, define the batch_size for training as 32 and train the model for 5 epochs on *x_train* and *y_train* by using the *fit* method of your model. Then calculate the score for your trained model by running *evaluate* on *x_test* and *y_test* with the same batch size as used in *fit*.", "_____no_output_____" ] ], [ [ "batch_size = 32 ###_YOUR_CODE_GOES_HERE_###\nmodel.fit(x_train, y_train, batch_size=batch_size, epochs=5, validation_data=(x_test,y_test))\nscore = model.evaluate(x_test,y_test, verbose=1)", "Epoch 1/5\n281/281 [==============================] - 4s 13ms/step - loss: 1.3959 - accuracy: 0.6851 - val_loss: 0.9874 - val_accuracy: 0.7778\nEpoch 2/5\n281/281 [==============================] - 3s 10ms/step - loss: 0.7804 - accuracy: 0.8170 - val_loss: 0.8553 - val_accuracy: 0.7907\nEpoch 3/5\n281/281 [==============================] - 3s 10ms/step - loss: 0.5514 - accuracy: 0.8719 - val_loss: 0.8216 - val_accuracy: 0.7996\nEpoch 4/5\n281/281 [==============================] - 3s 10ms/step - loss: 0.4290 - accuracy: 0.8913 - val_loss: 0.8225 - val_accuracy: 0.8014\nEpoch 5/5\n281/281 [==============================] - 3s 10ms/step - loss: 0.3442 - accuracy: 0.9093 - val_loss: 0.8737 - val_accuracy: 0.7934\n71/71 [==============================] - 0s 2ms/step - loss: 0.8737 - accuracy: 0.7934\n" ] ], [ [ "If you have done everything as specified, in particular set the random seed as we did above, your test accuracy should be around 80% ", "_____no_output_____" ] ], [ [ "score[1]", "_____no_output_____" ] ], [ [ "Congratulations, now it's time to submit your result to the Coursera grader by executing the following cells (Programming Assingment, Week2). \n\nWe have to install a little library in order to submit to coursera\n", "_____no_output_____" ] ], [ [ "!rm -f rklib.py\n!wget https://raw.githubusercontent.com/IBM/coursera/master/rklib.py", "--2022-01-19 08:13:18-- https://raw.githubusercontent.com/IBM/coursera/master/rklib.py\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.109.133, 185.199.108.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 2540 (2.5K) [text/plain]\nSaving to: ‘rklib.py’\n\nrklib.py 100%[===================>] 2.48K --.-KB/s in 0s \n\n2022-01-19 08:13:18 (46.6 MB/s) - ‘rklib.py’ saved [2540/2540]\n\n" ] ], [ [ "Please provide your email address and obtain a submission token (secret) on the grader’s submission page in coursera, then execute the cell", "_____no_output_____" ] ], [ [ "from rklib import submit\nimport json\n\nkey = \"XbAMqtjdEeepUgo7OOVwng\"\npart = \"HCvcp\"\nemail = \"[email protected]\"\ntoken = \"dZdkRAY3MAalkTjx\"\nsubmit(email, token, 'XbAMqtjdEeepUgo7OOVwng', part, [part], json.dumps(score[1]*100))", "Submission successful, please check on the coursera grader page for the status\n-------------------------\n{\"elements\":[{\"itemId\":\"ozVf2\",\"id\":\"tE4j0qhMEeecqgpT6QjMdA~ozVf2~s6W-Knj_EeywtgrLqOXVzQ\",\"courseId\":\"tE4j0qhMEeecqgpT6QjMdA\"}],\"paging\":{},\"linked\":{}}\n-------------------------\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4afb3281330fc309a0239ddd406dd169b6d045c5
23,652
ipynb
Jupyter Notebook
3 - NumPy Basics/3-4 NumPy Array Basics - Multi-dimensional Arrays.ipynb
zengyanjulia/Python
e9587ce5fd48041d8049ced2fd499dfaf17a0861
[ "Apache-2.0" ]
72
2015-03-08T21:31:01.000Z
2022-03-29T23:06:47.000Z
3 - NumPy Basics/3-4 NumPy Array Basics - Multi-dimensional Arrays.ipynb
zengyanjulia/Python
e9587ce5fd48041d8049ced2fd499dfaf17a0861
[ "Apache-2.0" ]
3
2015-02-26T19:38:38.000Z
2015-08-04T03:01:24.000Z
3 - NumPy Basics/3-4 NumPy Array Basics - Multi-dimensional Arrays.ipynb
zengyanjulia/Python
e9587ce5fd48041d8049ced2fd499dfaf17a0861
[ "Apache-2.0" ]
107
2015-02-28T17:10:31.000Z
2022-03-29T23:06:52.000Z
21.540984
444
0.396584
[ [ [ "# NumPy Array Basics - Multi-dimensional Arrays", "_____no_output_____" ] ], [ [ "import sys\nprint(sys.version)\nimport numpy as np\nprint(np.__version__)", "3.3.2 (v3.3.2:d047928ae3f6, May 13 2013, 13:52:24) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]\n1.9.2\n" ], [ "npa = np.arange(25)", "_____no_output_____" ], [ "npa", "_____no_output_____" ] ], [ [ "We learned in the last video how to generate arrays, now let’s generate multidimensional arrays. These are, as you might guess, arrays with multiple dimensions.", "_____no_output_____" ], [ "We can create these by reshaping arrays. One of the simplest ways is to just reshape an array with the reshape command. That gives us an x by x array.", "_____no_output_____" ] ], [ [ "npa.reshape((5,5))", "_____no_output_____" ] ], [ [ "We can also use the zeros commands.", "_____no_output_____" ] ], [ [ "npa2 = np.zeros((5,5))", "_____no_output_____" ], [ "npa2", "_____no_output_____" ] ], [ [ "To get the size of the array we can use the size method.", "_____no_output_____" ] ], [ [ "npa2.size", "_____no_output_____" ] ], [ [ "To get the shape of the array we can use the shape method.", "_____no_output_____" ] ], [ [ "npa2.shape", "_____no_output_____" ] ], [ [ "to get the number of dimension we use the ndim method.", "_____no_output_____" ] ], [ [ "npa2.ndim", "_____no_output_____" ] ], [ [ "We can create as many dimensions as we need to, here's 3 dimensions.", "_____no_output_____" ] ], [ [ "np.arange(8).reshape(2,2,2)", "_____no_output_____" ] ], [ [ "Here's 4 dimensions", "_____no_output_____" ] ], [ [ "np.zeros((4,4,4,4))", "_____no_output_____" ], [ "np.arange(16).reshape(2,2,2,2)", "_____no_output_____" ] ], [ [ "For the most part we’ll be working with 2 dimensions.", "_____no_output_____" ] ], [ [ "npa2", "_____no_output_____" ], [ "npa", "_____no_output_____" ] ], [ [ "Now we can really see the power of vectorization, let’s create two random 2 dimensional arrays.\n\nNow I’m going to set the random seed. This basically makes your random number generation reproducible.", "_____no_output_____" ] ], [ [ "np.random.seed(10)", "_____no_output_____" ] ], [ [ "let’s try some random number generation and then we can perform some matrix comparisons.", "_____no_output_____" ] ], [ [ "npa2 = np.random.random_integers(1,10,25).reshape(5,5)\nnpa2", "_____no_output_____" ], [ "npa3 = np.random.random_integers(1,10,25).reshape(5,5)\nnpa3", "_____no_output_____" ] ], [ [ "We can do this comparison with greater than or equal to.", "_____no_output_____" ] ], [ [ "npa2 > npa3", "_____no_output_____" ] ], [ [ "We can also sum up the values where there are equal.", "_____no_output_____" ] ], [ [ "(npa2 == npa3).sum()", "_____no_output_____" ] ], [ [ "Or we can sum where one is greater than or equal to in the columns.\n\nWe can do that with sum or we could get the total by summing that array.", "_____no_output_____" ] ], [ [ "sum(npa2 >= npa3)", "_____no_output_____" ], [ "sum(npa2 >= npa3).sum()", "_____no_output_____" ] ], [ [ "We can also get the minimums and maximums like we got with single dimensional arrays or for specific dimensions.\n", "_____no_output_____" ] ], [ [ "npa2.min()", "_____no_output_____" ], [ "npa2.min(axis=1)", "_____no_output_____" ], [ "npa2.max(axis=0)", "_____no_output_____" ] ], [ [ "There are plenty of other functions that numpy as. we can transpose with .T property or transpose method. ", "_____no_output_____" ] ], [ [ "npa2.T", "_____no_output_____" ], [ "npa2.transpose()", "_____no_output_____" ], [ "npa2.T == npa2.transpose()", "_____no_output_____" ] ], [ [ "We can also multiply this transposition by itself for example. This will be an item by item multiplication", "_____no_output_____" ] ], [ [ "npa2.T * npa2", "_____no_output_____" ] ], [ [ "We can flatten these arrays in several different ways.\n\nwe can flatten it, which returns a new array that we can change\n", "_____no_output_____" ] ], [ [ "np2 = npa2.flatten()\nnp2", "_____no_output_____" ] ], [ [ "or we can ravel it which ends up returning the original array in a flattened format.", "_____no_output_____" ] ], [ [ "r = npa2.ravel()\nr", "_____no_output_____" ], [ "np2[0] = 25", "_____no_output_____" ], [ "npa2", "_____no_output_____" ] ], [ [ "With ravel if we change a value in the raveled array that will change it in the original n-dimensional array as well", "_____no_output_____" ] ], [ [ "r[0] = 25", "_____no_output_____" ], [ "npa2", "_____no_output_____" ] ], [ [ "\nNow we can use some other helpful functions like cumsum and comprod to get the cumulative products and sums. This works for any dimensional array.", "_____no_output_____" ] ], [ [ "npa2.cumsum()", "_____no_output_____" ], [ "npa2.cumprod()", "_____no_output_____" ] ], [ [ "\nThat really covers a lot of the basic functions you’re going to use or need when working with pandas but it is worth being aware that numpy is a very deep library that does a lot more things that I've covered here. I wanted to cover these basics because they're going to come up when we're working with pandas. I'm sure this has felt fairly academic at this point but I can promise you that it provides a valuable foundation to pandas.\n\n\nneed. If there’s anything you have questions about feel free to ask along the side and I can create some appendix videos to help you along.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4afb48699d4475169a89a814c6d64a6ac386955f
895
ipynb
Jupyter Notebook
venv/Lib/site-packages/nbdime/tests/files/single_cell_nb--changed_source_output_ec.ipynb
PeerHerholz/guideline_jupyter_book
ce445e4be0d53370b67708a22550565b90d71ac6
[ "BSD-3-Clause" ]
2
2021-02-16T16:17:07.000Z
2021-11-08T20:27:13.000Z
venv/Lib/site-packages/nbdime/tests/files/single_cell_nb--changed_source_output_ec.ipynb
PeerHerholz/guideline_jupyter_book
ce445e4be0d53370b67708a22550565b90d71ac6
[ "BSD-3-Clause" ]
null
null
null
venv/Lib/site-packages/nbdime/tests/files/single_cell_nb--changed_source_output_ec.ipynb
PeerHerholz/guideline_jupyter_book
ce445e4be0d53370b67708a22550565b90d71ac6
[ "BSD-3-Clause" ]
4
2020-11-14T17:05:36.000Z
2020-11-16T18:44:54.000Z
15.982143
34
0.480447
[ [ [ "def printit(x):\n print(x + 3)\nprintit(4)", "7\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
4afb492c52790137cbae8e6c15f03b27f1bf5122
13,575
ipynb
Jupyter Notebook
src/python/tests/covid_db_api_performance_tests2.ipynb
rockmind/LoveAndMarriage
2877d6af626eff2a3134a05ab7f03c52f14fde5c
[ "Apache-2.0" ]
null
null
null
src/python/tests/covid_db_api_performance_tests2.ipynb
rockmind/LoveAndMarriage
2877d6af626eff2a3134a05ab7f03c52f14fde5c
[ "Apache-2.0" ]
1
2021-12-18T16:07:39.000Z
2021-12-18T16:07:39.000Z
src/python/tests/covid_db_api_performance_tests2.ipynb
rockmind/LoveAndMarriage
2877d6af626eff2a3134a05ab7f03c52f14fde5c
[ "Apache-2.0" ]
null
null
null
62.557604
1,854
0.628287
[ [ [ "import os\nimport sys\nfrom asyncio import sleep, gather\n\nfrom numpy.random import randint\nfrom services.rpc_services import covid_db_api\n\nsys.path.append('C:\\\\Users\\\\29uiz\\\\OneDrive\\\\PycharmProjects\\\\LoveAndMarriage\\\\src\\\\python')\nos.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'", "_____no_output_____" ], [ "\nasync def f(i):\n await sleep(randint(1, 1000))\n result = await covid_db_api.rpc_request(['get_provinces_cases', 'get_provinces_geojson'])\n print(i,)\n\nawait gather(*[f(i) for i in range(1000)])", "67\n749\n434\n12\n165\n230\n647\n503\n799\n462\n129\n888\n713\n449\n368\n643\n366\n435\n419\n302\n788\n304\n196\n235\n22\n579\n568\n744\n57\n736\n657\n72\n937\n10\n774\n239\n75\n655\n615\n924\n133\n161\n78\n454\n118\n455\n171\n233\n58\n409\n373\n377\n561\n97\n756\n479\n124\n94\n732\n210\n46\n151\n495\n488\n284\n150\n1\n414\n344\n162\n717\n100\n308\n8\n986\n769\n676\n101\n482\n385\n901\n200\n21\n512\n994\n738\n848\n533\n323\n571\n176\n757\n681\n628\n825\n998\n867\n699\n359\n841\n98\n121\n223\n447\n73\n316\n782\n815\n566\n309\n792\n27\n336\n597\n202\n539\n714\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4afb4df15d63d31e4d589c7f9f44de49d91669f2
1,863
ipynb
Jupyter Notebook
notebooks/Splitter test.ipynb
innovationOUtside/notebook_processing
7444235112c2c0677f0873db54f080138c78ad95
[ "MIT" ]
2
2020-02-12T06:34:03.000Z
2021-09-30T04:55:10.000Z
notebooks/Splitter test.ipynb
innovationOUtside/notebook_processing
7444235112c2c0677f0873db54f080138c78ad95
[ "MIT" ]
8
2020-07-04T21:35:31.000Z
2022-01-10T17:13:40.000Z
notebooks/Splitter test.ipynb
innovationOUtside/notebook_processing
7444235112c2c0677f0873db54f080138c78ad95
[ "MIT" ]
null
null
null
15.270492
34
0.456253
[ [ [ "# Part 1", "_____no_output_____" ] ], [ [ "# part 1 code", "_____no_output_____" ] ], [ [ "Part 1 MD", "_____no_output_____" ] ], [ [ "#--SPLITHERE--", "_____no_output_____" ] ], [ [ "# Part 2", "_____no_output_____" ] ], [ [ "# part 2 code", "_____no_output_____" ] ], [ [ "Part 2 MD", "_____no_output_____" ], [ "# --SPLITHERE--", "_____no_output_____" ], [ "# Part 3", "_____no_output_____" ] ], [ [ "# part 3 code", "_____no_output_____" ] ], [ [ "Part 3 MD", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4afb6507715a6e62d33381b4f1665e02ad1f4d19
291,806
ipynb
Jupyter Notebook
Task1a.ipynb
parthivi1607/SMM4H21
8d667f3edbcb2c90351da5fdb6a42f6136936bfe
[ "MIT" ]
3
2021-07-14T06:19:09.000Z
2021-07-26T03:52:44.000Z
Task1a.ipynb
parthivi1607/SMM4H21
8d667f3edbcb2c90351da5fdb6a42f6136936bfe
[ "MIT" ]
null
null
null
Task1a.ipynb
parthivi1607/SMM4H21
8d667f3edbcb2c90351da5fdb6a42f6136936bfe
[ "MIT" ]
6
2021-05-08T16:14:50.000Z
2022-03-24T15:06:32.000Z
69.246796
3,496
0.525599
[ [ [ "<a href=\"https://colab.research.google.com/github/RSid8/SMM4H21/blob/main/Task1a.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "#Importing the Libraries and Models", "_____no_output_____" ] ], [ [ "from google.colab import drive\ndrive.mount('/content/drive')", "Mounted at /content/drive\n" ], [ "!pip install fairseq", "Collecting fairseq\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/15/ab/92c6efb05ffdfe16fbdc9e463229d9af8c3b74dc943ed4b4857a87b223c2/fairseq-0.10.2-cp37-cp37m-manylinux1_x86_64.whl (1.7MB)\n\u001b[K |████████████████████████████████| 1.7MB 14.2MB/s \n\u001b[?25hCollecting hydra-core\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/52/e3/fbd70dd0d3ce4d1d75c22d56c0c9f895cfa7ed6587a9ffb821d6812d6a60/hydra_core-1.0.6-py3-none-any.whl (123kB)\n\u001b[K |████████████████████████████████| 133kB 54.2MB/s \n\u001b[?25hRequirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from fairseq) (1.8.0+cu101)\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from fairseq) (1.19.5)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from fairseq) (4.41.1)\nCollecting sacrebleu>=1.4.12\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/7e/57/0c7ca4e31a126189dab99c19951910bd081dea5bbd25f24b77107750eae7/sacrebleu-1.5.1-py3-none-any.whl (54kB)\n\u001b[K |████████████████████████████████| 61kB 10.0MB/s \n\u001b[?25hCollecting dataclasses\n Downloading https://files.pythonhosted.org/packages/26/2f/1095cdc2868052dd1e64520f7c0d5c8c550ad297e944e641dbf1ffbb9a5d/dataclasses-0.6-py3-none-any.whl\nRequirement already satisfied: regex in /usr/local/lib/python3.7/dist-packages (from fairseq) (2019.12.20)\nRequirement already satisfied: cffi in /usr/local/lib/python3.7/dist-packages (from fairseq) (1.14.5)\nRequirement already satisfied: cython in /usr/local/lib/python3.7/dist-packages (from fairseq) (0.29.22)\nCollecting omegaconf<2.1,>=2.0.5\n Downloading https://files.pythonhosted.org/packages/d0/eb/9d63ce09dd8aa85767c65668d5414958ea29648a0eec80a4a7d311ec2684/omegaconf-2.0.6-py3-none-any.whl\nCollecting antlr4-python3-runtime==4.8\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/56/02/789a0bddf9c9b31b14c3e79ec22b9656185a803dc31c15f006f9855ece0d/antlr4-python3-runtime-4.8.tar.gz (112kB)\n\u001b[K |████████████████████████████████| 112kB 56.3MB/s \n\u001b[?25hRequirement already satisfied: importlib-resources; python_version < \"3.9\" in /usr/local/lib/python3.7/dist-packages (from hydra-core->fairseq) (5.1.2)\nRequirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch->fairseq) (3.7.4.3)\nCollecting portalocker==2.0.0\n Downloading https://files.pythonhosted.org/packages/89/a6/3814b7107e0788040870e8825eebf214d72166adf656ba7d4bf14759a06a/portalocker-2.0.0-py2.py3-none-any.whl\nRequirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi->fairseq) (2.20)\nCollecting PyYAML>=5.1.*\n\u001b[?25l Downloading https://files.pythonhosted.org/packages/7a/a5/393c087efdc78091afa2af9f1378762f9821c9c1d7a22c5753fb5ac5f97a/PyYAML-5.4.1-cp37-cp37m-manylinux1_x86_64.whl (636kB)\n\u001b[K |████████████████████████████████| 645kB 57.7MB/s \n\u001b[?25hRequirement already satisfied: zipp>=0.4; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from importlib-resources; python_version < \"3.9\"->hydra-core->fairseq) (3.4.1)\nBuilding wheels for collected packages: antlr4-python3-runtime\n Building wheel for antlr4-python3-runtime (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for antlr4-python3-runtime: filename=antlr4_python3_runtime-4.8-cp37-none-any.whl size=141231 sha256=f53e595e77b60c22b734ec8ed730b5b5dddae40e74f302ed5ec12d1f9eb68701\n Stored in directory: /root/.cache/pip/wheels/e3/e2/fa/b78480b448b8579ddf393bebd3f47ee23aa84c89b6a78285c8\nSuccessfully built antlr4-python3-runtime\nInstalling collected packages: PyYAML, omegaconf, antlr4-python3-runtime, hydra-core, portalocker, sacrebleu, dataclasses, fairseq\n Found existing installation: PyYAML 3.13\n Uninstalling PyYAML-3.13:\n Successfully uninstalled PyYAML-3.13\nSuccessfully installed PyYAML-5.4.1 antlr4-python3-runtime-4.8 dataclasses-0.6 fairseq-0.10.2 hydra-core-1.0.6 omegaconf-2.0.6 portalocker-2.0.0 sacrebleu-1.5.1\n" ], [ "!git clone https://github.com/pytorch/fairseq\n%cd fairseq", "Cloning into 'fairseq'...\nremote: Enumerating objects: 55, done.\u001b[K\nremote: Counting objects: 100% (55/55), done.\u001b[K\nremote: Compressing objects: 100% (36/36), done.\u001b[K\nremote: Total 21750 (delta 21), reused 26 (delta 16), pack-reused 21695\u001b[K\nReceiving objects: 100% (21750/21750), 10.08 MiB | 21.96 MiB/s, done.\nResolving deltas: 100% (16218/16218), done.\n/content/fairseq\n" ], [ "%%shell\nwget https://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz\ntar -xzvf roberta.large.tar.gz", "--2021-03-10 06:52:22-- https://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz\nResolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.74.142, 172.67.9.4, 104.22.75.142, ...\nConnecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.74.142|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 655283069 (625M) [application/gzip]\nSaving to: ‘roberta.large.tar.gz’\n\nroberta.large.tar.g 100%[===================>] 624.93M 12.2MB/s in 53s \n\n2021-03-10 06:53:15 (11.9 MB/s) - ‘roberta.large.tar.gz’ saved [655283069/655283069]\n\nroberta.large/\nroberta.large/dict.txt\nroberta.large/model.pt\nroberta.large/NOTE\n" ], [ "import torch\nfrom tqdm import tqdm\nroberta = torch.hub.load('pytorch/fairseq', 'roberta.large')", "Downloading: \"https://github.com/pytorch/fairseq/archive/master.zip\" to /root/.cache/torch/hub/master.zip\n" ], [ "!ls", "CODE_OF_CONDUCT.md fairseq\t pyproject.toml scripts\nCONTRIBUTING.md fairseq_cli README.md\t setup.py\ndocs\t\t hubconf.py\t roberta.large\t tests\nexamples\t LICENSE\t roberta.large.tar.gz train.py\n" ], [ "tokens = roberta.encode('Hello world!')\nassert tokens.tolist() == [0, 31414, 232, 328, 2]\nroberta.decode(tokens) # 'Hello world!'", "_____no_output_____" ] ], [ [ "# Preprocessing the data for training", "_____no_output_____" ] ], [ [ "import pandas as pd\ndf = pd.read_csv(\"/content/drive/MyDrive/UPENN/Task1a/train.tsv\", sep = '\\t')\ndf_tweets = pd.read_csv('/content/drive/MyDrive/UPENN/Task1a/tweets.tsv', sep = '\\t')\ndf_class = pd.read_csv('/content/drive/MyDrive/UPENN/Task1a/class.tsv', sep = '\\t')\ndf.columns = [\"tweet_id\", \"tweet\", \"label\"]\ndf_valid = pd.merge(df_tweets, df_class, on = 'tweet_id')\ndf = pd.concat([df, df_valid], axis=0)\ndf.head()", "_____no_output_____" ], [ "df.label.value_counts()", "_____no_output_____" ], [ "df.tweet_id.nunique()", "_____no_output_____" ], [ "import numpy as np\n# count = df['tweet'].str.split().apply(len).value_counts()\n# count.index = count.index.astype(str) + ' words:'\n# count.sort_index(inplace=True)\n# count\na = np.array(df['tweet'].str.split().apply(len))\nprint(f'Longest sentence {a.max()}, smallest sentence {a.min()}, average sentence length {a.mean()}')", "Longest sentence 443, smallest sentence 1, average sentence length 16.054064417177916\n" ], [ "# something is wrong in example - 11986", "303 24\n303 12\n443 8\n443 26\nName: tweet, dtype: int64\n" ], [ "index_names = df[df['tweet'].str.split().apply(len)>35].index\ndf.drop(index_names, inplace=True)\ndf.tweet_id.nunique()", "_____no_output_____" ], [ "df['label'].replace({\"NoADE\":0, \"ADE\":1}, inplace=True)\ndf.head()", "_____no_output_____" ], [ "import os\nimport random\nfrom glob import glob\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom collections import Counter\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.under_sampling import RandomUnderSampler\n\nX_train,X_val, Y_train, Y_val= train_test_split(df['tweet'], df['label'], test_size = 0.1, random_state = 21)\nX_train.reset_index(drop=True, inplace = True)\nX_val.reset_index(drop=True, inplace = True)\nY_train.reset_index(drop=True, inplace = True)\nY_val.reset_index(drop=True, inplace=True)\n# define oversampling strategy\nover = RandomOverSampler(sampling_strategy=0.1)\n# define undersampling strategy\nunder = RandomUnderSampler(sampling_strategy=0.5)\nX_train = X_train.values.reshape(-1, 1)\nX_train, Y_train = over.fit_resample(X_train, Y_train)\nX_train, Y_train = under.fit_resample(X_train, Y_train)\nprint(Counter(Y_train))\nprint(X_train[0][0])\nfor split in ['train', 'val']:\n out_fname = 'train' if split == 'train' else 'val'\n f1 = open(os.path.join(\"/content/drive/MyDrive/UPENN/Task1a\", out_fname+'.input0'), 'w')\n f2 = open(os.path.join(\"/content/drive/MyDrive/UPENN/Task1a\", out_fname+'.label'), 'w')\n if split=='train':\n for i in range(len(X_train)):\n f1.write(str(X_train[i][0])+'\\n')\n f2.write(str(Y_train[i])+'\\n')\n else:\n for i in range(len(X_val)):\n f1.write(X_val[i]+'\\n')\n f2.write(str(Y_val[i])+'\\n')\n f1.close()\n f2.close()\n\n", "/usr/local/lib/python3.7/dist-packages/sklearn/externals/six.py:31: FutureWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/).\n \"(https://pypi.org/project/six/).\", FutureWarning)\n/usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.neighbors.base module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.neighbors. Anything that cannot be imported from sklearn.neighbors is now part of the private API.\n warnings.warn(message, FutureWarning)\n" ] ], [ [ "# Tokenize the data and Finetune Roberta", "_____no_output_____" ] ], [ [ "%%shell\nwget -N 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/encoder.json'\nwget -N 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/vocab.bpe'\n\nfor SPLIT in train val; do\n python -m examples.roberta.multiprocessing_bpe_encoder \\\n --encoder-json encoder.json \\\n --vocab-bpe vocab.bpe \\\n --inputs \"/content/drive/MyDrive/UPENN/Task1a/$SPLIT.input0\" \\\n --outputs \"/content/drive/MyDrive/UPENN/Task1a/$SPLIT.input0.bpe\" \\\n --workers 60 \\\n --keep-empty\ndone", "--2021-02-28 16:29:06-- https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/encoder.json\nResolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.75.142, 172.67.9.4, 104.22.74.142, ...\nConnecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.75.142|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 1042301 (1018K) [text/plain]\nSaving to: ‘encoder.json’\n\nencoder.json 100%[===================>] 1018K 1.33MB/s in 0.7s \n\n2021-02-28 16:29:07 (1.33 MB/s) - ‘encoder.json’ saved [1042301/1042301]\n\n--2021-02-28 16:29:07-- https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/vocab.bpe\nResolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.75.142, 172.67.9.4, 104.22.74.142, ...\nConnecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.75.142|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 456318 (446K) [text/plain]\nSaving to: ‘vocab.bpe’\n\nvocab.bpe 100%[===================>] 445.62K 756KB/s in 0.6s \n\n2021-02-28 16:29:08 (756 KB/s) - ‘vocab.bpe’ saved [456318/456318]\n\n" ], [ "%%shell\nwget -N 'https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/dict.txt' \n", "--2021-02-28 16:29:34-- https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/dict.txt\nResolving dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)... 104.22.75.142, 172.67.9.4, 104.22.74.142, ...\nConnecting to dl.fbaipublicfiles.com (dl.fbaipublicfiles.com)|104.22.75.142|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 603290 (589K) [text/plain]\nSaving to: ‘dict.txt’\n\ndict.txt 100%[===================>] 589.15K 990KB/s in 0.6s \n\n2021-02-28 16:29:36 (990 KB/s) - ‘dict.txt’ saved [603290/603290]\n\n" ], [ "%%bash\nfairseq-preprocess \\\n --only-source \\\n --trainpref \"/content/drive/MyDrive/UPENN/Task1a/train.input0.bpe\" \\\n --validpref \"/content/drive/MyDrive/UPENN/Task1a/val.input0.bpe\" \\\n --destdir \"/content/drive/MyDrive/UPENN/Task1a-bin/input0\" \\\n --workers 60 \\\n --srcdict dict.txt\n", "2021-02-28 16:29:38 | INFO | fairseq_cli.preprocess | Namespace(align_suffix=None, alignfile=None, all_gather_list_size=16384, bf16=False, bpe=None, checkpoint_shard_count=1, checkpoint_suffix='', cpu=False, criterion='cross_entropy', dataset_impl='mmap', destdir='/content/drive/MyDrive/UPENN/Task1a-bin/input0', empty_cache_freq=0, fp16=False, fp16_init_scale=128, fp16_no_flatten_grads=False, fp16_scale_tolerance=0.0, fp16_scale_window=None, joined_dictionary=False, log_format=None, log_interval=100, lr_scheduler='fixed', memory_efficient_bf16=False, memory_efficient_fp16=False, min_loss_scale=0.0001, model_parallel_size=1, no_progress_bar=False, nwordssrc=-1, nwordstgt=-1, only_source=True, optimizer=None, padding_factor=8, profile=False, quantization_config_path=None, scoring='bleu', seed=1, source_lang=None, srcdict='dict.txt', target_lang=None, task='translation', tensorboard_logdir=None, testpref=None, tgtdict=None, threshold_loss_scale=None, thresholdsrc=0, thresholdtgt=0, tokenizer=None, tpu=False, trainpref='/content/drive/MyDrive/UPENN/Task1a/train.input0.bpe', user_dir=None, validpref='/content/drive/MyDrive/UPENN/Task1a/val.input0.bpe', workers=60)\n2021-02-28 16:29:38 | INFO | fairseq_cli.preprocess | [None] Dictionary: 50264 types\n2021-02-28 16:29:44 | INFO | fairseq_cli.preprocess | [None] /content/drive/MyDrive/UPENN/Task1a/train.input0.bpe: 4572 sents, 132354 tokens, 0.0% replaced by <unk>\n2021-02-28 16:29:44 | INFO | fairseq_cli.preprocess | [None] Dictionary: 50264 types\n2021-02-28 16:29:48 | INFO | fairseq_cli.preprocess | [None] /content/drive/MyDrive/UPENN/Task1a/val.input0.bpe: 1826 sents, 51455 tokens, 0.0% replaced by <unk>\n2021-02-28 16:29:48 | INFO | fairseq_cli.preprocess | Wrote preprocessed data to /content/drive/MyDrive/UPENN/Task1a-bin/input0\n" ], [ "%%bash\nfairseq-preprocess \\\n --only-source \\\n --trainpref \"/content/drive/MyDrive/UPENN/Task1a/train.label\" \\\n --validpref \"/content/drive/MyDrive/UPENN/Task1a/val.label\" \\\n --destdir \"/content/drive/MyDrive/UPENN/Task1a-bin/label\" \\\n --workers 60", "2021-02-28 16:29:49 | INFO | fairseq_cli.preprocess | Namespace(align_suffix=None, alignfile=None, all_gather_list_size=16384, bf16=False, bpe=None, checkpoint_shard_count=1, checkpoint_suffix='', cpu=False, criterion='cross_entropy', dataset_impl='mmap', destdir='/content/drive/MyDrive/UPENN/Task1a-bin/label', empty_cache_freq=0, fp16=False, fp16_init_scale=128, fp16_no_flatten_grads=False, fp16_scale_tolerance=0.0, fp16_scale_window=None, joined_dictionary=False, log_format=None, log_interval=100, lr_scheduler='fixed', memory_efficient_bf16=False, memory_efficient_fp16=False, min_loss_scale=0.0001, model_parallel_size=1, no_progress_bar=False, nwordssrc=-1, nwordstgt=-1, only_source=True, optimizer=None, padding_factor=8, profile=False, quantization_config_path=None, scoring='bleu', seed=1, source_lang=None, srcdict=None, target_lang=None, task='translation', tensorboard_logdir=None, testpref=None, tgtdict=None, threshold_loss_scale=None, thresholdsrc=0, thresholdtgt=0, tokenizer=None, tpu=False, trainpref='/content/drive/MyDrive/UPENN/Task1a/train.label', user_dir=None, validpref='/content/drive/MyDrive/UPENN/Task1a/val.label', workers=60)\n2021-02-28 16:29:50 | INFO | fairseq_cli.preprocess | [None] Dictionary: 8 types\n2021-02-28 16:29:53 | INFO | fairseq_cli.preprocess | [None] /content/drive/MyDrive/UPENN/Task1a/train.label: 4572 sents, 9144 tokens, 0.0% replaced by <unk>\n2021-02-28 16:29:53 | INFO | fairseq_cli.preprocess | [None] Dictionary: 8 types\n2021-02-28 16:29:55 | INFO | fairseq_cli.preprocess | [None] /content/drive/MyDrive/UPENN/Task1a/val.label: 1826 sents, 3652 tokens, 0.0% replaced by <unk>\n2021-02-28 16:29:55 | INFO | fairseq_cli.preprocess | Wrote preprocessed data to /content/drive/MyDrive/UPENN/Task1a-bin/label\n" ], [ "%%shell\nTOTAL_NUM_UPDATES=3614 # 10 epochs through UPENN for bsz 32\nWARMUP_UPDATES=217 # 6 percent of the number of updates\nLR=1e-05 # Peak LR for polynomial LR scheduler.\nHEAD_NAME=task1a_head # Custom name for the classification head.\nNUM_CLASSES=2 # Number of classes for the classification task.\nMAX_SENTENCES=8 # Batch size.\nROBERTA_PATH=/content/fairseq/roberta.large/model.pt #/content/fairseq/checkpoint/checkpoint_best.pt \nCUDA_VISIBLE_DEVICES=0 fairseq-train /content/drive/MyDrive/UPENN/Task1a-bin/ \\\n --restore-file $ROBERTA_PATH \\\n --max-positions 512 \\\n --batch-size $MAX_SENTENCES \\\n --max-tokens 4400 \\\n --task sentence_prediction \\\n --reset-optimizer --reset-dataloader --reset-meters \\\n --required-batch-size-multiple 1 \\\n --init-token 0 --separator-token 2 \\\n --arch roberta_large \\\n --criterion sentence_prediction \\\n --classification-head-name $HEAD_NAME \\\n --num-classes $NUM_CLASSES \\\n --dropout 0.1 --attention-dropout 0.1 \\\n --weight-decay 0.1 --optimizer adam --adam-betas \"(0.9, 0.98)\" --adam-eps 1e-06 \\\n --clip-norm 0.0 \\\n --lr-scheduler polynomial_decay --lr $LR --total-num-update $TOTAL_NUM_UPDATES --warmup-updates $WARMUP_UPDATES \\\n --fp16 --fp16-init-scale 4 --threshold-loss-scale 1 --fp16-scale-window 128 \\\n --max-epoch 6 \\\n --best-checkpoint-metric accuracy --maximize-best-checkpoint-metric \\\n --shorten-method \"truncate\" \\\n --find-unused-parameters \\\n --update-freq 4", "2021-02-28 16:30:03 | INFO | fairseq_cli.train | Namespace(activation_dropout=0.0, activation_fn='gelu', adam_betas='(0.9, 0.98)', adam_eps=1e-06, add_prev_output_tokens=False, all_gather_list_size=16384, arch='roberta_large', attention_dropout=0.1, batch_size=8, batch_size_valid=8, best_checkpoint_metric='accuracy', bf16=False, bpe=None, broadcast_buffers=False, bucket_cap_mb=25, checkpoint_shard_count=1, checkpoint_suffix='', classification_head_name='task1a_head', clip_norm=0.0, cpu=False, criterion='sentence_prediction', curriculum=0, data='/content/drive/MyDrive/UPENN/Task1a-bin/', data_buffer_size=10, dataset_impl=None, ddp_backend='c10d', device_id=0, disable_validation=False, distributed_backend='nccl', distributed_init_method=None, distributed_no_spawn=False, distributed_num_procs=1, distributed_port=-1, distributed_rank=0, distributed_world_size=1, distributed_wrapper='DDP', dropout=0.1, empty_cache_freq=0, encoder_attention_heads=16, encoder_embed_dim=1024, encoder_ffn_embed_dim=4096, encoder_layerdrop=0, encoder_layers=24, encoder_layers_to_keep=None, end_learning_rate=0.0, fast_stat_sync=False, find_unused_parameters=True, finetune_from_model=None, fix_batches_to_gpus=False, fixed_validation_seed=None, force_anneal=None, fp16=True, fp16_init_scale=4, fp16_no_flatten_grads=False, fp16_scale_tolerance=0.0, fp16_scale_window=128, gen_subset='test', init_token=0, keep_best_checkpoints=-1, keep_interval_updates=-1, keep_last_epochs=-1, localsgd_frequency=3, log_format=None, log_interval=100, lr=[1e-05], lr_scheduler='polynomial_decay', max_epoch=6, max_positions=512, max_tokens=4400, max_tokens_valid=4400, max_update=0, maximize_best_checkpoint_metric=True, memory_efficient_bf16=False, memory_efficient_fp16=False, min_loss_scale=0.0001, min_lr=-1.0, model_parallel_size=1, no_epoch_checkpoints=False, no_last_checkpoints=False, no_progress_bar=False, no_save=False, no_save_optimizer_state=False, no_seed_provided=False, no_shuffle=False, nprocs_per_node=1, num_classes=2, num_shards=1, num_workers=1, optimizer='adam', optimizer_overrides='{}', patience=-1, pipeline_balance=None, pipeline_checkpoint='never', pipeline_chunks=0, pipeline_decoder_balance=None, pipeline_decoder_devices=None, pipeline_devices=None, pipeline_encoder_balance=None, pipeline_encoder_devices=None, pipeline_model_parallel=False, pooler_activation_fn='tanh', pooler_dropout=0.0, power=1.0, profile=False, quant_noise_pq=0, quant_noise_pq_block_size=8, quant_noise_scalar=0, quantization_config_path=None, regression_target=False, required_batch_size_multiple=1, required_seq_len_multiple=1, reset_dataloader=True, reset_lr_scheduler=False, reset_meters=True, reset_optimizer=True, restore_file='/content/fairseq/roberta.large/model.pt', save_dir='checkpoints', save_interval=1, save_interval_updates=0, scoring='bleu', seed=1, sentence_avg=False, separator_token=2, shard_id=0, shorten_data_split_list='', shorten_method='truncate', skip_invalid_size_inputs_valid_test=False, slowmo_algorithm='LocalSGD', slowmo_momentum=None, spectral_norm_classification_head=False, stop_time_hours=0, task='sentence_prediction', tensorboard_logdir=None, threshold_loss_scale=1.0, tokenizer=None, total_num_update=3614, tpu=False, train_subset='train', update_freq=[4], use_bmuf=False, use_old_adam=False, user_dir=None, valid_subset='valid', validate_after_updates=0, validate_interval=1, validate_interval_updates=0, warmup_updates=217, weight_decay=0.1, zero_sharding='none')\n2021-02-28 16:30:03 | INFO | fairseq.tasks.sentence_prediction | [input] dictionary: 50265 types\n2021-02-28 16:30:03 | INFO | fairseq.tasks.sentence_prediction | [label] dictionary: 9 types\n2021-02-28 16:30:03 | INFO | fairseq.data.data_utils | loaded 1826 examples from: /content/drive/MyDrive/UPENN/Task1a-bin/input0/valid\n2021-02-28 16:30:03 | INFO | fairseq.data.data_utils | loaded 1826 examples from: /content/drive/MyDrive/UPENN/Task1a-bin/label/valid\n2021-02-28 16:30:03 | INFO | fairseq.tasks.sentence_prediction | Loaded valid with #samples: 1826\n2021-02-28 16:30:18 | INFO | fairseq_cli.train | RobertaModel(\n (encoder): RobertaEncoder(\n (sentence_encoder): TransformerSentenceEncoder(\n (dropout_module): FairseqDropout()\n (embed_tokens): Embedding(50265, 1024, padding_idx=1)\n (embed_positions): LearnedPositionalEmbedding(514, 1024, padding_idx=1)\n (layers): ModuleList(\n (0): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (1): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (2): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (3): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (4): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (5): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (6): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (7): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (8): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (9): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (10): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (11): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (12): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (13): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (14): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (15): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (16): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (17): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (18): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (19): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (20): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (21): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (22): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (23): TransformerSentenceEncoderLayer(\n (dropout_module): FairseqDropout()\n (activation_dropout_module): FairseqDropout()\n (self_attn): MultiheadAttention(\n (dropout_module): FairseqDropout()\n (k_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (v_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (q_proj): Linear(in_features=1024, out_features=1024, bias=True)\n (out_proj): Linear(in_features=1024, out_features=1024, bias=True)\n )\n (self_attn_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n (fc1): Linear(in_features=1024, out_features=4096, bias=True)\n (fc2): Linear(in_features=4096, out_features=1024, bias=True)\n (final_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n )\n (emb_layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n (lm_head): RobertaLMHead(\n (dense): Linear(in_features=1024, out_features=1024, bias=True)\n (layer_norm): LayerNorm((1024,), eps=1e-05, elementwise_affine=True)\n )\n )\n (classification_heads): ModuleDict(\n (task1a_head): RobertaClassificationHead(\n (dense): Linear(in_features=1024, out_features=1024, bias=True)\n (dropout): Dropout(p=0.0, inplace=False)\n (out_proj): Linear(in_features=1024, out_features=2, bias=True)\n )\n )\n)\n2021-02-28 16:30:18 | INFO | fairseq_cli.train | task: sentence_prediction (SentencePredictionTask)\n2021-02-28 16:30:18 | INFO | fairseq_cli.train | model: roberta_large (RobertaModel)\n2021-02-28 16:30:18 | INFO | fairseq_cli.train | criterion: sentence_prediction (SentencePredictionCriterion)\n2021-02-28 16:30:18 | INFO | fairseq_cli.train | num. model params: 356462683 (num. trained: 356462683)\n2021-02-28 16:30:27 | INFO | fairseq.trainer | detected shared parameter: encoder.sentence_encoder.embed_tokens.weight <- encoder.lm_head.weight\n2021-02-28 16:30:27 | INFO | fairseq.utils | ***********************CUDA enviroments for all 1 workers***********************\n2021-02-28 16:30:27 | INFO | fairseq.utils | rank 0: capabilities = 3.7 ; total memory = 11.173 GB ; name = Tesla K80 \n2021-02-28 16:30:27 | INFO | fairseq.utils | ***********************CUDA enviroments for all 1 workers***********************\n2021-02-28 16:30:27 | INFO | fairseq_cli.train | training on 1 devices (GPUs/TPUs)\n2021-02-28 16:30:27 | INFO | fairseq_cli.train | max tokens per GPU = 4400 and max sentences per GPU = 8\n2021-02-28 16:30:33 | INFO | fairseq.models.roberta.model | Overwriting classification_heads.task1a_head.dense.weight\n2021-02-28 16:30:33 | INFO | fairseq.models.roberta.model | Overwriting classification_heads.task1a_head.dense.bias\n2021-02-28 16:30:33 | INFO | fairseq.models.roberta.model | Overwriting classification_heads.task1a_head.out_proj.weight\n2021-02-28 16:30:33 | INFO | fairseq.models.roberta.model | Overwriting classification_heads.task1a_head.out_proj.bias\n2021-02-28 16:30:33 | INFO | fairseq.trainer | loaded checkpoint /content/fairseq/roberta.large/model.pt (epoch 1 @ 0 updates)\n2021-02-28 16:30:33 | INFO | fairseq.trainer | NOTE: your device does NOT support faster training with --fp16, please switch to FP32 which is likely to be faster\n2021-02-28 16:30:33 | INFO | fairseq.trainer | loading train data for epoch 1\n2021-02-28 16:30:33 | INFO | fairseq.data.data_utils | loaded 4572 examples from: /content/drive/MyDrive/UPENN/Task1a-bin/input0/train\n2021-02-28 16:30:33 | INFO | fairseq.data.data_utils | loaded 4572 examples from: /content/drive/MyDrive/UPENN/Task1a-bin/label/train\n2021-02-28 16:30:33 | INFO | fairseq.tasks.sentence_prediction | Loaded train with #samples: 4572\nepoch 001: 0% 0/143 [00:00<?, ?it/s]2021-02-28 16:30:33 | INFO | fairseq.trainer | begin training epoch 1\nepoch 001: 99% 142/143 [09:30<00:04, 4.03s/it, loss=1.086, nll_loss=0.036, accuracy=45.5, wps=237.3, ups=0.25, wpb=954.3, bsz=32, num_updates=100, lr=4.60829e-06, gnorm=11.617, loss_scale=4, train_wall=402, wall=408]2021-02-28 16:40:08 | INFO | fairseq_cli.train | begin validation on \"valid\" subset\n\nepoch 001 | valid on 'valid' subset: 0% 0/229 [00:00<?, ?it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 0% 1/229 [00:00<01:26, 2.62it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 1% 2/229 [00:00<01:25, 2.67it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 1% 3/229 [00:01<01:19, 2.83it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 2% 4/229 [00:01<01:17, 2.89it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 2% 5/229 [00:01<01:16, 2.94it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 3% 6/229 [00:02<01:15, 2.96it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 3% 7/229 [00:02<01:14, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 3% 8/229 [00:02<01:11, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 4% 9/229 [00:02<01:12, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 4% 10/229 [00:03<01:10, 3.13it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 5% 11/229 [00:03<01:12, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 5% 12/229 [00:03<01:12, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 6% 13/229 [00:04<01:09, 3.09it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 6% 14/229 [00:04<01:10, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 7% 15/229 [00:04<01:10, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 7% 16/229 [00:05<01:10, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 7% 17/229 [00:05<01:08, 3.11it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 8% 18/229 [00:05<01:10, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 8% 19/229 [00:06<01:11, 2.93it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 9% 20/229 [00:06<01:08, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 9% 21/229 [00:06<01:08, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 10% 22/229 [00:07<01:06, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 10% 23/229 [00:07<01:05, 3.16it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 10% 24/229 [00:07<01:05, 3.11it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 11% 25/229 [00:08<01:06, 3.09it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 11% 26/229 [00:08<01:06, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 12% 27/229 [00:08<01:04, 3.13it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 12% 28/229 [00:09<01:04, 3.11it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 13% 29/229 [00:09<01:04, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 13% 30/229 [00:09<01:03, 3.15it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 14% 31/229 [00:10<01:03, 3.11it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 14% 32/229 [00:10<01:04, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 14% 33/229 [00:10<01:02, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 15% 34/229 [00:11<01:04, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 15% 35/229 [00:11<01:06, 2.94it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 16% 36/229 [00:11<01:03, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 16% 37/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 17% 38/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 17% 39/229 [00:12<01:02, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 17% 40/229 [00:13<01:00, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 18% 41/229 [00:13<01:01, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 18% 42/229 [00:13<01:02, 2.97it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 19% 43/229 [00:14<01:05, 2.84it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 19% 44/229 [00:14<01:04, 2.88it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 20% 45/229 [00:14<01:01, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 20% 46/229 [00:15<01:02, 2.92it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 21% 47/229 [00:15<01:03, 2.88it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 21% 48/229 [00:15<01:05, 2.76it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 21% 49/229 [00:16<01:06, 2.69it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 22% 50/229 [00:16<01:04, 2.78it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 22% 51/229 [00:17<01:03, 2.78it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 23% 52/229 [00:17<01:02, 2.84it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 23% 53/229 [00:17<01:00, 2.90it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 24% 54/229 [00:18<00:59, 2.93it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 24% 55/229 [00:18<00:57, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 24% 56/229 [00:18<00:57, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 25% 57/229 [00:18<00:56, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 25% 58/229 [00:19<00:55, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 26% 59/229 [00:19<00:55, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 26% 60/229 [00:19<00:55, 3.06it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 27% 61/229 [00:20<00:51, 3.26it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 27% 62/229 [00:20<00:52, 3.19it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 28% 63/229 [00:20<00:53, 3.13it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 28% 64/229 [00:21<00:51, 3.18it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 28% 65/229 [00:21<00:52, 3.13it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 29% 66/229 [00:21<00:52, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 29% 67/229 [00:22<00:54, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 30% 68/229 [00:22<00:53, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 30% 69/229 [00:22<00:53, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 31% 70/229 [00:23<00:53, 2.98it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 31% 71/229 [00:23<00:52, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 31% 72/229 [00:23<00:52, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 32% 73/229 [00:24<00:51, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 32% 74/229 [00:24<00:51, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 33% 75/229 [00:24<00:51, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 33% 76/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 34% 77/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 34% 78/229 [00:25<00:49, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 34% 79/229 [00:26<00:48, 3.09it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 35% 80/229 [00:26<00:49, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 35% 81/229 [00:26<00:48, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 36% 82/229 [00:27<00:48, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 36% 83/229 [00:27<00:46, 3.12it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 37% 84/229 [00:27<00:45, 3.17it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 37% 85/229 [00:28<00:45, 3.20it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 38% 86/229 [00:28<00:45, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 38% 87/229 [00:28<00:45, 3.11it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 38% 88/229 [00:29<00:46, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 39% 89/229 [00:29<00:45, 3.09it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 39% 90/229 [00:29<00:46, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 40% 91/229 [00:30<00:46, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 40% 92/229 [00:30<00:44, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 41% 93/229 [00:30<00:44, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 41% 94/229 [00:31<00:44, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 41% 95/229 [00:31<00:44, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 42% 96/229 [00:31<00:43, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 42% 97/229 [00:32<00:43, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 43% 98/229 [00:32<00:43, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 43% 99/229 [00:32<00:42, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 44% 100/229 [00:33<00:41, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 44% 101/229 [00:33<00:40, 3.16it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 45% 102/229 [00:33<00:40, 3.12it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 45% 103/229 [00:34<00:41, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 45% 104/229 [00:34<00:42, 2.94it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 46% 105/229 [00:34<00:41, 2.96it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 46% 106/229 [00:35<00:41, 2.97it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 47% 107/229 [00:35<00:40, 2.98it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 47% 108/229 [00:35<00:40, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 48% 109/229 [00:35<00:39, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 48% 110/229 [00:36<00:38, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 48% 111/229 [00:36<00:39, 2.97it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 49% 112/229 [00:36<00:38, 3.06it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 49% 113/229 [00:37<00:37, 3.13it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 50% 114/229 [00:37<00:37, 3.09it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 50% 115/229 [00:37<00:38, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 51% 116/229 [00:38<00:37, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 51% 117/229 [00:38<00:38, 2.92it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 52% 118/229 [00:39<00:38, 2.87it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 52% 119/229 [00:39<00:36, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 52% 120/229 [00:39<00:36, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 53% 121/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 53% 122/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 54% 123/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 54% 124/229 [00:40<00:33, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 55% 125/229 [00:41<00:35, 2.91it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 55% 126/229 [00:41<00:35, 2.87it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 55% 127/229 [00:42<00:35, 2.91it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 56% 128/229 [00:42<00:35, 2.87it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 56% 129/229 [00:42<00:34, 2.92it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 57% 130/229 [00:43<00:33, 2.94it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 57% 131/229 [00:43<00:34, 2.82it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 58% 132/229 [00:43<00:33, 2.86it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 58% 133/229 [00:44<00:33, 2.91it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 59% 134/229 [00:44<00:32, 2.94it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 59% 135/229 [00:44<00:31, 2.96it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 59% 136/229 [00:45<00:30, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 60% 137/229 [00:45<00:31, 2.96it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 60% 138/229 [00:45<00:29, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 61% 139/229 [00:46<00:29, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 61% 140/229 [00:46<00:28, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 62% 141/229 [00:46<00:27, 3.16it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 62% 142/229 [00:47<00:27, 3.12it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 62% 143/229 [00:47<00:28, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 63% 144/229 [00:47<00:29, 2.93it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 63% 145/229 [00:48<00:30, 2.71it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 64% 146/229 [00:48<00:30, 2.73it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 64% 147/229 [00:48<00:29, 2.81it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 65% 148/229 [00:49<00:28, 2.86it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 65% 149/229 [00:49<00:28, 2.84it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 66% 150/229 [00:49<00:26, 2.96it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 66% 151/229 [00:50<00:26, 2.97it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 66% 152/229 [00:50<00:25, 2.98it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 67% 153/229 [00:50<00:24, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 67% 154/229 [00:51<00:24, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 68% 155/229 [00:51<00:24, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 68% 156/229 [00:51<00:24, 3.03it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 69% 157/229 [00:52<00:23, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 69% 158/229 [00:52<00:23, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 69% 159/229 [00:52<00:22, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 70% 160/229 [00:53<00:21, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 70% 161/229 [00:53<00:21, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 71% 162/229 [00:53<00:21, 3.16it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 71% 163/229 [00:54<00:21, 3.11it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 72% 164/229 [00:54<00:21, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 72% 165/229 [00:54<00:20, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 72% 166/229 [00:55<00:20, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 73% 167/229 [00:55<00:19, 3.12it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 73% 168/229 [00:55<00:19, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 74% 169/229 [00:56<00:19, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 74% 170/229 [00:56<00:19, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 75% 171/229 [00:56<00:18, 3.09it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 75% 172/229 [00:57<00:18, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 76% 173/229 [00:57<00:17, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 76% 174/229 [00:57<00:17, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 76% 175/229 [00:57<00:17, 3.15it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 77% 176/229 [00:58<00:15, 3.32it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 77% 177/229 [00:58<00:16, 3.22it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 78% 178/229 [00:58<00:16, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 78% 179/229 [00:59<00:15, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 79% 180/229 [00:59<00:15, 3.18it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 79% 181/229 [00:59<00:15, 3.13it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 79% 182/229 [01:00<00:14, 3.17it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 80% 183/229 [01:00<00:14, 3.21it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 80% 184/229 [01:00<00:13, 3.24it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 81% 185/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 81% 186/229 [01:01<00:13, 3.23it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 82% 187/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 82% 188/229 [01:02<00:13, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 83% 189/229 [01:02<00:13, 2.95it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 83% 190/229 [01:02<00:13, 2.97it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 83% 191/229 [01:03<00:12, 2.99it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 84% 192/229 [01:03<00:11, 3.10it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 84% 193/229 [01:03<00:11, 3.15it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 85% 194/229 [01:04<00:10, 3.19it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 85% 195/229 [01:04<00:10, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 86% 196/229 [01:04<00:10, 3.18it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 86% 197/229 [01:05<00:10, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 86% 198/229 [01:05<00:09, 3.11it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 87% 199/229 [01:05<00:09, 3.16it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 87% 200/229 [01:05<00:09, 3.12it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 88% 201/229 [01:06<00:09, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 88% 202/229 [01:06<00:09, 2.89it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 89% 203/229 [01:06<00:08, 3.00it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 89% 204/229 [01:07<00:08, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 90% 205/229 [01:07<00:07, 3.08it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 90% 206/229 [01:08<00:07, 2.97it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 90% 207/229 [01:08<00:07, 2.98it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 91% 208/229 [01:08<00:06, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 91% 209/229 [01:08<00:06, 3.14it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 92% 210/229 [01:09<00:06, 3.07it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 92% 211/229 [01:09<00:05, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 93% 212/229 [01:09<00:05, 3.12it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 93% 213/229 [01:10<00:05, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 93% 214/229 [01:10<00:04, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 94% 215/229 [01:10<00:04, 2.93it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 94% 216/229 [01:11<00:04, 3.02it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 95% 217/229 [01:11<00:04, 2.94it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 95% 218/229 [01:11<00:03, 2.96it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 96% 219/229 [01:12<00:03, 2.98it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 96% 220/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 97% 221/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 97% 222/229 [01:13<00:02, 2.95it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 97% 223/229 [01:13<00:01, 3.05it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 98% 224/229 [01:13<00:01, 2.97it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 98% 225/229 [01:14<00:01, 2.91it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 99% 226/229 [01:14<00:00, 3.04it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 99% 227/229 [01:14<00:00, 3.12it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 100% 228/229 [01:15<00:00, 3.19it/s]\u001b[A\nepoch 001 | valid on 'valid' subset: 100% 229/229 [01:15<00:00, 3.97it/s]\u001b[A\n \u001b[A2021-02-28 16:41:23 | INFO | valid | epoch 001 | valid on 'valid' subset | loss 0.381 | nll_loss 0.013 | accuracy 90.6 | wps 706.7 | wpb 232.7 | bsz 8 | num_updates 143\n2021-02-28 16:41:23 | INFO | fairseq_cli.train | begin save checkpoint\ntcmalloc: large alloc 1425858560 bytes == 0x5649e8214000 @ 0x7f59d375cb6b 0x7f59d377c379 0x7f597693574e 0x7f59769377b6 0x7f59b13a1e43 0x7f59b0d8c7ff 0x7f59b10a3bdc 0x7f59b104f24b 0x7f59b106e065 0x7f59b1049a7b 0x7f59b104f24b 0x7f59b106e065 0x7f59b11381ee 0x7f59b264ad9e 0x7f59b104f24b 0x7f59b106e065 0x7f59b1049a7b 0x7f59b104f24b 0x7f59b106e065 0x7f59b11381ee 0x7f59b0d7a840 0x7f59b12f3323 0x7f59b08f7a68 0x7f59b1075573 0x7f59b13740e9 0x7f59c0ce0b02 0x7f59c0df9a9c 0x56494128d050 0x56494137e99d 0x564941300fe9 0x5649412fbb0e\ntcmalloc: large alloc 1425858560 bytes == 0x564a3d1e2000 @ 0x7f59d375cb6b 0x7f59d377c379 0x7f597693574e 0x7f59769377b6 0x7f59b13a1e43 0x7f59b0d8c7ff 0x7f59b10a3bdc 0x7f59b104f24b 0x7f59b106e065 0x7f59b1049a7b 0x7f59b104f24b 0x7f59b106e065 0x7f59b11381ee 0x7f59b264ad9e 0x7f59b104f24b 0x7f59b106e065 0x7f59b1049a7b 0x7f59b104f24b 0x7f59b106e065 0x7f59b11381ee 0x7f59b0d7a840 0x7f59b12f3323 0x7f59b08f7a68 0x7f59b1075573 0x7f59b13740e9 0x7f59c0ce0b02 0x7f59c0df9a9c 0x56494128d050 0x56494137e99d 0x564941300fe9 0x5649412fbb0e\ntcmalloc: large alloc 1425858560 bytes == 0x564a9fe0e000 @ 0x7f59d377a1e7 0x5649412bef48 0x5649412899c7 0x7f59c118a3f7 0x7f59b1ad0465 0x7f59b1acc9ca 0x7f59b1ad1609 0x7f59c118e00e 0x7f59c0e130a0 0x56494128dc38 0x56494130163d 0x5649412fbe0d 0x56494128e77a 0x5649412fca45 0x5649412fbb0e 0x56494128e77a 0x564941300e50 0x56494128e69a 0x5649412fca45 0x5649412fbb0e 0x56494128e77a 0x564941300e50 0x56494128e69a 0x5649412fcc9e 0x5649412fbe0d 0x56494128e77a 0x564941300e50 0x56494128e69a 0x5649412fca45 0x5649411cdd14 0x5649412fe1e6\n2021-02-28 16:47:04 | INFO | fairseq.checkpoint_utils | saved checkpoint checkpoints/checkpoint1.pt (epoch 1 @ 143 updates, score 90.6) (writing took 341.21901983700013 seconds)\n2021-02-28 16:47:05 | INFO | fairseq_cli.train | end of epoch 1 (average epoch stats below)\n2021-02-28 16:47:05 | INFO | train | epoch 001 | loss 0.989 | nll_loss 0.033 | accuracy 53.4 | wps 137.7 | ups 0.14 | wpb 957.5 | bsz 32 | num_updates 143 | lr 6.58986e-06 | gnorm 11.184 | loss_scale 8 | train_wall 574 | wall 998\nepoch 002: 0% 0/143 [00:00<?, ?it/s]2021-02-28 16:47:05 | INFO | fairseq.trainer | begin training epoch 2\nepoch 002: 99% 142/143 [09:30<00:04, 4.04s/it, loss=0.614, nll_loss=0.02, accuracy=79.7, wps=117.7, ups=0.12, wpb=965.2, bsz=31.9, num_updates=200, lr=9.21659e-06, gnorm=14.105, loss_scale=8, train_wall=403, wall=1228]2021-02-28 16:56:39 | INFO | fairseq_cli.train | begin validation on \"valid\" subset\n\nepoch 002 | valid on 'valid' subset: 0% 0/229 [00:00<?, ?it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 0% 1/229 [00:00<01:28, 2.57it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 1% 2/229 [00:00<01:26, 2.63it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 1% 3/229 [00:01<01:20, 2.80it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 2% 4/229 [00:01<01:18, 2.86it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 2% 5/229 [00:01<01:16, 2.91it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 3% 6/229 [00:02<01:15, 2.94it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 3% 7/229 [00:02<01:14, 2.97it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 3% 8/229 [00:02<01:12, 3.07it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 4% 9/229 [00:03<01:12, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 4% 10/229 [00:03<01:09, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 5% 11/229 [00:03<01:12, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 5% 12/229 [00:03<01:11, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 6% 13/229 [00:04<01:09, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 6% 14/229 [00:04<01:09, 3.07it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 7% 15/229 [00:04<01:10, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 7% 16/229 [00:05<01:09, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 7% 17/229 [00:05<01:08, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 8% 18/229 [00:05<01:10, 3.00it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 8% 19/229 [00:06<01:11, 2.92it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 9% 20/229 [00:06<01:08, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 9% 21/229 [00:06<01:08, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 10% 22/229 [00:07<01:06, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 10% 23/229 [00:07<01:05, 3.15it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 10% 24/229 [00:07<01:06, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 11% 25/229 [00:08<01:06, 3.08it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 11% 26/229 [00:08<01:06, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 12% 27/229 [00:08<01:04, 3.12it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 12% 28/229 [00:09<01:04, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 13% 29/229 [00:09<01:05, 3.07it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 13% 30/229 [00:09<01:03, 3.14it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 14% 31/229 [00:10<01:03, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 14% 32/229 [00:10<01:04, 3.07it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 14% 33/229 [00:10<01:02, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 15% 34/229 [00:11<01:04, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 15% 35/229 [00:11<01:06, 2.93it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 16% 36/229 [00:11<01:03, 3.04it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 16% 37/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 17% 38/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 17% 39/229 [00:12<01:02, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 17% 40/229 [00:13<01:00, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 18% 41/229 [00:13<01:01, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 18% 42/229 [00:13<01:03, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 19% 43/229 [00:14<01:05, 2.83it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 19% 44/229 [00:14<01:04, 2.87it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 20% 45/229 [00:14<01:01, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 20% 46/229 [00:15<01:02, 2.92it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 21% 47/229 [00:15<01:03, 2.87it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 21% 48/229 [00:15<01:05, 2.76it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 21% 49/229 [00:16<01:06, 2.69it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 22% 50/229 [00:16<01:04, 2.77it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 22% 51/229 [00:17<01:04, 2.78it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 23% 52/229 [00:17<01:02, 2.84it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 23% 53/229 [00:17<01:00, 2.89it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 24% 54/229 [00:18<00:59, 2.92it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 24% 55/229 [00:18<00:57, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 24% 56/229 [00:18<00:57, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 25% 57/229 [00:19<00:56, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 25% 58/229 [00:19<00:55, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 26% 59/229 [00:19<00:55, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 26% 60/229 [00:20<00:55, 3.04it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 27% 61/229 [00:20<00:51, 3.24it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 27% 62/229 [00:20<00:52, 3.17it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 28% 63/229 [00:20<00:53, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 28% 64/229 [00:21<00:52, 3.16it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 28% 65/229 [00:21<00:52, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 29% 66/229 [00:21<00:52, 3.08it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 29% 67/229 [00:22<00:54, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 30% 68/229 [00:22<00:53, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 30% 69/229 [00:22<00:53, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 31% 70/229 [00:23<00:53, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 31% 71/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 31% 72/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 32% 73/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 32% 74/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 33% 75/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 33% 76/229 [00:25<00:50, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 34% 77/229 [00:25<00:50, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 34% 78/229 [00:25<00:50, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 34% 79/229 [00:26<00:48, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 35% 80/229 [00:26<00:49, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 35% 81/229 [00:26<00:48, 3.07it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 36% 82/229 [00:27<00:48, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 36% 83/229 [00:27<00:46, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 37% 84/229 [00:27<00:45, 3.17it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 37% 85/229 [00:28<00:44, 3.20it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 38% 86/229 [00:28<00:45, 3.15it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 38% 87/229 [00:28<00:45, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 38% 88/229 [00:29<00:46, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 39% 89/229 [00:29<00:45, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 39% 90/229 [00:29<00:46, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 40% 91/229 [00:30<00:45, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 40% 92/229 [00:30<00:44, 3.08it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 41% 93/229 [00:30<00:44, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 41% 94/229 [00:31<00:44, 3.04it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 41% 95/229 [00:31<00:44, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 42% 96/229 [00:31<00:43, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 42% 97/229 [00:32<00:43, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 43% 98/229 [00:32<00:43, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 43% 99/229 [00:32<00:42, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 44% 100/229 [00:33<00:41, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 44% 101/229 [00:33<00:40, 3.15it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 45% 102/229 [00:33<00:40, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 45% 103/229 [00:34<00:42, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 45% 104/229 [00:34<00:42, 2.93it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 46% 105/229 [00:34<00:42, 2.95it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 46% 106/229 [00:35<00:41, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 47% 107/229 [00:35<00:41, 2.97it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 47% 108/229 [00:35<00:40, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 48% 109/229 [00:36<00:39, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 48% 110/229 [00:36<00:38, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 48% 111/229 [00:36<00:39, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 49% 112/229 [00:37<00:38, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 49% 113/229 [00:37<00:37, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 50% 114/229 [00:37<00:37, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 50% 115/229 [00:38<00:38, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 51% 116/229 [00:38<00:37, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 51% 117/229 [00:38<00:38, 2.91it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 52% 118/229 [00:39<00:38, 2.86it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 52% 119/229 [00:39<00:36, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 52% 120/229 [00:39<00:36, 3.00it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 53% 121/229 [00:40<00:35, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 53% 122/229 [00:40<00:35, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 54% 123/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 54% 124/229 [00:41<00:33, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 55% 125/229 [00:41<00:35, 2.89it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 55% 126/229 [00:41<00:36, 2.86it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 55% 127/229 [00:42<00:35, 2.90it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 56% 128/229 [00:42<00:35, 2.85it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 56% 129/229 [00:42<00:34, 2.91it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 57% 130/229 [00:43<00:33, 2.93it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 57% 131/229 [00:43<00:34, 2.80it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 58% 132/229 [00:43<00:33, 2.86it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 58% 133/229 [00:44<00:33, 2.90it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 59% 134/229 [00:44<00:32, 2.94it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 59% 135/229 [00:44<00:31, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 59% 136/229 [00:45<00:30, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 60% 137/229 [00:45<00:31, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 60% 138/229 [00:45<00:29, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 61% 139/229 [00:46<00:29, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 61% 140/229 [00:46<00:28, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 62% 141/229 [00:46<00:27, 3.16it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 62% 142/229 [00:47<00:27, 3.12it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 62% 143/229 [00:47<00:28, 3.00it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 63% 144/229 [00:47<00:29, 2.93it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 63% 145/229 [00:48<00:30, 2.71it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 64% 146/229 [00:48<00:30, 2.73it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 64% 147/229 [00:48<00:29, 2.81it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 65% 148/229 [00:49<00:28, 2.87it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 65% 149/229 [00:49<00:28, 2.84it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 66% 150/229 [00:49<00:26, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 66% 151/229 [00:50<00:26, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 66% 152/229 [00:50<00:25, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 67% 153/229 [00:50<00:24, 3.08it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 67% 154/229 [00:51<00:24, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 68% 155/229 [00:51<00:24, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 68% 156/229 [00:51<00:23, 3.04it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 69% 157/229 [00:52<00:23, 3.04it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 69% 158/229 [00:52<00:23, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 69% 159/229 [00:52<00:22, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 70% 160/229 [00:53<00:21, 3.16it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 70% 161/229 [00:53<00:21, 3.12it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 71% 162/229 [00:53<00:21, 3.18it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 71% 163/229 [00:54<00:21, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 72% 164/229 [00:54<00:21, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 72% 165/229 [00:54<00:20, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 72% 166/229 [00:55<00:20, 3.08it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 73% 167/229 [00:55<00:19, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 73% 168/229 [00:55<00:19, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 74% 169/229 [00:56<00:19, 3.16it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 74% 170/229 [00:56<00:19, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 75% 171/229 [00:56<00:18, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 75% 172/229 [00:57<00:18, 3.08it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 76% 173/229 [00:57<00:17, 3.14it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 76% 174/229 [00:57<00:17, 3.10it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 76% 175/229 [00:58<00:17, 3.16it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 77% 176/229 [00:58<00:15, 3.34it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 77% 177/229 [00:58<00:16, 3.24it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 78% 178/229 [00:58<00:16, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 78% 179/229 [00:59<00:15, 3.15it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 79% 180/229 [00:59<00:15, 3.19it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 79% 181/229 [00:59<00:15, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 79% 182/229 [01:00<00:14, 3.18it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 80% 183/229 [01:00<00:14, 3.22it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 80% 184/229 [01:00<00:13, 3.25it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 81% 185/229 [01:01<00:13, 3.18it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 81% 186/229 [01:01<00:13, 3.23it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 82% 187/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 82% 188/229 [01:02<00:13, 3.04it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 83% 189/229 [01:02<00:13, 2.95it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 83% 190/229 [01:02<00:13, 2.97it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 83% 191/229 [01:03<00:12, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 84% 192/229 [01:03<00:11, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 84% 193/229 [01:03<00:11, 3.14it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 85% 194/229 [01:04<00:10, 3.19it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 85% 195/229 [01:04<00:10, 3.15it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 86% 196/229 [01:04<00:10, 3.19it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 86% 197/229 [01:05<00:10, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 86% 198/229 [01:05<00:09, 3.11it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 87% 199/229 [01:05<00:09, 3.16it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 87% 200/229 [01:06<00:09, 3.12it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 88% 201/229 [01:06<00:09, 3.08it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 88% 202/229 [01:06<00:09, 2.89it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 89% 203/229 [01:07<00:08, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 89% 204/229 [01:07<00:08, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 90% 205/229 [01:07<00:07, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 90% 206/229 [01:08<00:07, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 90% 207/229 [01:08<00:07, 2.99it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 91% 208/229 [01:08<00:06, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 91% 209/229 [01:08<00:06, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 92% 210/229 [01:09<00:06, 3.09it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 92% 211/229 [01:09<00:05, 3.06it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 93% 212/229 [01:09<00:05, 3.13it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 93% 213/229 [01:10<00:05, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 93% 214/229 [01:10<00:04, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 94% 215/229 [01:10<00:04, 2.94it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 94% 216/229 [01:11<00:04, 3.03it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 95% 217/229 [01:11<00:04, 2.95it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 95% 218/229 [01:11<00:03, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 96% 219/229 [01:12<00:03, 2.98it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 96% 220/229 [01:12<00:02, 3.00it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 97% 221/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 97% 222/229 [01:13<00:02, 2.95it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 97% 223/229 [01:13<00:01, 3.05it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 98% 224/229 [01:14<00:01, 2.96it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 98% 225/229 [01:14<00:01, 2.91it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 99% 226/229 [01:14<00:00, 3.04it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 99% 227/229 [01:14<00:00, 3.12it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 100% 228/229 [01:15<00:00, 3.19it/s]\u001b[A\nepoch 002 | valid on 'valid' subset: 100% 229/229 [01:15<00:00, 3.98it/s]\u001b[A\n \u001b[A2021-02-28 16:57:55 | INFO | valid | epoch 002 | valid on 'valid' subset | loss 0.343 | nll_loss 0.012 | accuracy 89.8 | wps 706.6 | wpb 232.7 | bsz 8 | num_updates 286 | best_accuracy 90.6\n2021-02-28 16:57:55 | INFO | fairseq_cli.train | begin save checkpoint\n2021-02-28 17:01:28 | INFO | fairseq.checkpoint_utils | saved checkpoint checkpoints/checkpoint2.pt (epoch 2 @ 286 updates, score 89.8) (writing took 213.32354600899998 seconds)\n2021-02-28 17:01:28 | INFO | fairseq_cli.train | end of epoch 2 (average epoch stats below)\n2021-02-28 17:01:28 | INFO | train | epoch 002 | loss 0.399 | nll_loss 0.013 | accuracy 88.8 | wps 158.6 | ups 0.17 | wpb 957.5 | bsz 32 | num_updates 286 | lr 9.79688e-06 | gnorm 17.138 | loss_scale 16 | train_wall 574 | wall 1861\nepoch 003: 0% 0/143 [00:00<?, ?it/s]2021-02-28 17:01:28 | INFO | fairseq.trainer | begin training epoch 3\nepoch 003: 99% 142/143 [09:30<00:04, 4.04s/it, loss=0.203, nll_loss=0.007, accuracy=95.3, wps=237.8, ups=0.25, wpb=957.3, bsz=32, num_updates=400, lr=9.46129e-06, gnorm=15.506, loss_scale=32, train_wall=402, wall=2320]2021-02-28 17:11:03 | INFO | fairseq_cli.train | begin validation on \"valid\" subset\n\nepoch 003 | valid on 'valid' subset: 0% 0/229 [00:00<?, ?it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 0% 1/229 [00:00<01:26, 2.63it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 1% 2/229 [00:00<01:24, 2.68it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 1% 3/229 [00:01<01:19, 2.84it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 2% 4/229 [00:01<01:17, 2.90it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 2% 5/229 [00:01<01:16, 2.94it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 3% 6/229 [00:02<01:15, 2.96it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 3% 7/229 [00:02<01:14, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 3% 8/229 [00:02<01:11, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 4% 9/229 [00:02<01:11, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 4% 10/229 [00:03<01:09, 3.13it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 5% 11/229 [00:03<01:12, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 5% 12/229 [00:03<01:11, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 6% 13/229 [00:04<01:09, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 6% 14/229 [00:04<01:10, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 7% 15/229 [00:04<01:10, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 7% 16/229 [00:05<01:10, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 7% 17/229 [00:05<01:08, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 8% 18/229 [00:05<01:10, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 8% 19/229 [00:06<01:11, 2.92it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 9% 20/229 [00:06<01:08, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 9% 21/229 [00:06<01:08, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 10% 22/229 [00:07<01:06, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 10% 23/229 [00:07<01:05, 3.16it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 10% 24/229 [00:07<01:05, 3.12it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 11% 25/229 [00:08<01:06, 3.09it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 11% 26/229 [00:08<01:06, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 12% 27/229 [00:08<01:04, 3.13it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 12% 28/229 [00:09<01:04, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 13% 29/229 [00:09<01:05, 3.07it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 13% 30/229 [00:09<01:03, 3.14it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 14% 31/229 [00:10<01:03, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 14% 32/229 [00:10<01:04, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 14% 33/229 [00:10<01:02, 3.14it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 15% 34/229 [00:11<01:04, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 15% 35/229 [00:11<01:05, 2.94it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 16% 36/229 [00:11<01:03, 3.05it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 16% 37/229 [00:12<01:03, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 17% 38/229 [00:12<01:02, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 17% 39/229 [00:12<01:02, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 17% 40/229 [00:13<01:00, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 18% 41/229 [00:13<01:01, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 18% 42/229 [00:13<01:02, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 19% 43/229 [00:14<01:05, 2.84it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 19% 44/229 [00:14<01:04, 2.88it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 20% 45/229 [00:14<01:01, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 20% 46/229 [00:15<01:02, 2.91it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 21% 47/229 [00:15<01:03, 2.88it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 21% 48/229 [00:15<01:05, 2.77it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 21% 49/229 [00:16<01:06, 2.70it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 22% 50/229 [00:16<01:04, 2.78it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 22% 51/229 [00:17<01:04, 2.78it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 23% 52/229 [00:17<01:02, 2.84it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 23% 53/229 [00:17<01:00, 2.89it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 24% 54/229 [00:18<01:00, 2.92it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 24% 55/229 [00:18<00:57, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 24% 56/229 [00:18<00:57, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 25% 57/229 [00:18<00:57, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 25% 58/229 [00:19<00:55, 3.09it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 26% 59/229 [00:19<00:55, 3.07it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 26% 60/229 [00:19<00:55, 3.05it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 27% 61/229 [00:20<00:51, 3.24it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 27% 62/229 [00:20<00:52, 3.18it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 28% 63/229 [00:20<00:53, 3.12it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 28% 64/229 [00:21<00:52, 3.16it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 28% 65/229 [00:21<00:52, 3.12it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 29% 66/229 [00:21<00:52, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 29% 67/229 [00:22<00:54, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 30% 68/229 [00:22<00:53, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 30% 69/229 [00:22<00:53, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 31% 70/229 [00:23<00:53, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 31% 71/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 31% 72/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 32% 73/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 32% 74/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 33% 75/229 [00:24<00:51, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 33% 76/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 34% 77/229 [00:25<00:50, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 34% 78/229 [00:25<00:50, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 34% 79/229 [00:26<00:48, 3.09it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 35% 80/229 [00:26<00:49, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 35% 81/229 [00:26<00:48, 3.07it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 36% 82/229 [00:27<00:48, 3.05it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 36% 83/229 [00:27<00:46, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 37% 84/229 [00:27<00:45, 3.17it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 37% 85/229 [00:28<00:45, 3.20it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 38% 86/229 [00:28<00:45, 3.14it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 38% 87/229 [00:28<00:45, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 38% 88/229 [00:29<00:46, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 39% 89/229 [00:29<00:45, 3.09it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 39% 90/229 [00:29<00:46, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 40% 91/229 [00:30<00:46, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 40% 92/229 [00:30<00:44, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 41% 93/229 [00:30<00:44, 3.05it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 41% 94/229 [00:31<00:44, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 41% 95/229 [00:31<00:44, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 42% 96/229 [00:31<00:43, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 42% 97/229 [00:32<00:43, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 43% 98/229 [00:32<00:43, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 43% 99/229 [00:32<00:42, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 44% 100/229 [00:33<00:41, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 44% 101/229 [00:33<00:40, 3.16it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 45% 102/229 [00:33<00:40, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 45% 103/229 [00:34<00:42, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 45% 104/229 [00:34<00:42, 2.93it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 46% 105/229 [00:34<00:42, 2.95it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 46% 106/229 [00:35<00:41, 2.97it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 47% 107/229 [00:35<00:41, 2.97it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 47% 108/229 [00:35<00:40, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 48% 109/229 [00:36<00:39, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 48% 110/229 [00:36<00:38, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 48% 111/229 [00:36<00:39, 2.96it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 49% 112/229 [00:37<00:38, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 49% 113/229 [00:37<00:37, 3.13it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 50% 114/229 [00:37<00:37, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 50% 115/229 [00:38<00:38, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 51% 116/229 [00:38<00:37, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 51% 117/229 [00:38<00:38, 2.92it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 52% 118/229 [00:39<00:38, 2.87it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 52% 119/229 [00:39<00:36, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 52% 120/229 [00:39<00:36, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 53% 121/229 [00:40<00:35, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 53% 122/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 54% 123/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 54% 124/229 [00:41<00:33, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 55% 125/229 [00:41<00:35, 2.90it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 55% 126/229 [00:41<00:35, 2.86it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 55% 127/229 [00:42<00:35, 2.91it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 56% 128/229 [00:42<00:35, 2.86it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 56% 129/229 [00:42<00:34, 2.92it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 57% 130/229 [00:43<00:33, 2.94it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 57% 131/229 [00:43<00:34, 2.82it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 58% 132/229 [00:43<00:33, 2.87it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 58% 133/229 [00:44<00:32, 2.92it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 59% 134/229 [00:44<00:32, 2.95it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 59% 135/229 [00:44<00:31, 2.97it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 59% 136/229 [00:45<00:30, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 60% 137/229 [00:45<00:30, 2.97it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 60% 138/229 [00:45<00:29, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 61% 139/229 [00:46<00:29, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 61% 140/229 [00:46<00:28, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 62% 141/229 [00:46<00:27, 3.17it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 62% 142/229 [00:47<00:27, 3.12it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 62% 143/229 [00:47<00:28, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 63% 144/229 [00:47<00:28, 2.93it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 63% 145/229 [00:48<00:30, 2.71it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 64% 146/229 [00:48<00:30, 2.73it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 64% 147/229 [00:48<00:29, 2.81it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 65% 148/229 [00:49<00:28, 2.87it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 65% 149/229 [00:49<00:28, 2.84it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 66% 150/229 [00:49<00:26, 2.97it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 66% 151/229 [00:50<00:26, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 66% 152/229 [00:50<00:25, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 67% 153/229 [00:50<00:24, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 67% 154/229 [00:51<00:24, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 68% 155/229 [00:51<00:24, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 68% 156/229 [00:51<00:24, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 69% 157/229 [00:52<00:23, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 69% 158/229 [00:52<00:23, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 69% 159/229 [00:52<00:22, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 70% 160/229 [00:53<00:21, 3.15it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 70% 161/229 [00:53<00:21, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 71% 162/229 [00:53<00:21, 3.16it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 71% 163/229 [00:54<00:21, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 72% 164/229 [00:54<00:21, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 72% 165/229 [00:54<00:20, 3.07it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 72% 166/229 [00:55<00:20, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 73% 167/229 [00:55<00:19, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 73% 168/229 [00:55<00:19, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 74% 169/229 [00:56<00:19, 3.14it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 74% 170/229 [00:56<00:19, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 75% 171/229 [00:56<00:18, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 75% 172/229 [00:57<00:18, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 76% 173/229 [00:57<00:17, 3.14it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 76% 174/229 [00:57<00:17, 3.11it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 76% 175/229 [00:57<00:17, 3.16it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 77% 176/229 [00:58<00:15, 3.34it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 77% 177/229 [00:58<00:16, 3.24it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 78% 178/229 [00:58<00:16, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 78% 179/229 [00:59<00:15, 3.15it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 79% 180/229 [00:59<00:15, 3.19it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 79% 181/229 [00:59<00:15, 3.13it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 79% 182/229 [01:00<00:14, 3.17it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 80% 183/229 [01:00<00:14, 3.21it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 80% 184/229 [01:00<00:13, 3.24it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 81% 185/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 81% 186/229 [01:01<00:13, 3.23it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 82% 187/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 82% 188/229 [01:02<00:13, 3.04it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 83% 189/229 [01:02<00:13, 2.95it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 83% 190/229 [01:02<00:13, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 83% 191/229 [01:03<00:12, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 84% 192/229 [01:03<00:11, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 84% 193/229 [01:03<00:11, 3.16it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 85% 194/229 [01:04<00:10, 3.20it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 85% 195/229 [01:04<00:10, 3.15it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 86% 196/229 [01:04<00:10, 3.19it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 86% 197/229 [01:05<00:10, 3.06it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 86% 198/229 [01:05<00:09, 3.13it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 87% 199/229 [01:05<00:09, 3.18it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 87% 200/229 [01:05<00:09, 3.14it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 88% 201/229 [01:06<00:09, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 88% 202/229 [01:06<00:09, 2.91it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 89% 203/229 [01:06<00:08, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 89% 204/229 [01:07<00:08, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 90% 205/229 [01:07<00:07, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 90% 206/229 [01:07<00:07, 2.99it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 90% 207/229 [01:08<00:07, 3.00it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 91% 208/229 [01:08<00:06, 3.08it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 91% 209/229 [01:08<00:06, 3.14it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 92% 210/229 [01:09<00:06, 3.10it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 92% 211/229 [01:09<00:05, 3.07it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 93% 212/229 [01:09<00:05, 3.13it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 93% 213/229 [01:10<00:05, 3.02it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 93% 214/229 [01:10<00:04, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 94% 215/229 [01:10<00:04, 2.93it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 94% 216/229 [01:11<00:04, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 95% 217/229 [01:11<00:04, 2.94it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 95% 218/229 [01:11<00:03, 2.97it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 96% 219/229 [01:12<00:03, 2.98it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 96% 220/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 97% 221/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 97% 222/229 [01:13<00:02, 2.95it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 97% 223/229 [01:13<00:01, 3.05it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 98% 224/229 [01:13<00:01, 2.97it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 98% 225/229 [01:14<00:01, 2.91it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 99% 226/229 [01:14<00:00, 3.03it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 99% 227/229 [01:14<00:00, 3.12it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 100% 228/229 [01:15<00:00, 3.19it/s]\u001b[A\nepoch 003 | valid on 'valid' subset: 100% 229/229 [01:15<00:00, 3.97it/s]\u001b[A\n \u001b[A2021-02-28 17:12:18 | INFO | valid | epoch 003 | valid on 'valid' subset | loss 0.506 | nll_loss 0.017 | accuracy 86.4 | wps 707 | wpb 232.7 | bsz 8 | num_updates 429 | best_accuracy 90.6\n2021-02-28 17:12:18 | INFO | fairseq_cli.train | begin save checkpoint\n2021-02-28 17:15:53 | INFO | fairseq.checkpoint_utils | saved checkpoint checkpoints/checkpoint3.pt (epoch 3 @ 429 updates, score 86.4) (writing took 214.7876592140001 seconds)\n2021-02-28 17:15:53 | INFO | fairseq_cli.train | end of epoch 3 (average epoch stats below)\n2021-02-28 17:15:53 | INFO | train | epoch 003 | loss 0.21 | nll_loss 0.007 | accuracy 95.2 | wps 158.3 | ups 0.17 | wpb 957.5 | bsz 32 | num_updates 429 | lr 9.37592e-06 | gnorm 16.54 | loss_scale 32 | train_wall 574 | wall 2726\nepoch 004: 0% 0/143 [00:00<?, ?it/s]2021-02-28 17:15:53 | INFO | fairseq.trainer | begin training epoch 4\nepoch 004: 99% 142/143 [09:30<00:03, 3.94s/it, loss=0.182, nll_loss=0.006, accuracy=95.8, wps=137.8, ups=0.14, wpb=952.9, bsz=32, num_updates=500, lr=9.16691e-06, gnorm=20.508, loss_scale=32, train_wall=401, wall=3012]2021-02-28 17:25:28 | INFO | fairseq_cli.train | begin validation on \"valid\" subset\n\nepoch 004 | valid on 'valid' subset: 0% 0/229 [00:00<?, ?it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 0% 1/229 [00:00<01:26, 2.63it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 1% 2/229 [00:00<01:24, 2.68it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 1% 3/229 [00:01<01:19, 2.83it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 2% 4/229 [00:01<01:17, 2.89it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 2% 5/229 [00:01<01:16, 2.94it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 3% 6/229 [00:02<01:15, 2.96it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 3% 7/229 [00:02<01:14, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 3% 8/229 [00:02<01:12, 3.07it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 4% 9/229 [00:02<01:12, 3.05it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 4% 10/229 [00:03<01:10, 3.12it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 5% 11/229 [00:03<01:12, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 5% 12/229 [00:03<01:12, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 6% 13/229 [00:04<01:10, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 6% 14/229 [00:04<01:10, 3.05it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 7% 15/229 [00:04<01:10, 3.04it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 7% 16/229 [00:05<01:10, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 7% 17/229 [00:05<01:08, 3.10it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 8% 18/229 [00:05<01:10, 2.99it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 8% 19/229 [00:06<01:11, 2.92it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 9% 20/229 [00:06<01:09, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 9% 21/229 [00:06<01:09, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 10% 22/229 [00:07<01:06, 3.10it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 10% 23/229 [00:07<01:05, 3.16it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 10% 24/229 [00:07<01:05, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 11% 25/229 [00:08<01:06, 3.09it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 11% 26/229 [00:08<01:06, 3.07it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 12% 27/229 [00:08<01:04, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 12% 28/229 [00:09<01:04, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 13% 29/229 [00:09<01:04, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 13% 30/229 [00:09<01:03, 3.15it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 14% 31/229 [00:10<01:03, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 14% 32/229 [00:10<01:03, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 14% 33/229 [00:10<01:02, 3.13it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 15% 34/229 [00:11<01:04, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 15% 35/229 [00:11<01:06, 2.93it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 16% 36/229 [00:11<01:03, 3.04it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 16% 37/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 17% 38/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 17% 39/229 [00:12<01:02, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 17% 40/229 [00:13<01:00, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 18% 41/229 [00:13<01:01, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 18% 42/229 [00:13<01:02, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 19% 43/229 [00:14<01:05, 2.84it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 19% 44/229 [00:14<01:04, 2.89it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 20% 45/229 [00:14<01:01, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 20% 46/229 [00:15<01:02, 2.93it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 21% 47/229 [00:15<01:03, 2.89it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 21% 48/229 [00:15<01:05, 2.77it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 21% 49/229 [00:16<01:06, 2.70it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 22% 50/229 [00:16<01:04, 2.78it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 22% 51/229 [00:17<01:03, 2.78it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 23% 52/229 [00:17<01:02, 2.84it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 23% 53/229 [00:17<01:00, 2.89it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 24% 54/229 [00:18<00:59, 2.92it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 24% 55/229 [00:18<00:57, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 24% 56/229 [00:18<00:57, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 25% 57/229 [00:19<00:57, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 25% 58/229 [00:19<00:55, 3.09it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 26% 59/229 [00:19<00:55, 3.06it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 26% 60/229 [00:19<00:55, 3.04it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 27% 61/229 [00:20<00:51, 3.24it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 27% 62/229 [00:20<00:52, 3.17it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 28% 63/229 [00:20<00:53, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 28% 64/229 [00:21<00:52, 3.16it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 28% 65/229 [00:21<00:52, 3.12it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 29% 66/229 [00:21<00:52, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 29% 67/229 [00:22<00:54, 2.99it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 30% 68/229 [00:22<00:53, 2.99it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 30% 69/229 [00:22<00:53, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 31% 70/229 [00:23<00:53, 2.99it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 31% 71/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 31% 72/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 32% 73/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 32% 74/229 [00:24<00:51, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 33% 75/229 [00:24<00:51, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 33% 76/229 [00:25<00:50, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 34% 77/229 [00:25<00:50, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 34% 78/229 [00:25<00:50, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 34% 79/229 [00:26<00:48, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 35% 80/229 [00:26<00:49, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 35% 81/229 [00:26<00:48, 3.06it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 36% 82/229 [00:27<00:48, 3.05it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 36% 83/229 [00:27<00:46, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 37% 84/229 [00:27<00:45, 3.16it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 37% 85/229 [00:28<00:45, 3.20it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 38% 86/229 [00:28<00:45, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 38% 87/229 [00:28<00:45, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 38% 88/229 [00:29<00:47, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 39% 89/229 [00:29<00:45, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 39% 90/229 [00:29<00:46, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 40% 91/229 [00:30<00:46, 2.99it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 40% 92/229 [00:30<00:44, 3.07it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 41% 93/229 [00:30<00:44, 3.05it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 41% 94/229 [00:31<00:44, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 41% 95/229 [00:31<00:44, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 42% 96/229 [00:31<00:43, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 42% 97/229 [00:32<00:43, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 43% 98/229 [00:32<00:43, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 43% 99/229 [00:32<00:42, 3.04it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 44% 100/229 [00:33<00:41, 3.10it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 44% 101/229 [00:33<00:40, 3.16it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 45% 102/229 [00:33<00:40, 3.12it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 45% 103/229 [00:34<00:41, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 45% 104/229 [00:34<00:42, 2.93it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 46% 105/229 [00:34<00:41, 2.95it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 46% 106/229 [00:35<00:41, 2.97it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 47% 107/229 [00:35<00:40, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 47% 108/229 [00:35<00:40, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 48% 109/229 [00:36<00:39, 3.07it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 48% 110/229 [00:36<00:38, 3.06it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 48% 111/229 [00:36<00:39, 2.95it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 49% 112/229 [00:37<00:38, 3.05it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 49% 113/229 [00:37<00:37, 3.12it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 50% 114/229 [00:37<00:37, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 50% 115/229 [00:38<00:38, 2.97it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 51% 116/229 [00:38<00:37, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 51% 117/229 [00:38<00:38, 2.90it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 52% 118/229 [00:39<00:38, 2.86it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 52% 119/229 [00:39<00:36, 2.97it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 52% 120/229 [00:39<00:36, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 53% 121/229 [00:40<00:36, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 53% 122/229 [00:40<00:35, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 54% 123/229 [00:40<00:35, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 54% 124/229 [00:41<00:33, 3.10it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 55% 125/229 [00:41<00:35, 2.90it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 55% 126/229 [00:41<00:35, 2.86it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 55% 127/229 [00:42<00:35, 2.91it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 56% 128/229 [00:42<00:35, 2.87it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 56% 129/229 [00:42<00:34, 2.92it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 57% 130/229 [00:43<00:33, 2.95it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 57% 131/229 [00:43<00:34, 2.82it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 58% 132/229 [00:43<00:33, 2.88it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 58% 133/229 [00:44<00:32, 2.92it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 59% 134/229 [00:44<00:32, 2.95it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 59% 135/229 [00:44<00:31, 2.97it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 59% 136/229 [00:45<00:30, 3.07it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 60% 137/229 [00:45<00:30, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 60% 138/229 [00:45<00:29, 3.06it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 61% 139/229 [00:46<00:29, 3.04it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 61% 140/229 [00:46<00:28, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 62% 141/229 [00:46<00:27, 3.16it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 62% 142/229 [00:47<00:27, 3.12it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 62% 143/229 [00:47<00:28, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 63% 144/229 [00:47<00:28, 2.93it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 63% 145/229 [00:48<00:30, 2.72it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 64% 146/229 [00:48<00:30, 2.74it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 64% 147/229 [00:48<00:29, 2.81it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 65% 148/229 [00:49<00:28, 2.87it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 65% 149/229 [00:49<00:28, 2.84it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 66% 150/229 [00:49<00:26, 2.96it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 66% 151/229 [00:50<00:26, 2.97it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 66% 152/229 [00:50<00:25, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 67% 153/229 [00:50<00:24, 3.07it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 67% 154/229 [00:51<00:24, 3.05it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 68% 155/229 [00:51<00:24, 3.04it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 68% 156/229 [00:51<00:24, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 69% 157/229 [00:52<00:23, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 69% 158/229 [00:52<00:23, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 69% 159/229 [00:52<00:22, 3.10it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 70% 160/229 [00:53<00:21, 3.15it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 70% 161/229 [00:53<00:21, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 71% 162/229 [00:53<00:21, 3.17it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 71% 163/229 [00:54<00:21, 3.12it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 72% 164/229 [00:54<00:21, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 72% 165/229 [00:54<00:20, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 72% 166/229 [00:55<00:20, 3.06it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 73% 167/229 [00:55<00:19, 3.13it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 73% 168/229 [00:55<00:19, 3.09it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 74% 169/229 [00:56<00:19, 3.15it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 74% 170/229 [00:56<00:19, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 75% 171/229 [00:56<00:18, 3.10it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 75% 172/229 [00:57<00:18, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 76% 173/229 [00:57<00:17, 3.15it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 76% 174/229 [00:57<00:17, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 76% 175/229 [00:58<00:17, 3.16it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 77% 176/229 [00:58<00:15, 3.33it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 77% 177/229 [00:58<00:16, 3.22it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 78% 178/229 [00:58<00:16, 3.07it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 78% 179/229 [00:59<00:15, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 79% 180/229 [00:59<00:15, 3.18it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 79% 181/229 [00:59<00:15, 3.13it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 79% 182/229 [01:00<00:14, 3.18it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 80% 183/229 [01:00<00:14, 3.21it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 80% 184/229 [01:00<00:13, 3.24it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 81% 185/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 81% 186/229 [01:01<00:13, 3.21it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 82% 187/229 [01:01<00:13, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 82% 188/229 [01:02<00:13, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 83% 189/229 [01:02<00:13, 2.93it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 83% 190/229 [01:02<00:13, 2.96it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 83% 191/229 [01:03<00:12, 2.97it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 84% 192/229 [01:03<00:11, 3.09it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 84% 193/229 [01:03<00:11, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 85% 194/229 [01:04<00:10, 3.18it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 85% 195/229 [01:04<00:10, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 86% 196/229 [01:04<00:10, 3.18it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 86% 197/229 [01:05<00:10, 3.04it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 86% 198/229 [01:05<00:09, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 87% 199/229 [01:05<00:09, 3.16it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 87% 200/229 [01:06<00:09, 3.12it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 88% 201/229 [01:06<00:09, 3.09it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 88% 202/229 [01:06<00:09, 2.89it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 89% 203/229 [01:07<00:08, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 89% 204/229 [01:07<00:08, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 90% 205/229 [01:07<00:07, 3.09it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 90% 206/229 [01:08<00:07, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 90% 207/229 [01:08<00:07, 2.99it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 91% 208/229 [01:08<00:06, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 91% 209/229 [01:08<00:06, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 92% 210/229 [01:09<00:06, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 92% 211/229 [01:09<00:05, 3.08it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 93% 212/229 [01:09<00:05, 3.14it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 93% 213/229 [01:10<00:05, 3.02it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 93% 214/229 [01:10<00:04, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 94% 215/229 [01:11<00:04, 2.93it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 94% 216/229 [01:11<00:04, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 95% 217/229 [01:11<00:04, 2.94it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 95% 218/229 [01:12<00:03, 2.97it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 96% 219/229 [01:12<00:03, 2.98it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 96% 220/229 [01:12<00:03, 3.00it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 97% 221/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 97% 222/229 [01:13<00:02, 2.95it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 97% 223/229 [01:13<00:01, 3.05it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 98% 224/229 [01:14<00:01, 2.96it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 98% 225/229 [01:14<00:01, 2.91it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 99% 226/229 [01:14<00:00, 3.03it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 99% 227/229 [01:14<00:00, 3.11it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 100% 228/229 [01:15<00:00, 3.19it/s]\u001b[A\nepoch 004 | valid on 'valid' subset: 100% 229/229 [01:15<00:00, 3.97it/s]\u001b[A\n \u001b[A2021-02-28 17:26:43 | INFO | valid | epoch 004 | valid on 'valid' subset | loss 0.36 | nll_loss 0.012 | accuracy 92.6 | wps 706.4 | wpb 232.7 | bsz 8 | num_updates 572 | best_accuracy 92.6\n2021-02-28 17:26:43 | INFO | fairseq_cli.train | begin save checkpoint\n2021-02-28 17:32:25 | INFO | fairseq.checkpoint_utils | saved checkpoint checkpoints/checkpoint4.pt (epoch 4 @ 572 updates, score 92.6) (writing took 341.53966797799967 seconds)\n2021-02-28 17:32:25 | INFO | fairseq_cli.train | end of epoch 4 (average epoch stats below)\n2021-02-28 17:32:25 | INFO | train | epoch 004 | loss 0.149 | nll_loss 0.005 | accuracy 96.5 | wps 138 | ups 0.14 | wpb 957.5 | bsz 32 | num_updates 572 | lr 8.95496e-06 | gnorm 18.026 | loss_scale 64 | train_wall 574 | wall 3718\nepoch 005: 0% 0/143 [00:00<?, ?it/s]2021-02-28 17:32:25 | INFO | fairseq.trainer | begin training epoch 5\nepoch 005: 99% 142/143 [09:30<00:03, 3.98s/it, loss=0.084, nll_loss=0.003, accuracy=98.2, wps=237.6, ups=0.25, wpb=953.8, bsz=32, num_updates=700, lr=8.57816e-06, gnorm=10.711, loss_scale=128, train_wall=401, wall=4233]2021-02-28 17:42:00 | INFO | fairseq_cli.train | begin validation on \"valid\" subset\n\nepoch 005 | valid on 'valid' subset: 0% 0/229 [00:00<?, ?it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 0% 1/229 [00:00<01:26, 2.63it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 1% 2/229 [00:00<01:24, 2.68it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 1% 3/229 [00:01<01:19, 2.84it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 2% 4/229 [00:01<01:17, 2.89it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 2% 5/229 [00:01<01:16, 2.94it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 3% 6/229 [00:02<01:15, 2.96it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 3% 7/229 [00:02<01:14, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 3% 8/229 [00:02<01:11, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 4% 9/229 [00:02<01:11, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 4% 10/229 [00:03<01:10, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 5% 11/229 [00:03<01:12, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 5% 12/229 [00:03<01:12, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 6% 13/229 [00:04<01:10, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 6% 14/229 [00:04<01:10, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 7% 15/229 [00:04<01:10, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 7% 16/229 [00:05<01:10, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 7% 17/229 [00:05<01:08, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 8% 18/229 [00:05<01:10, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 8% 19/229 [00:06<01:12, 2.91it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 9% 20/229 [00:06<01:09, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 9% 21/229 [00:06<01:09, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 10% 22/229 [00:07<01:06, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 10% 23/229 [00:07<01:05, 3.15it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 10% 24/229 [00:07<01:06, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 11% 25/229 [00:08<01:06, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 11% 26/229 [00:08<01:06, 3.05it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 12% 27/229 [00:08<01:04, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 12% 28/229 [00:09<01:04, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 13% 29/229 [00:09<01:05, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 13% 30/229 [00:09<01:03, 3.13it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 14% 31/229 [00:10<01:04, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 14% 32/229 [00:10<01:04, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 14% 33/229 [00:10<01:02, 3.13it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 15% 34/229 [00:11<01:04, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 15% 35/229 [00:11<01:06, 2.94it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 16% 36/229 [00:11<01:03, 3.05it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 16% 37/229 [00:12<01:03, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 17% 38/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 17% 39/229 [00:12<01:02, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 17% 40/229 [00:13<01:01, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 18% 41/229 [00:13<01:01, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 18% 42/229 [00:13<01:02, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 19% 43/229 [00:14<01:05, 2.85it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 19% 44/229 [00:14<01:04, 2.89it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 20% 45/229 [00:14<01:01, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 20% 46/229 [00:15<01:02, 2.93it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 21% 47/229 [00:15<01:02, 2.89it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 21% 48/229 [00:15<01:05, 2.78it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 21% 49/229 [00:16<01:06, 2.70it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 22% 50/229 [00:16<01:04, 2.79it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 22% 51/229 [00:17<01:03, 2.79it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 23% 52/229 [00:17<01:02, 2.85it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 23% 53/229 [00:17<01:00, 2.90it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 24% 54/229 [00:18<00:59, 2.93it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 24% 55/229 [00:18<00:57, 3.03it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 24% 56/229 [00:18<00:57, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 25% 57/229 [00:19<00:57, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 25% 58/229 [00:19<00:55, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 26% 59/229 [00:19<00:55, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 26% 60/229 [00:19<00:55, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 27% 61/229 [00:20<00:51, 3.24it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 27% 62/229 [00:20<00:52, 3.17it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 28% 63/229 [00:20<00:53, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 28% 64/229 [00:21<00:52, 3.17it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 28% 65/229 [00:21<00:52, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 29% 66/229 [00:21<00:52, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 29% 67/229 [00:22<00:54, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 30% 68/229 [00:22<00:53, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 30% 69/229 [00:22<00:53, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 31% 70/229 [00:23<00:53, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 31% 71/229 [00:23<00:52, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 31% 72/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 32% 73/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 32% 74/229 [00:24<00:51, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 33% 75/229 [00:24<00:51, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 33% 76/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 34% 77/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 34% 78/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 34% 79/229 [00:26<00:48, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 35% 80/229 [00:26<00:49, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 35% 81/229 [00:26<00:48, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 36% 82/229 [00:27<00:48, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 36% 83/229 [00:27<00:46, 3.13it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 37% 84/229 [00:27<00:45, 3.18it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 37% 85/229 [00:28<00:44, 3.21it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 38% 86/229 [00:28<00:45, 3.15it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 38% 87/229 [00:28<00:45, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 38% 88/229 [00:29<00:46, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 39% 89/229 [00:29<00:45, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 39% 90/229 [00:29<00:46, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 40% 91/229 [00:30<00:45, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 40% 92/229 [00:30<00:44, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 41% 93/229 [00:30<00:44, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 41% 94/229 [00:31<00:44, 3.05it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 41% 95/229 [00:31<00:44, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 42% 96/229 [00:31<00:43, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 42% 97/229 [00:32<00:43, 3.03it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 43% 98/229 [00:32<00:43, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 43% 99/229 [00:32<00:42, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 44% 100/229 [00:33<00:41, 3.11it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 44% 101/229 [00:33<00:40, 3.17it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 45% 102/229 [00:33<00:40, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 45% 103/229 [00:34<00:41, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 45% 104/229 [00:34<00:42, 2.94it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 46% 105/229 [00:34<00:41, 2.96it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 46% 106/229 [00:35<00:41, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 47% 107/229 [00:35<00:40, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 47% 108/229 [00:35<00:40, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 48% 109/229 [00:36<00:38, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 48% 110/229 [00:36<00:38, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 48% 111/229 [00:36<00:39, 2.97it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 49% 112/229 [00:36<00:38, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 49% 113/229 [00:37<00:37, 3.13it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 50% 114/229 [00:37<00:37, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 50% 115/229 [00:37<00:38, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 51% 116/229 [00:38<00:37, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 51% 117/229 [00:38<00:38, 2.92it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 52% 118/229 [00:39<00:38, 2.87it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 52% 119/229 [00:39<00:36, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 52% 120/229 [00:39<00:36, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 53% 121/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 53% 122/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 54% 123/229 [00:40<00:35, 3.02it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 54% 124/229 [00:40<00:33, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 55% 125/229 [00:41<00:35, 2.91it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 55% 126/229 [00:41<00:35, 2.87it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 55% 127/229 [00:42<00:35, 2.91it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 56% 128/229 [00:42<00:35, 2.87it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 56% 129/229 [00:42<00:34, 2.92it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 57% 130/229 [00:43<00:33, 2.94it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 57% 131/229 [00:43<00:34, 2.81it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 58% 132/229 [00:43<00:33, 2.87it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 58% 133/229 [00:44<00:32, 2.92it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 59% 134/229 [00:44<00:32, 2.95it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 59% 135/229 [00:44<00:31, 2.97it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 59% 136/229 [00:45<00:30, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 60% 137/229 [00:45<00:30, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 60% 138/229 [00:45<00:29, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 61% 139/229 [00:46<00:29, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 61% 140/229 [00:46<00:28, 3.11it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 62% 141/229 [00:46<00:27, 3.17it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 62% 142/229 [00:47<00:27, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 62% 143/229 [00:47<00:28, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 63% 144/229 [00:47<00:28, 2.93it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 63% 145/229 [00:48<00:30, 2.71it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 64% 146/229 [00:48<00:30, 2.73it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 64% 147/229 [00:48<00:29, 2.81it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 65% 148/229 [00:49<00:28, 2.87it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 65% 149/229 [00:49<00:28, 2.85it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 66% 150/229 [00:49<00:26, 2.96it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 66% 151/229 [00:50<00:26, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 66% 152/229 [00:50<00:25, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 67% 153/229 [00:50<00:24, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 67% 154/229 [00:51<00:24, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 68% 155/229 [00:51<00:24, 3.05it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 68% 156/229 [00:51<00:24, 3.03it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 69% 157/229 [00:52<00:23, 3.03it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 69% 158/229 [00:52<00:23, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 69% 159/229 [00:52<00:22, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 70% 160/229 [00:53<00:21, 3.16it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 70% 161/229 [00:53<00:21, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 71% 162/229 [00:53<00:21, 3.17it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 71% 163/229 [00:54<00:21, 3.13it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 72% 164/229 [00:54<00:21, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 72% 165/229 [00:54<00:20, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 72% 166/229 [00:55<00:20, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 73% 167/229 [00:55<00:19, 3.14it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 73% 168/229 [00:55<00:19, 3.11it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 74% 169/229 [00:55<00:18, 3.16it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 74% 170/229 [00:56<00:19, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 75% 171/229 [00:56<00:18, 3.11it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 75% 172/229 [00:56<00:18, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 76% 173/229 [00:57<00:17, 3.15it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 76% 174/229 [00:57<00:17, 3.11it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 76% 175/229 [00:57<00:17, 3.16it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 77% 176/229 [00:58<00:15, 3.34it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 77% 177/229 [00:58<00:16, 3.23it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 78% 178/229 [00:58<00:16, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 78% 179/229 [00:59<00:15, 3.15it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 79% 180/229 [00:59<00:15, 3.19it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 79% 181/229 [00:59<00:15, 3.13it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 79% 182/229 [01:00<00:14, 3.17it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 80% 183/229 [01:00<00:14, 3.21it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 80% 184/229 [01:00<00:13, 3.24it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 81% 185/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 81% 186/229 [01:01<00:13, 3.23it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 82% 187/229 [01:01<00:13, 3.16it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 82% 188/229 [01:02<00:13, 3.03it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 83% 189/229 [01:02<00:13, 2.94it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 83% 190/229 [01:02<00:13, 2.97it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 83% 191/229 [01:03<00:12, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 84% 192/229 [01:03<00:11, 3.09it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 84% 193/229 [01:03<00:11, 3.14it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 85% 194/229 [01:03<00:10, 3.19it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 85% 195/229 [01:04<00:10, 3.15it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 86% 196/229 [01:04<00:10, 3.19it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 86% 197/229 [01:04<00:10, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 86% 198/229 [01:05<00:09, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 87% 199/229 [01:05<00:09, 3.16it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 87% 200/229 [01:05<00:09, 3.11it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 88% 201/229 [01:06<00:09, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 88% 202/229 [01:06<00:09, 2.89it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 89% 203/229 [01:06<00:08, 3.00it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 89% 204/229 [01:07<00:08, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 90% 205/229 [01:07<00:07, 3.08it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 90% 206/229 [01:07<00:07, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 90% 207/229 [01:08<00:07, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 91% 208/229 [01:08<00:06, 3.07it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 91% 209/229 [01:08<00:06, 3.13it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 92% 210/229 [01:09<00:06, 3.10it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 92% 211/229 [01:09<00:05, 3.06it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 93% 212/229 [01:09<00:05, 3.12it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 93% 213/229 [01:10<00:05, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 93% 214/229 [01:10<00:04, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 94% 215/229 [01:10<00:04, 2.93it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 94% 216/229 [01:11<00:04, 3.04it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 95% 217/229 [01:11<00:04, 2.95it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 95% 218/229 [01:11<00:03, 2.98it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 96% 219/229 [01:12<00:03, 2.99it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 96% 220/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 97% 221/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 97% 222/229 [01:13<00:02, 2.95it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 97% 223/229 [01:13<00:01, 3.05it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 98% 224/229 [01:13<00:01, 2.96it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 98% 225/229 [01:14<00:01, 2.91it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 99% 226/229 [01:14<00:00, 3.03it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 99% 227/229 [01:14<00:00, 3.11it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 100% 228/229 [01:15<00:00, 3.18it/s]\u001b[A\nepoch 005 | valid on 'valid' subset: 100% 229/229 [01:15<00:00, 3.95it/s]\u001b[A\n \u001b[A2021-02-28 17:43:15 | INFO | valid | epoch 005 | valid on 'valid' subset | loss 0.679 | nll_loss 0.023 | accuracy 89 | wps 707.3 | wpb 232.7 | bsz 8 | num_updates 715 | best_accuracy 92.6\n2021-02-28 17:43:15 | INFO | fairseq_cli.train | begin save checkpoint\n2021-02-28 17:46:48 | INFO | fairseq.checkpoint_utils | saved checkpoint checkpoints/checkpoint5.pt (epoch 5 @ 715 updates, score 89.0) (writing took 213.62495311699968 seconds)\n2021-02-28 17:46:48 | INFO | fairseq_cli.train | end of epoch 5 (average epoch stats below)\n2021-02-28 17:46:48 | INFO | train | epoch 005 | loss 0.082 | nll_loss 0.003 | accuracy 98.2 | wps 158.6 | ups 0.17 | wpb 957.5 | bsz 32 | num_updates 715 | lr 8.534e-06 | gnorm 11.204 | loss_scale 128 | train_wall 574 | wall 4582\nepoch 006: 0% 0/143 [00:00<?, ?it/s]2021-02-28 17:46:49 | INFO | fairseq.trainer | begin training epoch 6\nepoch 006: 93% 133/143 [08:54<00:40, 4.06s/it, loss=0.059, nll_loss=0.002, accuracy=98.6, wps=139, ups=0.14, wpb=962.3, bsz=32, num_updates=800, lr=8.28378e-06, gnorm=11.161, loss_scale=256, train_wall=403, wall=4925]2021-02-28 17:55:47 | INFO | fairseq.trainer | NOTE: overflow detected, setting loss scale to: 128.0\nepoch 006: 99% 142/143 [09:30<00:04, 4.00s/it, loss=0.059, nll_loss=0.002, accuracy=98.6, wps=139, ups=0.14, wpb=962.3, bsz=32, num_updates=800, lr=8.28378e-06, gnorm=11.161, loss_scale=256, train_wall=403, wall=4925]2021-02-28 17:56:23 | INFO | fairseq.trainer | NOTE: overflow detected, setting loss scale to: 64.0\n2021-02-28 17:56:23 | INFO | fairseq_cli.train | begin validation on \"valid\" subset\n\nepoch 006 | valid on 'valid' subset: 0% 0/229 [00:00<?, ?it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 0% 1/229 [00:00<01:26, 2.63it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 1% 2/229 [00:00<01:24, 2.67it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 1% 3/229 [00:01<01:19, 2.84it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 2% 4/229 [00:01<01:17, 2.89it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 2% 5/229 [00:01<01:16, 2.94it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 3% 6/229 [00:02<01:15, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 3% 7/229 [00:02<01:14, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 3% 8/229 [00:02<01:12, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 4% 9/229 [00:02<01:12, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 4% 10/229 [00:03<01:10, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 5% 11/229 [00:03<01:12, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 5% 12/229 [00:03<01:12, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 6% 13/229 [00:04<01:10, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 6% 14/229 [00:04<01:10, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 7% 15/229 [00:04<01:10, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 7% 16/229 [00:05<01:10, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 7% 17/229 [00:05<01:08, 3.10it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 8% 18/229 [00:05<01:10, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 8% 19/229 [00:06<01:11, 2.92it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 9% 20/229 [00:06<01:09, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 9% 21/229 [00:06<01:08, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 10% 22/229 [00:07<01:06, 3.09it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 10% 23/229 [00:07<01:05, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 10% 24/229 [00:07<01:06, 3.10it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 11% 25/229 [00:08<01:06, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 11% 26/229 [00:08<01:06, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 12% 27/229 [00:08<01:04, 3.12it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 12% 28/229 [00:09<01:05, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 13% 29/229 [00:09<01:05, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 13% 30/229 [00:09<01:03, 3.12it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 14% 31/229 [00:10<01:04, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 14% 32/229 [00:10<01:04, 3.06it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 14% 33/229 [00:10<01:02, 3.13it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 15% 34/229 [00:11<01:04, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 15% 35/229 [00:11<01:05, 2.94it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 16% 36/229 [00:11<01:03, 3.04it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 16% 37/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 17% 38/229 [00:12<01:03, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 17% 39/229 [00:12<01:02, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 17% 40/229 [00:13<01:01, 3.09it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 18% 41/229 [00:13<01:01, 3.06it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 18% 42/229 [00:13<01:03, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 19% 43/229 [00:14<01:05, 2.83it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 19% 44/229 [00:14<01:04, 2.87it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 20% 45/229 [00:14<01:01, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 20% 46/229 [00:15<01:02, 2.92it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 21% 47/229 [00:15<01:03, 2.88it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 21% 48/229 [00:15<01:05, 2.76it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 21% 49/229 [00:16<01:06, 2.69it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 22% 50/229 [00:16<01:04, 2.78it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 22% 51/229 [00:17<01:03, 2.78it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 23% 52/229 [00:17<01:02, 2.85it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 23% 53/229 [00:17<01:00, 2.90it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 24% 54/229 [00:18<00:59, 2.92it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 24% 55/229 [00:18<00:57, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 24% 56/229 [00:18<00:57, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 25% 57/229 [00:19<00:57, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 25% 58/229 [00:19<00:55, 3.09it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 26% 59/229 [00:19<00:55, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 26% 60/229 [00:20<00:55, 3.04it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 27% 61/229 [00:20<00:51, 3.23it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 27% 62/229 [00:20<00:52, 3.16it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 28% 63/229 [00:20<00:53, 3.10it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 28% 64/229 [00:21<00:52, 3.16it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 28% 65/229 [00:21<00:52, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 29% 66/229 [00:21<00:52, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 29% 67/229 [00:22<00:54, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 30% 68/229 [00:22<00:53, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 30% 69/229 [00:22<00:53, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 31% 70/229 [00:23<00:52, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 31% 71/229 [00:23<00:52, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 31% 72/229 [00:23<00:52, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 32% 73/229 [00:24<00:51, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 32% 74/229 [00:24<00:51, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 33% 75/229 [00:24<00:51, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 33% 76/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 34% 77/229 [00:25<00:50, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 34% 78/229 [00:25<00:50, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 34% 79/229 [00:26<00:48, 3.09it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 35% 80/229 [00:26<00:49, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 35% 81/229 [00:26<00:48, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 36% 82/229 [00:27<00:48, 3.06it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 36% 83/229 [00:27<00:46, 3.12it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 37% 84/229 [00:27<00:45, 3.17it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 37% 85/229 [00:28<00:45, 3.20it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 38% 86/229 [00:28<00:45, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 38% 87/229 [00:28<00:45, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 38% 88/229 [00:29<00:46, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 39% 89/229 [00:29<00:45, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 39% 90/229 [00:29<00:46, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 40% 91/229 [00:30<00:46, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 40% 92/229 [00:30<00:44, 3.06it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 41% 93/229 [00:30<00:44, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 41% 94/229 [00:31<00:44, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 41% 95/229 [00:31<00:44, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 42% 96/229 [00:31<00:44, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 42% 97/229 [00:32<00:43, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 43% 98/229 [00:32<00:43, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 43% 99/229 [00:32<00:43, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 44% 100/229 [00:33<00:41, 3.10it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 44% 101/229 [00:33<00:40, 3.15it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 45% 102/229 [00:33<00:41, 3.10it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 45% 103/229 [00:34<00:42, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 45% 104/229 [00:34<00:42, 2.92it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 46% 105/229 [00:34<00:42, 2.94it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 46% 106/229 [00:35<00:41, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 47% 107/229 [00:35<00:41, 2.97it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 47% 108/229 [00:35<00:40, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 48% 109/229 [00:36<00:39, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 48% 110/229 [00:36<00:38, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 48% 111/229 [00:36<00:39, 2.95it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 49% 112/229 [00:37<00:38, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 49% 113/229 [00:37<00:37, 3.12it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 50% 114/229 [00:37<00:37, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 50% 115/229 [00:38<00:38, 2.97it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 51% 116/229 [00:38<00:38, 2.97it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 51% 117/229 [00:38<00:38, 2.90it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 52% 118/229 [00:39<00:38, 2.86it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 52% 119/229 [00:39<00:36, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 52% 120/229 [00:39<00:36, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 53% 121/229 [00:40<00:35, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 53% 122/229 [00:40<00:35, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 54% 123/229 [00:40<00:35, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 54% 124/229 [00:41<00:34, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 55% 125/229 [00:41<00:35, 2.90it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 55% 126/229 [00:41<00:36, 2.86it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 55% 127/229 [00:42<00:35, 2.90it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 56% 128/229 [00:42<00:35, 2.85it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 56% 129/229 [00:42<00:34, 2.90it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 57% 130/229 [00:43<00:33, 2.93it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 57% 131/229 [00:43<00:34, 2.80it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 58% 132/229 [00:43<00:33, 2.86it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 58% 133/229 [00:44<00:33, 2.91it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 59% 134/229 [00:44<00:32, 2.94it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 59% 135/229 [00:44<00:31, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 59% 136/229 [00:45<00:30, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 60% 137/229 [00:45<00:31, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 60% 138/229 [00:45<00:29, 3.06it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 61% 139/229 [00:46<00:29, 3.04it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 61% 140/229 [00:46<00:28, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 62% 141/229 [00:46<00:27, 3.15it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 62% 142/229 [00:47<00:27, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 62% 143/229 [00:47<00:28, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 63% 144/229 [00:47<00:29, 2.92it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 63% 145/229 [00:48<00:31, 2.71it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 64% 146/229 [00:48<00:30, 2.73it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 64% 147/229 [00:49<00:29, 2.81it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 65% 148/229 [00:49<00:28, 2.86it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 65% 149/229 [00:49<00:28, 2.84it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 66% 150/229 [00:50<00:26, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 66% 151/229 [00:50<00:26, 2.97it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 66% 152/229 [00:50<00:25, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 67% 153/229 [00:50<00:24, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 67% 154/229 [00:51<00:24, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 68% 155/229 [00:51<00:24, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 68% 156/229 [00:51<00:24, 3.04it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 69% 157/229 [00:52<00:23, 3.04it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 69% 158/229 [00:52<00:23, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 69% 159/229 [00:52<00:22, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 70% 160/229 [00:53<00:21, 3.16it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 70% 161/229 [00:53<00:21, 3.12it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 71% 162/229 [00:53<00:21, 3.18it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 71% 163/229 [00:54<00:21, 3.13it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 72% 164/229 [00:54<00:21, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 72% 165/229 [00:54<00:20, 3.09it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 72% 166/229 [00:55<00:20, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 73% 167/229 [00:55<00:19, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 73% 168/229 [00:55<00:19, 3.10it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 74% 169/229 [00:56<00:19, 3.15it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 74% 170/229 [00:56<00:19, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 75% 171/229 [00:56<00:18, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 75% 172/229 [00:57<00:18, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 76% 173/229 [00:57<00:17, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 76% 174/229 [00:57<00:17, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 76% 175/229 [00:58<00:17, 3.16it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 77% 176/229 [00:58<00:15, 3.33it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 77% 177/229 [00:58<00:16, 3.23it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 78% 178/229 [00:59<00:16, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 78% 179/229 [00:59<00:15, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 79% 180/229 [00:59<00:15, 3.18it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 79% 181/229 [00:59<00:15, 3.12it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 79% 182/229 [01:00<00:14, 3.16it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 80% 183/229 [01:00<00:14, 3.22it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 80% 184/229 [01:00<00:13, 3.25it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 81% 185/229 [01:01<00:13, 3.18it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 81% 186/229 [01:01<00:13, 3.24it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 82% 187/229 [01:01<00:13, 3.17it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 82% 188/229 [01:02<00:13, 3.04it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 83% 189/229 [01:02<00:13, 2.95it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 83% 190/229 [01:02<00:13, 2.97it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 83% 191/229 [01:03<00:12, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 84% 192/229 [01:03<00:11, 3.09it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 84% 193/229 [01:03<00:11, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 85% 194/229 [01:04<00:10, 3.19it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 85% 195/229 [01:04<00:10, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 86% 196/229 [01:04<00:10, 3.18it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 86% 197/229 [01:05<00:10, 3.04it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 86% 198/229 [01:05<00:09, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 87% 199/229 [01:05<00:09, 3.16it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 87% 200/229 [01:06<00:09, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 88% 201/229 [01:06<00:09, 3.08it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 88% 202/229 [01:06<00:09, 2.89it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 89% 203/229 [01:07<00:08, 3.00it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 89% 204/229 [01:07<00:08, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 90% 205/229 [01:07<00:07, 3.09it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 90% 206/229 [01:08<00:07, 2.98it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 90% 207/229 [01:08<00:07, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 91% 208/229 [01:08<00:06, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 91% 209/229 [01:09<00:06, 3.14it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 92% 210/229 [01:09<00:06, 3.10it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 92% 211/229 [01:09<00:05, 3.07it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 93% 212/229 [01:10<00:05, 3.13it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 93% 213/229 [01:10<00:05, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 93% 214/229 [01:10<00:04, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 94% 215/229 [01:11<00:04, 2.93it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 94% 216/229 [01:11<00:04, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 95% 217/229 [01:11<00:04, 2.95it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 95% 218/229 [01:12<00:03, 2.97it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 96% 219/229 [01:12<00:03, 2.99it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 96% 220/229 [01:12<00:02, 3.01it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 97% 221/229 [01:13<00:02, 3.02it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 97% 222/229 [01:13<00:02, 2.95it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 97% 223/229 [01:13<00:01, 3.05it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 98% 224/229 [01:14<00:01, 2.96it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 98% 225/229 [01:14<00:01, 2.91it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 99% 226/229 [01:14<00:00, 3.03it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 99% 227/229 [01:15<00:00, 3.11it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 100% 228/229 [01:15<00:00, 3.18it/s]\u001b[A\nepoch 006 | valid on 'valid' subset: 100% 229/229 [01:15<00:00, 3.95it/s]\u001b[A\n \u001b[A2021-02-28 17:57:38 | INFO | valid | epoch 006 | valid on 'valid' subset | loss 0.365 | nll_loss 0.012 | accuracy 94.2 | wps 705.9 | wpb 232.7 | bsz 8 | num_updates 856 | best_accuracy 94.2\n2021-02-28 17:57:38 | INFO | fairseq_cli.train | begin save checkpoint\n2021-02-28 18:03:20 | INFO | fairseq.checkpoint_utils | saved checkpoint checkpoints/checkpoint6.pt (epoch 6 @ 856 updates, score 94.2) (writing took 341.54576320399974 seconds)\n2021-02-28 18:03:20 | INFO | fairseq_cli.train | end of epoch 6 (average epoch stats below)\n2021-02-28 18:03:20 | INFO | train | epoch 006 | loss 0.047 | nll_loss 0.002 | accuracy 98.9 | wps 136.2 | ups 0.14 | wpb 957.9 | bsz 32 | num_updates 856 | lr 8.11893e-06 | gnorm 9.595 | loss_scale 64 | train_wall 574 | wall 5573\n2021-02-28 18:03:20 | INFO | fairseq_cli.train | done training in 5566.9 seconds\n" ], [ "!cp checkpoints/checkpoint_best.pt /content/drive/MyDrive/UPENN/checkpoints/ckpt_6_fin_rob.pt", "_____no_output_____" ], [ "%ls /content/drive/MyDrive/UPENN/checkpoints/", "ckpt_6_fin_rob.pt\n" ], [ "", "_____no_output_____" ] ], [ [ "# Testing the Validation Split", "_____no_output_____" ] ], [ [ "from fairseq.models.roberta import RobertaModel\nroberta = RobertaModel.from_pretrained(\n 'checkpoints',\n checkpoint_file='checkpoint_best.pt',\n data_name_or_path='/content/drive/MyDrive/UPENN/Task1a-bin'\n)\nroberta.eval() # disable dropout", "_____no_output_____" ], [ "label_fn = lambda label: roberta.task.label_dictionary.string(\n [label + roberta.task.label_dictionary.nspecial]\n)\npreds, labels = [], []\nfor i in tqdm(range(len(X_val)), total=len(X_val)):\n tokens = roberta.encode(X_val[i])\n pred = label_fn(roberta.predict('task1a_head',tokens).argmax().item())\n preds.append(pred)\n labels.append(Y_val[i])", "100%|██████████| 1826/1826 [15:33<00:00, 1.96it/s]\n" ], [ "import pandas as pd\nfrom sklearn.metrics import classification_report\ndf_preds=pd.read_csv(\"/content/val_final.tsv\", sep='\\t')\ndf_label=pd.read_csv(\"/content/class.tsv\", sep='\\t')\ndf=df_preds.merge(df_label, on=\"tweet_id\")\ndf.columns=[\"tweet_id\",\"preds\",\"label\"]\ndf['label'].replace({\"NoADE\":0, \"ADE\":1}, inplace=True)\ndf['preds'].replace({\"NoADE\":0, \"ADE\":1}, inplace=True)\ndf.head()", "_____no_output_____" ], [ "import pandas as pd\nfrom sklearn.metrics import classification_report\npreds=df[\"preds\"]\nlabels=df[\"label\"]\nreport = classification_report(labels, list(map(int, preds)))\nprint(report)", " precision recall f1-score support\n\n 0 0.99 0.95 0.97 848\n 1 0.59 0.92 0.72 65\n\n accuracy 0.95 913\n macro avg 0.79 0.94 0.85 913\nweighted avg 0.97 0.95 0.95 913\n\n" ], [ "!rm checkpoints/checkpoint1.pt checkpoints/checkpoint2.pt checkpoints/checkpoint3.pt checkpoints/checkpoint4.pt", "_____no_output_____" ] ], [ [ "# Running on the Validation Set\n", "_____no_output_____" ] ], [ [ "df_tweets = pd.read_csv('/content/tweets.tsv', sep = '\\t')\ndf_class = pd.read_csv('/content/class.tsv', sep = '\\t')\ndf_valid = pd.merge(df_tweets, df_class, on = 'tweet_id')\ndf_valid['label'].replace({\"NoADE\":0, \"ADE\":1}, inplace=True)\ndf_valid.head()", "_____no_output_____" ], [ "df_test = pd.read_csv('/content/drive/MyDrive/UPENN/test_tweets.tsv', sep='\\t')", "_____no_output_____" ], [ "index_names = df_test[df_test['tweet'].str.split().apply(len)>35].index\ndf_test.drop(index_names, inplace=True)\ndf_test.tweet_id.nunique()", "_____no_output_____" ], [ "label_fn = lambda label: roberta.task.label_dictionary.string(\n [label + roberta.task.label_dictionary.nspecial]\n)\npreds, id = [], []\nfor index, row in tqdm(df_test.iterrows(), total=len(df_test)):\n tokens = roberta.encode(row[\"tweet\"])\n pred = label_fn(roberta.predict('task1a_head',tokens).argmax().item())\n preds.append(pred)\n id.append(row[\"tweet_id\"])", "100%|██████████| 10472/10472 [1:26:06<00:00, 2.03it/s]\n" ], [ "df_1a = pd.DataFrame(list(zip(id, preds)), columns = ['tweet_id', 'label'])\ndf_1a['label']=df_1a['label'].replace({0:\"NoADE\", 1:\"ADE\"})\ndf_1a.reset_index(drop=True, inplace=True)\ndf_1a.head()", "_____no_output_____" ], [ "df_1a.to_csv(\"/content/drive/MyDrive/UPENN/1a_sub2.tsv\", sep='\\t')", "_____no_output_____" ], [ "from sklearn.metrics import classification_report\nreport = classification_report(labels, list(map(int, preds)))\nprint(report)", "_____no_output_____" ], [ "print(Counter(preds))", "Counter({'0': 9543, '1': 929})\n" ], [ "df_preds = pd.DataFrame(preds, columns = ['Predictions'])\ndf_id = pd.DataFrame(df_valid['tweet_id'], columns = ['tweet_id'])\ndf_results = pd.concat([df_id, df_preds], join = 'outer', axis = 1)\ndf_results.head()", "_____no_output_____" ], [ "df_results.to_csv('/content/val.tsv', sep = '\\t')", "_____no_output_____" ], [ "len(df_id)", "_____no_output_____" ], [ "import pandas as pd\ndf = pd.read_csv('/content/drive/MyDrive/UPENN/1a_sub2.tsv', sep = '\\t')\ndf.drop([\"Unnamed: 0\"], axis=1, inplace=True)\ndf.columns = [\"tweet_id\", \"label\"]\ndf['label'].replace({0:\"NoADE\", 1:\"ADE\"}, inplace=True)\ndf.reset_index(drop=True, inplace=True)\ndf = df[df.label==\"ADE\"]\ndf.head()", "_____no_output_____" ], [ "df.to_csv('/content/test_sub2.tsv', sep = '\\t', index= False)", "_____no_output_____" ], [ "import pandas as pd\ndf_1a = pd.read_csv('/content/test_sub2.tsv', sep = '\\t') \ndf_1b = pd.read_csv('/content/1b_new.tsv', sep = '\\t')\ndf_1b.drop([\"Unnamed: 0\"], axis=1, inplace=True)\ndf_1b.head()", "_____no_output_____" ], [ "df_1 = df_1a.merge(df_1b, on = 'tweet_id')\ndf_1.columns = [\"tweet_id\", \"label\", \"start\", \"end\", \"span\"]\ndf_1[\"start\"] = df_1[\"start\"].astype(int)\ndf_1[\"end\"] = df_1[\"end\"].astype(int)\ndf_1.dropna(axis=0, inplace=True)\ndf_1 = df_1[df_1.label==\"ADE\"]\ndf_1.head()", "_____no_output_____" ], [ "df_1.to_csv('/content/testb_final.tsv', sep = '\\t', index= False)", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "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" ] ]
4afb68c087e7bc04d6faf572da3677a7c2da785a
62,905
ipynb
Jupyter Notebook
joint_optimization.ipynb
huynh-alex/greens-function
e245cc3f00df8da3708c378a0e387082bcbd0a79
[ "MIT" ]
null
null
null
joint_optimization.ipynb
huynh-alex/greens-function
e245cc3f00df8da3708c378a0e387082bcbd0a79
[ "MIT" ]
null
null
null
joint_optimization.ipynb
huynh-alex/greens-function
e245cc3f00df8da3708c378a0e387082bcbd0a79
[ "MIT" ]
null
null
null
32.475478
468
0.487338
[ [ [ "# imports\nimport warnings\nwarnings. filterwarnings('ignore')\n\nimport numpy\nfrom qpsolvers import solve_qp\nfrom qiskit.chemistry import FermionicOperator\nfrom qiskit.aqua.operators.legacy.op_converter import to_weighted_pauli_operator\nfrom qiskit.chemistry.components.variational_forms import UCCSD\nfrom qiskit.aqua.components.optimizers import L_BFGS_B\nfrom qiskit import Aer\nfrom qiskit.quantum_info import Pauli\nfrom qiskit.aqua.operators import WeightedPauliOperator\nfrom qiskit.aqua.operators.legacy import op_converter\nfrom qiskit.aqua.algorithms import VQE\nfrom qiskit.aqua import QuantumInstance\nfrom tqdm import tqdm\nfrom joblib import Parallel, delayed\nimport itertools\nfrom qiskit import QuantumRegister, QuantumCircuit, execute, ClassicalRegister\nfrom qiskit.circuit.library import U3Gate\nfrom qiskit.aqua.components.initial_states import Custom\nfrom qiskit.chemistry.components.initial_states import HartreeFock\nimport scipy\nimport matplotlib.pyplot as plt\nfrom qiskit.quantum_info import partial_trace, Statevector", "C:\\Users\\abhuynh\\Miniconda3\\envs\\qiskit\\lib\\site-packages\\qiskit\\chemistry\\__init__.py:170: DeprecationWarning: The package qiskit.chemistry is deprecated. It was moved/refactored to qiskit_nature (pip install qiskit-nature). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>\n warn_package('chemistry', 'qiskit_nature', 'qiskit-nature')\n" ], [ "# 2 site Hubbard model parameters\nt = 1 #hopping factor\nU = 2 #coulomb repulsion factor\nmu = U/2 #chemical potential factor", "_____no_output_____" ], [ "# 2x1 Hubbard Hamiltonian\ndef HubbardHamiltonian(U,t,num_spin_orbitals,num_particles):\n h1=numpy.zeros((4,4))\n h2=numpy.zeros((4,4,4,4))\n num_sites=int(num_spin_orbitals // 2)\n for i in range(num_sites - 1):\n h1[i, i + 1] = h1[i + 1, i] = -t\n h1[i + num_sites, i + 1 + num_sites] = h1[i + 1 + num_sites, i + num_sites] = -t\n h1[i][i] = -mu\n h1[i + num_sites][i + num_sites] = -mu\n h1[num_sites - 1][num_sites - 1] = -mu\n h1[2 * num_sites - 1][2 * num_sites - 1] = -mu \n h1[0, num_sites - 1] = h1[num_sites - 1, 0] = -t\n h1[num_sites, 2 * num_sites - 1] = h1[2 * num_sites - 1, num_sites] = -t\n for i in range(num_sites):\n h2[i, i , i + num_sites, i + num_sites] = U\n fermion_op = FermionicOperator(h1 = h1, h2 = h2) # Fermionic Hamiltonian\n qubit_op = fermion_op.mapping('jordan_wigner') #Qubit Hamiltonian\n return qubit_op", "_____no_output_____" ], [ "# construct the qubit operator rep. of the 2x1 Hubbard model and then the matrix representation\nqubit_H = HubbardHamiltonian(U = U, t = 1, num_spin_orbitals = 4, num_particles = 2)\n#constructing matrix rep. in the Fock space\nH_mat=op_converter.to_matrix_operator(qubit_H).dense_matrix", "C:\\Users\\abhuynh\\Miniconda3\\envs\\qiskit\\lib\\site-packages\\qiskit\\chemistry\\fermionic_operator.py:386: DeprecationWarning: The package qiskit.aqua.operators is deprecated. It was moved/refactored to qiskit.opflow (pip install qiskit-terra). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>\n pauli_list = WeightedPauliOperator(paulis=[])\nC:\\Users\\abhuynh\\Miniconda3\\envs\\qiskit\\lib\\site-packages\\qiskit\\chemistry\\fermionic_operator.py:394: DeprecationWarning: The variable qiskit.aqua.aqua_globals is deprecated. It was moved/refactored to qiskit.utils.algorithm_globals (pip install qiskit-terra). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>\n task_args=(threshold,), num_processes=aqua_globals.num_processes)\n" ], [ "# compute exact ground state energy and wavefunction through diagonalization\nw,v = numpy.linalg.eigh(H_mat)\nEg = w[0]\n# print(\"ground state energy-\", w[0])\nstate_g = v[:,0]\n# print(\"ground state wvfn.\", state_g)", "_____no_output_____" ], [ "def rotated_state(labels,params,state0):\n U=WeightedPauliOperator([[1,Pauli.from_label('IIII')]])\n for i in range(len(labels)):\n U=WeightedPauliOperator([[numpy.cos(params[i]),Pauli.from_label('IIII')],[-1j*numpy.sin(params[i]),Pauli.from_label(labels[i])]]).multiply(U)\n U_mat=op_converter.to_matrix_operator(U).dense_matrix\n rot_state=numpy.dot(U_mat,state0) \n return rot_state", "_____no_output_____" ], [ "def TimeEvolutionOperator(T):\n return numpy.dot(numpy.dot(v,numpy.diag(numpy.exp(-1j*w*T))),numpy.conjugate(v.T))", "_____no_output_____" ] ], [ [ "### $G_{1,2}^{\\uparrow,\\uparrow}(t>0)=\\langle G|e^{iHT}c_{1\\uparrow}(0)e^{-iHT}c^{\\dagger}_{2\\uparrow}(0)|G\\rangle$, $c^{\\dagger}_{2\\uparrow}(0)=IIXZ+iIIYZ$, <br>\n### $|\\mathcal{E}\\rangle = IIXZ|G\\rangle= e^{i\\frac{\\pi}{2}IIXZ}e^{i\\frac{2\\pi}{27}IZXY}e^{i\\frac{\\pi}{4}XYII}e^{i\\frac{\\pi}{4}IIXY}e^{-i\\frac{\\pi}{2}}|G\\rangle$, <br>\n\n### also constructing $IIIY|G\\rangle$ ", "_____no_output_____" ] ], [ [ "# excited state 1\nexc_labels = ['IIII','IIXZ']\nexc_params = numpy.array([-numpy.pi/2,numpy.pi/2])\nexc_state = rotated_state(exc_labels,exc_params,state_g)\n\n# excited state 2\nexc_labels2 = ['IIII','IIIY']\nexc_params2 = [-numpy.pi/2,numpy.pi/2]\nexc_state2 = rotated_state(exc_labels2,exc_params2,state_g)\nexc_state2[numpy.abs(exc_state)<1e-5] = 0", "_____no_output_____" ], [ "# greens function evolution\ndef greens_function(T, dT, T0):\n steps = int((T-T0)/dT)\n T_arr = numpy.linspace(T0, T, steps)\n GF_exact = []\n for i in tqdm(range(len(T_arr))):\n U_T = TimeEvolutionOperator(T_arr[i])\n exact_evolved_state = numpy.dot(U_T, exc_state)\n G1 = numpy.exp(1j*(U-rho)/2.)*numpy.dot(numpy.conjugate(exc_state2), exact_evolved_state)\n GF_exact.append(G1)\n return GF_exact", "_____no_output_____" ], [ "# parameters for greens function\nT = 30\ndT = 0.1\nT0 = 0\nsteps = int((T-T0)/dT)\nT_arr = numpy.linspace(T0,T,steps)\nrho = numpy.sqrt(U**2+16*t*t)\nG = greens_function(T,dT,T0)", "100%|█████████████████████████████████████████████████████████████████████████████| 300/300 [00:00<00:00, 33305.75it/s]\n" ], [ "# graphing greens function and spectral function\n# fig, ax = plt.subplots(1,2)\n# plt.rcParams[\"figure.figsize\"] = (40, 20)\n\n# ax[0].tick_params(labelsize=30)\n# ax[0].plot(T_arr, numpy.real(G), color='black')\n\n# \"\"\"SPECTRAL FUNCTION\"\"\"\n# # Number of sample points\n# # num_samp1=len(G)\n# # sample spacing\n# # ImgGf = numpy.fft.fft(numpy.imag(G))\n# # Tf1 = numpy.linspace(0, 40, num_samp1//2)\n# # ax[1].set_yscale('log')\n# # ax[1].tick_params(labelsize=20)\n# # ax[1].plot(Tf1, 2.0/num_samp1 * numpy.abs(ImgGf[:num_samp1//2])/numpy.pi, color='black', linestyle='-')\n# # ax[1].plot(-Tf1, 2.0/num_samp1 * numpy.abs(ImgGf[:num_samp1//2])/numpy.pi, color='black', linestyle='-')\n# # ax[1].plot(Tf1, 2.0/num_samp1 * numpy.abs(ImgGf[:num_samp1//2])/numpy.pi, color='black', linestyle='-')\n# # ax[1].plot(-Tf1, 2.0/num_samp1 * numpy.abs(ImgGf[:num_samp1//2])/numpy.pi, color='black', linestyle='-')\n# # ax[1].plot(T_arr,numpy.imag(G),linestyle='-')\n# plt.show()", "_____no_output_____" ], [ "# generators and angles for constructing adaptive ansatz for the 2x1 Hubbard model at U=2 t=1\nlabels=['IIXY', 'XYII', 'IZXY']\n\n# U = 2\nparams = [-0.7853980948120887, -0.7853983093282092, 0.23182381954801887]\n\n# U = 3\n# params = [0.7853959259806095, 0.7853996767775284, -1.2490064682759752]", "_____no_output_____" ], [ "#circuit initialization\ninit_circ = QuantumCircuit(2*2)\ninit_circ.x(0)\ninit_circ.x(2)\ninit_state_circuit=Custom(4, circuit = init_circ)\ninit_state = init_state_circuit #HartreeFock(num_spin_orbitals,num_particles=4,qubit_mapping='jordan_wigner',two_qubit_reduction=False)\nvar_form_base = UCCSD(4,num_particles=2, initial_state=init_state,qubit_mapping='jordan_wigner',two_qubit_reduction=False)\nbackend = Aer.get_backend('statevector_simulator')\noptimizer = L_BFGS_B()\n\n#adaptive circuit construction\nvar_form_base.manage_hopping_operators()\ncirc0 = var_form_base.construct_circuit(parameters = [])\nstate0 = execute(circ0,backend).result().get_statevector()\nstate0[numpy.abs(state0)<1e-5] = 0\nadapt_state = rotated_state(labels, params, state0)", "C:\\Users\\abhuynh\\Miniconda3\\envs\\qiskit\\lib\\site-packages\\qiskit\\aqua\\components\\initial_states\\custom.py:79: DeprecationWarning: The Custom class is deprecated as of Aqua 0.9 and will be removed no earlier than 3 months after the release date. Instead, all algorithms and circuits accept a plain QuantumCircuit. Custom(state_vector=vector) is the same as a circuit where the ``initialize(vector/np.linalg.norm(vector))`` method has been called.\n super().__init__()\nC:\\Users\\abhuynh\\Miniconda3\\envs\\qiskit\\lib\\site-packages\\qiskit\\aqua\\components\\variational_forms\\variational_form.py:48: DeprecationWarning: The package qiskit.aqua.components.variational_forms is deprecated. For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>\n warn_package('aqua.components.variational_forms')\nC:\\Users\\abhuynh\\Miniconda3\\envs\\qiskit\\lib\\site-packages\\qiskit\\aqua\\components\\optimizers\\optimizer.py:49: DeprecationWarning: The package qiskit.aqua.components.optimizers is deprecated. It was moved/refactored to qiskit.algorithms.optimizers (pip install qiskit-terra). For more information see <https://github.com/Qiskit/qiskit-aqua/blob/master/README.md#migration-guide>\n warn_package('aqua.components.optimizers',\n" ], [ "# checking inner product between numerical and exact ground state\nprint(\"overlap between analytic and numerical ground state is-\",numpy.dot(state_g,adapt_state))", "overlap between analytic and numerical ground state is- (-0.999999999999987+0j)\n" ], [ "# confirming exact energy\n\n# check expectation value of the Hamiltonian with respect to adaptive ansatz\ndef expectation_op(Op,state):\n return numpy.dot(numpy.dot(state,Op),numpy.conjugate(state))\n\nE_adapt = expectation_op(H_mat,adapt_state)\n\n# print(\"exact energy-\",Eg)\n# print(\"Energy from adaptive ansatz-\",E_adapt)\n# print(\"convergence error\", E_adapt-Eg)", "_____no_output_____" ], [ "# constructing the excited state ansatz\nexc_labels = ['IIII','IIXZ']\nexc_params = numpy.array([-numpy.pi/2,numpy.pi/2])\nexc_state = rotated_state(exc_labels,exc_params,adapt_state)\nexc_state[numpy.abs(exc_state)<1e-5] = 0", "_____no_output_____" ], [ "# exact excited state\nexact_exc_state=rotated_state(exc_labels,exc_params,state_g)\n#checking inner product between numerical and analytic state\nprint(\"overlap between analytic and numerical exc. state is-\",numpy.dot(numpy.conjugate(exact_exc_state),exc_state))", "overlap between analytic and numerical exc. state is- (-0.999999999999987+0j)\n" ], [ "def M(p,q,vqs_params,ref_state):\n thetas=numpy.array(vqs_params)\n shift_1=numpy.array([0]*(p)+[numpy.pi/2]+[0]*(len(vqs_params)-p-1))\n shift_2=numpy.array([0]*(q)+[numpy.pi/2]+[0]*(len(vqs_params)-q-1))\n state_1=rotated_state(vqs_generators,vqs_params+shift_1,ref_state)\n state_2=rotated_state(vqs_generators,vqs_params+shift_2,ref_state)\n M_arr=numpy.real(numpy.dot(numpy.conjugate(state_1),state_2))\n return M_arr", "_____no_output_____" ], [ "def V(p,vqs_params,ref_state):\n thetas=numpy.array(vqs_params)\n shift_1=numpy.array([0]*(p)+[numpy.pi/2]+[0]*(len(vqs_params)-p-1))\n state_1=rotated_state(vqs_generators,vqs_params+shift_1,ref_state)\n state=rotated_state(vqs_generators,vqs_params,ref_state)\n V_arr=numpy.imag(numpy.dot(numpy.dot(numpy.conjugate(state_1),H_mat),state))\n return V_arr", "_____no_output_____" ] ], [ [ "# Alex stuff", "_____no_output_____" ] ], [ [ "# basic setup\nimport numpy as np\nimport copy\n\nPAULI_X = np.array([[0,1],[1,0]], dtype='complex128')\nPAULI_Y = np.array([[0,-1j],[1j,0]], dtype='complex128')\nPAULI_Z = np.array([[1,0],[0,-1]], dtype='complex128')\nIDENTITY = np.eye(2, dtype='complex128')\n\ndef pauli_string_to_matrix(pauli_string):\n return Pauli(pauli_string).to_matrix()\n\ndef pauli_string_exp_to_matrix(pauli_string, param):\n return expm(-1j * param * Pauli(pauli_string).to_matrix())\n\n\nbackend = Aer.get_backend('statevector_simulator')\nqasm_backend = Aer.get_backend('qasm_simulator')\n\n# circuit creation\n\ndef rotate_state(pauli_string, param, circuit):\n ancilla_boolean = (1 if circuit.num_qubits == 5 else 0)\n if pauli_string == 'IIII':\n gate = 1\n for j in range(len(pauli_string)):\n gate = np.kron(gate, IDENTITY)\n gate *= -1j * np.sin(param)\n gate += np.cos(param) * np.eye(16)\n qubits_to_act_on = [1,2,3,4] if ancilla_boolean else [0,1,2,3]\n circuit.unitary(gate, qubits_to_act_on, label=pauli_string)\n else:\n qubits_to_act_on = []\n gate = 1\n for j in range(len(pauli_string)):\n if pauli_string[j] == 'X':\n gate = np.kron(gate, PAULI_X)\n elif pauli_string[j] == 'Y':\n gate = np.kron(gate, PAULI_Y)\n elif pauli_string[j] == 'Z':\n gate = np.kron(gate, PAULI_Z)\n if pauli_string[j] != 'I':\n qubits_to_act_on.append(np.abs(j - 3) + (0,1)[ancilla_boolean])\n gate *= (-1j * np.sin(param))\n gate += np.cos(param) * np.eye(2**len(qubits_to_act_on))\n qubits_to_act_on.reverse()\n circuit.unitary(gate, qubits_to_act_on, label = pauli_string)\n circuit.barrier()\n\ndef create_initial_state():\n circuit = QuantumCircuit(4)\n circuit.x(0)\n circuit.x(2)\n circuit.barrier()\n return circuit\n\ndef create_adapt_ground_state():\n labels = ['IIXY', 'XYII', 'IZXY']\n params = [-0.7853980948120887, -0.7853983093282092, 0.23182381954801887]\n circuit = create_initial_state()\n for i in range(len(labels)):\n rotate_state(labels[i], params[i], circuit)\n return circuit\n\ndef create_excited_state():\n labels=['IIXY', 'XYII', 'IZXY', 'IIII', 'IIXZ']\n params=[-0.7853980948120887, -0.7853983093282092, 0.23182381954801887,numpy.pi/2,-numpy.pi/2.] \n circuit = create_initial_state()\n for i in range(len(labels)):\n rotate_state(labels[i], params[i], circuit)\n circuit.barrier()\n return circuit\n\ndef create_excited_state2():\n labels = ['IIXY', 'XYII', 'IZXY', 'IIII', 'IIIY']\n params = [-0.7853980948120887, -0.7853983093282092, 0.23182381954801887, -numpy.pi/2, numpy.pi/2]\n circuit = create_initial_state()\n for i in range(len(labels)):\n rotate_state(labels[i], params[i], circuit)\n return circuit\n\nexcited_state = execute(create_excited_state(), backend).result().get_statevector()\nexcited_state2 = execute(create_excited_state2(), backend).result().get_statevector()", "_____no_output_____" ], [ "def create_circuit_ancilla(ancilla_boolean, state):\n circuit = QuantumCircuit(4 + (0,1)[ancilla_boolean])\n circuit.x(0 + (0,1)[ancilla_boolean])\n circuit.x(2 + (0,1)[ancilla_boolean])\n labels = ['IIXY', 'XYII', 'IZXY']\n params = [-0.7853980948120887, -0.7853983093282092, 0.23182381954801887]\n\n if state == 'state2':\n labels.extend(['IIII', 'IIXZ'])\n params.extend([numpy.pi/2,-numpy.pi/2.])\n \n for i in range(len(labels)):\n rotate_state(labels[i], params[i], circuit) \n\n circuit.barrier()\n return circuit", "_____no_output_____" ], [ "def controlled_rotate_state(pauli_string, param, circuit):\n if pauli_string == 'IIII':\n return\n num_qubits = 4 #the ancilla does not count\n qubits_to_act_on = []\n gate = 1\n for j in range(len(pauli_string)):\n if pauli_string[j] == 'X':\n gate = np.kron(gate, PAULI_X)\n elif pauli_string[j] == 'Y':\n gate = np.kron(gate, PAULI_Y)\n elif pauli_string[j] == 'Z':\n gate = np.kron(gate, PAULI_Z)\n if pauli_string[j] != 'I':\n qubits_to_act_on.append(np.abs(j - num_qubits + 1) + 1)\n qubits_to_act_on.reverse()\n\n #convert unitary to gate through a temporary circuit\n temp_circuit = QuantumCircuit(2)\n temp_circuit.unitary(gate, [0, 1]) #we only have controlled 2-qubit unitaries: IIXX, XXII, IIYY, YYII, ZIZI, IZIZ\n controlled_gate = temp_circuit.to_gate(label = 'Controlled ' + pauli_string).control(1)\n qubits_to_act_on.insert(0, 0) #insert ancilla bit to front of list\n circuit.append(controlled_gate, qubits_to_act_on)", "_____no_output_____" ], [ "def measure_ancilla(circuit, shots):\n classical_register = ClassicalRegister(1, 'classical_reg')\n circuit.add_register(classical_register)\n circuit.measure(0, classical_register[0])\n\n result = execute(circuit, qasm_backend, shots = shots).result() \n counts = result.get_counts(circuit)\n if counts.get('0') != None:\n return 2 * (result.get_counts(circuit)['0'] / shots) - 1\n else:\n return -1\n\ndef measure_ancilla_statevector(circuit):\n full_statevector = Statevector(circuit)\n partial_density_matrix = partial_trace(full_statevector, [1, 2, 3, 4])\n partial_statevector = np.diagonal(partial_density_matrix)\n return ((2 * partial_statevector[0]) - 1).real ", "_____no_output_____" ], [ "def calculate_m_statevector(p, q, vqs_generators, vqs_params, state):\n circuit = create_circuit_ancilla(True, state)\n\n circuit.h(0)\n circuit.x(0)\n circuit.barrier()\n \n for i in range(0, p):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n controlled_rotate_state(vqs_generators[p], vqs_params[p], circuit)\n circuit.barrier()\n\n for i in range(p, q):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n circuit.x(0)\n controlled_rotate_state(vqs_generators[q], vqs_params[q], circuit)\n circuit.h(0)\n circuit.barrier()\n return measure_ancilla_statevector(circuit)\n\ndef calculate_v_statevector(p, vqs_generators, vqs_params, state):\n n_theta = len(vqs_params) \n circuit = create_circuit_ancilla(True, state)\n\n circuit.h(0)\n circuit.x(0)\n \n for i in range(0, p):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n controlled_rotate_state(vqs_generators[p], vqs_params[p], circuit)\n circuit.barrier()\n\n for i in range(p, n_theta):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n circuit.x(0)\n\n coeffs = [0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -1.0]\n measurements = []\n for i in range(len(coeffs)):\n single_h_circuit = copy.deepcopy(circuit)\n controlled_rotate_state(vqs_generators[i], coeffs[i], single_h_circuit)\n single_h_circuit.h(0)\n measurements.append(measure_ancilla_statevector(single_h_circuit))\n results = 0\n for i in range(len(coeffs)):\n results += measurements[i] * coeffs[i]\n return results\n\ndef calculate_m_shots(p, q, vqs_generators, vqs_params, shots, state):\n circuit = create_circuit_ancilla(True, state) #Creates |E>\n\n circuit.h(0)\n circuit.x(0)\n circuit.barrier()\n \n for i in range(0, p):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n controlled_rotate_state(vqs_generators[p], vqs_params[p], circuit)\n circuit.barrier()\n\n for i in range(p, q):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n circuit.x(0)\n controlled_rotate_state(vqs_generators[q], vqs_params[q], circuit)\n circuit.h(0)\n circuit.barrier()\n return measure_ancilla(circuit, shots)\n\ndef calculate_v_shots(p, vqs_generators, vqs_params, shots, state):\n n_theta = len(vqs_params) \n circuit = create_circuit_ancilla(True, state)\n\n circuit.h(0)\n circuit.x(0)\n \n for i in range(0, p):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n controlled_rotate_state(vqs_generators[p], vqs_params[p], circuit)\n circuit.barrier()\n\n for i in range(p, n_theta):\n rotate_state(vqs_generators[i], vqs_params[i], circuit)\n circuit.barrier()\n\n circuit.x(0)\n\n coeffs = [0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -1.0]\n measurements = []\n for i in range(len(coeffs)):\n single_h_circuit = copy.deepcopy(circuit)\n controlled_rotate_state(vqs_generators[i], coeffs[i], single_h_circuit)\n single_h_circuit.h(0)\n measurements.append(measure_ancilla(single_h_circuit, shots))\n results = 0\n for i in range(len(coeffs)):\n results += measurements[i] * coeffs[i]\n return results", "_____no_output_____" ], [ "def Cost(M,V):\n #f=1/2x^TPx+q^{T}x\n #Gx<=h\n #Ax=b\n# alpha = 0\n alpha=1e-3\n P=M.T@M+alpha*numpy.eye(len(V))\n q=M.T@V\n thetaDot=solve_qp(P,-q)\n return thetaDot\n\ndef McEvolve(vqs_params_init,T,dT,T0,exc_state, way):\n steps=int((T-T0)/dT)\n T_arr=numpy.linspace(T0,T,steps)\n vqs_params=vqs_params_init\n vqs_dot_hist=[]\n vqs_hist=[vqs_params]\n FidelityArr=[]\n GF_exact=[]\n GF_sim=[]\n U = 2\n for i in tqdm(range(len(T_arr))):\n #evaluations at time step t_i\n U_T=TimeEvolutionOperator(T_arr[i])\n #exact state\n exact_evolved_state=numpy.dot(U_T,exc_state)\n vqs_state=rotated_state(vqs_generators,vqs_hist[-1], exc_state)\n\n G1=np.exp(1j*(U-rho)/2)*numpy.dot(np.conj(exc_state2), exact_evolved_state).real\n GF_exact.append(G1)\n G2=np.exp(1j*(U-rho)/2)*numpy.dot(np.conj(exc_state2), vqs_state).real\n GF_sim.append(G2)\n# print(\"Green functions\",G1,G2)\n \n FidelityArr.append(numpy.abs(numpy.dot(vqs_state,numpy.conjugate(exact_evolved_state)))**2)\n print(\"Fidelity\",FidelityArr[-1]) \n \n arr = [(j,k) for j in range(len(vqs_params)) for k in range(len(vqs_params)) if j<=k]\n M_mat = numpy.zeros((len(vqs_params),len(vqs_params)))\n\n #constructing McLachlan\n if way == 'Anirban':\n M_elems = Parallel(n_jobs=-1,verbose=0)(delayed(M)(arr[i][0],arr[i][1],vqs_params,exc_state) for i in range(len(arr)))\n V_vec=numpy.array([V(p,vqs_params,exc_state) for p in range(len(vqs_params))])\n \n # Statevector way\n elif way == 'statevector':\n M_elems = Parallel(n_jobs=-1)(delayed(calculate_m_statevector)(arr[i][0], arr[i][1], vqs_generators, vqs_params, 'state2') for i in range(len(arr))) \n V_vec = Parallel(n_jobs=-1)(delayed(calculate_v_statevector)(p, vqs_generators, vqs_params, 'state2') for p in range(len(vqs_params)))\n \n # Shots way\n elif way == 'shots':\n shots = 2**15\n M_elems = Parallel(n_jobs=-1)(delayed(calculate_m_shots)(arr[i][0], arr[i][1], vqs_generators, vqs_params, shots, 'state2') for i in range(len(arr))) \n V_vec = Parallel(n_jobs=-1)(delayed(calculate_v_shots)(p, vqs_generators, vqs_params, shots, 'state2') for p in range(len(vqs_params)))\n\n for p in range(len(arr)):\n M_mat[arr[p][0]][arr[p][1]] = M_mat[arr[p][1]][arr[p][0]] = M_elems[p]\n \n vqs_params_dot=Cost(M_mat,V_vec)#numpy.linalg.lstsq(M_mat,V_vec,rcond=None)[0]\n vqs_dot_hist.append(vqs_params_dot)\n \n \n# def Error(vqs_params_dot):\n# quant=numpy.sum((M_mat@vqs_params_dot-V_vec)@(M_mat@vqs_params_dot-V_vec).T)\n# print(quant)\n# return quant\n# error=Error(vqs_params_dot)\n# print(\"Initial Error after least squares-\", error)\n \n #Euler\n #vqs_params=vqs_params+vqs_dot_hist[-1]*dT\n #Adams-Bashforth\n \n if i>0:\n vqs_params=vqs_params+1.5*dT*vqs_dot_hist[-1]-0.5*dT*vqs_dot_hist[-2]\n else:\n vqs_params=vqs_params+vqs_dot_hist[-1]*dT \n vqs_hist.append(vqs_params)\n \n return vqs_hist,FidelityArr,GF_sim,GF_exact ", "_____no_output_____" ], [ "# Single optimization\nT=5\ndT=0.1\n\nnd=2\nvqs_generators=['ZIZI','IZIZ','IIXX','IIYY','XXII','YYII','IIII']*nd\nvqs_params=numpy.zeros(len(vqs_generators))\n\n# vqs_params_history,FidelityArr,GF_sim,GF_exact=McEvolve(vqs_params,T,dT,0,exc_state, 'statevector')", "_____no_output_____" ], [ "# fig, ax = plt.subplots(dpi=160)\n# ax.set_title('t=30, dt=0.1, U=2')\n# T_arr\n# ax.plot(GF_sim, label = 'VQS - statevector', color = 'blue')\n# ax.plot(GF_exact, label = 'Exact', color = 'red')\n# plt.legend()\n# plt.show()", "_____no_output_____" ], [ "# # Spectral function plot\n# G_sim = GF_sim\n# G_exact = GF_exact\n# # Number of sample points\n# num_samp=len(G_sim)\n# # sample spacing\n# ImgG_1f = numpy.fft.fft(numpy.real(G_sim))\n# ImgG_2f = numpy.fft.fft(numpy.real(G_exact))\n# plt.rcParams[\"figure.figsize\"] = (20,10)\n# Tf = numpy.linspace(0.0, 1//(2.0*dT), num_samp//2)\n# fig, ax = plt.subplots()\n# ax.set_xlabel(r'$\\omega$',fontsize=20)\n# ax.tick_params(labelsize=20)\n# ax.set_yscale('log')\n# ax.plot(Tf, 2.0/num_samp * numpy.abs(ImgG_1f[:num_samp//2])/numpy.pi,marker='s',color='b',linestyle='',label=r'$Im G_{VHS - statevector}^{1,2}(1,2,\\omega)$')\n# ax.plot(-Tf, 2.0/num_samp * numpy.abs(ImgG_1f[:num_samp//2])/numpy.pi,marker='s',color='b',linestyle='')\n# ax.plot(Tf, 2.0/num_samp * numpy.abs(ImgG_2f[:num_samp//2])/numpy.pi,color='r',linestyle='-',label=r'$Im G_{exact}^{1,2}(1,2,\\omega)$')\n# ax.plot(-Tf, 2.0/num_samp * numpy.abs(ImgG_2f[:num_samp//2])/numpy.pi,color='r',linestyle='-')\n# plt.legend(fontsize=15)\n# plt.show()", "_____no_output_____" ] ], [ [ "Find a circuit rep of U(theta) such that\n$U(\\theta)|G\\rangle \\approx e^{-iHT}|G\\rangle$ and $U(\\theta)|E\\rangle \\approx e^{-iHT}|E\\rangle$.<br>\n$U(\\theta)|G\\rangle \\approx e^{-iHT}|G\\rangle\\to M_{1}\\dot{\\theta}=V_{1}$, $U(\\theta)|G\\rangle \\approx e^{-iHT}|E\\rangle\\to M_{2}\\dot{\\theta}=V_{2}$<br>\nMap this to a quadratic optimization problem<br>\n$(\\dot{\\boldsymbol{\\theta}}^{T}M_{1}^{T}-V_{1}^{T})(M_{1}\\dot{\\boldsymbol{\\theta}}-V_{1})=\\dot{\\boldsymbol{\\theta}}^{T}M_{1}^{T}M_{1}\\dot{\\boldsymbol{\\theta}}-\\dot{\\boldsymbol{\\theta}}^{T}M_{1}^{T}V_{1}-V^{T}_{1}M_{1}\\dot{\\boldsymbol{\\theta}}+V_{1}^{T}V_{1}\\propto \\frac{1}{2}\\dot{\\boldsymbol{\\theta}}^{T}M_{1}^{T}M_{1}\\dot{\\boldsymbol{\\theta}}-(M_{1}^{T}V_{1})^{T}\\dot{\\boldsymbol{\\theta}}$<br>\n$(\\dot{\\boldsymbol{\\theta}}^{T}M_{1}^{T}-V_{1}^{T})(M_{1}\\dot{\\boldsymbol{\\theta}}-V_{1})+(\\dot{\\boldsymbol{\\theta}}^{T}M_{2}^{T}-V_{2}^{T})(M_{2}\\dot{\\boldsymbol{\\theta}}-V_{2})\\propto\\frac{1}{2}\\dot{\\boldsymbol{\\theta}}^{T}(M_{1}^{T}M_{1}+M_{2}^{T}M_{2})\\dot{\\boldsymbol{\\theta}}-\\left[(M_{1}^{T}V_{1})^{T}+(M_{2}^{T}V_{2})^{T}\\right]\\dot{\\boldsymbol{\\theta}}$<br>\nCost Function<br>\n$Cost=\\frac{1}{2}\\dot{\\boldsymbol{\\theta}}^{T}(M_{1}^{T}M_{1}+M_{2}^{T}M_{2})\\dot{\\boldsymbol{\\theta}}-\\left[(M_{1}^{T}V_{1})^{T}+(M_{2}^{T}V_{2})^{T}\\right]\\dot{\\boldsymbol{\\theta}}$\n<br>\n$P=(M_{1}^{T}M_{1}+M_{2}^{T}M_{2})+\\alpha$, $\\alpha= $Tikhonov Regularization<br>\n$q=M^{T}V$<br>\n$f=1/2x^TPx+q^{T}x$, $x=\\dot{\\theta}$", "_____no_output_____" ] ], [ [ "def JointCost(M1, V1, M2, V2, alpha):\n #f=1/2 {x^T} Px + q^{T}x\n #Gx<=h\n #Ax=b\n P = M1.T@M1 + M2.T@M2 + alpha * np.eye(len(V1))\n q = M1.T@V1 + M2.T@V2\n# thetaDot = numpy.linalg.lstsq(M1, V1, rcond=None)[0]\n thetaDot = solve_qp(P, -q)\n return thetaDot\n\nerror_list = []\nresidual_list = []\n\ndef McEvolveJointOptimization(vqs_params_init, T, dT, T0, state1,state2, way, alpha):\n steps = int((T-T0)/dT) + 1\n T_arr = numpy.linspace(T0, T, steps)\n vqs_params = vqs_params_init\n vqs_dot_hist = []\n vqs_hist = [vqs_params]\n FidelityArr = []\n \n for i in tqdm(range(len(T_arr))):\n \n # compute exact state\n U_T = TimeEvolutionOperator(T_arr[i])\n exact_evolved_state1 = U_T@state1\n exact_evolved_state2 = U_T@state2\n\n # compute simulated state\n vqs_state1 = rotated_state(vqs_generators,vqs_hist[-1], state1)\n vqs_state2 = rotated_state(vqs_generators,vqs_hist[-1], state2)\n\n # compute fidelity\n FidelityArr.append([np.abs([email protected](exact_evolved_state1))**2, np.abs([email protected](exact_evolved_state2))**2])\n print(\"Fidelity\",FidelityArr[-1]) \n \n #constructing McLachlan\n arr = [(j,k) for j in range(len(vqs_params)) for k in range(len(vqs_params)) if j <= k]\n M1 = numpy.zeros((len(vqs_params),len(vqs_params)))\n M2 = numpy.zeros((len(vqs_params),len(vqs_params)))\n\n # Anirban's way\n if way == 'Anirban':\n M_elems1 = Parallel(n_jobs=-1,verbose=0)(delayed(M)(arr[i][0],arr[i][1],vqs_params,state1) for i in range(len(arr)))\n M_elems2 = Parallel(n_jobs=-1,verbose=0)(delayed(M)(arr[i][0],arr[i][1],vqs_params,state2) for i in range(len(arr)))\n V1 = numpy.array([V(p,vqs_params,state1) for p in range(len(vqs_params))])\n V2 = numpy.array([V(p,vqs_params,state2) for p in range(len(vqs_params))])\n \n # Statevector way\n if way == 'statevector':\n M_elems1 = Parallel(n_jobs=-1)(delayed(calculate_m_statevector)(arr[i][0], arr[i][1], vqs_generators, vqs_params, 'state1') for i in range(len(arr))) \n M_elems2 = Parallel(n_jobs=-1)(delayed(calculate_m_statevector)(arr[i][0], arr[i][1], vqs_generators, vqs_params, 'state2') for i in range(len(arr))) \n V1 = Parallel(n_jobs=-1)(delayed(calculate_v_statevector)(p, vqs_generators, vqs_params, 'state1') for p in range(len(vqs_params)))\n V2 = Parallel(n_jobs=-1)(delayed(calculate_v_statevector)(p, vqs_generators, vqs_params, 'state2') for p in range(len(vqs_params)))\n \n # Shots way\n if way == 'shots':\n shots = 2**17\n M_elems1 = Parallel(n_jobs=-1)(delayed(calculate_m_shots)(arr[i][0], arr[i][1], vqs_generators, vqs_params, shots, 'state1') for i in range(len(arr))) \n M_elems2 = Parallel(n_jobs=-1)(delayed(calculate_m_shots)(arr[i][0], arr[i][1], vqs_generators, vqs_params, shots, 'state2') for i in range(len(arr))) \n V1 = Parallel(n_jobs=-1)(delayed(calculate_v_shots)(p, vqs_generators, vqs_params, shots, 'state1') for p in range(len(vqs_params)))\n V2 = Parallel(n_jobs=-1)(delayed(calculate_v_shots)(p, vqs_generators, vqs_params, shots, 'state2') for p in range(len(vqs_params)))\n \n \n for p in range(len(arr)):\n M1[arr[p][0]][arr[p][1]] = M1[arr[p][1]][arr[p][0]] = M_elems1[p]\n M2[arr[p][0]][arr[p][1]] = M2[arr[p][1]][arr[p][0]] = M_elems2[p]\n \n vqs_params_dot = JointCost(np.array(M1), np.array(V1), np.array(M2), np.array(V2), alpha) \n vqs_dot_hist.append(vqs_params_dot)\n \n #Euler\n# vqs_params += vqs_dot_hist[-1]*dT\n \n #Complete Adams-Bashforth\n if i == 0:\n vqs_params = vqs_params + vqs_dot_hist[-1]*dT \n else:\n vqs_params = vqs_params + (3/2)*dT*vqs_dot_hist[-1]-(1/2)*dT*vqs_dot_hist[-2]\n \n vqs_hist.append(vqs_params)\n \n return vqs_hist,FidelityArr ", "_____no_output_____" ], [ "fidelities = []\n\nalpha = 0.001\ndepth = 2\nvqs_generators=['ZIZI','IZIZ','IIXX','IIYY','XXII','YYII','IIII'] * depth\nvqs_params=numpy.zeros(len(vqs_generators))\nT = 5\ndT = 0.1\noutside_vqs_hist, fidelity_list = McEvolveJointOptimization(vqs_params, T, dT, 0, adapt_state, exc_state, 'statevector', alpha)\nfidelities.append(fidelity_list)", "\r 0%| | 0/51 [00:00<?, ?it/s]" ], [ "colors = plt.cm.cividis(np.linspace(0, 1, len(fidelities)))\ncolors = np.flip(colors, axis=0)\nfig, ax = plt.subplots(dpi=160)\nax.set_xlabel('Time')\nax.set_ylabel('Fidelity')\nax.set_title(\"t=50, dt=0.1, depth = 2, averaged fidelity\")\n\nfor i in range(len(fidelities)):\n ax.plot(list(range(0,int(T/dT))), np.mean(fidelities[i], axis=1), label = 'alpha = ' + str(10**-i), color = colors[i])\nplt.legend()\nplt.show()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "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" ], [ "markdown" ], [ "code", "code", "code" ] ]
4afb696961a748687bcc04fb313632326c652e01
3,263
ipynb
Jupyter Notebook
notes/Chapter_2:_Functions/Item 21 Enforce Clarity with Keyword-Only Arguments.ipynb
johannstruongle/effective_python
da69221698ee0e21ecf8632baaeddf980cadd4fb
[ "MIT" ]
1
2019-04-11T21:01:38.000Z
2019-04-11T21:01:38.000Z
notes/Chapter_2:_Functions/Item 21 Enforce Clarity with Keyword-Only Arguments.ipynb
TruongLes/effective_python
da69221698ee0e21ecf8632baaeddf980cadd4fb
[ "MIT" ]
null
null
null
notes/Chapter_2:_Functions/Item 21 Enforce Clarity with Keyword-Only Arguments.ipynb
TruongLes/effective_python
da69221698ee0e21ecf8632baaeddf980cadd4fb
[ "MIT" ]
null
null
null
30.783019
812
0.58106
[ [ [ "# Item 21 Enforce Clarity with Keyword-Only Arguments", "_____no_output_____" ], [ "Sometimes it is good to enforce the user of your code to use keyword-only arugments. That's a way to force the user to actually think about what he is setting. ", "_____no_output_____" ] ], [ [ "# Example of how to use it (Python 3 example)\n\ndef fun(pos, *, keyword_only):\n print(pos, keyword_only)\nfun(1, 2)", "_____no_output_____" ], [ "fun(1, keyword_only=2)", "1 2\n" ] ], [ [ "With Python 2, you need to work with *args and * *kwargs", "_____no_output_____" ], [ "## Things to remember\n* Keyword arugments enhance readability and understanding of intention\n* Use keyword-oly to force caller to supply keyword arguments for potentially confusing functions\n* Python 3 has explicit syntax for that, python 2 needs a workaround with **kwargs", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
4afb6b3af19c2a95bd1dc5d5d5dd01dc710af386
320,933
ipynb
Jupyter Notebook
2.5 多因子策略和理论.ipynb
Yanie1asdfg/Quant-Lectures
4e4b84cf2aff290b715a7924277335a23f5e8168
[ "MIT" ]
6
2020-12-29T07:53:46.000Z
2022-01-17T07:07:54.000Z
2.5 多因子策略和理论.ipynb
Yanie1asdfg/Quant-Lectures
4e4b84cf2aff290b715a7924277335a23f5e8168
[ "MIT" ]
null
null
null
2.5 多因子策略和理论.ipynb
Yanie1asdfg/Quant-Lectures
4e4b84cf2aff290b715a7924277335a23f5e8168
[ "MIT" ]
4
2020-12-28T03:11:26.000Z
2021-02-09T06:12:51.000Z
3,343.052083
319,448
0.969386
[ [ [ "# 多因子选股策略", "_____no_output_____" ], [ "基本思想:", "_____no_output_____" ], [ "> 找到某些影响股票收益的因子,然后利用这些因子进行选股", "_____no_output_____" ], [ "特征:因子 \n目标值:股票收益 \n多因子就是数据指标", "_____no_output_____" ], [ "### 多因子的种类", "_____no_output_____" ], [ "![多因子.png](attachment:cc64697b-4a82-4b2e-854a-51958f27d6f0.png)", "_____no_output_____" ], [ "上百种因子", "_____no_output_____" ], [ "### 如何去寻找有价值的因子?", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4afb93817ffe065b067d6cc4e7c113901c0fe640
8,969
ipynb
Jupyter Notebook
malware-analysis/Malware-Analysis.ipynb
sAsPeCt488/blue-jupyter
d110cfd8a305a057f85af723a26380b5e707af6c
[ "MIT" ]
null
null
null
malware-analysis/Malware-Analysis.ipynb
sAsPeCt488/blue-jupyter
d110cfd8a305a057f85af723a26380b5e707af6c
[ "MIT" ]
null
null
null
malware-analysis/Malware-Analysis.ipynb
sAsPeCt488/blue-jupyter
d110cfd8a305a057f85af723a26380b5e707af6c
[ "MIT" ]
null
null
null
25.264789
283
0.566395
[ [ [ "# Malware Analysis & Triage Kit\nThis notebook performs the initial stages of immediate malware triage.\n\n## How To\nTake your malware specimen and drop it into the `dropbox` directory. The notebook will walk you through the stages of initial analysis.\n\nAt the end of this process, you will have a triage report in the `saved-specimens` directory. This report includes findings from initial triage, including the defanged specimen in a password-proteced Zip file and static analysis artifacts.", "_____no_output_____" ], [ "# Imports and Setup", "_____no_output_____" ] ], [ [ "# Imports\nfrom hashlib import *\nimport sys\nimport os\nfrom getpass import getpass\nfrom virus_total_apis import PublicApi as VirusTotalPublicApi\nimport json\nfrom MalwareSample import *\nfrom pprint import pprint\nimport os.path\nfrom time import sleep", "_____no_output_____" ] ], [ [ "### Check Dropbox and Saved-Specimens", "_____no_output_____" ] ], [ [ "MalwareSample.check_dir(\"dropbox\")\nMalwareSample.check_dir(\"saved-specimens\")\nempty = MalwareSample.is_dir_empty(\"dropbox\")\nif empty:\n print(r\" \\\\--> \" + recc + \"Put some samples in the dropbox!\")", "_____no_output_____" ] ], [ [ "### Enumerate Samples in the Dropbox", "_____no_output_____" ] ], [ [ "samples=!ls dropbox/*\nfor s in samples:\n print(info + \"Sample: \" + s)", "_____no_output_____" ], [ "sample_obj = [MalwareSample(s) for s in samples]", "_____no_output_____" ] ], [ [ "### Create a Saved Specimen directory for the specimen(s)", "_____no_output_____" ] ], [ [ "for obj in sample_obj:\n saved_sample_name = MalwareSample.create_specimen_dirs(obj.sample_name)\n obj.saved_sample_name = saved_sample_name", "_____no_output_____" ] ], [ [ "### Defang Sample", "_____no_output_____" ] ], [ [ "for obj in sample_obj:\n sample_path = MalwareSample.move_and_defang(obj.sample_name, obj.saved_sample_name)\n obj.sample_path = sample_path", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "## File Hashes", "_____no_output_____" ], [ "### SHA256 Sum", "_____no_output_____" ] ], [ [ "for obj in sample_obj:\n hash = MalwareSample.get_sha256sum(obj.sample_path, obj.saved_sample_name)\n obj.sha256sum = hash\n print(info + obj.sample_name + \": \" + obj.sha256sum)", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "## String Analysis", "_____no_output_____" ], [ "### StringSifter\nStringSifter is a FLARE developed tool that uses an ML model to rank a binary's strings by relevance to malware analysis.", "_____no_output_____" ] ], [ [ "length = int(input(recc + \"Input your desired minimum string length [default is 4, 6-8 is recommended] > \"))", "_____no_output_____" ], [ "for obj in sample_obj:\n MalwareSample.pull_strings(length, obj.saved_sample_name, obj.sample_path)", "_____no_output_____" ] ], [ [ "## VT Analysis\nSubmit samples to Virus Total and generate a malicious confidence level.", "_____no_output_____" ] ], [ [ "VT_API_KEY = getpass(\"Enter VirusTotal API Key (blank if none): \")", "_____no_output_____" ], [ "if VT_API_KEY:\n vt = VirusTotalPublicApi(VT_API_KEY)\nelse:\n print(info + \"No VT API Key. Skipping...\")", "_____no_output_____" ] ], [ [ "Note: If there are more than 4 samples in the dropbox, hashes are submitted with a sleep of 16 seconds to remain under the public API rate limit. So hit go, grab a beverage of choice, stretch out and relax. This could be a while depending on how many samples you're submitting.", "_____no_output_____" ] ], [ [ "if VT_API_KEY:\n for obj in sample_obj:\n print(info + obj.sample_name + \":\")\n print(r\" \\\\--> \" + info + \"SHA256sum: \" + obj.sha256sum)\n res = vt.get_file_report(obj.sha256sum)\n conf = malicious_confidence(res)\n print(r\" \\\\--> \" + info + \"Confidence level: \" + str(conf))\n crit_level = determine_criticality(conf)\n obj.criticality = crit_level\n \n\n if len(sample_obj) >= 5:\n sleep(16)\n \nelse:\n print(info + \"No VT API Key. Skipping...\")", "_____no_output_____" ] ], [ [ "## Zip and Password Protect", "_____no_output_____" ] ], [ [ "for obj in sample_obj:\n zip_file = MalwareSample.zip_and_password_protect(obj.sample_path, obj.saved_sample_name)\n MalwareSample.delete_unzipped_sample(obj.sample_path, zip_file)", "_____no_output_____" ] ], [ [ "---", "_____no_output_____" ], [ "### Debug Object Vars", "_____no_output_____" ] ], [ [ "for obj in sample_obj:\n pprint(vars(obj))", "_____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", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4afb98aedc34fced17a43ef2869265cf4ea3d87e
76,751
ipynb
Jupyter Notebook
notebooks/downscaling_pipeline/pull_cmip6_data_from_gcs.ipynb
brews/downscaleCMIP6
7ce377f50c5a1b9d554668efeb30e969dd6ede18
[ "MIT" ]
19
2020-10-31T11:37:10.000Z
2022-03-30T22:44:43.000Z
notebooks/downscaling_pipeline/pull_cmip6_data_from_gcs.ipynb
brews/downscaleCMIP6
7ce377f50c5a1b9d554668efeb30e969dd6ede18
[ "MIT" ]
413
2020-09-18T00:11:42.000Z
2022-03-30T22:42:49.000Z
notebooks/downscaling_pipeline/pull_cmip6_data_from_gcs.ipynb
brews/downscaleCMIP6
7ce377f50c5a1b9d554668efeb30e969dd6ede18
[ "MIT" ]
11
2021-01-28T01:05:10.000Z
2022-03-31T02:57:20.000Z
47.057633
3,184
0.499264
[ [ [ "import intake\nimport xarray as xr\nimport os \nimport pandas as pd\nimport numpy as np\nimport zarr \nimport rhg_compute_tools.kubernetes as rhgk", "_____no_output_____" ], [ "import warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "write_direc = '/gcs/rhg-data/climate/downscaled/workdir'", "_____no_output_____" ], [ "client, cluster = rhgk.get_standard_cluster()\ncluster", "_____no_output_____" ] ], [ [ "get some CMIP6 data from GCS", "_____no_output_____" ], [ "here we're going to get daily `tmax` from `IPSL` for historical and SSP370 runs. The ensemble member `r1i1p1f1` isn't available in GCS so we're using `r4i1p1f1` instead. \n\nNote that the `activity_id` for historical runs is `CMIP`, not `ScenarioMIP` as it is for the ssp-rcp scenarios. ", "_____no_output_____" ] ], [ [ "activity_id = 'ScenarioMIP'\nexperiment_id = 'ssp370'\ntable_id = 'day'\nvariable_id = 'tasmax'\nsource_id = 'IPSL-CM6A-LR'\ninstitution_id = 'NCAR'\nmember_id = 'r4i1p1f1'", "_____no_output_____" ] ], [ [ "first we'll take a look at what our options are", "_____no_output_____" ] ], [ [ "df_cmip6 = pd.read_csv('https://cmip6.storage.googleapis.com/cmip6-zarr-consolidated-stores-noQC.csv', dtype={'version': 'unicode'})\nlen(df_cmip6)", "_____no_output_____" ], [ "df_subset_future = df_cmip6.loc[(df_cmip6['activity_id'] == activity_id) & (df_cmip6['experiment_id'] == experiment_id) \n & (df_cmip6['table_id'] == table_id) & (df_cmip6['variable_id'] == variable_id)\n & (df_cmip6['source_id'] == source_id) & (df_cmip6['member_id'] == member_id)]", "_____no_output_____" ], [ "df_subset_future ", "_____no_output_____" ], [ "df_subset_hist = df_cmip6.loc[(df_cmip6['experiment_id'] == 'historical') \n & (df_cmip6['table_id'] == table_id) & (df_cmip6['variable_id'] == variable_id) \n & (df_cmip6['source_id'] == source_id) & (df_cmip6['member_id'] == member_id)]", "_____no_output_____" ], [ "df_subset_hist", "_____no_output_____" ] ], [ [ "now let's actually pull the data ", "_____no_output_____" ] ], [ [ "# search the cmip6 catalog\ncol = intake.open_esm_datastore(\"https://storage.googleapis.com/cmip6/pangeo-cmip6.json\")\n\ncat = col.search(activity_id=['CMIP', activity_id], \n experiment_id=['historical', experiment_id], table_id=table_id, variable_id=variable_id,\n source_id=source_id, member_id=member_id)", "_____no_output_____" ], [ "ds_model = {}\nds_model['historical'] = cat['CMIP.IPSL.IPSL-CM6A-LR.historical.day.gr'].to_dask().isel(member_id=0\n ).squeeze(drop=True).drop(['member_id', \n 'height',\n 'time_bounds'])", "_____no_output_____" ], [ "ds_model['ssp370'] = cat['ScenarioMIP.IPSL.IPSL-CM6A-LR.ssp370.day.gr'].to_dask().isel(member_id=0\n ).squeeze(drop=True).drop(['member_id',\n 'height',\n 'time_bounds'])", "_____no_output_____" ], [ "ds_model['historical']", "_____no_output_____" ] ], [ [ "rechunk in space for global bias correction ", "_____no_output_____" ] ], [ [ "chunks = {'lat': 10, 'lon': 10, 'time': -1}\n\nds_model['historical'] = ds_model['historical'].chunk(chunks)\nds_model['historical'] = ds_model['historical'].persist()\n\nds_model['historical'] = ds_model['historical'].load()\n\nds_model['ssp370'] = ds_model['ssp370'].chunk(chunks)\nds_model['ssp370'] = ds_model['ssp370'].persist()", "_____no_output_____" ], [ "ds_model['historical'].to_zarr(os.path.join(write_direc, 'cmip6_test_model_historical'), \n consolidated=True, compute=False, mode='w')", "_____no_output_____" ], [ "ds_test = xr.open_zarr(os.path.join(write_direc, 'cmip6_test_model_historical.zarr'))", "_____no_output_____" ], [ "ds_test", "_____no_output_____" ], [ "ds_test.info ", "_____no_output_____" ], [ "ds_model['historical'].to_zarr(os.path.join(write_direc, 'cmip6_test_model_historical'), mode='w')", "_____no_output_____" ], [ "ds_model['ssp370'].to_netcdf(os.path.join(write_direc, 'cmip6_test_model_ssp370.nc'))", "_____no_output_____" ] ], [ [ "read in the zarr stores and see how hard it is to rechunk them in time instead of space for computing weights", "_____no_output_____" ] ], [ [ "ds_hist = zarr.open(os.path.join(write_direc, 'cmip6_test_model_historical.zarr'), mode='r')", "_____no_output_____" ], [ "ds_hist", "_____no_output_____" ], [ "ds_hist.info", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4afb9d7456603266030d2512b50e2b48dc120993
6,877
ipynb
Jupyter Notebook
Pymaceuticals/pymaceuticals_starter.ipynb
spencerfox06/matplotlib-challenge
9907bc28c747c7cca3cffa45258d4e7a3fcc24c6
[ "ADSL" ]
null
null
null
Pymaceuticals/pymaceuticals_starter.ipynb
spencerfox06/matplotlib-challenge
9907bc28c747c7cca3cffa45258d4e7a3fcc24c6
[ "ADSL" ]
null
null
null
Pymaceuticals/pymaceuticals_starter.ipynb
spencerfox06/matplotlib-challenge
9907bc28c747c7cca3cffa45258d4e7a3fcc24c6
[ "ADSL" ]
null
null
null
23.391156
138
0.563763
[ [ [ "## Observations and Insights ", "_____no_output_____" ] ], [ [ "# Dependencies and Setup\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport scipy.stats as st\n\n# Study data files\nmouse_metadata_path = \"data/Mouse_metadata.csv\"\nstudy_results_path = \"data/Study_results.csv\"\n\n# Read the mouse data and the study results\nmouse_metadata = pd.read_csv(mouse_metadata_path)\nstudy_results = pd.read_csv(study_results_path)\n\n# Combine the data into a single dataset\n\n# Display the data table for preview\n", "_____no_output_____" ], [ "# Checking the number of mice.\n", "_____no_output_____" ], [ "# Getting the duplicate mice by ID number that shows up for Mouse ID and Timepoint. \n\n", "_____no_output_____" ], [ "# Optional: Get all the data for the duplicate mouse ID. \n\n", "_____no_output_____" ], [ "# Create a clean DataFrame by dropping the duplicate mouse by its ID.\n", "_____no_output_____" ], [ "# Checking the number of mice in the clean DataFrame.\n", "_____no_output_____" ] ], [ [ "## Summary Statistics", "_____no_output_____" ] ], [ [ "# Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen\n\n# Use groupby and summary statistical methods to calculate the following properties of each drug regimen: \n# mean, median, variance, standard deviation, and SEM of the tumor volume. \n# Assemble the resulting series into a single summary dataframe.\n\n", "_____no_output_____" ], [ "# Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen\n\n# Using the aggregation method, produce the same summary statistics in a single line\n", "_____no_output_____" ] ], [ [ "## Bar and Pie Charts", "_____no_output_____" ] ], [ [ "# Generate a bar plot showing the total number of measurements taken on each drug regimen using pandas.\n\n", "_____no_output_____" ], [ "# Generate a bar plot showing the total number of measurements taken on each drug regimen using pyplot.\n\n", "_____no_output_____" ], [ "# Generate a pie plot showing the distribution of female versus male mice using pandas\n\n", "_____no_output_____" ], [ "# Generate a pie plot showing the distribution of female versus male mice using pyplot\n\n", "_____no_output_____" ] ], [ [ "## Quartiles, Outliers and Boxplots", "_____no_output_____" ] ], [ [ "# Calculate the final tumor volume of each mouse across four of the treatment regimens: \n# Capomulin, Ramicane, Infubinol, and Ceftamin\n\n# Start by getting the last (greatest) timepoint for each mouse\n\n\n# Merge this group df with the original dataframe to get the tumor volume at the last timepoint\n", "_____no_output_____" ], [ "# Put treatments into a list for for loop (and later for plot labels)\n\n\n# Create empty list to fill with tumor vol data (for plotting)\n\n\n# Calculate the IQR and quantitatively determine if there are any potential outliers. \n\n \n # Locate the rows which contain mice on each drug and get the tumor volumes\n \n \n # add subset \n \n \n # Determine outliers using upper and lower bounds\n ", "_____no_output_____" ], [ "# Generate a box plot of the final tumor volume of each mouse across four regimens of interest\n", "_____no_output_____" ] ], [ [ "## Line and Scatter Plots", "_____no_output_____" ] ], [ [ "# Generate a line plot of tumor volume vs. time point for a mouse treated with Capomulin\n", "_____no_output_____" ], [ "# Generate a scatter plot of average tumor volume vs. mouse weight for the Capomulin regimen\n", "_____no_output_____" ] ], [ [ "## Correlation and Regression", "_____no_output_____" ] ], [ [ "# Calculate the correlation coefficient and linear regression model \n# for mouse weight and average tumor volume for the Capomulin regimen\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "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" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4afbaf6844546d6ff699db2cee344ee20308811d
54,985
ipynb
Jupyter Notebook
mining_gutenberg_for_relations.ipynb
kbooten/gymnasion
ffae3e95be1a0927bcbcbc90f690ee9c35ed9339
[ "MIT" ]
2
2018-01-07T02:37:34.000Z
2018-01-15T09:41:20.000Z
mining_gutenberg_for_relations.ipynb
kbooten/gymnasion
ffae3e95be1a0927bcbcbc90f690ee9c35ed9339
[ "MIT" ]
null
null
null
mining_gutenberg_for_relations.ipynb
kbooten/gymnasion
ffae3e95be1a0927bcbcbc90f690ee9c35ed9339
[ "MIT" ]
null
null
null
30.838474
837
0.440993
[ [ [ "# Gymnasion Data Processing\n\nHere I'm going to mine some chunk of Project Gutenberg texts for `(adj,noun)` and `(noun,verb,object)` relations using mostly SpaCy and textacy. Extracting them is easy. Filtering out the chaff is not so easy. ", "_____no_output_____" ] ], [ [ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-", "_____no_output_____" ], [ "from tqdm import tqdm\nimport json\nfrom collections import defaultdict\nfrom nltk import ngrams", "_____no_output_____" ], [ "from textacy import extract", "_____no_output_____" ], [ "import spacy\nnlp = spacy.load('en')", "_____no_output_____" ] ], [ [ "Load in some randomly chosen Gutenberg texts.", "_____no_output_____" ] ], [ [ "import os\ngb_files = [f for f in os.listdir(\"/Users/kyle/Documents/gutenberg_samples/\") if f.startswith('gb_')]", "_____no_output_____" ] ], [ [ "Define a function to extract `(adj,noun)` relations.", "_____no_output_____" ] ], [ [ "def extract_adj2nouns(tempspacy):\n \"\"\"\n For a sentence like \"I ate the small frog.\" returns [(small, frog)].\n lemmatizes the noun, lowers the adjective\n \"\"\"\n nouns = [\"NN\",\"NNS\"]\n adj_noun_tuples = []\n for token in tempspacy:\n if token.dep_==\"amod\":\n if token.head.tag_ in nouns:\n adj_noun_tuples.append((token.text.lower(),token.head.lemma_))\n return adj_noun_tuples\n \nextract_adj2nouns(nlp(u\"The small frogs were not the only ones there. The dog walked itself through the house.\"))", "_____no_output_____" ] ], [ [ "Textacy extracts `(s,v,o)` triples.", "_____no_output_____" ] ], [ [ "for triple in extract.subject_verb_object_triples(nlp(u\"The husband ignored his wife.\")):\n print triple", "(husband, ignored, wife)\n" ] ], [ [ "I want to loop through a bunch of Gutenberg texts that I've randomly downloaded with the Gutenberg python package. ", "_____no_output_____" ] ], [ [ "from langdetect import detect ## to make sure texts are english", "_____no_output_____" ], [ "from unidecode import unidecode ## to crudely deal with text encoding issues", "_____no_output_____" ], [ "noun2adj = defaultdict(list)\nnoun2object = defaultdict(list)", "_____no_output_____" ], [ "noun2adj_tuples = []\nsvo_triples = []\nerrors = 0\n\nfor fy in tqdm(gb_files[:1000]):\n with open(\"/Users/kyle/Documents/gutenberg_samples/\"+fy,'r') as f:\n tempdata = f.read()\n try:\n if detect(tempdata)==\"en\": ## check english\n tempspacy = nlp(tempdata.decode('utf-8'))\n\n ### adjectives\n try:\n for pair in extract_adj2nouns(tempspacy):\n noun2adj_tuples.append(pair)\n except:\n pass\n\n ### svo triples\n try:\n gutenberg_svo_triples = extract.subject_verb_object_triples(tempspacy)\n for trip in gutenberg_svo_triples:\n svo_triples.append(trip)\n except:\n pass\n except:\n errors+=1\n \n", "100%|██████████| 1000/1000 [1:14:54<00:00, 6.57s/it] \n" ] ], [ [ "How many pairs (not unique) do I have of `(adj,noun)` relations?", "_____no_output_____" ] ], [ [ "len(noun2adj_tuples)", "_____no_output_____" ] ], [ [ "Of `(s,v,o)` relations?", "_____no_output_____" ] ], [ [ "len(svo_triples)", "_____no_output_____" ] ], [ [ "## Inspecting the data so far...", "_____no_output_____" ], [ "### `(adj, noun)` relations", "_____no_output_____" ] ], [ [ "import random", "_____no_output_____" ], [ "random.sample(noun2adj_tuples,20)", "_____no_output_____" ] ], [ [ "Another way to inspect data: frequency distributions.", "_____no_output_____" ] ], [ [ "from nltk import FreqDist as fd", "_____no_output_____" ], [ "ADJ_noun_fd = fd([a for a,n in noun2adj_tuples])\nadj_NOUN_fd = fd([n for a,n in noun2adj_tuples])", "_____no_output_____" ], [ "ADJ_noun_fd.most_common(40)", "_____no_output_____" ], [ "adj_NOUN_fd.most_common(40)", "_____no_output_____" ] ], [ [ "#### Ideas...\n\nSo there are really two problems. Looking at the frequency distribution tells me that some of the most common adjectives (e.g. \"few\", \"other\")) are undesirable, because they aren't closely tied to a noun. That leaves are `green` is better to know than that leaves can be `other`. (Also, certain common nouns are probably not as interesting, especially ones like `other`). I have two intuitions: 1) really common relationships between adjectives and nouns are less interesting/desirable than less common ones, and 2) at the same time, I really don't want `(adj,noun)` pairs that are totally aberrant. Regarding the second point, I could filter out any adjective that doesn't occur at least `n` in modification of a certain noun, but that really penalizes uncommon nouns (which won't have many adjectives modifying them).\n\nMy plan:\n\n1. Filter out relations containing the most adjectives as well as a handful of annoying nouns\n2. Filter out those relations between words that are not strongly related according to a word2vec model", "_____no_output_____" ], [ "A handmade list of nouns to exclude.", "_____no_output_____" ] ], [ [ "ADJS_nouns_to_exclude = [word for word,count in ADJ_noun_fd.most_common(40)]", "_____no_output_____" ], [ "print ADJS_nouns_to_exclude", "[u'great', u'other', u'little', u'old', u'good', u'own', u'first', u'many', u'same', u'such', u'young', u'new', u'long', u'few', u'last', u'small', u'whole', u'large', u'more', u'white', u'several', u'much', u'next', u'certain', u'poor', u'black', u'high', u'human', u'full', u'different', u'only', u'general', u'best', u'second', u'big', u'present', u'public', u'short', u'various', u'very']\n" ], [ "from nltk.corpus import stopwords\nstops = stopwords.words('english')", "_____no_output_____" ], [ "stops = stops + [\"whose\",\"less\",\"thee\",\"thine\",\"thy\",\"thou\",\"one\"] ##adjectives nouns\nstops = stops + [\"time\",\"thing\",\"one\",\"way\",\"part\",\"something\"] ##annoying nouns", "_____no_output_____" ], [ "noun2adj = defaultdict(list)\nfor a,n in noun2adj_tuples:\n if n not in stops:\n if (a not in ADJS_nouns_to_exclude) and (a not in stops):\n noun2adj[n].append(a)", "_____no_output_____" ], [ "import gensim\nword2vec_path = \"/Users/kyle/Desktop/GoogleNews-vectors-negative300.bin\"\nmodel = gensim.models.KeyedVectors.load_word2vec_format(word2vec_path, binary=True)", "Using Theano backend.\n" ] ], [ [ "Below I define a pretty confusing loop to go through the dictionary I just made to filter out those words that `(adj,noun)` pairs that are unrelated according to a word2vec model. (Here I'm using just cosine similarity but I could probably maybe just measure the probability of the text according to the model.)", "_____no_output_____" ] ], [ [ "new_noun2adj = defaultdict(list)\n\nfor k in tqdm(noun2adj.keys()):\n adjs = []\n for adj in noun2adj[k]:\n try:\n adjs.append((adj,model.similarity(adj,k)))\n except:\n pass\n adjs.sort(key = lambda x: x[1], reverse=True)\n adjs_ = []\n for a,score in adjs:\n if a not in adjs_:\n adjs_.append(a)\n \n ## this is some weird hand-crafted logic to filter adjectives belonging to rare and common nouns differently...\n ## the idea is to only take the cream of the crop when there are a lot of options --- i.e. when the noun is common\n if len(adjs_)>20:\n for adj in adjs_[:10]:\n new_noun2adj[k].append(adj)\n elif len(adjs_)>10:\n for adj in adjs_[:10]:\n new_noun2adj[k].append(adj)\n elif len(adjs_)>2:\n adj = adjs_[0]\n new_noun2adj[k].append(adj)\n else:\n pass", "100%|██████████| 34122/34122 [00:47<00:00, 724.92it/s] \n" ], [ "new_noun2adj['hat']", "_____no_output_____" ], [ "with open(\"data/noun2adj.json\",\"w\") as f:\n json.dump(new_noun2adj,f)", "_____no_output_____" ] ], [ [ "### `(s,v,o)` triples...", "_____no_output_____" ] ], [ [ "svo_triples_reformatted = [(s.lemma_,v.lemma_,o.text) for s,v,o, in svo_triples]", "_____no_output_____" ] ], [ [ "Inspect data.", "_____no_output_____" ] ], [ [ "random.sample(svo_triples_reformatted,20)", "_____no_output_____" ], [ "Svo_fd = fd([s for s,v,o in svo_triples_reformatted])\nsVo_fd = fd([v for s,v,o in svo_triples_reformatted])\nsvO_fd = fd([o for s,v,o, in svo_triples_reformatted])", "_____no_output_____" ], [ "topS = [word for word,count in Svo_fd.most_common(40)]\nprint topS", "[u'-PRON-', u'there', u'who', u'which', u'that', u'this', u'man', u'one', u'what', u'people', u'god', u'woman', u'father', u'all', u'boy', u'be', u'mother', u'some', u'thing', u'girl', u'king', u'other', u'thou', u'child', u'these', u'friend', u'name', u'\"', u'eye', u'word', u'nothing', u'person', u'have', u'lady', u'many', u'those', u'wife', u'son', u'face', u'life']\n" ], [ "topV = [word for word,count in sVo_fd.most_common(40)]\nprint topV", "[u'be', u'have', u'give', u'take', u'seem', u'make', u'see', u'tell', u'know', u'have be', u'begin', u'say', u'find', u'want', u'call', u'leave', u'do', u'get', u'bring', u'hear', u'ask', u'become', u'show', u'send', u'come', u'keep', u'use', u'love', u'put', u'ought', u'hold', u'go', u'appear', u'wish', u'be not', u'would be', u'feel', u'reach', u'try', u'mean']\n" ], [ "topO = [word for word,count in svO_fd.most_common(40)]\nprint topO", "[u'him', u'it', u'me', u'you', u'them', u'her', u'to be', u'one', u'us', u'nothing', u'that', u'man', u'himself', u'more', u'something', u'way', u'place', u'time', u'thing', u'to', u'to do', u'all', u'this', u'anything', u'head', u'to see', u'to go', u'to make', u'to have', u'hand', u'themselves', u'to say', u'things', u'part', u'men', u'eyes', u'name', u'life', u'to take', u'herself']\n" ] ], [ [ "The loop below filters out an `(s,v,o)` triple if any one of its elements meets certain exclusionary conditions.", "_____no_output_____" ] ], [ [ "svo_triples_filtered = []\n\nfor s,v,o, in svo_triples_reformatted:\n Sval,Vval,Oval=False,False,False\n if len(s.split())==1: ## make sure it's not a complicated noun chunk\n if s.lower() not in stops: ## make sure it's not a stopword\n Sval=True\n if v not in topV: ## make sure it's not really common\n if len(v.split())==1: ## make sure it's not a complicated verb chunk\n if v.lower() not in stops: ## make sure it's not a stopwords\n Vval=True \n if len(o.split())==1: ### make sure it's not a complicated noun chunk\n if o.lower() not in stops: ### make sure it's not a stopword\n if o.lower()==o: ## this is kind of a hack to exclude proper nouns\n if o.endswith(\"ing\")==False: ## filter out annoying present participles\n Oval=True\n if (Sval,Vval,Oval)==(True,True,True):\n svo_triples_filtered.append((s,v,o))", "_____no_output_____" ], [ "noun2v_o = defaultdict(list)\nfor s,v,o in svo_triples_filtered:\n noun2v_o[s].append((v,o))", "_____no_output_____" ], [ "noun2v_o[\"king\"]", "_____no_output_____" ] ], [ [ "Again, filter out those `(s,v,o)` combinations in which the `v` and `o` are not similar according to word2vec model.", "_____no_output_____" ] ], [ [ "new_noun2v_o = defaultdict(list)\n\nfor k in tqdm(noun2v_o.keys()):\n vos = []\n for verb,obj in noun2v_o[k]:\n try:\n vos.append((verb,obj,model.similarity(obj,verb)))\n except:\n pass\n vos.sort(key = lambda x: x[2], reverse=True)\n \n ##again, logic to handle rare and common nouns differently\n if len(vos)>20:\n for verb,obj,value in vos[:10]:\n new_noun2v_o[k].append((verb,obj))\n elif len(vos)>10:\n for verb,obj,value in vos[:5]:\n new_noun2v_o[k].append((verb,obj))\n elif len(vos)>2:\n verb,obj,value = vos[0]\n new_noun2v_o[k].append((verb,obj))\n else:\n pass", "100%|██████████| 23431/23431 [00:11<00:00, 2037.84it/s]\n" ], [ "new_noun2v_o[\"seed\"]", "_____no_output_____" ], [ "with open(\"data/noun2v_o.json\",\"w\") as f:\n json.dump(new_noun2v_o,f)", "_____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", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4afbb6051f23e8f256463d1ba019a269106385b0
4,560
ipynb
Jupyter Notebook
playbook/tactics/execution/T1129.ipynb
haresudhan/The-AtomicPlaybook
447b1d6bca7c3750c5a58112634f6bac31aff436
[ "MIT" ]
8
2021-05-25T15:25:31.000Z
2021-11-08T07:14:45.000Z
playbook/tactics/execution/T1129.ipynb
haresudhan/The-AtomicPlaybook
447b1d6bca7c3750c5a58112634f6bac31aff436
[ "MIT" ]
1
2021-08-23T17:38:02.000Z
2021-10-12T06:58:19.000Z
playbook/tactics/execution/T1129.ipynb
haresudhan/The-AtomicPlaybook
447b1d6bca7c3750c5a58112634f6bac31aff436
[ "MIT" ]
2
2021-05-29T20:24:24.000Z
2021-08-05T23:44:12.000Z
87.692308
1,498
0.75
[ [ [ "# T1129 - Shared Modules\nAdversaries may abuse shared modules to execute malicious payloads. The Windows module loader can be instructed to load DLLs from arbitrary local paths and arbitrary Universal Naming Convention (UNC) network paths. This functionality resides in NTDLL.dll and is part of the Windows [Native API](https://attack.mitre.org/techniques/T1106) which is called from functions like <code>CreateProcess</code>, <code>LoadLibrary</code>, etc. of the Win32 API. (Citation: Wikipedia Windows Library Files)\n\nThe module loader can load DLLs:\n\n* via specification of the (fully-qualified or relative) DLL pathname in the IMPORT directory;\n \n* via EXPORT forwarded to another DLL, specified with (fully-qualified or relative) pathname (but without extension);\n \n* via an NTFS junction or symlink program.exe.local with the fully-qualified or relative pathname of a directory containing the DLLs specified in the IMPORT directory or forwarded EXPORTs;\n \n* via <code>&#x3c;file name=\"filename.extension\" loadFrom=\"fully-qualified or relative pathname\"&#x3e;</code> in an embedded or external \"application manifest\". The file name refers to an entry in the IMPORT directory or a forwarded EXPORT.\n\nAdversaries may use this functionality as a way to execute arbitrary code on a victim system. For example, malware may execute share modules to load additional components or features.", "_____no_output_____" ], [ "## Atomic Tests:\nCurrently, no tests are available for this technique.", "_____no_output_____" ], [ "## Detection\nMonitoring DLL module loads may generate a significant amount of data and may not be directly useful for defense unless collected under specific circumstances, since benign use of Windows modules load functions are common and may be difficult to distinguish from malicious behavior. Legitimate software will likely only need to load routine, bundled DLL modules or Windows system DLLs such that deviation from known module loads may be suspicious. Limiting DLL module loads to <code>%SystemRoot%</code> and <code>%ProgramFiles%</code> directories will protect against module loads from unsafe paths. \n\nCorrelation of other events with behavior surrounding module loads using API monitoring and suspicious DLLs written to disk will provide additional context to an event that may assist in determining if it is due to malicious behavior.", "_____no_output_____" ], [ "## Shield Active Defense\n### Software Manipulation \n Make changes to a system's software properties and functions to achieve a desired effect. \n\n Software Manipulation allows a defender to alter or replace elements of the operating system, file system, or any other software installed and executed on a system.\n#### Opportunity\nThere is an opportunity for the defender to observe the adversary and control what they can see, what effects they can have, and/or what data they can access.\n#### Use Case\nA defender can modify system calls to break communications, route things to decoy systems, prevent full execution, etc.\n#### Procedures\nHook the Win32 Sleep() function so that it always performs a Sleep(1) instead of the intended duration. This can increase the speed at which dynamic analysis can be performed when a normal malicious file sleeps for long periods before attempting additional capabilities.\nHook the Win32 NetUserChangePassword() and modify it such that the new password is different from the one provided. The data passed into the function is encrypted along with the modified new password, then logged so a defender can get alerted about the change as well as decrypt the new password for use.\nAlter the output of an adversary's profiling commands to make newly-built systems look like the operating system was installed months earlier.\nAlter the output of adversary recon commands to not show important assets, such as a file server containing sensitive data.", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ] ]
4afbc3834c4e4e7037962cdee89b556ae46f0586
7,202
ipynb
Jupyter Notebook
singlepoint.ipynb
arminsalmasi/tc_python
0f1b5194bdf2a73cead490532eecd1b7da0823e9
[ "MIT" ]
null
null
null
singlepoint.ipynb
arminsalmasi/tc_python
0f1b5194bdf2a73cead490532eecd1b7da0823e9
[ "MIT" ]
null
null
null
singlepoint.ipynb
arminsalmasi/tc_python
0f1b5194bdf2a73cead490532eecd1b7da0823e9
[ "MIT" ]
null
null
null
38.308511
135
0.527492
[ [ [ "from tc_python import *\nimport itertools as itertool\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "def singlePoint(database=[\"tcfe9\"],T=[273],P=[1e5],components=[\"fe\",\"c\"],phases=[\"bcc\"],mole_fractions=[99.02,0.08]):\n \"\"\"\n Single point equilibrium calculations\n \n ## input: \n database name: [string],\n Temperature float,\n Pressure float,\n elements: [string], \n phases [string], if empty all phases from the database are included\n mole fractions [float]\n \n ## output: dictionary {\"nps\",\"vs\",\"ws\",\"xiphs\",\"ys\", \"acs\",\"mus\" }\n stable_phases: [string],\n npms: phase fractions [float],\n vpvs: volume fractions of phases [float], \n ws: weight fractions of elements [float],\n xiphs: mole fractions of elements in phases [float],\n ys: y fractions of elements is phases [float], \n bineries: binary list of all elements and stable phases [tuple (component,phase)]\n acs: activities of elements with respect to all phases \n mus: chemical potentials of all components\n \"\"\"\n with TCPython() as start:\n if not phases:\n system_int = start.select_database_and_elements(database,components)\n else: \n system_int = start.select_database_and_elements(database,components).without_default_phases()\n for phase in phases:\n system_int.select_phase(phase)\n system = system_int.get_system()\n ticc=time.time()\n calc = system.with_single_equilibrium_calculation()\n for i in range(len(components)-1):\n calc.set_condition(ThermodynamicQuantity.mole_fraction_of_a_component((components[i])), mole_fractions[i])\n calc.set_condition(ThermodynamicQuantity.temperature(), 1723.15)\n calc.set_condition(ThermodynamicQuantity.pressure(), 1e5)\n calc_res = calc.calculate()\n \n stable_phases = calc_res.get_stable_phases()\n volume_fractions,phase_fractions,weight_fractions,xs_in_phases,ys_in_phases,activities,chemical_potentials = \\\n [],[],[],[],[],[],[]\n for phase in stable_phases:\n volume_fractions.append(calc_res.get_value_of('vpv({})'.format(phase))) \n phase_fractions.append(calc_res.get_value_of('npm({})'.format(phase)))\n for element in components:\n weight_fractions.append(calc_res.get_value_of('w({})'.format(element)))\n chemical_potentials.append(calc_res.get_value_of('mu({})'.format(element)))\n binarys = list(itertool.product(stable_phases, components))\n for binary in binarys:\n xs_in_phases.append(calc_res.get_value_of('x({},{})'.format(binary[0], binary[1])))\n try:\n ys_in_phases.append(calc_res.get_value_of('y({},{})'.format(binary[0], binary[1])))\n except Exception as error:\n a=1\n #ys_in_phases.append(-1)\n try:\n activities.append(calc_res.get_value_of('ac({},{})'.format(binary[1], binary[0]))) \n except Exception as error:\n a=1\n #ys_in_phases.append(-1)\n tocc=time.time()\n print(tocc-ticc)\n return {\"stable_phases\":stable_phases,\"npms\":phase_fractions, \\\n \"vpvs\":volume_fractions,\"ws\":weight_fractions,\"xiphs\":xs_in_phases, \\\n \"ys\":ys_in_phases,\"acs\":activities,\"mus\":chemical_potentials,\"binaries\":binarys}", "_____no_output_____" ], [ "help(singlePoint)", "Help on function singlePoint in module __main__:\n\nsinglePoint(database=['tcfe9'], T=[273], P=[100000.0], components=['fe', 'c'], phases=['bcc'], mole_fractions=[99.02, 0.08])\n Single point equilibrium calculations\n \n ## input: \n database name: [string],\n Temperature float,\n Pressure float,\n elements: [string], \n phases [string], if empty all phases from the database are included\n mole fractions [float]\n \n ## output: dictionary {\"nps\",\"vs\",\"ws\",\"xiphs\",\"ys\", \"acs\",\"mus\" }\n stable_phases: [string],\n npms: phase fractions [float],\n vpvs: volume fractions of phases [float], \n ws: weight fractions of elements [float],\n xiphs: mole fractions of elements in phases [float],\n ys: y fractions of elements is phases [float], \n bineries: binary list of all elements and stable phases [tuple (component,phase)]\n acs: activities of elements with respect to all phases \n mus: chemical potentials of all components\n\n" ], [ "database = \"TCFE8\"\nelements = [\"C\",\"Co\",\"N\",\"Ti\",\"W\"]\nphases = [\"liquid\", \"fcc\", \"mc_shp\", \"graphite\"]\nmole_fractions = [0.42943834995313096,0.1,0.019999999999999993,0.01999999999999999,0.4305616500468691]", "_____no_output_____" ], [ "tic=time.time()\na=singlePoint(database,1723, 1e5, elements,phases,mole_fractions)\ntoc = time.time()\nprint(toc-tic)", "0.18500900268554688\n18.717572450637817\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4afbd2a349f0f77aeab88af0cb9efe7dd85e883b
195,438
ipynb
Jupyter Notebook
assignment_3/MVA_DM3_WANG Yifan_CHU Xiao.ipynb
alanwang93/MVA_Probabilistic_Graphical_Models
3591312394114a2ae470b8aee8ece5171ec46d57
[ "Apache-2.0" ]
3
2019-02-23T16:34:51.000Z
2019-02-24T14:58:51.000Z
assignment_3/MVA_DM3_WANG Yifan_CHU Xiao.ipynb
alanwang93/MVA_Probabilistic_Graphical_Models
3591312394114a2ae470b8aee8ece5171ec46d57
[ "Apache-2.0" ]
null
null
null
assignment_3/MVA_DM3_WANG Yifan_CHU Xiao.ipynb
alanwang93/MVA_Probabilistic_Graphical_Models
3591312394114a2ae470b8aee8ece5171ec46d57
[ "Apache-2.0" ]
2
2018-12-05T23:21:35.000Z
2019-02-23T20:30:07.000Z
219.100897
57,032
0.878273
[ [ [ "# <center>Master M2 MVA 2017/2018 - Graphical models - HWK 3<center/>\n### <center>WANG Yifan && CHU Xiao<center/>", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom scipy.stats import multivariate_normal as norm\nimport warnings\nwarnings.filterwarnings(\"ignore\")", "_____no_output_____" ], [ "# Data loading\ndata_path = 'classification_data_HWK3/'\ntrain = np.loadtxt(data_path + 'EMGaussian.data')\ntest = np.loadtxt(data_path + 'EMGaussian.test')\nprint(train.shape, test.shape)", "(500, 2) (500, 2)\n" ], [ "plt.scatter(train[0:100,0], train[0:100,1])\nplt.show()", "_____no_output_____" ] ], [ [ "## Question 1\nThe code is implemented in class `HMM`, in function `gamma_` ( for $p(q_t |u_1 ,... , u_T )$) and `ksi_` ( for $p(q_t , q_{t+1} |u_1 ,..., u_T )$).", "_____no_output_____" ] ], [ [ "class HMM(object):\n def __init__(self, K, A, means, covs, pi):\n \"\"\"\n Args:\n K (int): number of states\n A: transition matrix A(u, q) = p(u|q)\n pi (K,1): prior p(q)\n means: means of guassian distributions\n covs: covariances of gaussian distributions\n \"\"\"\n self.K = K\n self.A = A\n self.pi = pi\n self.means = means\n self.covs = covs\n \n def p_(self, z, u):\n \"\"\" Gaussian emission probability ~ N(means, covs)\n Args: \n z: latent variable, 0...K-1\n u: observation\n \"\"\"\n return norm.pdf(u, self.means[z], self.covs[z])\n \n def emission_(self, u):\n \"\"\" Compute p(u|q=0...K-1)\n u: observation\n q: latent variable\n Return:\n proba (K, 1)\n \"\"\"\n eps = 1e-30\n proba = np.asarray([self.p_(z, u) for z in range(self.K)]).reshape(-1,1) + eps\n return proba\n \n def alpha(self, data):\n \"\"\" p(u_1...u_t, q_t)\n Return:\n alpha (K, T)\n logalpha (K, T)\n \"\"\"\n T = len(data)\n eps = 1e-30\n logalpha = np.zeros((self.K, T))\n logalpha[:, 0] = (np.log(self.emission_(data[0]) + eps) + np.log(self.pi) + eps).reshape(-1)\n for t in range(1, T):\n logalpha_max = logalpha[:, t-1].max()\n p = np.exp(logalpha[:, t-1] - logalpha_max).reshape(-1,1)\n logalpha[:, t] = (np.log(self.emission_(data[t]) + eps) \\\n + np.log(self.A.dot(p) + eps) + logalpha_max).reshape(-1)\n alpha = np.exp(logalpha)\n return alpha, logalpha\n \n \n def beta(self, data):\n \"\"\" p(u_{t+1}...u_T|q_t)\n Return:\n beta (K, T)\n logbeta (K, T)\n \"\"\"\n T = len(data)\n eps = 1e-30\n logbeta = np.zeros((self.K, T))\n logbeta[:, T-1] = (np.log(self.emission_(data[0]) + eps) + np.log(self.pi + eps)).reshape(-1)\n for t in range(1, T):\n t = T - t -1 # T-2 ... 0\n logbeta_max = logbeta[:, t+1].max()\n p = np.exp((logbeta[:, t+1] - logbeta_max).reshape(-1,1) + np.log(self.emission_(data[t+1]) + eps)).reshape(-1,1)\n logbeta[:, t] = (np.log(self.A.T.dot(p) + eps) + logbeta_max).reshape(-1)\n beta = np.exp(logbeta)\n return beta, logbeta\n \n def gamma_(self, data):\n \"\"\" Marginal posterior distribution of all latent variable q_t=0..T-1: p(q_t|U) \n Return: \n gamma (K, T)\n \"\"\"\n T = len(data)\n _, logalpha = self.alpha(data)\n _, logbeta = self.beta(data)\n gamma = np.zeros((self.K, T))\n for t in range(T):\n log_alpha_beta = logalpha[:,t] + logbeta[:,t]\n log_alpha_beta_max = np.max(log_alpha_beta)\n # p(q_t, U)\n p = np.exp(log_alpha_beta-log_alpha_beta_max)\n gamma[:, t] = p/np.sum(p)\n return gamma\n \n def ksi_(self, data):\n \"\"\" Joint posterior distribution of two successive latent variables: ksi[i,j] = p(q_t=i, q_t+1=j|U) \n Return: \n ksi (K, K, T-1)\n \"\"\"\n T = len(data)\n _, logalpha = self.alpha(data)\n _, logbeta = self.beta(data)\n ksi = np.zeros((self.K, self.K, T-1))\n log_ksi = np.zeros((self.K, self.K, T-1))\n for t in range(T-1):\n for i in range(self.K):\n for j in range(self.K):\n log_alpha_beta = logalpha[:, t] + logbeta[:, t]\n log_alpha_beta_max = log_alpha_beta.max()\n log_p = log_alpha_beta_max + np.log(np.sum(np.exp(log_alpha_beta - log_alpha_beta_max)))\n log_ksi[i, j, t] = -log_p + logalpha[i, t] + logbeta[j, t+1] + np.log(self.A[j, i]) \\\n + np.log(self.p_(j, data[t+1]))\n ksi[i, j, t] = np.exp(log_ksi[i, j, t])\n return ksi, log_ksi\n \n def smoothing(self, data):\n \"\"\" p(q_t|U) \n Return: \n gamma (K, T)\n \"\"\"\n return self.gamma_(data)\n \n\n def lower_bound(self, data):\n \"\"\"Compute lower bound of complete log likelihood\n \"\"\"\n ll = 0\n eps = 1e-30\n T = len(data)\n gamma = self.gamma_(data)\n ksi, _ = self.ksi_(data)\n \n ll += np.sum(gamma[:,0].reshape(-1,1) * np.log(self.pi + eps))\n for t in range(T-1):\n ll += np.sum(ksi[:,:,t].reshape(self.K, self.K).T * np.log(self.A + eps))\n for t in range(1, T):\n ll += np.sum(gamma[:,t].reshape(-1,1) * np.log(self.emission_(data[t]) + eps))\n return ll\n \n def log_likelihood(self, data):\n \"\"\" Compute the log likelihood of the observations\n \"\"\"\n T = len(data)\n _, logalpha = self.alpha(data)\n _, logbeta = self.beta(data)\n mx = (logalpha[:,0] + logbeta[:,0]).max()\n ll = np.log(np.sum([np.exp(logalpha[:,0] + logbeta[:,0] - mx) for i in range(self.K)])) + mx\n return ll\n \n \n def train(self, data, max_iter=100, verbal=True, validation=None):\n \"\"\"\n Args:\n data: (T, D), training data, D is the feature dimension\n max_iter: int, maximal number of iterations\n verbal: boolean, if True, print log likelyhood\n valdation: None or (T, D), if provided, its log likelyhood will be computed and returned\n Return:\n lls: list, log likelyhoods of training data\n lls_valid: list, log likelyhoods of validation dataset\n \"\"\"\n i = 0\n eps = 1e-4\n lls = [self.log_likelihood(data)]\n lls_valid = [] if validation is None else [self.log_likelihood(validation)]\n if verbal:\n print(\"\\tTrain log likelihood: {1}\".format(i, lls[0]))\n if validation is not None:\n print(\"\\tValid log likelihood: {0}\".format(lls_valid[0]))\n while i < max_iter:\n i += 1\n self.train_step(data)\n ll = self.log_likelihood(data)\n if len(lls) > 2 and (ll - lls[-1]) < eps:\n break\n lls.append(ll)\n if verbal:\n print(\"Iteration {0}:\\n\\tTrain log likelihood: {1}\".format(i, ll))\n if validation is not None:\n ll_valid = self.log_likelihood(validation)\n lls_valid.append(ll_valid)\n if verbal:\n print(\"\\tValid log likelihood: {0}\".format(ll_valid))\n return lls, lls_valid\n \n \n def train_step(self, data):\n \"\"\" Perform EM algorithm for one step\n Args:\n data: (T, D), training data, D is the feature dimension\n \"\"\"\n T = len(data)\n # E-step\n gamma = self.gamma_(data)\n ksi, _ = self.ksi_(data)\n # M-step\n self.pi = (gamma[:,0] / gamma[:,0].sum()).reshape(-1,1)\n for j in range(self.K):\n for k in range(self.K):\n self.A[k, j] = ksi[j, k, :].sum()/np.sum(ksi[j, :, :])\n for k in range(self.K):\n self.means[k] = gamma[k,:].dot(data)/gamma[k,:].sum() # (1,T)*(T,D) -> (1,D)\n self.covs[k] = np.sum([gamma[k,n]*(data[n]-self.means[k]).reshape(-1, 1).dot((data[n]-self.means[k]).reshape(1,-1)) for n in range(T)], 0)/gamma[k,:].sum()\n \n \n def decode(self, data):\n \"\"\" Viterbi algorithm (forward)\n Args:\n data: (T, D), training data, D is the feature dimension\n \"\"\"\n # Initialization\n T = len(data)\n eps = 1e-30\n maxProb = np.zeros((self.K, T))\n prev_state = np.zeros((self.K, T))\n # Find the index which can maximiser the tmp_proba\n for t in range(T):\n if (t==0):\n maxProb[:,0] = np.log(self.pi).reshape(-1)\n else:\n for i in range(self.K):\n tmp_proba = maxProb[:,t-1] + np.log(A[i,:].T + eps) + np.log(self.emission_(data[t-1]) + eps).reshape(-1)\n maxValue = np.max(tmp_proba)\n maxIndex = np.argmax(tmp_proba)\n maxProb[i,t] = maxValue\n prev_state[i,t] = maxIndex \n\n tmp_proba = np.log(maxProb[:,T-1]) + np.log(self.emission_(data[T-1]) + eps).reshape(-1)\n maxValue = np.max(tmp_proba)\n maxIndex = np.argmax(tmp_proba)\n # Find the best path\n state_index_path = np.zeros(T, dtype=int)\n state_index_path[T-1] = maxIndex;\n for t in range(T-2,-1,-1):\n state_index_path[t] = prev_state[state_index_path[t+1],t+1]\n \n# # Viterbi algorithm (backward)\n# T = len(data)\n# log_viterbi = np.zeros((self.K, T))\n# log_post_viterbi = np.zeros((self.K, T))\n# viterbi_path = np.zeros((self.K, T), dtype=int)\n# for t in range(T-1,-1,-1):\n# if t == T-1:\n# log_post_viterbi[:, t] = np.zeros(self.K)\n# else:\n# mxvalue = np.max(log_viterbi[:, t + 1])\n# p = np.exp(log_viterbi[:, t + 1] - mxvalue)\n# max_x = [np.max(A.T[i, :] * p) for i in range(self.K)]\n# viterbi_path[:, t] = [np.argmax(self.A.T[i, :] * p) for i in range(self.K)]\n# log_post_viterbi[:, t] = np.log(max_x) + mxvalue\n# log_viterbi[:, t] = log_post_viterbi[:, t] + np.log(self.emission_(data[t])).reshape(-1)\n\n# state_index_path = np.ones(T, dtype=int) * -1\n# z = np.argmax(log_viterbi[:, 0])\n# state_index_path[0] = z\n# for t in range(T - 1):\n# z = viterbi_path[z, t]\n# state_index_path[t+1] = z\n# return state_index_path\n return state_index_path\n", "_____no_output_____" ], [ "# GMM classifier\n\nclass GMM(object):\n def __init__(self, k, covariance_type='full'):\n self.k = k\n self.mus = None\n self.alpha2 = None\n self.sigmas = None\n self.resp = None\n self.pis = None\n self.clusters = {}\n self.labels = None\n self.label_history = []\n self.covariance_type = covariance_type\n \n def train(self, X, init=\"kmeans\"):\n n, d = X.shape\n centers = None\n # initialize\n if init == \"kmeans\":\n clf = KMeans(self.k)\n clf.train(X)\n self.mus = clf.centers\n self.labels = clf.labels\n self.pis = np.array([len(clf.clusters[i])/n for i in range(self.k)])\n if self.covariance_type == 'spherical':\n self.alpha2 = np.array([np.sum((np.array(clf.clusters[i]) - self.mus[i]) ** 2)/len(clf.clusters[i])/2. for i in range(self.k)])\n self.sigmas = np.array([self.alpha2[i] * np.eye(d) for i in range(self.k)])\n elif self.covariance_type == 'full':\n self.sigmas = np.array([np.cov(np.array(clf.clusters[k]).T) for k in range(self.k)])\n self.resp = np.zeros((self.k, n))\n for i in range(self.k):\n self.resp[i] = np.array(gamma(X, i, self.k, self.pis, self.mus, self.sigmas)) \n\n t = 0\n resp = self.resp.copy()\n pis = self.pis.copy()\n mus = self.mus.copy()\n if self.covariance_type == 'spherical':\n alpha2 = self.alpha2.copy()\n sigmas = self.sigmas.copy()\n while t < 30:\n t += 1\n # update\n for i in range(self.k):\n pis[i] = np.mean(self.resp[i])\n mus[i] = np.sum(X * self.resp[i][:, np.newaxis], 0)/np.sum(self.resp[i])\n if self.covariance_type == 'spherical':\n alpha2[i] = np.sum([(X[j] - self.mus[i]) ** 2 * self.resp[i,j] for j in range(n)])/np.sum(self.resp[i])/2.\n sigmas[i] = alpha2[i] * np.eye(d)\n elif self.covariance_type == 'full':\n sigmas[i] = np.sum([(X[j] - self.mus[i]).reshape(-1,1).dot((X[j] - self.mus[i]).reshape(1,-1)) * self.resp[i,j] for j in range(n)], 0)/np.sum(self.resp[i])\n for i in range(self.k):\n resp[i] = np.array(gamma(X, i, self.k, pis, mus, sigmas))\n self.resp = resp.copy()\n self.pis = pis.copy()\n self.mus = mus.copy()\n if self.covariance_type == 'spherical':\n self.alpha2 = alpha2.copy()\n self.sigmas = sigmas.copy()\n labels = np.zeros(n)\n for i in range(n):\n self.labels[i] = np.argmax(self.resp[:, i])\n \n def test(self, X):\n n, d = X.shape\n resp = np.zeros((self.k, n))\n for i in range(self.k):\n resp[i] = np.array(gamma(X, i, self.k, self.pis, self.mus, self.sigmas)) \n labels = np.zeros(n)\n for i in range(n):\n labels[i] = np.argmax(resp[:, i])\n return labels.astype(np.int32), resp\n \n def log_likelihood(self, X):\n n, d = X.shape\n _, resp = self.test(X)\n return np.sum([[resp[k,i] * np.log(self.pis[k] * norm.pdf(X[i], self.mus[k], self.sigmas[k])) for k in range(self.k)] for i in range(n)])\n \n \n# K-means classifier\n\nclass KMeans(object):\n def __init__(self, k):\n self.k = k\n self.centers = None\n self.clusters = {}\n self.labels = None\n self.inertia = None\n self.label_history = []\n \n def train(self, X, init=\"random\"):\n n = X.shape[0]\n centers = None\n # initialize\n if init == \"random\":\n self.centers = X[np.random.choice(n, self.k, replace=False)]\n elif init == 'kmeans++':\n # TODO: implement K-means++\n pass\n \n while (centers is None or np.abs(centers - self.centers).max() > 1e-5):\n # old centers\n centers = self.centers.copy()\n \n for i in range(self.k):\n self.clusters[i] = []\n labels = []\n for x in X:\n dis = np.sum((centers - x)**2, 1)\n label = np.argmin(dis)\n self.clusters[label].append(x)\n labels.append(label)\n self.labels = np.array(labels)\n self.label_history.append(self.labels)\n \n # new centers\n for i in range(self.k):\n self.centers[i] = np.mean(np.array(self.clusters[i]), 0) \n \ndef gamma(X, k, K, pis, mus, sigmas):\n \"\"\" Responsibilities\n \"\"\"\n return (pis[k]* norm.pdf(X, mus[k], sigmas[k]))/(np.sum([pis[i]* norm.pdf(X, mus[i], sigmas[i]) for i in range(K)], 0))", "_____no_output_____" ] ], [ [ "## Question 2\nRepresent $p(q_t |u_1 ,..., u_T )$ for each of the 4 states as a function of time for the 100 first data points in `EMGaussienne.test`.", "_____no_output_____" ] ], [ [ "A = np.diag([1./2 - 1./6]*4) + np.ones((4,4)) * 1./6\npi = np.ones((4,1))/4.\n# pre-train GMM\nclf = GMM(4, covariance_type='full')\nclf.train(test)\n# train HMM\nhmm = HMM(K=4, A=A, pi=pi, means=clf.mus, covs=clf.sigmas)", "_____no_output_____" ], [ "smoothing = hmm.smoothing(test)\nprint(smoothing.shape)", "(4, 500)\n" ], [ "for i in range(4):\n plt.scatter(range(100), smoothing[i, :100])\nplt.legend(['state 1', 'state 2', 'state 3', 'state 4'])\nplt.show()", "_____no_output_____" ] ], [ [ "## Question 3\nDerive the estimation equations of the EM algorithm.\n", "_____no_output_____" ], [ "## Question 4\nImplement the EM algorithm to learn the parameters of the model ($\\pi$, $A$, $\\mu_k$ , $\\Sigma_k$, $k = 1...4$). The means and covariances could be initialized with the ones obtained in the previous homework. Learn the model from the training data in“EMGaussienne.data”.\n", "_____no_output_____" ] ], [ [ "A = np.diag([1./2 - 1./6]*4) + np.ones((4,4)) * 1./6\npi = np.ones((4,1))/4.\nclf = GMM(4, covariance_type='full')\nclf.train(train)\n# train HMM\nhmm = HMM(K=4, A=A, pi=pi, means=clf.mus, covs=clf.sigmas)\nll, ll_valid = hmm.train(train, max_iter=20, verbal=True, validation=test)", "\tTrain log likelihood: -2303.3517562913344\n\tValid log likelihood: -2426.4932058164354\nIteration 1:\n\tTrain log likelihood: -1914.8263003513314\n\tValid log likelihood: -1978.5710222419336\nIteration 2:\n\tTrain log likelihood: -1900.7279063146755\n\tValid log likelihood: -1961.6284824594331\nIteration 3:\n\tTrain log likelihood: -1899.10218646958\n\tValid log likelihood: -1958.274752108972\nIteration 4:\n\tTrain log likelihood: -1898.896972517673\n\tValid log likelihood: -1957.1146329638389\nIteration 5:\n\tTrain log likelihood: -1898.8675874724195\n\tValid log likelihood: -1956.628536351202\nIteration 6:\n\tTrain log likelihood: -1898.8634074916206\n\tValid log likelihood: -1956.4391473903618\nIteration 7:\n\tTrain log likelihood: -1898.862829300888\n\tValid log likelihood: -1956.3681585928646\n" ] ], [ [ "## Question 5\nPlot the log-likelihood on the train data “EMGaussienne.data” and on the test data “EMGaussienne.test” as a function of the iterations of the algorithm. Comment.", "_____no_output_____" ] ], [ [ "plt.plot(ll)\nplt.plot(ll_valid)\nplt.legend(['EMGaussienne.data', 'EMGaussienne.test'])\nplt.title(\"Log-likelihood on train and test data\")\nplt.xlabel(\"iteration\")\nplt.ylabel(\"log-likelihood\")\nplt.show()", "_____no_output_____" ] ], [ [ "## Question 6\nReturn in a table the values of the log-likelihoods of the Gaussian mixture models and of the HMM on the train and on the test data. ", "_____no_output_____" ] ], [ [ "# GMM\nprint(\"GMM-train:\", clf.log_likelihood(train))\nprint(\"GMM-test:\", clf.log_likelihood(test))\n\n# HMM\nprint(\"HMM-train:\", hmm.log_likelihood(train))\nprint(\"HMM-test:\", hmm.log_likelihood(test))", "GMM-train: -2373.00003677\nGMM-test: -2453.46384428\nHMM-train: -1898.86275178\nHMM-test: -1956.34194126\n" ] ], [ [ "### 8. Implement Viterbi decoding.", "_____no_output_____" ] ], [ [ "viterbi_path = hmm.decode(train)", "_____no_output_____" ], [ "plt.figure()\nplt.title(\"Most likely sequence of states (Viterbi algorithm)\")\nplt.scatter(train[:,0], train[:,1], c=viterbi_path)\nplt.scatter(hmm.means[:,0], hmm.means[:,1], color = \"red\")\nplt.show()", "_____no_output_____" ], [ "plt.figure()\nplt.title(\"Most likely sequence of states (Viterbi algorithm)\")\nplt.scatter(train[0:100,0], train[0:100,1], c=viterbi_path[0:100])\nplt.scatter(hmm.means[:,0], hmm.means[:,1], color = \"red\")\nplt.show()", "_____no_output_____" ] ], [ [ "### 9. For the datapoints in the test file “EMGaussienne.test”, compute the marginal probability p(qt|u_1, . . . , u_T) for each point to be in state {1,2,3,4} for the parameters learned on the training set.", "_____no_output_____" ] ], [ [ "gamma_test = hmm.smoothing(test)", "_____no_output_____" ], [ "plt.figure(figsize=(15,5))\nplt.title(\"The smoothing distribution (test file)\")\nplt.imshow(1-gamma_test[:,0:100], cmap=\"gray\",origin=\"lower\")\nplt.xlabel(\"T\")\nplt.ylabel(\"States\")\nplt.show()", "_____no_output_____" ] ], [ [ "### 10. For each of these same 100 points, compute their most likely state according to the marginal probability computed in the previous question.", "_____no_output_____" ] ], [ [ "state_smoothing = np.argmax(gamma_test, axis=0)", "_____no_output_____" ], [ "plt.figure(figsize=(12,3))\nplt.title(\"Most likely states (Smoothing distribution)\")\nplt.scatter(np.arange(100), state_smoothing[0:100]+1)\nplt.xlabel(\"T\")\nplt.ylabel(\"States\")\nplt.show()", "_____no_output_____" ] ], [ [ "### 11. Run Viterbi on the test data. Compare the most likely sequence of states obtained for the 100 first data points with the sequence of states obtained in the previous question.", "_____no_output_____" ] ], [ [ "viterbi_test = hmm.decode(test)", "_____no_output_____" ], [ "plt.figure(figsize=(12,3))\nplt.title(\"Most likely states (Viterbi algorithm)\")\nplt.scatter(np.arange(100), viterbi_test[0:100]+1)\nplt.xlabel(\"T\")\nplt.ylabel(\"States\")\nplt.show()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4afbe0738bd6d81987b944e8f5bfbde1fd3f1269
16,673
ipynb
Jupyter Notebook
P1.ipynb
lukadog/udacity-self-driving-lane-line
a411e01732dec5b06398e8a69fc24f21809ddd67
[ "MIT" ]
null
null
null
P1.ipynb
lukadog/udacity-self-driving-lane-line
a411e01732dec5b06398e8a69fc24f21809ddd67
[ "MIT" ]
null
null
null
P1.ipynb
lukadog/udacity-self-driving-lane-line
a411e01732dec5b06398e8a69fc24f21809ddd67
[ "MIT" ]
null
null
null
39.230588
522
0.597313
[ [ [ "# Self-Driving Car Engineer Nanodegree\n\n\n## Project: **Finding Lane Lines on the Road** \n***\nIn this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n\nOnce you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n\nIn addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n\n---\nLet's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n\n**Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n\n---", "_____no_output_____" ], [ "**The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**\n\n---\n\n<figure>\n <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n </figcaption>\n</figure>\n <p></p> \n<figure>\n <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n <figcaption>\n <p></p> \n <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n </figcaption>\n</figure>", "_____no_output_____" ], [ "## Build a Lane Finding Pipeline\n\n", "_____no_output_____" ], [ "Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n\nTry tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.", "_____no_output_____" ] ], [ [ "# Build pipeline that draws the detected lane lines on the original images\n\ndef process_image(image):\n \n # Mask the image with color selection filter \n color_filtered_image = color_selection(image)\n # Convert the RGB image to grayscale\n gray_image = grayscale(color_filtered_image)\n # Blur the image with Gaussian filter\n blurred_image = gaussian_blur(gray_image, kernel_size=15)\n # Extrct the edge using Canny edge filter\n edge_image = canny(blurred_image, low_threshold=50, high_threshold=150)\n # Return the coordinates of the vertices of ROI\n vertices = select_vertices(edge_image)\n # Mask the edge_image with ROI\n roi_image = region_of_interest(edge_image, vertices)\n # Detect the straight lines using the Hough transform\n lines = hough_lines(roi_image, rho=1, theta=np.pi/180, threshold=20, min_line_len = 20, max_line_gap = 300)\n # Merge the detected lines into two lines: left line and right line\n left_lane, right_lane = average_line(lines)\n # Detect the (x1,y1) , (x2, y2) points for each line and plot them on blank image\n lane_image = lane_points(image, left_lane, right_lane)\n # Overlay the lane line on the origin RGB image\n lane_image_scene = cv2.addWeighted(image, 1.0, lane_image, 0.50, 0.0)\n # return the overlay image\n return lane_image_scene", "_____no_output_____" ] ], [ [ "## Helper Functions", "_____no_output_____" ] ], [ [ "# Mask the pavement images with lane colors: yellow and white \ndef color_selection(img): \n # white color selection\n lower = np.uint8([200, 200, 200])\n upper = np.uint8([255, 255, 255])\n white_pixels = cv2.inRange(img, lower, upper)\n # yellow color selection\n lower = np.uint8([190, 190, 0])\n upper = np.uint8([255, 255, 255])\n yellow_pixels = cv2.inRange(img, lower, upper)\n # mask the image\n masked_pixels = cv2.bitwise_or(white_pixels, yellow_pixels)\n masked_image = cv2.bitwise_and(img, img, mask = masked_pixels)\n return masked_image", "_____no_output_____" ], [ "# Covert the RGB image into gray image\ndef grayscale(img):\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)", "_____no_output_____" ], [ "# Apply gaussian blur filter\ndef gaussian_blur(img, kernel_size):\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)", "_____no_output_____" ], [ "# Apply edge detection\ndef canny(img, low_threshold, high_threshold):\n return cv2.Canny(img, low_threshold, high_threshold)", "_____no_output_____" ], [ "# Mask region of interest\ndef region_of_interest(img, vertices):\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n# Select vertices for the mask\ndef select_vertices(img):\n # first, define the polygon by vertices\n rows, cols = img.shape[:2]\n bottom_left = [cols*0.1, rows*0.95]\n top_left = [cols*0.4, rows*0.6]\n bottom_right = [cols*0.9, rows*0.95]\n top_right = [cols*0.6, rows*0.6] \n # the vertices are an array of polygons (i.e array of arrays) and the data type must be integer\n vertices = np.array([[bottom_left, top_left, top_right, bottom_right]], dtype=np.int32)\n return vertices", "_____no_output_____" ], [ "# Apply Hough transform to detect the line\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n return lines\n\n# Draw lines on the image\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=2):\n for line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n ", "_____no_output_____" ], [ "# Merge the detected lines into two lines: left and right\ndef average_line(lines):\n left_lines = [] # (slope, intercept)\n left_weights = [] # (length,)\n right_lines = [] # (slope, intercept)\n right_weights = [] # (length,)\n \n for line in lines:\n for x1, y1, x2, y2 in line:\n if x2==x1:\n continue # ignore a vertical line\n slope = (float(y2)-float(y1))/(float(x2)-float(x1))\n intercept = y1 - slope*x1\n length = np.sqrt((y2-y1)**2+(x2-x1)**2)\n if slope < 0: # y is reversed in image\n left_lines.append((slope, intercept))\n left_weights.append((length))\n else:\n right_lines.append((slope, intercept))\n right_weights.append((length))\n \n # add more weight to longer lines \n left_lane = np.dot(left_weights, left_lines) /np.sum(left_weights) if len(left_weights) >0 else None\n right_lane = np.dot(right_weights, right_lines)/np.sum(right_weights) if len(right_weights)>0 else None\n # return two lanes in the format of slope and intercept\n return left_lane, right_lane \n\n# convert the y = mX +b to x1, y1, x2, y2\ndef make_line_points(y1, y2, line):\n\n if line is None:\n return None\n \n slope, intercept = line\n \n # make sure everything is integer as cv2.line requires it\n x1 = int((y1 - intercept)/slope)\n x2 = int((y2 - intercept)/slope)\n y1 = int(y1)\n y2 = int(y2)\n \n return ((x1, y1), (x2, y2))\n\n# Plot the lane line points\ndef lane_points(img, left_lane, right_lane):\n lane_image = np.zeros_like(image)\n \n y1 = img.shape[0] # bottom of the image\n y2 = y1*0.6 # slightly lower than the middle\n left_lane_points = make_line_points(y1, y2, left_lane)\n right_lane_points = make_line_points(y1, y2, right_lane)\n \n cv2.line(lane_image, left_lane_points[0], left_lane_points[1], color=[0, 255, 0], thickness=10)\n cv2.line(lane_image, right_lane_points[0], right_lane_points[1], color=[0, 255, 0], thickness=10)\n\n return lane_image\n ", "_____no_output_____" ] ], [ [ "## Test on Videos\n\nYou know what's cooler than drawing lanes over images? Drawing lanes over video!\n\nWe can test our solution on two provided videos:\n\n`solidWhiteRight.mp4`\n\n`solidYellowLeft.mp4`\n\n**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n\n**If you get an error that looks like this:**\n```\nNeedDownloadError: Need ffmpeg exe. \nYou can download it by calling: \nimageio.plugins.ffmpeg.download()\n```\n**Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.image as mpimg\nimport os\nimport cv2\nimport math\n\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\nout = cv2.VideoWriter('output.avi',fourcc, 15.0, (540, 960))\ncap = cv2.VideoCapture('test_videos/solidYellowLeft.mp4')\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n RGB_img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n processed_image = process_image(RGB_img)\n processed_image_RGB = cv2.cvtColor(processed_image, cv2.COLOR_BGR2RGB)\n out.write(processed_image_RGB)\n cv2.imshow('frame', processed_image_RGB)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\nout.release()\ncv2.destroyAllWindows()", "_____no_output_____" ], [ "def process_image(image):\n \n color_filtered_image = color_selection(image)\n gray_image = grayscale(color_filtered_image)\n blurred_image = gaussian_blur(gray_image, kernel_size=15)\n edge_image = canny(blurred_image, low_threshold=50, high_threshold=150)\n vertices = select_vertices(edge_image)\n roi_image = region_of_interest(edge_image, vertices)\n lines = hough_lines(roi_image, rho=1, theta=np.pi/180, threshold=20, min_line_len = 20, max_line_gap = 300)\n left_lane, right_lane = average_line(lines)\n lane_image = lane_points(image, left_lane, right_lane)\n lane_image_scene = cv2.addWeighted(image, 1.0, lane_image, 0.50, 0.0)\n\n return result", "_____no_output_____" ] ], [ [ "Let's try the one with the solid white lane on the right first ...", "_____no_output_____" ], [ "## Writeup and Submission\n\nIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) to the writeup template file.\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
4afbf891cb4c4917e9bed1e2a323d503de75f762
91,810
ipynb
Jupyter Notebook
docs/Demo1_OceanDataset.ipynb
rabernat/oceanspy
9bd58f8529cb0fa865393c057ad7498e4f99681d
[ "MIT" ]
null
null
null
docs/Demo1_OceanDataset.ipynb
rabernat/oceanspy
9bd58f8529cb0fa865393c057ad7498e4f99681d
[ "MIT" ]
null
null
null
docs/Demo1_OceanDataset.ipynb
rabernat/oceanspy
9bd58f8529cb0fa865393c057ad7498e4f99681d
[ "MIT" ]
3
2019-08-22T18:23:07.000Z
2021-08-19T19:26:33.000Z
40.232252
189
0.51087
[ [ [ "# Demo 1: The OceanDataset object", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport oceanspy as ospy\nimport xarray as xr\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "### Open get_started dataset", "_____no_output_____" ] ], [ [ "od = ospy.open_oceandataset.get_started()", "Opening [Getting Started with OceanSpy]:\n[A small cutout from EGshelfIIseas2km_ASR.].\n" ] ], [ [ "### The OceanDataset object\n", "_____no_output_____" ] ], [ [ "print(od)", "<oceanspy.OceanDataset>\n\nMain attributes:\n .dataset: <xarray.Dataset>\n .grid: <xgcm.Grid>\n .projection: <cartopy.crs.Mercator object at 0x7f05eb165db0>\n\nMore attributes:\n .name: Getting Started with OceanSpy\n .description: A small cutout from EGshelfIIseas2km_ASR.\n .parameters: <class 'dict'>\n .grid_coords: <class 'dict'>\n" ] ], [ [ "### Dataset", "_____no_output_____" ] ], [ [ "# xarray.Dataset resembles a NetCDF\nprint(od.dataset)\nprint()\nprint('Total size: {}GB'.format(round(od.dataset.nbytes*1.E-9)))", "<xarray.Dataset>\nDimensions: (X: 341, Xp1: 342, Y: 262, Yp1: 263, Z: 139, Zl: 139, Zp1: 140, Zu: 139, time: 40, time_midp: 39)\nCoordinates:\n * Z (Z) float64 -1.0 -3.5 -7.0 ... -1.956e+03 -1.972e+03 -1.986e+03\n * Zp1 (Zp1) float64 0.0 -2.0 -5.0 ... -1.964e+03 -1.979e+03 -1.994e+03\n * Zu (Zu) float64 -2.0 -5.0 -9.0 ... -1.964e+03 -1.979e+03 -1.994e+03\n * Zl (Zl) float64 0.0 -2.0 -5.0 ... -1.949e+03 -1.964e+03 -1.979e+03\n * X (X) float64 -29.98 -29.94 -29.89 -29.85 ... -15.12 -15.07 -15.03\n * Y (Y) float64 66.01 66.03 66.05 66.07 ... 70.93 70.95 70.97 70.99\n XC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n YC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n * Xp1 (Xp1) float64 -30.0 -29.96 -29.92 -29.87 ... -15.1 -15.05 -15.01\n XU (Y, Xp1) float64 dask.array<shape=(262, 342), chunksize=(262, 342)>\n YU (Y, Xp1) float64 dask.array<shape=(262, 342), chunksize=(262, 342)>\n * Yp1 (Yp1) float64 66.0 66.02 66.04 66.06 ... 70.94 70.96 70.98 71.0\n XV (Yp1, X) float64 dask.array<shape=(263, 341), chunksize=(263, 341)>\n YV (Yp1, X) float64 dask.array<shape=(263, 341), chunksize=(263, 341)>\n XG (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n YG (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n * time (time) datetime64[ns] 2007-09-01 ... 2007-09-10T18:00:00\n * time_midp (time_midp) datetime64[ns] 2007-09-01T03:00:00 ... 2007-09-10T15:00:00\nData variables:\n drC (Zp1) float64 dask.array<shape=(140,), chunksize=(140,)>\n drF (Z) float64 dask.array<shape=(139,), chunksize=(139,)>\n dxC (Y, Xp1) float64 dask.array<shape=(262, 342), chunksize=(262, 342)>\n dyC (Yp1, X) float64 dask.array<shape=(263, 341), chunksize=(263, 341)>\n dxF (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n dyF (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n dxG (Yp1, X) float64 dask.array<shape=(263, 341), chunksize=(263, 341)>\n dyG (Y, Xp1) float64 dask.array<shape=(262, 342), chunksize=(262, 342)>\n dxV (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n dyU (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n rA (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n rAw (Y, Xp1) float64 dask.array<shape=(262, 342), chunksize=(262, 342)>\n rAs (Yp1, X) float64 dask.array<shape=(263, 341), chunksize=(263, 341)>\n rAz (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n fCori (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n fCoriG (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n R_low (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n Ro_surf (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n Depth (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n HFacC (Z, Y, X) float64 dask.array<shape=(139, 262, 341), chunksize=(139, 262, 341)>\n HFacW (Z, Y, Xp1) float64 dask.array<shape=(139, 262, 342), chunksize=(139, 262, 342)>\n HFacS (Z, Yp1, X) float64 dask.array<shape=(139, 263, 341), chunksize=(139, 263, 341)>\n KPPGHAT (Z, Y, X) float64 dask.array<shape=(139, 262, 341), chunksize=(139, 262, 341)>\n KPPHBL (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n KPPdiffKzS (Z, Y, X) float64 dask.array<shape=(139, 262, 341), chunksize=(139, 262, 341)>\n KPPdiffKzT (Z, Y, X) float64 dask.array<shape=(139, 262, 341), chunksize=(139, 262, 341)>\n KPPviscAz (Z, Y, X) float64 dask.array<shape=(139, 262, 341), chunksize=(139, 262, 341)>\n EXFaqh (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFatemp (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFempmr (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFevap (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFhl (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFhs (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFlwnet (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFpreci (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFpress (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFqnet (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFroff (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFroft (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFsnow (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFswnet (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFtaux (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFtauy (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFuwind (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n EXFvwind (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n Eta (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n S (time, Z, Y, X) float64 dask.array<shape=(40, 139, 262, 341), chunksize=(40, 139, 262, 341)>\n Temp (time, Z, Y, X) float64 dask.array<shape=(40, 139, 262, 341), chunksize=(40, 139, 262, 341)>\n U (time, Z, Y, Xp1) float64 dask.array<shape=(40, 139, 262, 342), chunksize=(40, 139, 262, 342)>\n V (time, Z, Yp1, X) float64 dask.array<shape=(40, 139, 263, 341), chunksize=(40, 139, 263, 341)>\n W (time, Zl, Y, X) float64 dask.array<shape=(40, 139, 262, 341), chunksize=(40, 139, 262, 341)>\n KPPhbl (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n MXLDEPTH (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n RHOAnoma (time, Z, Y, X) float64 dask.array<shape=(40, 139, 262, 341), chunksize=(40, 139, 262, 341)>\n SIarea (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n SIheff (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n SIhsnow (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n SIhsalt (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n SIuice (time, Y, Xp1) float64 dask.array<shape=(40, 262, 342), chunksize=(40, 262, 342)>\n SIvice (time, Yp1, X) float64 dask.array<shape=(40, 263, 341), chunksize=(40, 263, 341)>\n TRELAX (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n SRELAX (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n momVort3 (time, Z, Yp1, Xp1) float64 dask.array<shape=(40, 139, 263, 342), chunksize=(40, 139, 263, 342)>\n oceTAUX (time, Y, Xp1) float64 dask.array<shape=(40, 262, 342), chunksize=(40, 262, 342)>\n oceTAUY (time, Yp1, X) float64 dask.array<shape=(40, 263, 341), chunksize=(40, 263, 341)>\n oceFWflx (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n oceSflux (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n oceQnet (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n oceQsw (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n oceFreez (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n oceSPflx (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n oceSPDep (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n phiHyd (time, Z, Y, X) float64 dask.array<shape=(40, 139, 262, 341), chunksize=(40, 139, 262, 341)>\n phiHydLow (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n surForcT (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\n surForcS (time, Y, X) float64 dask.array<shape=(40, 262, 341), chunksize=(40, 262, 341)>\nAttributes:\n OceanSpy_grid_coords: {'Y': {'Y': None, 'Yp1': 0.5}, 'X': {'X': None, ...\n OceanSpy_name: Getting Started with OceanSpy\n OceanSpy_description: A small cutout from EGshelfIIseas2km_ASR.\n OceanSpy_parameters: {'rSphere': 6371.0, 'eq_state': 'jmd95', 'rho0':...\n OceanSpy_projection: Mercator(**{'central_longitude': -23.92803909531...\n OceanSpy_grid_periodic: []\n\nTotal size: 34GB\n" ], [ "# Easy to check variables\nprint(od.dataset['Temp'])", "<xarray.DataArray 'Temp' (time: 40, Z: 139, Y: 262, X: 341)>\ndask.array<shape=(40, 139, 262, 341), dtype=float64, chunksize=(40, 139, 262, 341)>\nCoordinates:\n * Z (Z) float64 -1.0 -3.5 -7.0 ... -1.956e+03 -1.972e+03 -1.986e+03\n * X (X) float64 -29.98 -29.94 -29.89 -29.85 ... -15.12 -15.07 -15.03\n * Y (Y) float64 66.01 66.03 66.05 66.07 ... 70.93 70.95 70.97 70.99\n XC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n YC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n * time (time) datetime64[ns] 2007-09-01 ... 2007-09-10T18:00:00\nAttributes:\n units: degC\n long_name: potential_temperature\n coordinates: XC YC RC iter\n original_output: snapshot\n" ] ], [ [ "### Grid", "_____no_output_____" ] ], [ [ "# Easy to work with Arakawa C grids\nprint(od.grid)\nprint()\nprint(od.dataset.coords)", "<xgcm.Grid>\nX Axis (not periodic):\n * center X (341) --> outer\n * outer Xp1 (342) --> center\nY Axis (not periodic):\n * center Y (262) --> outer\n * outer Yp1 (263) --> center\ntime Axis (not periodic):\n * center time_midp (39) --> outer\n * outer time (40) --> center\nZ Axis (not periodic):\n * center Z (139) --> left\n * left Zl (139) --> center\n * outer Zp1 (140) --> center\n * right Zu (139) --> center\n\nCoordinates:\n * Z (Z) float64 -1.0 -3.5 -7.0 ... -1.956e+03 -1.972e+03 -1.986e+03\n * Zp1 (Zp1) float64 0.0 -2.0 -5.0 ... -1.964e+03 -1.979e+03 -1.994e+03\n * Zu (Zu) float64 -2.0 -5.0 -9.0 ... -1.964e+03 -1.979e+03 -1.994e+03\n * Zl (Zl) float64 0.0 -2.0 -5.0 ... -1.949e+03 -1.964e+03 -1.979e+03\n * X (X) float64 -29.98 -29.94 -29.89 -29.85 ... -15.12 -15.07 -15.03\n * Y (Y) float64 66.01 66.03 66.05 66.07 ... 70.93 70.95 70.97 70.99\n XC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n YC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n * Xp1 (Xp1) float64 -30.0 -29.96 -29.92 -29.87 ... -15.1 -15.05 -15.01\n XU (Y, Xp1) float64 dask.array<shape=(262, 342), chunksize=(262, 342)>\n YU (Y, Xp1) float64 dask.array<shape=(262, 342), chunksize=(262, 342)>\n * Yp1 (Yp1) float64 66.0 66.02 66.04 66.06 ... 70.94 70.96 70.98 71.0\n XV (Yp1, X) float64 dask.array<shape=(263, 341), chunksize=(263, 341)>\n YV (Yp1, X) float64 dask.array<shape=(263, 341), chunksize=(263, 341)>\n XG (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n YG (Yp1, Xp1) float64 dask.array<shape=(263, 342), chunksize=(263, 342)>\n * time (time) datetime64[ns] 2007-09-01 ... 2007-09-10T18:00:00\n * time_midp (time_midp) datetime64[ns] 2007-09-01T03:00:00 ... 2007-09-10T15:00:00\n" ] ], [ [ "### Projection", "_____no_output_____" ] ], [ [ "od.projection", "_____no_output_____" ] ], [ [ "### Manipulation of datasets outside of OceanSpy", "_____no_output_____" ] ], [ [ "# Extract dataset\nds = od.dataset\n\n# Store global attributes just in case they will get lost\nattrs = od.dataset.attrs \n\n# Manipulate the dataset\nds = od.dataset\nds['Temp2'] = ds['Temp']*ds['Temp']\n\n# Global attributes are still there, but it's good practice\nds.attrs = attrs\n\n# Connect the dataset to OceanSpy again\nod = ospy.OceanDataset(ds)\nprint(od)\nprint()\nprint(od.dataset['Temp2'])", "<oceanspy.OceanDataset>\n\nMain attributes:\n .dataset: <xarray.Dataset>\n .grid: <xgcm.Grid>\n .projection: <cartopy.crs.Mercator object at 0x7f05ea644888>\n\nMore attributes:\n .name: Getting Started with OceanSpy\n .description: A small cutout from EGshelfIIseas2km_ASR.\n .parameters: <class 'dict'>\n .grid_coords: <class 'dict'>\n\n<xarray.DataArray 'Temp2' (time: 40, Z: 139, Y: 262, X: 341)>\ndask.array<shape=(40, 139, 262, 341), dtype=float64, chunksize=(40, 139, 262, 341)>\nCoordinates:\n * Z (Z) float64 -1.0 -3.5 -7.0 ... -1.956e+03 -1.972e+03 -1.986e+03\n * X (X) float64 -29.98 -29.94 -29.89 -29.85 ... -15.12 -15.07 -15.03\n * Y (Y) float64 66.01 66.03 66.05 66.07 ... 70.93 70.95 70.97 70.99\n XC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n YC (Y, X) float64 dask.array<shape=(262, 341), chunksize=(262, 341)>\n * time (time) datetime64[ns] 2007-09-01 ... 2007-09-10T18:00:00\n" ] ], [ [ "### OceanDataset overview", "_____no_output_____" ] ], [ [ "help(ospy.OceanDataset)", "Help on class OceanDataset in module oceanspy._oceandataset:\n\nclass OceanDataset(builtins.object)\n | OceanDataset(dataset)\n | \n | OceanDataset combines a xarray.Dataset with other objects used by OceanSpy (e.g., xgcm.Grid).\n | \n | Additional objects are attached to the xarray.Dataset as global attributes.\n | \n | OceanDataset adds, reads, and decodes dataset global attributes.\n | \n | Methods defined here:\n | \n | __copy__(self)\n | Shallow copy\n | \n | __deepcopy__(self)\n | Deep copy\n | \n | __init__(self, dataset)\n | Parameters\n | ----------\n | dataset: xarray.Dataset\n | The multi-dimensional, in memory, array database.\n | \n | References\n | ----------\n | http://xarray.pydata.org/en/stable/generated/xarray.Dataset.html\n | \n | __repr__(self)\n | Return repr(self).\n | \n | create_tree(self, grid_pos='C')\n | Create a scipy.spatial.cKDTree for quick nearest-neighbor lookup.\n | \n | Parameters\n | -----------\n | grid_pos: str\n | Grid position. Option: {'C', 'G', 'U', 'V'}\n | Reference grid: https://mitgcm.readthedocs.io/en/latest/algorithm/horiz-grid.html\n | \n | Returns\n | -------\n | tree: scipy.spatial.cKDTree\n | Return tree that can be used to query a point.\n | \n | References\n | ----------\n | https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html\n | \n | import_MITgcm_curv_nc(self, shift_averages=True)\n | Set coordinates of a dataset from a MITgcm run with curvilinear grid and data stored in NetCDF format.\n | Open and concatentate dataset before running this function.\n | \n | Parameters\n | ----------\n | shift_averages: bool\n | If True, shift average variable to time_midp. \n | Average variables must have attribute original_output = 'average'\n | \n | import_MITgcm_rect_bin(self, shift_averages=True)\n | Set coordinates of a dataset from a MITgcm run with rectilinear grid and data stored in bin format.\n | Open and concatentate dataset before running this function.\n | \n | Parameters\n | ----------\n | shift_averages: bool\n | If True, shift average variable to time_midp. \n | Average variables must have attribute original_output = 'average'\n | \n | import_MITgcm_rect_nc(self, shift_averages=True)\n | Set coordinates of a dataset from a MITgcm run with rectilinear grid and data stored in NetCDF format.\n | Open and concatentate dataset before running this function.\n | \n | Parameters\n | ----------\n | shift_averages: bool\n | If True, shift average variable to time_midp. \n | Average variables must have attribute original_output = 'average'\n | \n | merge_into_oceandataset(self, obj, overwrite=False)\n | Merge a dataset or DataArray into the oceandataset\n | \n | Parameters\n | ----------\n | obj: xarray.DataArray or xarray.Dataset\n | xarray object to merge\n | overwrite: bool or None\n | If True, overwrite existing DataArrays with same name. \n | If False, use xarray.merge\n | \n | set_aliases(self, aliases, overwrite=None)\n | Set aliases to connect custom variables names to OceanSpy reference names.\n | \n | Parameters\n | ----------\n | aliases: dict\n | Keys are OceanSpy names, values are custom names: {'ospy_name': 'custom_name'}\n | overwrite: bool or None\n | If None, raise error if aliases has been previously set.\n | If True, overwrite previous aliases. \n | If False, combine with previous aliases.\n | \n | set_coords(self, fillna=False, coords1Dfrom2D=False, coords2Dfrom1D=False, coordsUVfromG=False)\n | Set dataset coordinates: dimensions + 2D horizontal coordinates. \n | \n | Parameters\n | ----------\n | fillna: bool\n | If True, fill NaNs in 2D coordinates propagating backward and forward. \n | coords1Dfrom2D: bool\n | If True, compute 1D coordinates from 2D coordinates (means). \n | Use with rectilinear grid only!\n | coords2Dfrom1D: bool\n | If True, compute 2D coordinates from 1D coordinates (brodacast). \n | coordsUVfromCG: bool\n | If True, compute missing coords (U and V points) from G points.\n | \n | set_description(self, description, overwrite=None)\n | Set description of the OceanDataset.\n | \n | Parameters\n | ----------\n | description: str\n | Desription of the OceanDataset\n | overwrite: bool or None\n | If None, raise error if description has been previously set.\n | If True, overwrite previous description. \n | If False, combine with previous description.\n | \n | set_grid_coords(self, grid_coords, add_midp=False, overwrite=None)\n | Set grid coordinates used by xgcm.Grid (see oceanspy.OCEANSPY_AXES).\n | \n | Parameters\n | ----------\n | grid_coords: str\n | Grid coordinates used by xgcm.Grid. \n | Keys are axis, and values are dict with key=dim and value=c_grid_axis_shift.\n | Available c_grid_axis_shift are {0.5, None, -0.5}\n | add_midp: bool\n | If true, add inner dimension (mid points) to axis with outer dimension only.\n | The new dimension will be called as the outer dimension + '_midp'\n | overwrite: bool or None\n | If None, raise error if grid_coords has been previously set.\n | If True, overwrite previous grid_coors. \n | If False, combine with previous grid_coors.\n | \n | References\n | ----------\n | https://xgcm.readthedocs.io/en/stable/grids.html#Grid-Metadata\n | \n | set_grid_periodic(self, grid_periodic, overwrite=None)\n | Set grid axes that need to be treated as periodic by xgcm.Grid.\n | Axis that are not set periodic are non-periodic by default. \n | Note that this is opposite than xgcm, which sets periodic=True by default.\n | \n | Parameters\n | ----------\n | grid_periodic: list\n | List of periodic axes.\n | Available axis are {'X', 'Y', 'Z', 'time'}.\n | overwrite: bool or None\n | If None, raise error if grid_periodic has been previously set.\n | If True, overwrite previous grid_periodic. \n | If False, combine with previous grid_periodic.\n | \n | set_name(self, name, overwrite=None)\n | Set name of the OceanDataset.\n | \n | Parameters\n | ----------\n | name: str\n | Name of the OceanDataset\n | overwrite: bool or None\n | If None, raise error if name has been previously set.\n | If True, overwrite previous name. \n | If False, combine with previous name.\n | \n | set_parameters(self, parameters)\n | Set model parameters used by OceanSpy (see oceanspy.DEFAULT_PARAMETERS)\n | \n | Parameters\n | ----------\n | parameters: dict\n | {'parameter_name': parameter_value}\n | \n | set_projection(self, projection, **kwargs)\n | Projection of the OceanDataset.\n | \n | Parameters\n | ----------\n | projection: str\n | cartopy projection of the OceanDataset\n | **kwargs:\n | Keyword arguments used by cartopy\n | E.g., central_longitude=0.0 for PlateCarree\n | References\n | ----------\n | https://scitools.org.uk/cartopy/docs/latest/crs/projections.html\n | \n | to_netcdf(self, path, **kwargs)\n | Write dataset contents to a netCDF file.\n | \n | Parameters\n | ----------\n | path: str\n | Path to which to save this dataset.\n | **kwargs:\n | Keyword arguments for xarray.DataSet.to_netcdf()\n | \n | References\n | ----------\n | http://xarray.pydata.org/en/stable/generated/xarray.Dataset.to_netcdf.html\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n | \n | aliases\n | A dictionary to connect custom variable names to OceanSpy reference names.\n | Keys are OceanSpy names, values are custom names: {'ospy_name': 'custom_name'}\n | \n | animate\n | Access animating functions.\n | \n | Examples\n | --------\n | >>> od = ospy.open_oceandataset.get_started()\n | >>> od.animate.TS_diagram(meanAxes=['time', 'Z'], cutout_kwargs={'ZRange': [0, -100]})\n | \n | compute\n | Access computing functions, and merge the computed dataset into the oceandataset.\n | Set overwrite=True to overwrite DataArrays already existing in the oceandataset.\n | \n | Examples\n | --------\n | >>> od = ospy.open_oceandataset.get_started()\n | >>> od.compute.gradient(varNameList='Temp', overwrite=True)\n | \n | dataset\n | xarray.Dataset: A multi-dimensional, in memory, array database.\n | \n | References\n | ----------\n | http://xarray.pydata.org/en/stable/generated/xarray.Dataset.html\n | \n | description\n | Description of the OceanDataset\n | \n | grid\n | xgcm.Grid: A collection of axis, which is a group of coordinates that all lie along the same physical dimension but describe different positions relative to a grid cell. \n | \n | References\n | ----------\n | https://xgcm.readthedocs.io/en/stable/api.html#Grid\n | \n | grid_coords\n | Grid coordinates used by xgcm.Grid\n | \n | References\n | ----------\n | https://xgcm.readthedocs.io/en/stable/grids.html#Grid-Metadata\n | \n | grid_periodic\n | List of xgcm.Grid axes that are periodic\n | \n | name\n | Name of the OceanDataset\n | \n | parameters\n | A dictionary defining model parameters that are used by OceanSpy.\n | {'parameter_name': parameter value}\n | If a parameter is not available, use default.\n | \n | plot\n | Access plotting functions.\n | \n | Examples\n | --------\n | >>> od = ospy.open_oceandataset.get_started()\n | >>> od.plot.TS_diagram(meanAxes=['time', 'Z'], cutout_kwargs={'ZRange': [0, -100]})\n | \n | projection\n | Projection of the OceanDataset.\n | \n | subsample\n | Access subsampling functions.\n | \n | Examples\n | --------\n | >>> od = ospy.open_oceandataset.get_started()\n | >>> od.subsample.cutout(ZRange=[0, -100], varList=['Temp'])\n\n" ] ], [ [ "To do:\n\n* Fully implement and test the compatibility with models other than MITgcm", "_____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" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4afbfa263eb668e8943de7d4fff9ef55ff1196b2
6,093
ipynb
Jupyter Notebook
aulas/regressao_linear_multipla.ipynb
danilovbarbosa/machine_learning
55b7c752c24b988f6a2f3f77d9ad82ca5d990e3b
[ "MIT" ]
null
null
null
aulas/regressao_linear_multipla.ipynb
danilovbarbosa/machine_learning
55b7c752c24b988f6a2f3f77d9ad82ca5d990e3b
[ "MIT" ]
null
null
null
aulas/regressao_linear_multipla.ipynb
danilovbarbosa/machine_learning
55b7c752c24b988f6a2f3f77d9ad82ca5d990e3b
[ "MIT" ]
null
null
null
6,093
6,093
0.709667
[ [ [ "#Explorando as diferenças entre Regressão linear simples e Regressão linear múltipla", "_____no_output_____" ], [ "##Começando com a regressão linear SIMPLES\n##Importando Libs e estruturando variáveis", "_____no_output_____" ] ], [ [ "import numpy as np\n\n## Crie x contendo um array em duas dimensões com os valores de Horas_de_Estudo já registrados no passado\n##Repressanta a variável independente\nx = np.array([1,5,7,8,10,11,14,15,15,19]).reshape((-1,1))\n\n\n#Crie y contendo um array com os valores históricos da Nota já registrados no passado (vide tabela acima)\ny = np.array([53,74,59,43,56,84,96,69,84,83])", "_____no_output_____" ] ], [ [ "## Importando a biblioteca de regressão linear do sklearn e criando o modelo", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LinearRegression\n\n# Crie o modelo de regressão linear, fazendo o fit de x e y.\nmodelo = LinearRegression().fit(x,y)", "_____no_output_____" ] ], [ [ "##Avalie o modelo. Qual seu score, intercept e slope?", "_____no_output_____" ] ], [ [ "print(\"Score: \", modelo.score(x,y))\nprint(\"Intercept: \", modelo.intercept_)\nprint(\"Coef: \", modelo.coef_)", "Score: 0.39412152258869326\nIntercept: 49.477126654064264\nCoef: [1.96408318]\n" ] ], [ [ "##Testando", "_____no_output_____" ] ], [ [ "#7. Crie novo_x contendo um array as seguintes horas de estudo dos novos alunos: 6, 9, 12, 15, 16, 4\nnovo_x = np.array([6,9,12,15,16,4]).reshape((-1,1))\n\n#Predict\nprevisao = modelo.predict(novo_x)\nprint(previsao)", "[61.26162571 67.15387524 73.04612476 78.93837429 80.90245747 57.33345936]\n" ] ], [ [ "##Regressão Linear Mútipla\n##Importando libs", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom sklearn.linear_model import LinearRegression", "_____no_output_____" ] ], [ [ "##Criando dados", "_____no_output_____" ] ], [ [ "x = np.array([[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]])\ny = np.array([4, 5, 20, 14, 32, 22, 38, 43])", "_____no_output_____" ] ], [ [ "##Criando modelo", "_____no_output_____" ] ], [ [ "model = LinearRegression().fit(x, y)\n\nprint('coefficient of determination:', model.score(x, y))\nprint('intercept:', model.intercept_)\nprint('slope:', model.coef_)", "coefficient of determination: 0.8615939258756776\nintercept: 5.52257927519819\nslope: [0.44706965 0.25502548]\n" ] ], [ [ "##Testando", "_____no_output_____" ] ], [ [ "novo_x = np.arange(10).reshape((-1, 2))\n\nprevisao_y = model.predict(novo_x)\nprint(previsao_y)", "[ 5.77760476 7.18179502 8.58598528 9.99017554 11.3943658 ]\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" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4afbffbc5a524e0db4c5686f6e75967e1a8b8f24
128,973
ipynb
Jupyter Notebook
WorkingWithGenomes-BAM.ipynb
CompBiochBiophLab/IntroBioinfo
ddbfb45f6cbcede2e10b589e3d6dab840cccb484
[ "MIT" ]
null
null
null
WorkingWithGenomes-BAM.ipynb
CompBiochBiophLab/IntroBioinfo
ddbfb45f6cbcede2e10b589e3d6dab840cccb484
[ "MIT" ]
null
null
null
WorkingWithGenomes-BAM.ipynb
CompBiochBiophLab/IntroBioinfo
ddbfb45f6cbcede2e10b589e3d6dab840cccb484
[ "MIT" ]
4
2020-04-03T14:04:32.000Z
2021-01-26T14:16:43.000Z
152.450355
51,532
0.86225
[ [ [ "Adapted from [https://github.com/PacktPublishing/Bioinformatics-with-Python-Cookbook-Second-Edition](https://github.com/PacktPublishing/Bioinformatics-with-Python-Cookbook-Second-Edition), Chapter 2.\n\n# Getting the necessary packages\n\n```\nconda config --add channels bioconda\nconda install samtools pysam\n```\n\n# Getting the necessary data", "_____no_output_____" ], [ "You just need to do this only once", "_____no_output_____" ] ], [ [ "!rm -f data/NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam 2>/dev/null\n!rm -f data/NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam.bai 2>/dev/null\n# BAM is the alignment file and BAI is the index, generated by samtools\n!wget ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/phase3/data/NA18489/exome_alignment/NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam\n!wget ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/phase3/data/NA18489/exome_alignment/NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam.bai\n!mv *bam *bai data", "--2020-04-23 14:27:44-- ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/phase3/data/NA18489/exome_alignment/NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam\n => «NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam»\nS'està resolent ftp.1000genomes.ebi.ac.uk (ftp.1000genomes.ebi.ac.uk)… 193.62.197.77\nS'està connectant a ftp.1000genomes.ebi.ac.uk (ftp.1000genomes.ebi.ac.uk)|193.62.197.77|:21… connectat.\nS'està entrant com a «anonymous» … S'ha entrat amb èxit!\n==> SYST ... fet. ==> PWD ... fet.\n==> TYPE I ... fet. ==> CWD (1) /vol1/ftp/phase3/data/NA18489/exome_alignment ... fet.\n==> SIZE NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam ... 327067172\n==> PASV ... fet. ==> RETR NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam ... fet.\nMida: 327067172 (312M) (no autoritatiu)\n\nNA18489.chrom20.ILL 100%[===================>] 311,92M 1,20MB/s in 6m 23s \n\n2020-04-23 14:34:08 (835 KB/s) - s'ha desat «NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam» [327067172]\n\n--2020-04-23 14:34:08-- ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/phase3/data/NA18489/exome_alignment/NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam.bai\n => «NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam.bai»\nS'està resolent ftp.1000genomes.ebi.ac.uk (ftp.1000genomes.ebi.ac.uk)… 193.62.193.140\nS'està connectant a ftp.1000genomes.ebi.ac.uk (ftp.1000genomes.ebi.ac.uk)|193.62.193.140|:21… connectat.\nS'està entrant com a «anonymous» … S'ha entrat amb èxit!\n==> SYST ... fet. ==> PWD ... fet.\n==> TYPE I ... fet. ==> CWD (1) /vol1/ftp/phase3/data/NA18489/exome_alignment ... fet.\n==> SIZE NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam.bai ... 170688\n==> PASV ... fet. ==> RETR NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam.bai ... fet.\nMida: 170688 (167K) (no autoritatiu)\n\nNA18489.chrom20.ILL 100%[===================>] 166,69K 816KB/s in 0,2s \n\n2020-04-23 14:34:10 (816 KB/s) - s'ha desat «NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam.bai» [170688]\n\n" ] ], [ [ "# The recipe", "_____no_output_____" ] ], [ [ "#pip install pysam\nfrom collections import defaultdict\n\nimport numpy as np\n\n%matplotlib inline\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport pysam", "_____no_output_____" ], [ "bam = pysam.AlignmentFile('data/NA18489.chrom20.ILLUMINA.bwa.YRI.exome.20121211.bam', 'rb')", "_____no_output_____" ], [ "headers = bam.header\nfor record_type, records in headers.items():\n print (record_type)\n for i, record in enumerate(records):\n if type(record) == dict:\n print('\\t%d' % (i + 1))\n for field, value in record.items():\n print('\\t\\t%s\\t%s' % (field, value))\n else:\n print('\\t\\t%s' % record)", "HD\n\t\tVN\n\t\tSO\nSQ\n\t1\n\t\tSN\t1\n\t\tLN\t249250621\n\t\tM5\t1b22b98cdeb4a9304cb5d48026a85128\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t2\n\t\tSN\t2\n\t\tLN\t243199373\n\t\tM5\ta0d9851da00400dec1098a9255ac712e\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t3\n\t\tSN\t3\n\t\tLN\t198022430\n\t\tM5\tfdfd811849cc2fadebc929bb925902e5\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t4\n\t\tSN\t4\n\t\tLN\t191154276\n\t\tM5\t23dccd106897542ad87d2765d28a19a1\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t5\n\t\tSN\t5\n\t\tLN\t180915260\n\t\tM5\t0740173db9ffd264d728f32784845cd7\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t6\n\t\tSN\t6\n\t\tLN\t171115067\n\t\tM5\t1d3a93a248d92a729ee764823acbbc6b\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t7\n\t\tSN\t7\n\t\tLN\t159138663\n\t\tM5\t618366e953d6aaad97dbe4777c29375e\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t8\n\t\tSN\t8\n\t\tLN\t146364022\n\t\tM5\t96f514a9929e410c6651697bded59aec\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t9\n\t\tSN\t9\n\t\tLN\t141213431\n\t\tM5\t3e273117f15e0a400f01055d9f393768\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t10\n\t\tSN\t10\n\t\tLN\t135534747\n\t\tM5\t988c28e000e84c26d552359af1ea2e1d\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t11\n\t\tSN\t11\n\t\tLN\t135006516\n\t\tM5\t98c59049a2df285c76ffb1c6db8f8b96\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t12\n\t\tSN\t12\n\t\tLN\t133851895\n\t\tM5\t51851ac0e1a115847ad36449b0015864\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t13\n\t\tSN\t13\n\t\tLN\t115169878\n\t\tM5\t283f8d7892baa81b510a015719ca7b0b\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t14\n\t\tSN\t14\n\t\tLN\t107349540\n\t\tM5\t98f3cae32b2a2e9524bc19813927542e\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t15\n\t\tSN\t15\n\t\tLN\t102531392\n\t\tM5\te5645a794a8238215b2cd77acb95a078\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t16\n\t\tSN\t16\n\t\tLN\t90354753\n\t\tM5\tfc9b1a7b42b97a864f56b348b06095e6\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t17\n\t\tSN\t17\n\t\tLN\t81195210\n\t\tM5\t351f64d4f4f9ddd45b35336ad97aa6de\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t18\n\t\tSN\t18\n\t\tLN\t78077248\n\t\tM5\tb15d4b2d29dde9d3e4f93d1d0f2cbc9c\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t19\n\t\tSN\t19\n\t\tLN\t59128983\n\t\tM5\t1aacd71f30db8e561810913e0b72636d\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t20\n\t\tSN\t20\n\t\tLN\t63025520\n\t\tM5\t0dec9660ec1efaaf33281c0d5ea2560f\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t21\n\t\tSN\t21\n\t\tLN\t48129895\n\t\tM5\t2979a6085bfe28e3ad6f552f361ed74d\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t22\n\t\tSN\t22\n\t\tLN\t51304566\n\t\tM5\ta718acaa6135fdca8357d5bfe94211dd\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t23\n\t\tSN\tX\n\t\tLN\t155270560\n\t\tM5\t7e0e2e580297b7764e31dbc80c2540dd\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t24\n\t\tSN\tY\n\t\tLN\t59373566\n\t\tM5\t1fa3474750af0948bdf97d5a0ee52e51\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t25\n\t\tSN\tMT\n\t\tLN\t16569\n\t\tM5\tc68f52674c9fb33aef52dcf399755519\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t26\n\t\tSN\tGL000207.1\n\t\tLN\t4262\n\t\tM5\tf3814841f1939d3ca19072d9e89f3fd7\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t27\n\t\tSN\tGL000226.1\n\t\tLN\t15008\n\t\tM5\t1c1b2cd1fccbc0a99b6a447fa24d1504\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t28\n\t\tSN\tGL000229.1\n\t\tLN\t19913\n\t\tM5\td0f40ec87de311d8e715b52e4c7062e1\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t29\n\t\tSN\tGL000231.1\n\t\tLN\t27386\n\t\tM5\tba8882ce3a1efa2080e5d29b956568a4\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t30\n\t\tSN\tGL000210.1\n\t\tLN\t27682\n\t\tM5\t851106a74238044126131ce2a8e5847c\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t31\n\t\tSN\tGL000239.1\n\t\tLN\t33824\n\t\tM5\t99795f15702caec4fa1c4e15f8a29c07\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t32\n\t\tSN\tGL000235.1\n\t\tLN\t34474\n\t\tM5\t118a25ca210cfbcdfb6c2ebb249f9680\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t33\n\t\tSN\tGL000201.1\n\t\tLN\t36148\n\t\tM5\tdfb7e7ec60ffdcb85cb359ea28454ee9\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t34\n\t\tSN\tGL000247.1\n\t\tLN\t36422\n\t\tM5\t7de00226bb7df1c57276ca6baabafd15\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t35\n\t\tSN\tGL000245.1\n\t\tLN\t36651\n\t\tM5\t89bc61960f37d94abf0df2d481ada0ec\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t36\n\t\tSN\tGL000197.1\n\t\tLN\t37175\n\t\tM5\t6f5efdd36643a9b8c8ccad6f2f1edc7b\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t37\n\t\tSN\tGL000203.1\n\t\tLN\t37498\n\t\tM5\t96358c325fe0e70bee73436e8bb14dbd\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t38\n\t\tSN\tGL000246.1\n\t\tLN\t38154\n\t\tM5\te4afcd31912af9d9c2546acf1cb23af2\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t39\n\t\tSN\tGL000249.1\n\t\tLN\t38502\n\t\tM5\t1d78abec37c15fe29a275eb08d5af236\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t40\n\t\tSN\tGL000196.1\n\t\tLN\t38914\n\t\tM5\td92206d1bb4c3b4019c43c0875c06dc0\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t41\n\t\tSN\tGL000248.1\n\t\tLN\t39786\n\t\tM5\t5a8e43bec9be36c7b49c84d585107776\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t42\n\t\tSN\tGL000244.1\n\t\tLN\t39929\n\t\tM5\t0996b4475f353ca98bacb756ac479140\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t43\n\t\tSN\tGL000238.1\n\t\tLN\t39939\n\t\tM5\t131b1efc3270cc838686b54e7c34b17b\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t44\n\t\tSN\tGL000202.1\n\t\tLN\t40103\n\t\tM5\t06cbf126247d89664a4faebad130fe9c\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t45\n\t\tSN\tGL000234.1\n\t\tLN\t40531\n\t\tM5\t93f998536b61a56fd0ff47322a911d4b\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t46\n\t\tSN\tGL000232.1\n\t\tLN\t40652\n\t\tM5\t3e06b6741061ad93a8587531307057d8\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t47\n\t\tSN\tGL000206.1\n\t\tLN\t41001\n\t\tM5\t43f69e423533e948bfae5ce1d45bd3f1\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t48\n\t\tSN\tGL000240.1\n\t\tLN\t41933\n\t\tM5\t445a86173da9f237d7bcf41c6cb8cc62\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t49\n\t\tSN\tGL000236.1\n\t\tLN\t41934\n\t\tM5\tfdcd739913efa1fdc64b6c0cd7016779\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t50\n\t\tSN\tGL000241.1\n\t\tLN\t42152\n\t\tM5\tef4258cdc5a45c206cea8fc3e1d858cf\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t51\n\t\tSN\tGL000243.1\n\t\tLN\t43341\n\t\tM5\tcc34279a7e353136741c9fce79bc4396\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t52\n\t\tSN\tGL000242.1\n\t\tLN\t43523\n\t\tM5\t2f8694fc47576bc81b5fe9e7de0ba49e\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t53\n\t\tSN\tGL000230.1\n\t\tLN\t43691\n\t\tM5\tb4eb71ee878d3706246b7c1dbef69299\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t54\n\t\tSN\tGL000237.1\n\t\tLN\t45867\n\t\tM5\te0c82e7751df73f4f6d0ed30cdc853c0\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t55\n\t\tSN\tGL000233.1\n\t\tLN\t45941\n\t\tM5\t7fed60298a8d62ff808b74b6ce820001\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t56\n\t\tSN\tGL000204.1\n\t\tLN\t81310\n\t\tM5\tefc49c871536fa8d79cb0a06fa739722\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t57\n\t\tSN\tGL000198.1\n\t\tLN\t90085\n\t\tM5\t868e7784040da90d900d2d1b667a1383\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t58\n\t\tSN\tGL000208.1\n\t\tLN\t92689\n\t\tM5\taa81be49bf3fe63a79bdc6a6f279abf6\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t59\n\t\tSN\tGL000191.1\n\t\tLN\t106433\n\t\tM5\td75b436f50a8214ee9c2a51d30b2c2cc\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t60\n\t\tSN\tGL000227.1\n\t\tLN\t128374\n\t\tM5\ta4aead23f8053f2655e468bcc6ecdceb\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t61\n\t\tSN\tGL000228.1\n\t\tLN\t129120\n\t\tM5\tc5a17c97e2c1a0b6a9cc5a6b064b714f\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t62\n\t\tSN\tGL000214.1\n\t\tLN\t137718\n\t\tM5\t46c2032c37f2ed899eb41c0473319a69\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t63\n\t\tSN\tGL000221.1\n\t\tLN\t155397\n\t\tM5\t3238fb74ea87ae857f9c7508d315babb\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t64\n\t\tSN\tGL000209.1\n\t\tLN\t159169\n\t\tM5\tf40598e2a5a6b26e84a3775e0d1e2c81\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t65\n\t\tSN\tGL000218.1\n\t\tLN\t161147\n\t\tM5\t1d708b54644c26c7e01c2dad5426d38c\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t66\n\t\tSN\tGL000220.1\n\t\tLN\t161802\n\t\tM5\tfc35de963c57bf7648429e6454f1c9db\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t67\n\t\tSN\tGL000213.1\n\t\tLN\t164239\n\t\tM5\t9d424fdcc98866650b58f004080a992a\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t68\n\t\tSN\tGL000211.1\n\t\tLN\t166566\n\t\tM5\t7daaa45c66b288847b9b32b964e623d3\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t69\n\t\tSN\tGL000199.1\n\t\tLN\t169874\n\t\tM5\t569af3b73522fab4b40995ae4944e78e\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t70\n\t\tSN\tGL000217.1\n\t\tLN\t172149\n\t\tM5\t6d243e18dea1945fb7f2517615b8f52e\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t71\n\t\tSN\tGL000216.1\n\t\tLN\t172294\n\t\tM5\t642a232d91c486ac339263820aef7fe0\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t72\n\t\tSN\tGL000215.1\n\t\tLN\t172545\n\t\tM5\t5eb3b418480ae67a997957c909375a73\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t73\n\t\tSN\tGL000205.1\n\t\tLN\t174588\n\t\tM5\td22441398d99caf673e9afb9a1908ec5\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t74\n\t\tSN\tGL000219.1\n\t\tLN\t179198\n\t\tM5\tf977edd13bac459cb2ed4a5457dba1b3\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t75\n\t\tSN\tGL000224.1\n\t\tLN\t179693\n\t\tM5\td5b2fc04f6b41b212a4198a07f450e20\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t76\n\t\tSN\tGL000223.1\n\t\tLN\t180455\n\t\tM5\t399dfa03bf32022ab52a846f7ca35b30\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t77\n\t\tSN\tGL000195.1\n\t\tLN\t182896\n\t\tM5\t5d9ec007868d517e73543b005ba48535\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t78\n\t\tSN\tGL000212.1\n\t\tLN\t186858\n\t\tM5\t563531689f3dbd691331fd6c5730a88b\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t79\n\t\tSN\tGL000222.1\n\t\tLN\t186861\n\t\tM5\t6fe9abac455169f50470f5a6b01d0f59\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t80\n\t\tSN\tGL000200.1\n\t\tLN\t187035\n\t\tM5\t75e4c8d17cd4addf3917d1703cacaf25\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t81\n\t\tSN\tGL000193.1\n\t\tLN\t189789\n\t\tM5\tdbb6e8ece0b5de29da56601613007c2a\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t82\n\t\tSN\tGL000194.1\n\t\tLN\t191469\n\t\tM5\t6ac8f815bf8e845bb3031b73f812c012\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t83\n\t\tSN\tGL000225.1\n\t\tLN\t211173\n\t\tM5\t63945c3e6962f28ffd469719a747e73c\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t84\n\t\tSN\tGL000192.1\n\t\tLN\t547496\n\t\tM5\t325ba9e808f669dfeee210fdd7b470ac\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t85\n\t\tSN\tNC_007605\n\t\tLN\t171823\n\t\tM5\t6743bd63b3ff2b5b8985d8933c53290a\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\n\t86\n\t\tSN\ths37d5\n\t\tLN\t35477943\n\t\tM5\t5b6a4b3a81a2d3c134b7d14bf6ad39f1\n\t\tUR\tftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_reference_assembly_sequence/hs37d5.fa.gz AS:NCBI37 SP:Human\nRG\n\t1\n\t\tID\tSRR100025\n\t\tLB\tSolexa-51039\n\t\tSM\tNA18489\n\t\tPI\t220\n\t\tCN\tBI\n\t\tPL\tILLUMINA\n\t\tDS\tSRP004074\nPG\n\t1\n\t\tID\tbwa_index\n\t\tPN\tbwa\n\t\tVN\t0.5.9-r16\n\t\tCL\tbwa index -a bwtsw $reference_fasta\n\t2\n\t\tID\tbwa_aln_fastq\n\t\tPN\tbwa\n\t\tPP\tbwa_index\n\t\tVN\t0.5.9-r16\n\t\tCL\tbwa aln -q 15 -f $sai_file $reference_fasta $fastq_file\n\t3\n\t\tID\tbwa_sam\n\t\tPN\tbwa\n\t\tPP\tbwa_aln_fastq\n\t\tVN\t0.5.9-r16\n\t\tCL\tbwa sampe -a 660 -r $rg_line -f $sam_file $reference_fasta $sai_file(s) $fastq_file(s)\n\t4\n\t\tID\tsam_to_fixed_bam\n\t\tPN\tsamtools\n\t\tPP\tbwa_sam\n\t\tVN\t0.1.17 (r973:277)\n\t\tCL\tsamtools view -bSu $sam_file | samtools sort -n -o - samtools_nsort_tmp | samtools fixmate /dev/stdin /dev/stdout | samtools sort -o - samtools_csort_tmp | samtools fillmd -u - $reference_fasta > $fixed_bam_file\n\t5\n\t\tID\tgatk_target_interval_creator\n\t\tPN\tGenomeAnalysisTK\n\t\tPP\tsam_to_fixed_bam\n\t\tVN\t1.2-29-g0acaf2d\n\t\tCL\tjava $jvm_args -jar GenomeAnalysisTK.jar -T RealignerTargetCreator -R $reference_fasta -o $intervals_file -known $known_indels_file(s)\n\t6\n\t\tID\tbam_realignment_around_known_indels\n\t\tPN\tGenomeAnalysisTK\n\t\tPP\tgatk_target_interval_creator\n\t\tVN\t1.2-29-g0acaf2d\n\t\tCL\tjava $jvm_args -jar GenomeAnalysisTK.jar -T IndelRealigner -R $reference_fasta -I $bam_file -o $realigned_bam_file -targetIntervals $intervals_file -known $known_indels_file(s) -LOD 0.4 -model KNOWNS_ONLY -compress 0 --disable_bam_indexing\n\t7\n\t\tID\tbam_count_covariates\n\t\tPN\tGenomeAnalysisTK\n\t\tPP\tbam_realignment_around_known_indels\n\t\tVN\t1.2-29-g0acaf2d\n\t\tCL\tjava $jvm_args -jar GenomeAnalysisTK.jar -T CountCovariates -R $reference_fasta -I $bam_file -recalFile $bam_file.recal_data.csv -knownSites $known_sites_file(s) -l INFO -L '1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;X;Y;MT' -cov ReadGroupCovariate -cov QualityScoreCovariate -cov CycleCovariate -cov DinucCovariate\n\t8\n\t\tID\tbam_recalibrate_quality_scores\n\t\tPN\tGenomeAnalysisTK\n\t\tPP\tbam_count_covariates\n\t\tVN\t1.2-29-g0acaf2d\n\t\tCL\tjava $jvm_args -jar GenomeAnalysisTK.jar -T TableRecalibration -R $reference_fasta -recalFile $bam_file.recal_data.csv -I $bam_file -o $recalibrated_bam_file -l INFO -compress 0 --disable_bam_indexing\n\t9\n\t\tID\tbam_calculate_bq\n\t\tPN\tsamtools\n\t\tPP\tbam_recalibrate_quality_scores\n\t\tVN\t0.1.17 (r973:277)\n\t\tCL\tsamtools calmd -Erb $bam_file $reference_fasta > $bq_bam_file\n\t10\n\t\tID\tbam_merge\n\t\tPN\tpicard\n\t\tPP\tbam_calculate_bq\n\t\tVN\t1.53\n\t\tCL\tjava $jvm_args -jar MergeSamFiles.jar INPUT=$bam_file(s) OUTPUT=$merged_bam VALIDATION_STRINGENCY=SILENT\n\t11\n\t\tID\tbam_mark_duplicates\n\t\tPN\tpicard\n\t\tPP\tbam_merge\n\t\tVN\t1.53\n\t\tCL\tjava $jvm_args -jar MarkDuplicates.jar INPUT=$bam_file OUTPUT=$markdup_bam_file ASSUME_SORTED=TRUE METRICS_FILE=/dev/null VALIDATION_STRINGENCY=SILENT\n\t12\n\t\tID\tbam_merge.1\n\t\tPN\tpicard\n\t\tPP\tbam_mark_duplicates\n\t\tVN\t1.53\n\t\tCL\tjava $jvm_args -jar MergeSamFiles.jar INPUT=$bam_file(s) OUTPUT=$merged_bam VALIDATION_STRINGENCY=SILENT\nCO\n\t\t$known_indels_file(s) = ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_mapping_resources/ALL.wgs.indels_mills_devine_hg19_leftAligned_collapsed_double_hit.indels.sites.vcf.gz\n\t\t$known_indels_file(s) .= ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_mapping_resources/ALL.wgs.low_coverage_vqsr.20101123.indels.sites.vcf.gz\n\t\t$known_sites_file(s) = ftp://ftp.1000genomes.ebi.ac.uk/vol1/ftp/technical/reference/phase2_mapping_resources/ALL.wgs.dbsnp.build135.snps.sites.vcf.gz\n" ] ], [ [ "check the meaning of [paired-end reads](https://www.illumina.com/science/technology/next-generation-sequencing/plan-experiments/paired-end-vs-single-read.html)", "_____no_output_____" ] ], [ [ "# pysam is 0-based\nfor rec in bam:\n if rec.cigarstring.find('M') > -1 and rec.cigarstring.find('S') > -1 and not rec.is_unmapped and not rec.mate_is_unmapped:\n break\n\nprint('query template name and ID')\nprint(rec.query_name, rec.reference_id, bam.getrname(rec.reference_id), rec.reference_start, rec.reference_end)\nprint('CIGAR string (indicates how many mapped bases. How many bases per read here?)')\nprint(rec.cigarstring)\nprint('position and length of the alignment')\nprint(rec.query_alignment_start, rec.query_alignment_end, rec.query_alignment_length)\nprint('info for the paired end')\nprint(rec.next_reference_id, rec.next_reference_start, rec.template_length)\nprint(rec.is_paired, rec.is_proper_pair, rec.is_unmapped, rec.mapping_quality)\nprint('Phred score for mapped and complete sequence')\nprint(rec.query_qualities)\nprint(rec.query_alignment_qualities)\nprint('Finally, the complete sequence of this read')\nprint(rec.query_sequence)", "query template name and ID\nSRR100025.29222641 19 20 60074 60134\nCIGAR string (indicates how many mapped bases. How many bases per read here?)\n16S60M\nposition and length of the alignment\n16 76 60\ninfo for the paired end\n19 60056 -77\nTrue True False 60\nPhred score for mapped and complete sequence\narray('B', [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 34, 30, 39, 37, 38, 28, 34, 32, 37, 24, 34, 36, 36, 19, 34, 38, 37, 36, 37, 21, 37, 36, 37, 25, 28, 31, 35, 37, 37, 38, 31, 33, 39, 34, 34, 38, 39, 37, 38, 34, 26, 33, 32, 39, 29, 39, 26, 36, 10, 37, 37, 39, 31, 37, 38, 30, 30, 33, 31])\narray('B', [2, 34, 30, 39, 37, 38, 28, 34, 32, 37, 24, 34, 36, 36, 19, 34, 38, 37, 36, 37, 21, 37, 36, 37, 25, 28, 31, 35, 37, 37, 38, 31, 33, 39, 34, 34, 38, 39, 37, 38, 34, 26, 33, 32, 39, 29, 39, 26, 36, 10, 37, 37, 39, 31, 37, 38, 30, 30, 33, 31])\nFinally, the complete sequence of this read\nACCAGATCCTGCCCCTAAACAGGTGGTAAGGAAGGAGAGAGTGAAGGAACTGCCAGGTGACACACTCCCACCATGG\n" ] ], [ [ "Now, let us plot the distribution of the successfully mapped positions in a subset of sequences in the BAM file. we will use only the positions between 0 and 10Mbp of chromosome 20. Mappability is not homogeneous!", "_____no_output_____" ] ], [ [ "counts = [0] * 76\nfor n, rec in enumerate(bam.fetch('20', 0, 10000000)):\n for i in range(rec.query_alignment_start, rec.query_alignment_end):\n counts[i] += 1\nfreqs = [x / (n + 1.) for x in counts]\nfig, ax = plt.subplots(figsize=(16,9))\nax.plot(range(1, 77), freqs)", "_____no_output_____" ], [ "phreds = defaultdict(list)\nfor rec in bam.fetch('20', 0, None):\n for i in range(rec.query_alignment_start, rec.query_alignment_end):\n phreds[i].append(rec.query_qualities[i])", "_____no_output_____" ], [ "maxs = [max(phreds[i]) for i in range(76)]\ntops = [np.percentile(phreds[i], 95) for i in range(76)]\nmedians = [np.percentile(phreds[i], 50) for i in range(76)]\nbottoms = [np.percentile(phreds[i], 5) for i in range(76)]\nmedians_fig = [x - y for x, y in zip(medians, bottoms)]\ntops_fig = [x - y for x, y in zip(tops, medians)]\nmaxs_fig = [x - y for x, y in zip(maxs, tops)]", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(16,9))\nax.stackplot(range(1, 77), (bottoms, medians_fig, tops_fig, maxs_fig))\nax.plot(range(1, 77), maxs, 'k-')", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4afc0237db311af0de822614eb593a0d9a5ac6fe
5,123
ipynb
Jupyter Notebook
Data Cleaning.ipynb
bevennyamande/Zimbabwe-Stock-Exchange-Daily-Pricesheets
fab8c0495548d42dfdb7392139c037161c2ef79b
[ "CC0-1.0" ]
1
2020-10-17T21:21:13.000Z
2020-10-17T21:21:13.000Z
Data Cleaning.ipynb
bevennyamande/Zimbabwe-Stock-Exchange-Daily-Pricesheets
fab8c0495548d42dfdb7392139c037161c2ef79b
[ "CC0-1.0" ]
null
null
null
Data Cleaning.ipynb
bevennyamande/Zimbabwe-Stock-Exchange-Daily-Pricesheets
fab8c0495548d42dfdb7392139c037161c2ef79b
[ "CC0-1.0" ]
null
null
null
36.592857
90
0.616045
[ [ [ "import os, csv\nfrom datetime import datetime\nimport pandas as pd\n\ntemp = []\ndates_collected = []\n\nfor directory, _, files in os.walk('./xls-daily-price-sheets/'):\n # TODO: implement way to exclude already loaded files\n \n for _file in files:\n dates_collected.append(_file.replace('.xlsx',\"\"))\n temp.append((os.path.join(directory, _file)))\n \ndf = pd.read_excel(temp[0])\n\n# TODO: create another csv file with the traded volumes only\n\n# TODO: sync the dates and label the dates accordingly\n\n# lets get all the names of listed companies\nlisted_companies = [comp for comp in df[0]][6::]\n\n# loop through each file to collect name,opening,closing prices and traded_volume\nfor idx in range(len(df)):\n \n if df[0][idx] in listed_companies:\n # print the company name, opening_price,closing_price, tot_volume_traded\n print(df[0][idx], df[1][idx], df[2][idx], df[3][idx])\n \n# TODO: Find a way to integrate the whole data into one csv file\n\n", "Afdis Distillers Limited 35.0000 40.0000 100\nAfrican Sun Limited 1.7811 1.5738 16500\nAmalgamated Regional Trading (Art) Holdings Limited 6.5386 6.5686 27100\nAriston Holdings Limited 2.3400 2.3381 134600\nAxia Corporation Limited 16.3664 15.9999 150500\nBindura Nickel Corporation Limited 5.8723 6.0081 52900\nBritish American Tobacco Zimbabwe Limited 874.0000 869.9000 400\nCafca Limited 110.0000 110.0000 80500\nCassava Smartech Zimbabwe Limited 10.0924 10.0782 169200\nCbz Holdings Limited 77.1882 83.0791 17700\nDairibord Holdings Limited 19.2500 19.3248 31600\nDelta Corporation Limited 43.2178 44.6643 76000\nEconet Wireless Zimbabwe Limited 17.0001 17.1675 141400\nEdgars Stores Limited 3.4965 3.5000 4600\nFbc Holdings Limited 27.5000 27.5000 2000\nFidelity Life Assurance Limited 2.5500 3.0000 200\nFirst Capital Bank Limited 1.8794 1.8800 587500\nFirst Mutual Holdings Limited 14.2840 14.5455 13300\nFirst Mutual Properties Limited 5.7613 5.7613 0\nGeneral Beltings Holdings Limited 0.2431 0.2506 400700\nGetbucks Microfinance Bank Limited 0.3105 0.3105 0\nHippo Valley Estates Limited 115.0833 120.3911 17900\nInnscor Africa Limited 58.1213 60.0704 80100\nLafarge Cement Zimbabwe Limited 27.6000 27.6000 0\nMashonaland Holdings Limited 1.1971 1.3047 93500\nMasimba Holdings Limited 17.9065 19.0000 325900\nMedtech Holdings Limited 0.0721 0.0749 7237200\nMeikles Limited 45.0000 44.3984 329800\nNampak Zimbabwe Limited 6.8945 7.0000 29700\nNational Foods Holdings Limited 221.7500 266.1000 500\nNational Tyre Services Limited 0.6800 0.8150 200\nNmbz Holdings Limited 6.4389 6.4389 0\nOk Zimbabwe Limited 15.2079 14.8620 1361100\nPadenga Holdings Limited 33.9000 31.5437 108700\nProplastics Limited 26.0000 24.4167 6600\nRainbow Tourism Group Limited 1.6621 1.5573 3000\nRiozim Limited 20.0000 20.0000 80200\nSeed Co Limited 21.6089 21.6089 0\nSimbisa Brands Limited 18.9505 19.5840 519200\nStarafricacorporation Limited 0.5079 0.5079 208400\nTruworths Limited 0.6043 0.6350 2000\nTsl Limited 43.0000 43.0000 5700\nTurnall Holdings Limited 1.3045 1.3000 60100\nUnifreight Africa Limited 4.6000 5.5200 100\nWilldale Limited 0.5500 0.5608 5600\nZb Financial Holdings Limited 40.0000 40.0000 0\nZeco Holdings Limited 0.0002 0.0002 0\nZimbabwe Newspapers (1980) Limited 1.1200 1.0000 700\nZimplow Holdings Limited 8.2000 8.2000 3400\nZimre Holdings Limited 2.0277 2.1395 170600\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
4afc117312883e0eb3ac55c2aef757ff77bc4468
171,724
ipynb
Jupyter Notebook
Complete/CIFAR10-Complete.ipynb
fermaat/afi_deep_learning_intro
f4f783168da9a161f187a9ae5dc4962ad6f3904f
[ "Apache-2.0" ]
null
null
null
Complete/CIFAR10-Complete.ipynb
fermaat/afi_deep_learning_intro
f4f783168da9a161f187a9ae5dc4962ad6f3904f
[ "Apache-2.0" ]
13
2020-02-22T18:42:13.000Z
2022-02-10T01:34:21.000Z
Complete/CIFAR10-Complete.ipynb
fermaat/afi_deep_learning_intro
f4f783168da9a161f187a9ae5dc4962ad6f3904f
[ "Apache-2.0" ]
null
null
null
266.652174
46,364
0.917705
[ [ [ "# CNN study case: train on Cifar10.\n\nOn this notebook we will cover the training of a simple model on the CIFAR 10 dataset, and we will cover the next topics:\n- Cifar10 dataset\n- Model architecture: \n - 2D Convolutional layers\n - MaxPooling\n - Relu activation\n - Batch normalization\n- Image generator data augmentation\n- TTA (Test time augmentation)\n### The dataset", "_____no_output_____" ], [ "The dataset is composed by 60000 32x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 test images. These are the image classes:\n- airplane \n- automobile \n- bird\n- cat\n- deer\n- dog\n- frog\n- horse\n- ship\n- truck", "_____no_output_____" ] ], [ [ "import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport tensorflow as tf\ntf.get_logger().setLevel('ERROR')\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\ntf.keras.backend.clear_session() # For easy reset of notebook state.\n\nfrom tensorflow.keras.datasets.cifar10 import load_data\nfrom tensorflow.keras.utils import to_categorical\n\n(trainX, trainY), (testX, testY) = load_data()\n# normalize pixel values\ntrainX = trainX.astype('float32') / 255\ntestX = testX.astype('float32') / 255\n# one hot encode target values\ntrainY = to_categorical(trainY)\ntestY = to_categorical(testY)\ntrainX[0].shape", "_____no_output_____" ] ], [ [ "<font color=red><b>Plot some examples of the dataset.\n<br>Hint: use the imshow function of the pyplot package</b>\n</font>", "_____no_output_____" ] ], [ [ "from matplotlib import pyplot as plt\n%matplotlib inline\nfor j in range (10):\n plt.imshow((trainX[j]*255).astype('uint8'))\n plt.show()\n ", "_____no_output_____" ], [ "from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import BatchNormalization\nfrom numpy import mean\nfrom numpy import std", "_____no_output_____" ] ], [ [ "## Model Architecture\nBuild the CNN model to be trained train on the data, on this config:\n- Conv2d layer, with 32 units and 3x3 filter, with relu activation and padding of \"same\" type. Use the \"he_uniform\" initializer.\n- batchnorm\n- max pooling (2x2)\n- Conv2d layer, with 64 units and 3x3 filter, with relu activation and padding of \"same\" type. Use the \"he_uniform\" initializer.\n- batchnorm\n- max pooling (2x2)\n- Dense layer, with 128 units\n- Dense softmax layer\n- On compilation, use adam as the optimizer and categorical_crossentropy as the loss function. Add 'accuracy' as a metric\n- Print the summary\n\n\n<font color=red><b>Remember to initialize it propperly and to include input_shape on the first layer. <br> Hint: \n- Use the imported libraries</b></font>", "_____no_output_____" ] ], [ [ "def define_model():\n # define model\n model = Sequential()\n model.add(Conv2D(32, (3, 3), activation='relu', padding='same', kernel_initializer='he_uniform', input_shape=(32, 32, 3)))\n model.add(BatchNormalization())\n model.add(MaxPooling2D((2, 2)))\n model.add(Conv2D(64, (3, 3), activation='relu', padding='same', kernel_initializer='he_uniform'))\n model.add(BatchNormalization())\n model.add(MaxPooling2D((2, 2)))\n model.add(Flatten())\n model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n model.add(BatchNormalization())\n model.add(Dense(10, activation='softmax'))\n # compile model\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n return model", "_____no_output_____" ] ], [ [ "We are going to train small steps of our model in order to evaluate the hyperparameters and the strategy. In order to do that, we will define a step epochs number and will train and evaluate the model for that amount of epochs. after a number of repeats we will reduce the effect random initialization of certain parameters.\n\n<font color=red>Evaluate the built model by training 10 times on different initializations<b> Hint: we would like to have some parameters of the score distribution, like the ones imported </b></font>", "_____no_output_____" ] ], [ [ "step_epochs = 3\nbatch_size = 128\n\ndef evaluate_model(model, trainX, trainY, testX, testY):\n # fit model\n model.fit(trainX, trainY, epochs=step_epochs, batch_size=batch_size, verbose=0)\n # evaluate model\n _, acc = model.evaluate(testX, testY, verbose=0)\n return acc\n\n\ndef evaluate(trainX, trainY, testX, testY, repeats=10):\n scores = list()\n for _ in range(repeats):\n # define model\n model = define_model()\n # fit and evaluate model\n accuracy = evaluate_model(model, trainX, trainY, testX, testY)\n # store score\n scores.append(accuracy)\n print('> %.3f' % accuracy)\n return scores\n\n\n# evaluate model\nscores = evaluate(trainX, trainY, testX, testY)\n# summarize result\nprint('Accuracy: %.3f (%.3f)' % (mean(scores), std(scores)))", "> 0.625\n> 0.671\n> 0.671\n> 0.667\n> 0.679\n> 0.664\n> 0.665\n> 0.689\n> 0.674\n> 0.680\nAccuracy: 0.669 (0.016)\n" ] ], [ [ "### Keras Image data generator\nIn order to perform some data augmentation, Keras includes the Image data generator, which can be used to improve performance and reduce generalization error when training neural network models for computer vision problems. \nA range of techniques are supported, as well as pixel scaling methods. Some of the most commn are: \n\n- Image shifts via the width_shift_range and height_shift_range arguments.\n- Image flips via the horizontal_flip and vertical_flip arguments.\n- Image rotations via the rotation_range argument\n- Image brightness via the brightness_range argument.\n- Image zoom via the zoom_range argument.\n\n\nLet's see it with an example:\n", "_____no_output_____" ] ], [ [ "# expand dimension to one sample\nfrom numpy import expand_dims\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\ndata = trainX[0]*255\nsamples = expand_dims(data, 0)\n# create image data augmentation generator\ndatagen = ImageDataGenerator(horizontal_flip=True, \n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2)\n\n# prepare iterator\nit = datagen.flow(samples, batch_size=1)\n# generate samples and plot\nfor i in range(9):\n # define subplot\n plt.subplot(330 + 1 + i)\n # generate batch of images\n batch = it.next()\n # convert to unsigned integers for viewing\n image = batch[0].astype('uint8')\n # plot raw pixel data\n plt.imshow(image)\n# show the figure\nplt.show()", "/home/fer/data/venvs/dl_tf2/lib/python3.6/site-packages/keras_preprocessing/image/image_data_generator.py:716: UserWarning: This ImageDataGenerator specifies `featurewise_center`, but it hasn't been fit on any training data. Fit it first by calling `.fit(numpy_data)`.\n warnings.warn('This ImageDataGenerator specifies '\n/home/fer/data/venvs/dl_tf2/lib/python3.6/site-packages/keras_preprocessing/image/image_data_generator.py:724: UserWarning: This ImageDataGenerator specifies `featurewise_std_normalization`, but it hasn't been fit on any training data. Fit it first by calling `.fit(numpy_data)`.\n warnings.warn('This ImageDataGenerator specifies '\n" ], [ "batch.shape", "_____no_output_____" ] ], [ [ "<font color=red>Evaluate the model with data augmentation <br> Hint: Use the ?model.fit_generator command and please take into acount the parameters of the model.fit_generator: It needs to include: epochs, steps_per_epoch and a generator (i.e: a flow of images). </font>", "_____no_output_____" ] ], [ [ "# fit and evaluate a defined model\ndef evaluate_model_increased(model, trainX, trainY, testX, testY):\n datagen = ImageDataGenerator(horizontal_flip=True)\n # in case there is mean/std to normalize\n datagen.fit(trainX)\n\n # Fit the model on the batches generated by datagen.flow().\n model.fit_generator(datagen.flow(trainX, trainY,\n batch_size=batch_size),\n epochs=step_epochs,\n steps_per_epoch=len(trainX) // batch_size,\n verbose = 0)\n \n # evaluate model\n _, acc = model.evaluate(testX, testY, verbose=0)\n return acc\n\n# repeatedly evaluate model, return distribution of scores\ndef repeated_evaluation_increased(trainX, trainY, testX, testY, repeats=10):\n scores = list()\n for _ in range(repeats):\n # define model\n model = define_model()\n # fit and evaluate model\n accuracy = evaluate_model_increased(model, trainX, trainY, testX, testY)\n # store score\n scores.append(accuracy)\n print('> %.3f' % accuracy)\n return scores\n\n# evaluate model\nscores = repeated_evaluation_increased(trainX, trainY, testX, testY)\n# summarize result\nprint('Accuracy: %.3f (%.3f)' % (mean(scores), std(scores)))", "> 0.672\n> 0.691\n> 0.696\n> 0.692\n> 0.645\n> 0.704\n> 0.699\n> 0.680\n> 0.677\n> 0.673\nAccuracy: 0.683 (0.016)\n" ] ], [ [ "### Test Time augmentation (TTA)\n\nThe image data augmentation technique can also be applied when making predictions with a fit model in order to allow the model to make predictions for multiple different versions of each image in the test dataset. Specifically, it involves creating multiple augmented copies of each image in the test set, having the model make a prediction for each, then returning an ensemble of those predictions.(e.g: majority voting in case of classification)\n\nAugmentations are chosen to give the model the best opportunity for correctly classifying a given image, and the number of copies of an image for which a model must make a prediction is often small, such as less than 10 or 20. Often, a single simple test-time augmentation is performed, such as a shift, crop, or image flip.", "_____no_output_____" ], [ "<font color=red>Evaluate the model with data augmentation. <b>Please note on this case we are not going to use the generateor on training, but on testing.</b> <br> Hint: Use the model.predict_generator function </font>", "_____no_output_____" ] ], [ [ "from sklearn.metrics import accuracy_score\nimport numpy as np\nn_examples_per_image = 3\n\n\n# make a prediction using test-time augmentation\ndef prediction_augmented_on_test(datagen, model, image, n_examples):\n # convert image into dataset\n samples = expand_dims(image, 0)\n # prepare iterator\n it = datagen.flow(samples, batch_size=n_examples)\n # make predictions for each augmented image\n yhats = model.predict_generator(it, steps=n_examples, verbose=0)\n # sum across predictions\n summed = np.sum(yhats, axis=0)\n # argmax across classes\n return np.argmax(summed)\n\n# evaluate a model on a dataset using test-time augmentation\ndef evaluate_model_test_time_agumented(model, testX, testY):\n # configure image data augmentation\n datagen = ImageDataGenerator(horizontal_flip=True)\n # define the number of augmented images to generate per test set image\n yhats = list()\n for i in range(len(testX)):\n # make augmented prediction\n yhat = prediction_augmented_on_test(datagen, model, testX[i], n_examples_per_image)\n # store for evaluation\n yhats.append(yhat)\n # calculate accuracy\n testY_labels = np.argmax(testY, axis=1)\n acc = accuracy_score(testY_labels, yhats)\n return acc\n\ndef evaluate_model_test_augmented(model, trainX, trainY, testX, testY):\n # fit model\n model.fit(trainX, trainY, epochs=step_epochs, batch_size=batch_size, verbose=0)\n # evaluate model\n acc = evaluate_model_test_time_agumented(model, testX, testY)\n return acc\n\ndef evaluate_test_augmented(trainX, trainY, testX, testY, repeats=10):\n scores = list()\n for _ in range(repeats):\n # define model\n model = define_model()\n # fit and evaluate model\n accuracy = evaluate_model_test_augmented(model, trainX, trainY, testX, testY)\n # store score\n scores.append(accuracy)\n print('> %.3f' % accuracy)\n return scores\n\n\n# evaluate model\nscores = evaluate_test_augmented(trainX, trainY, testX, testY)\n# summarize result\nprint('Accuracy: %.3f (%.3f)' % (mean(scores), std(scores)))", "> 0.712\n> 0.709\n> 0.685\n> 0.697\n> 0.696\n> 0.673\n> 0.678\n> 0.683\n> 0.681\n> 0.670\nAccuracy: 0.689 (0.014)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4afc2a73c0963acf17ee0ac7a12ba6685c4875b4
9,118
ipynb
Jupyter Notebook
NLTK_L1.ipynb
liufuyang/NLTK_tutorial_sentdex
39172578e2fd998e59a7bf702404444074f2baa4
[ "MIT" ]
null
null
null
NLTK_L1.ipynb
liufuyang/NLTK_tutorial_sentdex
39172578e2fd998e59a7bf702404444074f2baa4
[ "MIT" ]
null
null
null
NLTK_L1.ipynb
liufuyang/NLTK_tutorial_sentdex
39172578e2fd998e59a7bf702404444074f2baa4
[ "MIT" ]
null
null
null
23.260204
1,370
0.483659
[ [ [ "# Tokenizng, lexicon and corporas", "_____no_output_____" ] ], [ [ "import nltk", "Vendor: Continuum Analytics, Inc.\nPackage: mkl\nMessage: trial mode expires in 30 days\n" ], [ "nltk.download()", "showing info http://www.nltk.org/nltk_data/\n" ] ], [ [ "* tokenizing - word tokenizer; sentence tokenizers; seperate words or sentences\n* lexicon and corporas: \n * corpora - body of text. ex: medical journals, speeches\n * lexicon - words and their meaning/values\n * investor speak 'bull' = somone who is positive about the market\n * english speak 'bull' = scary animal you don't want to running at you.", "_____no_output_____" ] ], [ [ "from nltk.tokenize import sent_tokenize, word_tokenize", "_____no_output_____" ], [ "example_text = \"\"\"Hello Mr. Smith, how are you doing today?\nThe weather is great and Python is awesome. \nThe sky is pinkish-blue, and you should not eat keyboard.\"\"\"", "_____no_output_____" ], [ "print(sent_tokenize(example_text))", "['Hello there, how are you doing today?', 'The weather is great and Python is awesome.', 'The sky is pinkish-blue, and you should not eat keyboard.']\n" ], [ "print(word_tokenize(example_text))", "['Hello', 'there', ',', 'how', 'are', 'you', 'doing', 'today', '?', 'The', 'weather', 'is', 'great', 'and', 'Python', 'is', 'awesome', '.', 'The', 'sky', 'is', 'pinkish-blue', ',', 'and', 'you', 'should', 'not', 'eat', 'keyboard', '.']\n" ] ], [ [ "# Stop words:", "_____no_output_____" ] ], [ [ "from nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize", "_____no_output_____" ], [ "stop_words = set(stopwords.words(\"english\"))", "_____no_output_____" ], [ "example_text = \"\"\"Hello Mr. Smith, how are you doing today?\nThe weather is great and Python is wonderful. Basically speaking, it's fun here. \nThe sky is pinkish-blue, and you should not eat keyboard.\"\"\"", "_____no_output_____" ], [ "print stop_words", "set([u'all', u'just', u'being', u'over', u'both', u'through', u'yourselves', u'its', u'before', u'o', u'hadn', u'herself', u'll', u'had', u'should', u'to', u'only', u'won', u'under', u'ours', u'has', u'do', u'them', u'his', u'very', u'they', u'not', u'during', u'now', u'him', u'nor', u'd', u'did', u'didn', u'this', u'she', u'each', u'further', u'where', u'few', u'because', u'doing', u'some', u'hasn', u'are', u'our', u'ourselves', u'out', u'what', u'for', u'while', u're', u'does', u'above', u'between', u'mustn', u't', u'be', u'we', u'who', u'were', u'here', u'shouldn', u'hers', u'by', u'on', u'about', u'couldn', u'of', u'against', u's', u'isn', u'or', u'own', u'into', u'yourself', u'down', u'mightn', u'wasn', u'your', u'from', u'her', u'their', u'aren', u'there', u'been', u'whom', u'too', u'wouldn', u'themselves', u'weren', u'was', u'until', u'more', u'himself', u'that', u'but', u'don', u'with', u'than', u'those', u'he', u'me', u'myself', u'ma', u'these', u'up', u'will', u'below', u'ain', u'can', u'theirs', u'my', u'and', u've', u'then', u'is', u'am', u'it', u'doesn', u'an', u'as', u'itself', u'at', u'have', u'in', u'any', u'if', u'again', u'no', u'when', u'same', u'how', u'other', u'which', u'you', u'shan', u'needn', u'haven', u'after', u'most', u'such', u'why', u'a', u'off', u'i', u'm', u'yours', u'so', u'y', u'the', u'having', u'once'])\n" ], [ "words = word_tokenize(example_text)", "_____no_output_____" ], [ "filtered_words = filter(lambda w: w not in stop_words, words)\n\n#filtered_words = [w for w in words if not w in stop_words]", "_____no_output_____" ], [ "filtered_words", "_____no_output_____" ] ], [ [ "# Stemming", "_____no_output_____" ] ], [ [ "from nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize", "_____no_output_____" ], [ "ps = PorterStemmer()", "_____no_output_____" ], [ "\nwords = word_tokenize(example_text)\n\nfiltered_words = filter(lambda w: w not in stop_words, words)\n\nfiltered_stemmed_words = map(ps.stem, filtered_words)", "_____no_output_____" ], [ "filtered_stemmed_words", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4afc483e51b73baa4eaf0f163d7417885c0beb27
350,792
ipynb
Jupyter Notebook
Complete Machine Learning and Data Science - Zero to Mastery - AN/11.Heart Disease Project/Milestone Project - Heart Disease Classification.ipynb
ptyadana/probability-and-statistics-for-business-and-data-science
6c4d09c70e4c8546461eb7ebc401bb95a0827ef2
[ "MIT" ]
10
2021-01-14T15:14:03.000Z
2022-02-19T14:06:25.000Z
Complete Machine Learning and Data Science - Zero to Mastery - AN/11.Heart Disease Project/Milestone Project - Heart Disease Classification.ipynb
ptyadana/probability-and-statistics-for-business-and-data-science
6c4d09c70e4c8546461eb7ebc401bb95a0827ef2
[ "MIT" ]
null
null
null
Complete Machine Learning and Data Science - Zero to Mastery - AN/11.Heart Disease Project/Milestone Project - Heart Disease Classification.ipynb
ptyadana/probability-and-statistics-for-business-and-data-science
6c4d09c70e4c8546461eb7ebc401bb95a0827ef2
[ "MIT" ]
8
2021-03-24T13:00:02.000Z
2022-03-27T16:32:20.000Z
109.656768
118,640
0.838121
[ [ [ "# Predicting Heart Disease using Machine Learning\n\nThis notebook uses various Python based machine learning and data science libraries in an attempt to build a machine learning model capable of predicting whether or not someone has a Heart Disease based on their medical attributes.\n\nWe're going to take the following approach:\n1. [Problem Definition](#definition)\n2. [Data](#data) \n3. [Evaluation](#evaluation)\n4. [Features](#features)\n5. [Modelling](#modelling)\n6. [Experimentation](#experimentation)", "_____no_output_____" ], [ "## <a name=\"definition\">1. Problem Definition</a>\n\nIn a statement, \n> Given clinical parameters about a patient, can we predict whether or not a they have a heart disease or not?", "_____no_output_____" ], [ "## <a name=\"data\">2. Data</a>\n\n[Heart Disease UCI - Original Version](https://archive.ics.uci.edu/ml/datasets/heart+disease)\n\n\n[Heart Disease UCI - Kaggle Version](https://www.kaggle.com/ronitf/heart-disease-uci)", "_____no_output_____" ], [ "## <a name=\"evaluation\">3.Evaluation</a>", "_____no_output_____" ], [ "> If we can reach 95% of accuracy at predicting whether or not a patient has heart disease during the proof of concept, we'll pursue the project.", "_____no_output_____" ], [ "## <a name=\"features\">4.Features</a>", "_____no_output_____" ], [ "The following are the features we'll use to predict our target variable (heart disease or no heart disease).\n\n1. age - age in years \n2. sex - (1 = male; 0 = female) \n3. cp - chest pain type \n * 0: Typical angina: chest pain related decrease blood supply to the heart\n * 1: Atypical angina: chest pain not related to heart\n * 2: Non-anginal pain: typically esophageal spasms (non heart related)\n * 3: Asymptomatic: chest pain not showing signs of disease\n4. trestbps - resting blood pressure (in mm Hg on admission to the hospital)\n * anything above 130-140 is typically cause for concern\n5. chol - serum cholestoral in mg/dl \n * serum = LDL + HDL + .2 * triglycerides\n * above 200 is cause for concern\n6. fbs - (fasting blood sugar > 120 mg/dl) (1 = true; 0 = false) \n * '>126' mg/dL signals diabetes\n7. restecg - resting electrocardiographic results\n * 0: Nothing to note\n * 1: ST-T Wave abnormality\n - can range from mild symptoms to severe problems\n - signals non-normal heart beat\n * 2: Possible or definite left ventricular hypertrophy\n - Enlarged heart's main pumping chamber\n8. thalach - maximum heart rate achieved \n9. exang - exercise induced angina (1 = yes; 0 = no) \n10. oldpeak - ST depression induced by exercise relative to rest \n * looks at stress of heart during excercise\n * unhealthy heart will stress more\n11. slope - the slope of the peak exercise ST segment\n * 0: Upsloping: better heart rate with excercise (uncommon)\n * 1: Flatsloping: minimal change (typical healthy heart)\n * 2: Downslopins: signs of unhealthy heart\n12. ca - number of major vessels (0-3) colored by flourosopy \n * colored vessel means the doctor can see the blood passing through\n * the more blood movement the better (no clots)\n13. thal - thalium stress result\n * 1,3: normal\n * 6: fixed defect: used to be defect but ok now\n * 7: reversable defect: no proper blood movement when excercising \n14. target - have disease or not (1=yes, 0=no) (= the predicted attribute)\n\n**Note:** No personal identifiable information (PPI) can be found in the dataset.", "_____no_output_____" ] ], [ [ "# Regular EDA and plotting libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Models from scikit-learn\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Model Evaluations\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.metrics import precision_score, recall_score, f1_score\nfrom sklearn.metrics import plot_roc_curve, plot_confusion_matrix", "_____no_output_____" ] ], [ [ "---------", "_____no_output_____" ], [ " ## Load data", "_____no_output_____" ] ], [ [ "df = pd.read_csv('data/heart-disease.csv')", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "--------", "_____no_output_____" ], [ "## Exploratory Data Analysis (EDA)\n\n1. What question(s) are we trying to solve?\n2. What kind of data do we have and how do we treat different types?\n3. What are the missing data and how are we going to handle them?\n4. What are the outliers, why we care about them and how are we going to handle them?\n5. How can we add, change or remove features to get more out of the data?", "_____no_output_____" ] ], [ [ "df.tail()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 303 entries, 0 to 302\nData columns (total 14 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 age 303 non-null int64 \n 1 sex 303 non-null int64 \n 2 cp 303 non-null int64 \n 3 trestbps 303 non-null int64 \n 4 chol 303 non-null int64 \n 5 fbs 303 non-null int64 \n 6 restecg 303 non-null int64 \n 7 thalach 303 non-null int64 \n 8 exang 303 non-null int64 \n 9 oldpeak 303 non-null float64\n 10 slope 303 non-null int64 \n 11 ca 303 non-null int64 \n 12 thal 303 non-null int64 \n 13 target 303 non-null int64 \ndtypes: float64(1), int64(13)\nmemory usage: 33.3 KB\n" ], [ "# check if there is any missing data\ndf.isnull().sum()", "_____no_output_____" ], [ "# how many classes are in target variable?\ndf['target'].value_counts()", "_____no_output_____" ], [ "# visulaiztion of classes\n# sns.countplot(x=df['target']);\ndf['target'].value_counts().plot.bar(color=['salmon', 'lightblue']);\nplt.xlabel('0: No Disease, 1: Heart Disease')\nplt.ylabel('Count');", "_____no_output_____" ] ], [ [ "Seem like there are 2 categories and pretty balanced dataset.", "_____no_output_____" ], [ "-------", "_____no_output_____" ], [ "## Finding Patterns in data", "_____no_output_____" ] ], [ [ "df.describe().transpose()", "_____no_output_____" ] ], [ [ "### Heart disease frequency according to Sex", "_____no_output_____" ] ], [ [ "df['sex'].value_counts()", "_____no_output_____" ] ], [ [ "There are about 207 male and 96 females. So we have more male population, so we need to keep that in back of our mind\n\n(1 = male; 0 = female)", "_____no_output_____" ] ], [ [ "pd.crosstab(df['sex'], df['target'])", "_____no_output_____" ], [ "72/(24+72), 93/(114+93)", "_____no_output_____" ] ], [ [ "We can see that based on existing data, there are 75% chances that female can have a heart disease. For male, there are 45% chance.", "_____no_output_____" ] ], [ [ "# visualize the data\n# pd.crosstab(df['sex'], df['target']).plot(kind='bar', color=['salmon', 'lightblue']);\n\npd.crosstab(df['sex'], df['target']).plot(kind='bar');\nplt.title('Heart disease frequency by Sex')\nplt.xlabel('0: No Disease, 1: Heart Disease ')\nplt.ylabel('Count')\nplt.legend(['Female', 'Male']);\nplt.xticks(rotation=0);", "_____no_output_____" ] ], [ [ "### Age Vs Max. Heart Rate for people who have Heart Disease", "_____no_output_____" ] ], [ [ "df.columns", "_____no_output_____" ], [ "plt.figure(figsize=(10, 7))\n\n# positive cases\nsns.scatterplot(data=df, x=df.age[df.target==1], y=df.thalach[df.target==1], color='salmon', s=50, alpha=0.8);\n\n# negative cases\nsns.scatterplot(data=df, x=df.age[df.target==0], y=df.thalach[df.target==0], color='lightblue', s=50, alpha=0.8)\n\nplt.title('Heart Disease in function of Age and Max Heart Rate')\nplt.xlabel('Age')\nplt.ylabel('Max Heart Rate');\nplt.legend(['Heart Disease', 'No Disease']);", "_____no_output_____" ] ], [ [ "### Distribution of Age", "_____no_output_____" ] ], [ [ "sns.histplot(data=df, x=df['age'], bins=30);", "_____no_output_____" ] ], [ [ "### Heart Disease Frequency per Chest Pain level\n\ncp - chest pain type \n * 0: Typical angina: chest pain related decrease blood supply to the heart\n * 1: Atypical angina: chest pain not related to heart\n * 2: Non-anginal pain: typically esophageal spasms (non heart related)\n * 3: Asymptomatic: chest pain not showing signs of disease", "_____no_output_____" ] ], [ [ "pd.crosstab(df['target'], df['cp'])", "_____no_output_____" ], [ "pd.crosstab(df['cp'], df['target']).plot(kind='bar', color=['lightblue', 'salmon']);\n\nplt.title('Heart Disease Frequency per Chest Pain level')\nplt.xlabel('Chest Pain Level')\nplt.ylabel('Count')\nplt.legend(['No Diease', 'Heart Disease'])\nplt.xticks(rotation=0);", "_____no_output_____" ] ], [ [ "### Correlation between indepedent variables", "_____no_output_____" ] ], [ [ "df.corr()['target'][:-1]", "_____no_output_____" ], [ "# visualization\ncorr_matrix = df.corr()\n\nplt.figure(figsize=(12, 8))\nsns.heatmap(corr_matrix, annot=True, linewidth=0.5, fmt='.2f', cmap='viridis_r');", "_____no_output_____" ] ], [ [ "As per the heatmap above, `Chest pain (cp)` has the highest positive correlation with Target variable among the features, followed by `thalach (Maximum Heart Rate)` variable.\n\nOn the other hand, `exang - exercise induced angina` and `oldpeak - ST depression induced by exercise relative to rest` have the lowest correlation with Target variable.", "_____no_output_____" ], [ "--------", "_____no_output_____" ], [ "## <a name=\"modelling\">5. Modelling</a>", "_____no_output_____" ] ], [ [ "df.head(2)", "_____no_output_____" ], [ "# split features and labels\nX = df.drop('target', axis=1)\ny = df['target']", "_____no_output_____" ], [ "X.head(2)", "_____no_output_____" ], [ "y.head(2)", "_____no_output_____" ], [ "# split into training, testing datasets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)", "_____no_output_____" ], [ "X_train.shape, X_test.shape, y_train.shape, y_test.shape", "_____no_output_____" ] ], [ [ "As there is no missing data and no values to convert from categorical to numerical values, we will continue to build model and train them .", "_____no_output_____" ], [ "### Model Training", "_____no_output_____" ], [ "\nWe will try 3 different models.\n\n1. Logistic Regression\n2. K-Nearest Neighbours Classifier\n3. Random Forest Classifier", "_____no_output_____" ] ], [ [ "# put models in dictionary\n\nmodels = {\n 'LogisticRegression': LogisticRegression(max_iter=1000),\n 'KNN': KNeighborsClassifier(),\n 'RandomForestClassifer': RandomForestClassifier()\n}\n\n# create function to fit and score model\ndef fit_and_score(models, X_train, X_test, y_train, y_test):\n \"\"\"\n Fits and evalute given machine learning models.\n models: a dictionary of different scikit learn machine learning models\n X_train: training date (no labels)\n X_test: testing data (no labels)\n y_train: training labels\n y_test : testing labels\n returns model scores dictionary.\n \"\"\"\n \n # set random seed\n np.random.seed(42)\n \n # make dictonary to keep scores\n model_scores = {}\n \n # loop through models to fit and score\n for model_name, model in models.items():\n model.fit(X_train, y_train) # fit model\n score = model.score(X_test, y_test) # get score\n model_scores[model_name] = score # put score for each model\n \n return model_scores ", "_____no_output_____" ], [ "# fit and score\nmodel_scores = fit_and_score(models, X_train, X_test, y_train, y_test)\n\nmodel_scores", "_____no_output_____" ] ], [ [ "### Model Comparison", "_____no_output_____" ] ], [ [ "model_compare = pd.DataFrame(model_scores, index=['accuracy'])\n\nmodel_compare.head()", "_____no_output_____" ], [ "model_compare.T.plot(kind='bar');", "_____no_output_____" ] ], [ [ "---------", "_____no_output_____" ], [ "## <a name=\"experimentation\">6.Experimentation</a>", "_____no_output_____" ], [ "### Tuning or Improving our models", "_____no_output_____" ], [ "Now we've got baseline models. and we might want to experiment to improve the results.\n\nWe will be doing:\n* Hyperparameter tuning\n* Feature Importance\n* Confusion Matrix\n* Cross Validation\n* Precision\n* Recall\n* F1 Score\n* Classification Report\n* ROC curve\n* Area Under the Curve (AUC)\n\n\n### Hyperparameter Tuning\n1. [Hyperparameter Tuning - Manually](#manually)\n2. [Hyperparameter Tuning - using RandomizedSearchCV](#randomized)\n3.[Hyperparameter Tuning - using GridSearchCV](#grid)", "_____no_output_____" ], [ "### <a name='manually'>Hyperparameter Tuning - Manually</a>", "_____no_output_____" ] ], [ [ "train_scores = []\ntest_scores = []", "_____no_output_____" ] ], [ [ "### KNN ", "_____no_output_____" ] ], [ [ "# create a different values of parameters\nneighbours = range(1, 21)\n\n# instantiate instance\nknn = KNeighborsClassifier()\n\n# loop through different n_neighbors\nfor i in neighbours:\n # set param\n knn.set_params(n_neighbors=i)\n \n # fit model\n knn.fit(X_train, y_train)\n \n # get score\n train_scores.append(knn.score(X_train, y_train))\n test_scores.append(knn.score(X_test, y_test))", "_____no_output_____" ], [ "plt.plot(neighbours, train_scores, label='Train Score')\nplt.plot(neighbours, test_scores, label='Test Score');\n\nplt.xticks(np.arange(1,21,1))\nplt.legend();\nplt.xlabel('n_neighbor')\nplt.ylabel('score');\n\nprint(f\"Maximum KNN score on the test data: {max(test_scores) * 100:.2f}%\")", "Maximum KNN score on the test data: 75.41%\n" ] ], [ [ "-----", "_____no_output_____" ], [ "## <a name='randomized'>Hyperparameter Tuning - using RandomizedSearchCV</a>\n\nWe are going to tune the following models using RandomizedSearchCV.\n\n* Logistic Regression\n\n* RandomForest Classifier\n", "_____no_output_____" ] ], [ [ "# help(LogisticRegression)", "_____no_output_____" ], [ "np.logspace(-4, 4, 20)", "_____no_output_____" ], [ "# help(RandomForestClassifier)", "_____no_output_____" ] ], [ [ "#### Create Hyperparameter Grid", "_____no_output_____" ] ], [ [ "# create hyperparameter grid for Logistic Regression\nlog_reg_grid = {\n 'C': np.logspace(-4, 4, 20),\n 'solver': ['liblinear']\n}\n\n# create hyperparameter grid for Random Forest Classifier\nrf_grid = {\n 'n_estimators': np.arange(10, 1000, 50),\n 'max_depth': [None, 3, 5, 10],\n 'min_samples_split': np.arange(2, 20, 2),\n 'min_samples_leaf': np.arange(1, 20, 2)\n}", "_____no_output_____" ] ], [ [ "#### Create RandomizedSearchCV with created Hyperparameter Grid (Logistic Regression)", "_____no_output_____" ] ], [ [ "np.random.seed(42)\n\n# set up random hyperparameter search for Logistic Regression\nrs_log_reg = RandomizedSearchCV(LogisticRegression(), \n log_reg_grid, \n cv=5, \n n_iter=20, \n verbose=True)\n\n# fit random hyperparameter search model for Logistic Regression\nrs_log_reg.fit(X_train, y_train)", "Fitting 5 folds for each of 20 candidates, totalling 100 fits\n" ], [ "# check best parameters\nrs_log_reg.best_params_", "_____no_output_____" ], [ "# check the score\nrs_log_reg.score(X_test, y_test)", "_____no_output_____" ], [ "# comparing with baseline scores\nmodel_scores", "_____no_output_____" ] ], [ [ "#### Create RandomizedSearchCV with created Hyperparameter Grid (Random Forest Classifier)", "_____no_output_____" ] ], [ [ "np.random.seed(42)\n\n# set up random hyperparameter search for RandomForestClassifier\nrs_rf = RandomizedSearchCV(RandomForestClassifier(), rf_grid, cv=5, n_iter=20, verbose=True)\n\n# fit random hyperparamter search model\nrs_rf.fit(X_train, y_train)", "Fitting 5 folds for each of 20 candidates, totalling 100 fits\n" ], [ "# check best parameters\nrs_rf.best_params_", "_____no_output_____" ], [ "# check the score\nrs_rf.score(X_test, y_test)", "_____no_output_____" ], [ "# comparing with baseline scores\nmodel_scores", "_____no_output_____" ] ], [ [ "**We can see that between LogisticRegression and RandomForestClassifier using RandomizedSearchCV, LogisticRegression score is better.**\n\n**So we will explore using LogisticRegression with GridSearchCV to further improve the performance.**", "_____no_output_____" ], [ "---------", "_____no_output_____" ], [ "## <a name='grid'>Hyperparameter Tuning - using GridSearchCV</a>\n\nWe are going to tune the following models using GridSearchCV.\n\n* Logistic Regression", "_____no_output_____" ] ], [ [ "# create hyperparameter grid for Logistic Regression\nlog_reg_grid = {\n 'C': np.logspace(-4, 4, 20),\n 'solver': ['liblinear']\n}\n\n# set up grid hyperparameter search for Logistic Regression\ngs_log_reg = GridSearchCV(LogisticRegression(), \n log_reg_grid, \n cv=5, \n verbose=True)\n\n# train the model\ngs_log_reg.fit(X_train, y_train)", "Fitting 5 folds for each of 20 candidates, totalling 100 fits\n" ], [ "# get best parameters\ngs_log_reg.best_params_", "_____no_output_____" ], [ "# get the score\ngs_log_reg.score(X_test, y_test)", "_____no_output_____" ] ], [ [ "---------", "_____no_output_____" ], [ "### Evaluating Models\n\nEvaluating our tuned machine learning classifiers, beyond accuracy\n\n* ROC and AUC score\n* Confusion Matrix, Plot Confusion Matrix\n* Classification Report\n* Precision\n* Recall\n* F1", "_____no_output_____" ] ], [ [ "# make predictions\ny_preds = gs_log_reg.predict(X_test)", "_____no_output_____" ], [ "# ROC curve and AUC\nplot_roc_curve(gs_log_reg, X_test, y_test);", "_____no_output_____" ], [ "confusion_matrix(y_test, y_preds)", "_____no_output_____" ], [ "plot_confusion_matrix(gs_log_reg, X_test, y_test);", "_____no_output_____" ], [ "print(classification_report(y_test, y_preds))", " precision recall f1-score support\n\n 0 0.89 0.86 0.88 29\n 1 0.88 0.91 0.89 32\n\n accuracy 0.89 61\n macro avg 0.89 0.88 0.88 61\nweighted avg 0.89 0.89 0.89 61\n\n" ] ], [ [ "**NOTE: As the above `classification report` only covers ONE train test split set of Test data.**\n\n**So we may want to use cross validated precision, recall, f1 score to get the whole idea.**", "_____no_output_____" ], [ "--------", "_____no_output_____" ], [ "## Calculate evaluation metrics using Cross Validated Precision, Recall and F1 score\n\n- we will use `cross_val_score` for this with different `scoring` parameter.\n- we will create new model and validated on whole dataset.", "_____no_output_____" ] ], [ [ "# check current best parameter\ngs_log_reg.best_params_", "_____no_output_____" ], [ "# create a new classifier with current best parameter\nclf = LogisticRegression(C=0.23357214690901212, solver='liblinear')", "_____no_output_____" ], [ "# Cross Validated Accuracy\ncv_accuracy = cross_val_score(clf, X, y, scoring='accuracy', cv=5)\ncv_accuracy", "_____no_output_____" ], [ "# mean of cross valided accuracy\ncv_accuracy = np.mean(cv_accuracy)\ncv_accuracy", "_____no_output_____" ], [ "# Cross Validated Precision\ncv_precision = cross_val_score(clf, X, y, scoring='precision', cv=5)\n\ncv_precision = np.mean(cv_precision)\ncv_precision", "_____no_output_____" ], [ "# Cross Validated Recall\ncv_recall = cross_val_score(clf, X, y, scoring='recall', cv=5)\n\ncv_recall = np.mean(cv_recall)\ncv_recall", "_____no_output_____" ], [ "# Cross Validated F1\ncv_f1 = cross_val_score(clf, X, y, scoring='f1', cv=5)\n\ncv_f1 = np.mean(cv_f1)\ncv_f1", "_____no_output_____" ], [ "# Visualize cross-validated metrics\ncv_metrics = pd.DataFrame({'Accuracy': cv_accuracy,\n 'Precision': cv_precision,\n 'Recall': cv_recall,\n 'F1': cv_f1},\n index=[0])\n\ncv_metrics.T.plot.bar(legend=False);\n\nplt.title('Cross Validated Classification Metrics')\nplt.xticks(rotation=30); ", "_____no_output_____" ] ], [ [ "-----------", "_____no_output_____" ], [ "## Feature Importance\n\nFeature Importance is another as asking, \"which features contributed most to the outcomes of the model and how did they contribute?\n\nFinding Feature Importance is different for each machine learning model.\n", "_____no_output_____" ], [ "### Finding Feature Importance for Logistic Regression", "_____no_output_____" ] ], [ [ "model = LogisticRegression(C=0.23357214690901212, solver='liblinear')\nmodel.fit(X_train, y_train)", "_____no_output_____" ], [ "# check Coefficient of features\nmodel.coef_", "_____no_output_____" ], [ "df.head(2)", "_____no_output_____" ], [ "# Match coef's of features to columns name\nfeature_dict = dict(zip(df.columns, list(model.coef_[0])))\n\nfeature_dict", "_____no_output_____" ] ], [ [ "**NOTE: Unlike correlation which is done during EDA, cofficient is model driven.**\n\nWe got those coef_ values after we have the model.", "_____no_output_____" ] ], [ [ "# Visualize Feature Importance\nfeature_df = pd.DataFrame(feature_dict, index=[0])\n\nfeature_df.T.plot.bar(title='Feature Importance of Logistic Regression', legend=False);", "_____no_output_____" ], [ "pd.crosstab(df['slope'], df['target'])", "_____no_output_____" ] ], [ [ "based on the coef_, the higher the value of slope, the model tends to predict higher value (which is 0 to 1: meaning likely to have heart disease)", "_____no_output_____" ], [ "-------", "_____no_output_____" ] ], [ [ "pd.crosstab(df['sex'], df['target'])", "_____no_output_____" ], [ "72/24", "_____no_output_____" ], [ "93/114", "_____no_output_____" ] ], [ [ "based on the coef_, the higher the value of sex (0 => 1), the model tends to predict lower value.\n\nExample: \n\nFor Sex 0 (female), Target changes from 0 => 1 is 72/24 = 3.0\n\nFor Sex 1 (male), Target changes from 0 => 1 is 93/114 = 0.8157894736842105\n\nSo the value got decrease from 3.0 to 0.8157894736842105.", "_____no_output_____" ], [ "-------", "_____no_output_____" ], [ "## Additional Experimentation\nTo improve our evaluation metrics, we can\n\n* collect more data.\n* try different models like XGBoost or CatBoost.\n* improve the current model with additional hyperparameter tuning", "_____no_output_____" ] ], [ [ " # save the model\nfrom joblib import dump", "_____no_output_____" ], [ "dump(clf, 'model/mdl_logistic_regression')", "_____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", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ] ]
4afc585826bd64d49b1a62a37cd7cb4579123a10
46,756
ipynb
Jupyter Notebook
jacqueline_translate_r_code.ipynb
jackiekyu/homework-8-group-7-1
cca755b4a0f8883c80225fad8ab812440eb0eae5
[ "BSD-3-Clause" ]
null
null
null
jacqueline_translate_r_code.ipynb
jackiekyu/homework-8-group-7-1
cca755b4a0f8883c80225fad8ab812440eb0eae5
[ "BSD-3-Clause" ]
null
null
null
jacqueline_translate_r_code.ipynb
jackiekyu/homework-8-group-7-1
cca755b4a0f8883c80225fad8ab812440eb0eae5
[ "BSD-3-Clause" ]
null
null
null
54.877934
2,738
0.58307
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4afc5a58bfdc7e483baff9597e780e7e10265c26
783
ipynb
Jupyter Notebook
more/LearnToCodeWithPython/code/Appendix_B_Analysis_of_Algorithm.ipynb
chiachang100/LearningPython
bfaf1cd63a43098861da14393e56ea35625dd408
[ "Apache-2.0" ]
1
2019-03-13T22:03:05.000Z
2019-03-13T22:03:05.000Z
more/LearnToCodeWithPython/code/Appendix_B_Analysis_of_Algorithm.ipynb
chiachang100/quick-python-course
bfaf1cd63a43098861da14393e56ea35625dd408
[ "Apache-2.0" ]
null
null
null
more/LearnToCodeWithPython/code/Appendix_B_Analysis_of_Algorithm.ipynb
chiachang100/quick-python-course
bfaf1cd63a43098861da14393e56ea35625dd408
[ "Apache-2.0" ]
1
2019-03-13T17:36:55.000Z
2019-03-13T17:36:55.000Z
19.097561
106
0.547893
[ [ [ "# Appendix B: Analysis of Algorithm\n[Source: Think Python 2nd Edition by Allen B. Downey](https://greenteapress.com/wp/think-python-2e/)", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown" ] ]
4afc66779f94adb3780158762b92b2d996d3b73b
7,523
ipynb
Jupyter Notebook
day 3/Lab_15_DL Keras Callbacks and Functional API.ipynb
ghego/ztdlbootcamp
9a53309780a5c754e06e268e0fbcaf50ea7774ee
[ "MIT" ]
null
null
null
day 3/Lab_15_DL Keras Callbacks and Functional API.ipynb
ghego/ztdlbootcamp
9a53309780a5c754e06e268e0fbcaf50ea7774ee
[ "MIT" ]
null
null
null
day 3/Lab_15_DL Keras Callbacks and Functional API.ipynb
ghego/ztdlbootcamp
9a53309780a5c754e06e268e0fbcaf50ea7774ee
[ "MIT" ]
null
null
null
25.941379
299
0.552572
[ [ [ "# Keras Callbacks and Functional API", "_____no_output_____" ] ], [ [ "from keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation, Dropout\nfrom keras.optimizers import SGD, RMSprop\nfrom keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint\n\nimport numpy as np\n%matplotlib inline\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "(X_train_t, y_train), (X_test_t, y_test) = cifar10.load_data()\n\nX_train_t = X_train_t.astype('float32') / 255.\nX_test_t = X_test_t.astype('float32') / 255.\n\nX_train = X_train_t.reshape(len(X_train_t), 32*32*3)\nX_test = X_test_t.reshape(len(X_test_t), 32*32*3)", "_____no_output_____" ], [ "print(\"Training set:\")\nprint(\"Tensor images shape:\\t\", X_train_t.shape)\nprint(\"Flat images shape:\\t\", X_train.shape)\nprint(\"Labels shape:\\t\\t\", y_train.shape)", "_____no_output_____" ], [ "plt.figure(figsize=(15, 4))\nfor i in range(0, 8):\n plt.subplot(1, 8, i+1)\n plt.imshow(X_train[i].reshape(32, 32, 3))\n plt.title(y_train[i])", "_____no_output_____" ] ], [ [ "## Callbacks on a simple model", "_____no_output_____" ] ], [ [ "outpath='/tmp/tensorflow_logs/cifar/'\n\nearly_stopper = EarlyStopping(monitor='val_acc', patience=10)\ntensorboard = TensorBoard(outpath, histogram_freq=1)\ncheckpointer = ModelCheckpoint(outpath+'weights_epoch_{epoch:02d}_val_acc_{val_acc:.2f}.hdf5',\n monitor='val_acc')", "_____no_output_____" ], [ "model = Sequential()\nmodel.add(Dense(1024, activation='relu',\n input_dim=3072))\n\nmodel.add(Dense(512, activation='relu'))\n\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.compile(loss='sparse_categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])", "_____no_output_____" ], [ "model.fit(X_train, y_train,\n batch_size=128,\n epochs=5,\n verbose=1,\n validation_split=0.1,\n callbacks=[early_stopper,\n tensorboard,\n checkpointer])", "_____no_output_____" ], [ "import os\nsorted(os.listdir(outpath))", "_____no_output_____" ] ], [ [ "Now check the tensorboard.\n\n- If using provided instance, just browse to: `http://<your-ip>:6006`\n\n- If using local, open a terminal, activate the environment and run:\n```\ntensorboard --logdir=/tmp/tensorflow_logs/cifar/\n```\nthen open a browser at `localhost:6006`\n\nYou should see something like this:\n\n![tensorboard.png](../assets/tensorboard.png)", "_____no_output_____" ], [ "## Exercise 1: Keras functional API\n\nWe'e built a model using the `Sequential API` from Keras. Keras also offers a [functional API](https://keras.io/getting-started/functional-api-guide/). This API is the way to go for defining complex models, such as multi-output models, directed acyclic graphs, or models with shared layers.\n\nCan you rewrite the model above using the functional API?", "_____no_output_____" ] ], [ [ "from keras.layers import Input\nfrom keras.models import Model", "_____no_output_____" ], [ "model.compile(loss='sparse_categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\nmodel.fit(X_train, y_train,\n batch_size=128,\n epochs=10,\n verbose=1,\n validation_split=0.1)\n\n# Final test evaluation\nscore = model.evaluate(X_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])", "_____no_output_____" ] ], [ [ "## Exercise 2: Convolutional Model with Functional API\n\nThe above model is a very simple fully connected deep neural network. As we have seen, Convolutional Neural Networks are much more powerful when dealing with images. The original data has shape:\n\n (N_images, Height, Width, Channels)\n \nCan you write a convolutional model using the functional API?", "_____no_output_____" ] ], [ [ "from keras.layers.core import Dense, Dropout, Activation\nfrom keras.layers import Conv2D, MaxPool2D, AveragePooling2D, Flatten", "_____no_output_____" ] ], [ [ "## Exrcise 3: Discuss with the person next to you \n\n1. What are the pros/cons of the sequential API?\n- What are the pros/cons of the functional API?\n- What are the key differences between a Fully connected and a Convolutional neural network?\n- What is a dropout layer? How does it work? Why does it help?\n", "_____no_output_____" ], [ "*Copyright &copy; 2017 Francesco Mosconi & CATALIT LLC. All rights reserved.*", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4afc7110492e9e8d0ed5c324d0da9097dfd56c8a
14,890
ipynb
Jupyter Notebook
rbm.ipynb
pushpulldecoder/Restricted-Boltzmann-Machine
dadafd088eafa56b2b6d366d337be8e299d71d6a
[ "Apache-2.0" ]
1
2019-07-23T00:16:40.000Z
2019-07-23T00:16:40.000Z
rbm.ipynb
pushpull13/Restricted-Boltzmann-Machine
dadafd088eafa56b2b6d366d337be8e299d71d6a
[ "Apache-2.0" ]
null
null
null
rbm.ipynb
pushpull13/Restricted-Boltzmann-Machine
dadafd088eafa56b2b6d366d337be8e299d71d6a
[ "Apache-2.0" ]
null
null
null
38.675325
144
0.453526
[ [ [ "<pre>\nTorch : Manipulating vectors like dot product, addition etc and using GPU\nNumpy : Manipuliting vectors\nPandas : Reading CSV file\nMatplotlib : Plotting figure\n</pre>", "_____no_output_____" ] ], [ [ "import numpy as np\nimport torch\nimport pandas as pd\nfrom matplotlib import pyplot as plt", "_____no_output_____" ] ], [ [ "<pre>\n O\n O\n O\n O\n O\n O O\n O O\n O O\n O O\n O O\n O O\n O O\n O O\n O O\n O O\n O O\n O O\n O O\n O |\n O |\n O |\n O |\n O |\n | |\n | |\n | |\n | |\n | |\n | |\n | |\n Visible Hidden/Feature\n Layer Layer\n (n_v) (n_h)\n \n \nRBM : A class that initialize RBM with default values\n</pre>", "_____no_output_____" ], [ "<pre>\n Parameters\n\n n_v : Number of visible inputs\n Initialized by 0 but then take value of number of inputs\n n_h : Number of features want to extract\n Must be set by user\n k : Sampling steps for contrastive divergance\n Default value is 2 steps\n epochs : Number of epochs for training RBM\n Must be set by user\n mini_batch_size : Size of mini batch for training\n Must be set by user\n alpha : Learning rate for updating parameters of RBM\n Default value is 0.01\n momentum : Reduces large jumps for updating parameters\n weight_decay : Reduces the value of weight after every step of contrastive divergance\n data : Data to be fitted for RBM\n Must be given by user or else, thats all useless\n</pre>", "_____no_output_____" ] ], [ [ "class RBM():\n\n# Parameters\n\n# n_v : Number of visible inputs\n# Initialized by 0 but then take value of number of inputs\n# n_h : Number of features want to extract\n# Must be set by user\n# k : Sampling steps for contrastive divergance\n# Default value is 2 steps\n# epochs : Number of epochs for training RBM\n# Must be set by user\n# mini_batch_size : Size of mini batch for training\n# Must be set by user\n# alpha : Learning rate for updating parameters of RBM\n# Default value is 0.001\n# momentum : Reduces large jumps for updating parameters\n# weight_decay : Reduces the value of weight after every step of contrastive divergance\n# data : Data to be fitted for RBM\n# Must be given by user or else, thats all useless\n \n def __init__(self, n_v=0, n_h=0, k=2, epochs=15, mini_batch_size=64, alpha=0.001, momentum=0.9, weight_decay=0.001):\n self.number_features = 0\n self.n_v = n_v\n self.n_h = self.number_features\n self.k = k\n self.alpha = alpha\n self.momentum = momentum\n self.weight_decay = weight_decay\n self.mini_batch_size = mini_batch_size\n self.epochs = epochs\n self.data = torch.randn(1, device=\"cuda\")\n\n# fit method is called to fit RBM for provided data\n# First, data is converted in range of 0-1 cuda float tensors by dividing it by their maximum value\n# Here, after calling this method, n_v is reinitialized to number of input values present in data\n# number_features must be given by user before calling this method\n# w Tensor of weights of RBM\n# (n_v x n_h) Randomly initialized between 0-1\n# a Tensor of bias for visible units\n# (n_v x 1) Initialized by 1's\n# b Tensor of bias for hidden units\n# (n_b x 1) Initialized by 1's\n# w_moment Momentum value for weights\n# (n_v x n_h) Initialized by zeros\n# a_moment Momentum values for visible units\n# (n_v x 1) Initialized by zeros\n# b_moment Momentum values for hidden units\n# (n_h x 1) Initialized by zeros\n def fit(self):\n \n self.data /= self.data.max()\n \n self.data = self.data.type(torch.cuda.FloatTensor)\n \n self.n_v = len(self.data[0])\n self.n_h = self.number_features\n \n self.w = torch.randn(self.n_v, self.n_h, device=\"cuda\") * 0.1\n self.a = torch.ones(self.n_v, device=\"cuda\") * 0.5\n self.b = torch.ones(self.n_h, device=\"cuda\")\n\n self.w_moment = torch.zeros(self.n_v, self.n_h, device=\"cuda\")\n self.a_moment = torch.zeros(self.n_v, device=\"cuda\")\n self.b_moment = torch.zeros(self.n_h, device=\"cuda\")\n \n self.train()\n\n# train This method splits dataset into mini_batch and run for given epoch number of times\n def train(self):\n for epoch_no in range(self.epochs):\n ep_error = 0\n for i in range(0, len(self.data), self.mini_batch_size):\n mini_batch = self.data[i:i+self.mini_batch_size]\n ep_error += self.contrastive_divergence(mini_batch)\n print(\"Epoch Number : \", epoch_no, \" Error : \", ep_error.item())\n\n# cont_diverg It performs contrastive divergance using gibbs sampling algorithm\n# p_h_0 Value of hidden units for given visivle units\n# h_0 Activated hidden units as sampled from normal distribution (0 or 1)\n# g_0 Positive associations of RBM\n# wv_a Unactivated hidden units\n# p_v_h Probability of hidden neuron to be activated given values of visible neurons\n# p_h_v Probability of visible neuron to be activated given values of hidden neurons\n# p_v_k Value of visible units for given visivle units after k step Gibbs Sampling\n# p_h_k Value of hidden units for given visivle units after k step Gibbs Sampling\n# g_k Negative associations of RBM\n# error Recontruction error for given mini_batch\n def contrastive_divergence(self, v):\n p_h_0 = self.sample_hidden(v)\n h_0 = (p_h_0 >= torch.rand(self.n_h, device=\"cuda\")).float()\n g_0 = v.transpose(0, 1).mm(h_0)\n\n wv_a = h_0\n# Gibbs Sampling step\n for step in range(self.k):\n p_v_h = self.sample_visible(wv_a)\n p_h_v = self.sample_hidden(p_v_h)\n wv_a = (p_h_v >= torch.rand(self.n_h, device=\"cuda\")).float()\n\n p_v_k = p_v_h\n p_h_k = p_h_v\n\n g_k = p_v_k.transpose(0, 1).mm(p_h_k)\n\n self.update_parameters(g_0, g_k, v, p_v_k, p_h_0, p_h_k)\n\n error = torch.sum((v - p_v_k)**2)\n\n return error\n\n# p_v_h : Probability of hidden neuron to be activated given values of visible neurons\n# p_h_v : Probability of visible neuron to be activated given values of hidden neurons\n\n#-----------------------------------Bernoulli-Bernoulli RBM--------------------------------------------\n# p_h_v = sigmoid ( weight x visible + visible_bias )\n# p_v_h = sigmoid (weight.t x hidden + hidden_bias )\n#------------------------------------------------------------------------------------------------------\n def sample_hidden(self, p_v_h): # Bernoulli-Bernoulli RBM\n wv = p_v_h.mm(self.w)\n wv_a = wv + self.b\n p_h_v = torch.sigmoid(wv_a)\n return p_h_v\n\n def sample_visible(self, p_h_v): # Bernoulli-Bernoulli RBM\n wh = p_h_v.mm(self.w.transpose(0, 1))\n wh_b = wh + self.a\n p_v_h = torch.sigmoid(wh_b)\n return p_v_h\n\n# weight_(t) = weight_(t) + ( positive_association - negative_association ) + weight_(t-1)\n# visible_bias_(t) = visible_bias_(t) + sum( input - activated_visivle_at_k_step_sample ) + visible_bias_(t-1)\n# hidden_bias_(t) = hidden_bias_(t) + sum( activated_initial_hidden - activated_hidden_at_k_step_sample ) + hidden_bias_(t-1)\n def update_parameters(self, g_0, g_k, v, p_v_k, p_h_0, p_h_k):\n self.w_moment *= self.momentum\n del_w = (g_0 - g_k) + self.w_moment\n\n self.a_moment *= self.momentum\n del_a = torch.sum(v - p_v_k, dim=0) + self.a_moment\n\n self.b_moment *= self.momentum\n del_b = torch.sum(p_h_0 - p_h_k, dim=0) + self.b_moment\n\n batch_size = v.size(0)\n\n self.w += del_w * self.alpha / batch_size\n self.a += del_a * self.alpha / batch_size\n self.b += del_b * self.alpha / batch_size\n\n self.w -= (self.w * self.weight_decay)\n \n self.w_moment = del_w\n self.a_moment = del_a\n self.b_moment = del_b", "_____no_output_____" ], [ "dataset = pd.read_csv(\"/home/pushpull/mount/intHdd/dataset/mnist/mnist_train.csv\", header=None)\ndata = torch.tensor(np.array(dataset)[:, 1:], device=\"cuda\")", "_____no_output_____" ], [ "mnist = RBM()", "_____no_output_____" ], [ "mnist.data = data", "_____no_output_____" ], [ "mnist.number_features = 300", "_____no_output_____" ], [ "error = mnist.fit()", "Epoch Number : 0 Error : 527743.1875\nEpoch Number : 1 Error : 283213.125\nEpoch Number : 2 Error : 261696.796875\nEpoch Number : 3 Error : 258503.1875\nEpoch Number : 4 Error : 257862.4375\nEpoch Number : 5 Error : 258103.671875\nEpoch Number : 6 Error : 258327.65625\nEpoch Number : 7 Error : 258373.75\nEpoch Number : 8 Error : 258460.90625\nEpoch Number : 9 Error : 258357.0625\nEpoch Number : 10 Error : 258420.140625\nEpoch Number : 11 Error : 258400.65625\nEpoch Number : 12 Error : 258748.265625\nEpoch Number : 13 Error : 258971.53125\nEpoch Number : 14 Error : 258795.984375\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4afc92782e5ffcabd54982be47be942f80620727
15,428
ipynb
Jupyter Notebook
Tutorial_4. SQL data source for pipeline preset.ipynb
Zhurik/LightAutoML
506d0602f40eca79ed0e5d58e7d4f71aeb1d8059
[ "Apache-2.0" ]
null
null
null
Tutorial_4. SQL data source for pipeline preset.ipynb
Zhurik/LightAutoML
506d0602f40eca79ed0e5d58e7d4f71aeb1d8059
[ "Apache-2.0" ]
null
null
null
Tutorial_4. SQL data source for pipeline preset.ipynb
Zhurik/LightAutoML
506d0602f40eca79ed0e5d58e7d4f71aeb1d8059
[ "Apache-2.0" ]
1
2021-12-08T13:52:45.000Z
2021-12-08T13:52:45.000Z
26.6
212
0.557298
[ [ [ "# Step 0.0. Install LightAutoML ", "_____no_output_____" ], [ "Uncomment if doesn't clone repository by git. (ex.: colab, kaggle version)", "_____no_output_____" ] ], [ [ "#! pip install -U lightautoml", "_____no_output_____" ] ], [ [ "# Step 0.1. Import necessary libraries ", "_____no_output_____" ] ], [ [ "# Standard python libraries\nimport logging\nimport os\nimport time\nimport requests\nlogging.basicConfig(format='[%(asctime)s] (%(levelname)s): %(message)s', level=logging.INFO)\n\n# Installed libraries\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split\nimport torch\n\n# Imports from our package\nfrom lightautoml.automl.presets.tabular_presets import TabularAutoML, TabularUtilizedAutoML\nfrom lightautoml.dataset.roles import DatetimeRole\nfrom lightautoml.tasks import Task\nfrom lightautoml.utils.profiler import Profiler", "_____no_output_____" ] ], [ [ "# Step 0.2. Parameters ", "_____no_output_____" ] ], [ [ "N_THREADS = 8 # threads cnt for lgbm and linear models\nN_FOLDS = 5 # folds cnt for AutoML\nRANDOM_STATE = 42 # fixed random state for various reasons\nTEST_SIZE = 0.2 # Test size for metric check\nTIMEOUT = 300 # Time in seconds for automl run\nTARGET_NAME = 'TARGET' # Target column name", "_____no_output_____" ] ], [ [ "# Step 0.3. Fix torch number of threads and numpy seed ", "_____no_output_____" ] ], [ [ "np.random.seed(RANDOM_STATE)\ntorch.set_num_threads(N_THREADS)", "_____no_output_____" ] ], [ [ "# Step 0.4. Change profiling decorators settings ", "_____no_output_____" ], [ "By default, profiling decorators are turned off for speed and memory reduction. If you want to see profiling report after using LAMA, you need to turn on the decorators using command below: ", "_____no_output_____" ] ], [ [ "p = Profiler()\np.change_deco_settings({'enabled': True})", "_____no_output_____" ] ], [ [ "# Step 0.5. Example data load ", "_____no_output_____" ], [ "Load a dataset from the repository if doesn't clone repository by git.", "_____no_output_____" ] ], [ [ "DATASET_DIR = './example_data/test_data_files'\nDATASET_NAME = 'sampled_app_train.csv'\nDATASET_FULLNAME = os.path.join(DATASET_DIR, DATASET_NAME)\nDATASET_URL = 'https://raw.githubusercontent.com/sberbank-ai-lab/LightAutoML/master/example_data/test_data_files/sampled_app_train.csv'", "_____no_output_____" ], [ "%%time\n\nif not os.path.exists(DATASET_FULLNAME):\n os.makedirs(DATASET_DIR, exist_ok=True)\n\n dataset = requests.get(DATASET_URL).text\n with open(DATASET_FULLNAME, 'w') as output:\n output.write(dataset)", "_____no_output_____" ], [ "%%time\n\ndata = pd.read_csv('./example_data/test_data_files/sampled_app_train.csv')\ndata.head()", "_____no_output_____" ] ], [ [ "# Step 0.6. (Optional) Some user feature preparation ", "_____no_output_____" ], [ "Cell below shows some user feature preparations to create task more difficult (this block can be omitted if you don't want to change the initial data):", "_____no_output_____" ] ], [ [ "%%time\n\ndata['BIRTH_DATE'] = (np.datetime64('2018-01-01') + data['DAYS_BIRTH'].astype(np.dtype('timedelta64[D]'))).astype(str)\ndata['EMP_DATE'] = (np.datetime64('2018-01-01') + np.clip(data['DAYS_EMPLOYED'], None, 0).astype(np.dtype('timedelta64[D]'))\n ).astype(str)\n\ndata['constant'] = 1\ndata['allnan'] = np.nan\n\ndata['report_dt'] = np.datetime64('2018-01-01')\n\ndata.drop(['DAYS_BIRTH', 'DAYS_EMPLOYED'], axis=1, inplace=True)", "_____no_output_____" ] ], [ [ "# Step 0.7. (Optional) Data splitting for train-test ", "_____no_output_____" ], [ "Block below can be omitted if you are going to train model only or you have specific train and test files:", "_____no_output_____" ] ], [ [ "%%time\n\ntrain_data, test_data = train_test_split(data, \n test_size=TEST_SIZE, \n stratify=data[TARGET_NAME], \n random_state=RANDOM_STATE)\nlogging.info('Data splitted. Parts sizes: train_data = {}, test_data = {}'\n .format(train_data.shape, test_data.shape))", "_____no_output_____" ], [ "train_data.head()", "_____no_output_____" ] ], [ [ "# Step 0.8. (Optional) Reading data from SqlDataSource", "_____no_output_____" ], [ "### Preparing datasets as SQLite data bases", "_____no_output_____" ] ], [ [ "import sqlite3 as sql\n\nfor _fname in ('train.db', 'test.db'):\n if os.path.exists(_fname):\n os.remove(_fname)\n \ntrain_db = sql.connect('train.db')\ntrain_data.to_sql('data', train_db)\n\ntest_db = sql.connect('test.db')\ntest_data.to_sql('data', test_db)", "_____no_output_____" ] ], [ [ "### Using dataset wrapper for a connection", "_____no_output_____" ] ], [ [ "from lightautoml.reader.tabular_batch_generator import SqlDataSource\n\n# train_data is replaced with a wrapper for an SQLAlchemy connection\n# Wrapper requires SQLAlchemy connection string and query to obtain data from\ntrain_data = SqlDataSource('sqlite:///train.db', 'select * from data', index='index')\ntest_data = SqlDataSource('sqlite:///test.db', 'select * from data', index='index')", "_____no_output_____" ] ], [ [ "# ========= AutoML preset usage =========\n\n\n## Step 1. Create Task", "_____no_output_____" ] ], [ [ "%%time\n\ntask = Task('binary', )", "_____no_output_____" ] ], [ [ "## Step 2. Setup columns roles", "_____no_output_____" ], [ "Roles setup here set target column and base date, which is used to calculate date differences:", "_____no_output_____" ] ], [ [ "%%time\n\nroles = {'target': TARGET_NAME,\n DatetimeRole(base_date=True, seasonality=(), base_feats=False): 'report_dt',\n }", "_____no_output_____" ] ], [ [ "## Step 3. Create AutoML from preset", "_____no_output_____" ], [ "To create AutoML model here we use `TabularAutoML` preset, which looks like:\n\n![TabularAutoML preset pipeline](imgs/tutorial_2_pipeline.png)\n\nAll params we set above can be send inside preset to change its configuration:", "_____no_output_____" ] ], [ [ "%%time \n\nautoml = TabularAutoML(task = task, \n timeout = TIMEOUT,\n general_params = {'nested_cv': False, 'use_algos': [['linear_l2', 'lgb', 'lgb_tuned']]},\n reader_params = {'cv': N_FOLDS, 'random_state': RANDOM_STATE},\n tuning_params = {'max_tuning_iter': 20, 'max_tuning_time': 30},\n lgb_params = {'default_params': {'num_threads': N_THREADS}})\noof_pred = automl.fit_predict(train_data, roles = roles)\nlogging.info('oof_pred:\\n{}\\nShape = {}'.format(oof_pred, oof_pred.shape))", "_____no_output_____" ] ], [ [ "## Step 4. Predict to test data and check scores", "_____no_output_____" ] ], [ [ "%%time\n\ntest_pred = automl.predict(test_data)\nlogging.info('Prediction for test data:\\n{}\\nShape = {}'\n .format(test_pred, test_pred.shape))\n\nlogging.info('Check scores...')\nlogging.info('OOF score: {}'.format(roc_auc_score(train_data.data[TARGET_NAME].values, oof_pred.data[:, 0])))\nlogging.info('TEST score: {}'.format(roc_auc_score(test_data.data[TARGET_NAME].values, test_pred.data[:, 0])))", "_____no_output_____" ] ], [ [ "## Step 5. Profiling AutoML ", "_____no_output_____" ], [ "To build report here, we **must** turn on decorators on step 0.4. Report is interactive and you can go as deep into functions call stack as you want:", "_____no_output_____" ] ], [ [ "%%time\np.profile('my_report_profile.html')\nassert os.path.exists('my_report_profile.html'), 'Profile report failed to build'", "_____no_output_____" ] ], [ [ "## Step 6. Create AutoML with time utilization ", "_____no_output_____" ], [ "Below we are going to create specific AutoML preset for TIMEOUT utilization (try to spend it as much as possible):", "_____no_output_____" ] ], [ [ "%%time \n\nautoml = TabularUtilizedAutoML(task = task, \n timeout = TIMEOUT,\n general_params = {'nested_cv': False, 'use_algos': [['linear_l2', 'lgb', 'lgb_tuned']]},\n reader_params = {'cv': N_FOLDS, 'random_state': RANDOM_STATE},\n tuning_params = {'max_tuning_iter': 20, 'max_tuning_time': 30},\n lgb_params = {'default_params': {'num_threads': N_THREADS}})\noof_pred = automl.fit_predict(train_data, roles = roles)\nlogging.info('oof_pred:\\n{}\\nShape = {}'.format(oof_pred, oof_pred.shape))", "_____no_output_____" ] ], [ [ "## Step 7. Predict to test data and check scores for utilized automl", "_____no_output_____" ] ], [ [ "%%time\n\ntest_pred = automl.predict(test_data)\nlogging.info('Prediction for test data:\\n{}\\nShape = {}'\n .format(test_pred, test_pred.shape))\n\nlogging.info('Check scores...')\nlogging.info('OOF score: {}'.format(roc_auc_score(train_data.data[TARGET_NAME].values, oof_pred.data[:, 0])))\nlogging.info('TEST score: {}'.format(roc_auc_score(test_data.data[TARGET_NAME].values, test_pred.data[:, 0])))", "_____no_output_____" ] ], [ [ "## Step 8. Profiling utilized AutoML ", "_____no_output_____" ], [ "To build report here, we **must** turn on decorators on step 0.4. Report is interactive and you can go as deep into functions call stack as you want:", "_____no_output_____" ] ], [ [ "%%time\np.profile('my_report_profile.html')\nassert os.path.exists('my_report_profile.html'), 'Profile report failed to build'", "_____no_output_____" ] ], [ [ "# Appendix. Profiling report screenshots ", "_____no_output_____" ], [ "After loading HTML with profiling report, you can see fully folded report (please wait for green LOAD OK text for full load finish). If you click on triangle on the left, it unfolds and look like this: \n\n<img src=\"imgs/tutorial_2_initial_report.png\" alt=\"Initial profiling report\" style=\"width: 500px;\"/>\n\nIf we go even deeper we will receive situation like this:\n\n<img src=\"imgs/tutorial_2_unfolded_report.png\" alt=\"Profiling report after several unfoldings on different levels\" style=\"width: 600px;\"/>\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4afc9597b613767e94dbef012f0eb879cba71cc6
212,958
ipynb
Jupyter Notebook
pittsburgh-bridges-data-set-analysis/models-analyses/Data Space Report (Official) - template.ipynb
franec94/Pittsburgh-Bridge-Dataset
682ff0e3979ca565637e858cc36dc07c2aeda7d6
[ "MIT" ]
null
null
null
pittsburgh-bridges-data-set-analysis/models-analyses/Data Space Report (Official) - template.ipynb
franec94/Pittsburgh-Bridge-Dataset
682ff0e3979ca565637e858cc36dc07c2aeda7d6
[ "MIT" ]
7
2021-02-02T22:51:40.000Z
2022-03-12T00:39:08.000Z
pittsburgh-bridges-data-set-analysis/models-analyses/Data Space Report (Official) - template.ipynb
franec94/Pittsburgh-Bridge-Dataset
682ff0e3979ca565637e858cc36dc07c2aeda7d6
[ "MIT" ]
null
null
null
398.797753
59,820
0.924633
[ [ [ "# Data Space Report\n\n\n<img src=\"images/polito_logo.png\" alt=\"Polito Logo\" style=\"width: 200px;\"/>\n\n\n## Pittsburgh Bridges Data Set\n\n<img src=\"images/andy_warhol_bridge.jpg\" alt=\"Andy Warhol Bridge\" style=\"width: 200px;\"/>\n\n Andy Warhol Bridge - Pittsburgh.\n\nReport created by Student Francesco Maria Chiarlo s253666, for A.A 2019/2020.\n\n**Abstract**:The aim of this report is to evaluate the effectiveness of distinct, different statistical learning approaches, in particular focusing on their characteristics as well as on their advantages and backwards when applied onto a relatively small dataset as the one employed within this report, that is Pittsburgh Bridgesdataset.\n\n**Key words**:Statistical Learning, Machine Learning, Bridge Design.", "_____no_output_____" ], [ "### Imports Section <a class=\"anchor\" id=\"imports-section\"></a>", "_____no_output_____" ] ], [ [ "# =========================================================================== #\n# STANDARD IMPORTS\n# =========================================================================== #\nprint(__doc__)\n\n# Critical Imports\n# --------------------------------------------------------------------------- #\nimport warnings; warnings.filterwarnings(\"ignore\")\n\n# Imports through 'from' syntax\n# --------------------------------------------------------------------------- #\nfrom pprint import pprint\nfrom itertools import islice\nfrom os import listdir; from os.path import isfile, join\n# Standard Imports\n# --------------------------------------------------------------------------- #\nimport copy; import os\nimport sys; import time\nimport itertools\nimport sklearn\n\n# Imports through 'as' syntax\n# --------------------------------------------------------------------------- #\nimport numpy as np; import pandas as pd\n\n# Imports for handling graphics\n# --------------------------------------------------------------------------- #\n%matplotlib inline\n# Matplotlib pyplot provides plotting API\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport chart_studio.plotly.plotly as py\nimport seaborn as sns; sns.set(style=\"ticks\", color_codes=True) # sns.set()", "Automatically created module for IPython interactive environment\n" ], [ "# =========================================================================== #\n# UTILS IMPORTS (Done by myself)\n# =========================================================================== #\nfrom utils.load_dataset_pittsburg_utils import load_brdiges_dataset; from utils.display_utils import *\nfrom utils.preprocessing_utils import *; from utils.training_utils import *\nfrom utils.sklearn_functions_custom import *; from utils.learning_curves_custom import *\nfrom utils.training_utils_v2 import fit_by_n_components, fit_all_by_n_components, grid_search_all_by_n_components", "_____no_output_____" ], [ "# =========================================================================== #\n# sklearn IMPORT\n# =========================================================================== #\nfrom sklearn.decomposition import PCA, KernelPCA\n\n# Import scikit-learn classes: models (Estimators).\nfrom sklearn.naive_bayes import GaussianNB, MultinomialNB # Non-parametric Generative Model\nfrom sklearn.linear_model import LogisticRegression # Parametric Linear Discriminative Model\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC # Parametric Linear Discriminative \"Support Vector Classifier\"\nfrom sklearn.tree import DecisionTreeClassifier # Non-parametric Model\nfrom sklearn.ensemble import RandomForestClassifier # Non-parametric Model (Meta-Estimator, that is, an Ensemble Method)", "_____no_output_____" ], [ "# =========================================================================== #\n# READ INPUT DATASET\n# =========================================================================== #\n\ndataset_path = 'C:\\\\Users\\\\Francesco\\Documents\\\\datasets\\\\pittsburgh_dataset'\ndataset_name = 'bridges.data.csv'\n\nTARGET_COL = 'T-OR-D' # Target variable name\ndataset, feature_vs_values = load_brdiges_dataset(dataset_path, dataset_name)", "_____no_output_____" ], [ "columns_2_avoid = ['ERECTED', 'LENGTH', 'LOCATION']", "_____no_output_____" ], [ "# Make distinction between Target Variable and Predictors\n# --------------------------------------------------------------------------- #\n\ncolumns = dataset.columns # List of all attribute names\n\n# Get Target values and map to 0s and 1s\ny = np.array(list(map(lambda x: 0 if x == 1 else 1, dataset[TARGET_COL].values)))\nprint('Summary about Target Variable {target_col}')\nprint('-' * 50)\nprint(dataset[TARGET_COL].value_counts())\n\n# Get Predictors\nX = dataset.loc[:, dataset.columns != TARGET_COL].values", "Summary about Target Variable {target_col}\n--------------------------------------------------\n2 57\n1 13\nName: T-OR-D, dtype: int64\n" ], [ "# Standardizing the features\n# --------------------------------------------------------------------------- #\nscaler_methods = ['minmax', 'standard', 'norm']\nscaler_method = 'standard'\nrescaledX = preprocessing_data_rescaling(scaler_method, X)", "shape features matrix X, after normalizing: (70, 11)\n" ] ], [ [ "## Pricipal Component Analysis", "_____no_output_____" ] ], [ [ "n_components = rescaledX.shape[1]\npca = PCA(n_components=n_components)\n# pca = PCA(n_components=2)\n\n# X_pca = pca.fit_transform(X)\npca = pca.fit(rescaledX)\nX_pca = pca.transform(rescaledX)", "_____no_output_____" ], [ "print(f\"Cumulative varation explained(percentage) up to given number of pcs:\")\n\ntmp_data = []\nprincipal_components = [pc for pc in '2,5,6,7,8,9,10'.split(',')]\nfor _, pc in enumerate(principal_components):\n n_components = int(pc)\n \n cum_var_exp_up_to_n_pcs = np.cumsum(pca.explained_variance_ratio_)[n_components-1]\n # print(f\"Cumulative varation explained up to {n_components} pcs = {cum_var_exp_up_to_n_pcs}\")\n # print(f\"# pcs {n_components}: {cum_var_exp_up_to_n_pcs*100:.2f}%\")\n tmp_data.append([n_components, cum_var_exp_up_to_n_pcs * 100])\n\ntmp_df = pd.DataFrame(data=tmp_data, columns=['# PCS', 'Cumulative Varation Explained (percentage)'])\ntmp_df.head(len(tmp_data))", "Cumulative varation explained(percentage) up to given number of pcs:\n" ] ], [ [ "#### Major Pros & Cons of PCA\n\n", "_____no_output_____" ], [ "## Learning Models <a class=\"anchor\" id=\"learning-models\"></a>", "_____no_output_____" ] ], [ [ "# Parameters to be tested for Cross-Validation Approach\n\nestimators_list = [GaussianNB(), LogisticRegression(), KNeighborsClassifier(), SGDClassifier(), SVC(), DecisionTreeClassifier(), RandomForestClassifier()]\nestimators_names = ['GaussianNB', 'LogisticRegression', 'KNeighborsClassifier', 'SGDClassifier', 'SVC', 'DecisionTreeClassifier', 'RandomForestClassifier']\nplots_names = list(map(lambda xi: f\"{xi}_learning_curve.png\", estimators_names))\n\npca_kernels_list = ['linear', 'poly', 'rbf', 'cosine', 'sigmoid']\ncv_list = [10, 9, 8, 7, 6, 5, 4, 3, 2]\n\nparmas_logistic_regression = {\n 'penalty': ('l1', 'l2', 'elastic'),\n 'solver': ('newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'),\n 'fit_intercept': (True, False),\n 'tol': (1e-4, 1e-3, 1e-2),\n 'C': (1.0, .1, .01, .001),\n}\n\nparmas_knn_forest = {\n 'n_neighbors': (2,3,4,5,6,7,8,9,10),\n 'weights': ('uniform', 'distance'),\n 'algorithm': ('ball_tree', 'kd_tree', 'brute'),\n}\n\nparameters_sgd_classifier = {\n 'loss': ('log', 'modified_huber'), # ('hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron')\n 'penalty': ('l2', 'l1', 'elasticnet'),\n 'alpha': (1e-1, 1e-2, 1e-3, 1e-4),\n 'max_iter': (50, 100, 150, 200, 500, 1000, 1500, 2000, 2500),\n 'learning_rate': ('optimal',),\n 'tol': (None, 1e-2, 1e-4, 1e-5, 1e-6)\n}\n\nkernel_type = 'svm-rbf-kernel'\nparameters_svm = {\n 'gamma': (0.003, 0.03, 0.05, 0.5, 0.7, 1.0, 1.5),\n 'max_iter':(1e+2, 1e+3, 2 * 1e+3, 5 * 1e+3, 1e+4, 1.5 * 1e+3),\n # 'penalty': ('l2','l1'),\n 'kernel': ['linear', 'poly', 'rbf', 'sigmoid',],\n 'C': (1e-4, 1e-3, 1e-2, 0.1, 1.0, 10, 1e+2, 1e+3),\n 'probability': (True,), \n}\n\nparmas_decision_tree = {\n 'splitter': ('random', 'best'),\n 'criterion':('gini', 'entropy'),\n 'max_features': (None, 'auto', 'sqrt', 'log2')\n}\n\nparmas_random_forest = {\n 'n_estimators': (3, 5, 7, 10, 30, 50, 70, 100, 150, 200),\n 'criterion':('gini', 'entropy'),\n 'bootstrap': (True, False)\n}\n\nparam_grids = [parmas_logistic_regression, parmas_knn_forest, parameters_sgd_classifier, parameters_svm, parmas_decision_tree, parmas_random_forest]\n\nN_CV, N_KERNEL, N_GS = 9, 4, 6", "_____no_output_____" ], [ "n_components=9\nlearning_curves_by_kernels(\n# learning_curves_by_components(\n estimators_list[:], estimators_names[:],\n rescaledX, y,\n train_sizes=np.linspace(.1, 1.0, 10),\n n_components=9,\n pca_kernels_list=pca_kernels_list[0],\n verbose=0,\n by_pairs=True,\n savefigs=True,\n scoring='accuracy',\n figs_dest=os.path.join('figures', 'learning_curve', f\"Pcs_{n_components}\")\n # figsize=(20,5)\n)", "_____no_output_____" ] ], [ [ "### Improvements and Conclusions <a class=\"anchor\" id=\"Improvements-and-conclusions\"></a>", "_____no_output_____" ], [ "### References <a class=\"anchor\" id=\"references\"></a>\n- Data Domain Information part:\n - (Deck) https://en.wikipedia.org/wiki/Deck_(bridge)\n - (Cantilever bridge) https://en.wikipedia.org/wiki/Cantilever_bridge\n - (Arch bridge) https://en.wikipedia.org/wiki/Deck_(bridge)\n- Machine Learning part:\n - (Theory Book) https://jakevdp.github.io/PythonDataScienceHandbook/\n - (Decsion Trees) https://scikit-learn.org/stable/modules/tree.html#tree\n - (SVM) https://scikit-learn.org/stable/modules/svm.html\n - (PCA) https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html\n- Chart part:\n - (Seaborn Charts) https://acadgild.com/blog/data-visualization-using-matplotlib-and-seaborn\n- Markdown Math part:\n - https://share.cocalc.com/share/b4a30ed038ee41d868dad094193ac462ccd228e2/Homework%20/HW%201.2%20-%20Markdown%20and%20LaTeX%20Cheatsheet.ipynb?viewer=share\n - https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html\n \n#### others\n- Plots:\n - (Python Plot) https://www.datacamp.com/community/tutorials/matplotlib-tutorial-python?utm_source=adwords_ppc&utm_campaignid=898687156&utm_adgroupid=48947256715&utm_device=c&utm_keyword=&utm_matchtype=b&utm_network=g&utm_adpostion=&utm_creative=255798340456&utm_targetid=aud-299261629574:dsa-473406587955&utm_loc_interest_ms=&utm_loc_physical_ms=1008025&gclid=Cj0KCQjw-_j1BRDkARIsAJcfmTFu4LAUDhRGK2D027PHiqIPSlxK3ud87Ek_lwOu8rt8A8YLrjFiHqsaAoLDEALw_wcB\n- Third Party Library:\n - (statsmodels) https://www.statsmodels.org/stable/index.html#\n- KDE:\n - (TUTORIAL) https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/\n- Metrics:\n - (F1-Accuracy-Precision-Recall) https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
4afcb2a528bd4ce7a1165f00d6a2de5419ff2389
406,033
ipynb
Jupyter Notebook
Models.ipynb
kevroi/COVID_Predictor
13874592ec1ddf8337da9018871a8d65b2ab0126
[ "MIT" ]
null
null
null
Models.ipynb
kevroi/COVID_Predictor
13874592ec1ddf8337da9018871a8d65b2ab0126
[ "MIT" ]
null
null
null
Models.ipynb
kevroi/COVID_Predictor
13874592ec1ddf8337da9018871a8d65b2ab0126
[ "MIT" ]
null
null
null
129.681571
137,010
0.828763
[ [ [ "# Load Dataset and Important Libraries", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nfrom scipy import stats\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)", "_____no_output_____" ], [ "np.random.seed(42) # some functions like scipy.stats rely on this being consistent between runs", "_____no_output_____" ] ], [ [ "Load COVID data set.", "_____no_output_____" ] ], [ [ "!wget https://github.com/beoutbreakprepared/nCoV2019/blob/master/latest_data/latestdata.tar.gz?raw=true", "--2021-05-11 22:11:41-- https://github.com/beoutbreakprepared/nCoV2019/blob/master/latest_data/latestdata.tar.gz?raw=true\nResolving github.com (github.com)... 192.30.255.112\nConnecting to github.com (github.com)|192.30.255.112|:443... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://github.com/beoutbreakprepared/nCoV2019/raw/master/latest_data/latestdata.tar.gz [following]\n--2021-05-11 22:11:41-- https://github.com/beoutbreakprepared/nCoV2019/raw/master/latest_data/latestdata.tar.gz\nReusing existing connection to github.com:443.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://raw.githubusercontent.com/beoutbreakprepared/nCoV2019/master/latest_data/latestdata.tar.gz [following]\n--2021-05-11 22:11:41-- https://raw.githubusercontent.com/beoutbreakprepared/nCoV2019/master/latest_data/latestdata.tar.gz\nResolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.108.133, ...\nConnecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 16036070 (15M) [application/octet-stream]\nSaving to: ‘latestdata.tar.gz?raw=true.1’\n\nlatestdata.tar.gz?r 100%[===================>] 15.29M 63.5MB/s in 0.2s \n\n2021-05-11 22:11:42 (63.5 MB/s) - ‘latestdata.tar.gz?raw=true.1’ saved [16036070/16036070]\n\n" ] ], [ [ "Unzip the file", "_____no_output_____" ] ], [ [ "!tar -xvf latestdata.tar.gz?raw=true", "latestdata.csv\n" ] ], [ [ "When reasing in the .csv dataset, set `low memory` to `False` so Pandas does not guess a data type and raise errors.", "_____no_output_____" ] ], [ [ "df = pd.read_csv('latestdata.csv', low_memory=False)\noriginal_df = df.copy()", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 2676311 entries, 0 to 2676310\nData columns (total 33 columns):\n # Column Dtype \n--- ------ ----- \n 0 ID object \n 1 age object \n 2 sex object \n 3 city object \n 4 province object \n 5 country object \n 6 latitude float64\n 7 longitude float64\n 8 geo_resolution object \n 9 date_onset_symptoms object \n 10 date_admission_hospital object \n 11 date_confirmation object \n 12 symptoms object \n 13 lives_in_Wuhan object \n 14 travel_history_dates object \n 15 travel_history_location object \n 16 reported_market_exposure object \n 17 additional_information object \n 18 chronic_disease_binary bool \n 19 chronic_disease object \n 20 source object \n 21 sequence_available object \n 22 outcome object \n 23 date_death_or_discharge object \n 24 notes_for_discussion object \n 25 location object \n 26 admin3 object \n 27 admin2 object \n 28 admin1 object \n 29 country_new object \n 30 admin_id float64\n 31 data_moderator_initials object \n 32 travel_history_binary object \ndtypes: bool(1), float64(3), object(29)\nmemory usage: 655.9+ MB\n" ], [ "df.count()", "_____no_output_____" ] ], [ [ "Features worth noting in terms of relevance to outcome prediction and availibility in the data set:\n\n\n1. `longitude`, `latitude`, `geo_reolution`\n2. `date onset` and `admission`\n3. `date_confirmation`\n4. `travel_history_binary`\n5. `chronic_disease_binary`\n6. `outcome`\n\n", "_____no_output_____" ], [ "0 rows are completely filled.", "_____no_output_____" ], [ "# Data Cleaning\nBegin by fixing the data types of the features we intend to use. This involves dropping rows without the neccessary features filled in.", "_____no_output_____" ] ], [ [ "df.dropna(subset=['age', 'sex', 'latitude', 'longitude', 'chronic_disease_binary', 'travel_history_binary', 'outcome'], inplace=True)", "_____no_output_____" ], [ "# convert age to floats first\n# coerce to force any enrties that are age ranges to NaN\ndf['age'] = pd.to_numeric(df['age'], errors='coerce')\n\n#remove all NaNs\ndf.dropna(subset=['age'], inplace=True)\ndf['age'] = df['age'].astype(int)", "_____no_output_____" ], [ "df.dropna(subset=['travel_history_binary'], inplace=True)", "_____no_output_____" ], [ "thb_dict = {\n True: True,\n False: False\n}\n\ndf['travel_history_binary'] = df['travel_history_binary'].map(thb_dict)", "_____no_output_____" ] ], [ [ "Convert `sex` to binary for correlation purposes.", "_____no_output_____" ] ], [ [ "sexdict = {\n 'male': True,\n 'female': False\n}\n\ndf['sex'] = df['sex'].map(sexdict)", "_____no_output_____" ] ], [ [ "Convert `outcome` label to boolean.", "_____no_output_____" ] ], [ [ "df['outcome'].unique()", "_____no_output_____" ], [ "outdict = {'death': False,\n 'discharge': True,\n 'discharged': True,\n 'Discharged': True,\n 'recovered': True,\n 'released from quarantine': True,\n 'stable': True,\n 'Death': False,\n 'died': False,\n 'Alive': True,\n 'Dead': False,\n 'Recovered': True,\n 'Stable': True,\n 'Died': False,\n 'Deceased': False,\n 'stable condition': True,\n 'Under treatment': True,\n 'Receiving Treatment': True,\n 'severe illness': True,\n 'dead': False,\n 'critical condition': True,\n 'Hospitalized': True}\n\ndf['outcome'] = df['outcome'].map(outdict)", "_____no_output_____" ] ], [ [ "Explore `date_confirmation`\n\nDid not end up using this feature in final model.", "_____no_output_____" ] ], [ [ "\ndf['date_confirmation'] = pd.to_datetime(df['date_confirmation'],\n format='%d.%m.%Y',\n errors='coerce')", "_____no_output_____" ], [ "print(df['date_confirmation'].dtype)\ndf['date_confirmation']", "datetime64[ns]\n" ], [ "print(df['date_confirmation'].min())\nprint(df['date_confirmation'].max())", "2020-01-06 00:00:00\n2020-06-03 00:00:00\n" ], [ "df['date_confirmation'].dt.month.unique()", "_____no_output_____" ] ], [ [ "`date_confirmation` did not have year long data.", "_____no_output_____" ], [ "# Data Insights and Statistics", "_____no_output_____" ] ], [ [ "from pandas.plotting import scatter_matrix\nattributes = ['age', 'latitude', 'longitude']\nscatter_matrix(df[attributes], figsize=(12, 8))", "_____no_output_____" ] ], [ [ "Analyse Pearson's correlation coefficient.", "_____no_output_____" ] ], [ [ "df.corr(method='pearson')", "_____no_output_____" ], [ "import seaborn as sns\ncorr = df.corr(method='pearson')\nplt.figure(figsize=(10, 10))\nax = sns.heatmap(\n corr, \n vmin=-1, vmax=1, center=0,\n cmap=sns.diverging_palette(20, 220, n=200),\n square=True\n)\nax.set_xticklabels(\n ax.get_xticklabels(),\n rotation=45,\n horizontalalignment='right'\n)", "_____no_output_____" ] ], [ [ "Point Biserial Correlation between age (continuous) and outcome (binary)", "_____no_output_____" ] ], [ [ "stats.pointbiserialr(df['age'], df['outcome'])", "_____no_output_____" ] ], [ [ "Check if `age` is normally distributed.", "_____no_output_____" ] ], [ [ "stats.shapiro(df['age'])", "/usr/local/lib/python3.7/dist-packages/scipy/stats/morestats.py:1676: UserWarning: p-value may not be accurate for N > 5000.\n warnings.warn(\"p-value may not be accurate for N > 5000.\")\n" ] ], [ [ "Sample size too big for Shapiro-Wilk test, instead try Kolmogorov Smirnov test.", "_____no_output_____" ] ], [ [ "stats.kstest(df.loc[df['outcome']==True]['age'], 'norm')", "_____no_output_____" ], [ "stats.kstest(df.loc[df['outcome']==False]['age'], 'norm')", "_____no_output_____" ] ], [ [ "A very high test statistic is found, so age of a positive and negative COVID case are both normally distributed.\n\nNow, check if the mean of the ages differ based on outcomes using a Wilcoxon test on a random sample of each subset since subsets are of different sizes.", "_____no_output_____" ] ], [ [ "df_alive= df.loc[df['outcome']==True].sample(n=1000, random_state=4)\ndf_dead= df.loc[df['outcome']==False].sample(n=1000, random_state=4)", "_____no_output_____" ], [ "stats.wilcoxon(df_alive['age'], df_dead['age'])", "_____no_output_____" ] ], [ [ "# Data Preparation", "_____no_output_____" ] ], [ [ "len(df)", "_____no_output_____" ] ], [ [ "Todo: need to fix sex column, use one hot encoding on it!", "_____no_output_____" ] ], [ [ "ml_df = df.copy()\n# sex_bin inclued only to check gini importance of RF\nml_df = ml_df[['age', 'sex', 'latitude', 'longitude', 'chronic_disease_binary', 'travel_history_binary', 'outcome']]\nml_df.head()", "_____no_output_____" ] ], [ [ "Check if there are any nulls.", "_____no_output_____" ] ], [ [ "ml_df.isnull().sum().sort_values()", "_____no_output_____" ] ], [ [ "Create feature vector and label", "_____no_output_____" ] ], [ [ "# Feature Vector\nX = ml_df.drop(columns=['outcome'])\n# Label\ny = ml_df['outcome']", "_____no_output_____" ] ], [ [ "Perform train test split. ", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import StratifiedShuffleSplit\n\nstratified_split = StratifiedShuffleSplit(n_splits=1, test_size=0.3, random_state=42)\n\nfor train_index, test_index in stratified_split.split(ml_df, ml_df['outcome']):\n strat_train_set = ml_df.iloc[train_index]\n strat_test_set = ml_df.iloc[test_index]", "_____no_output_____" ], [ "print(len(strat_train_set))\nprint(len(strat_test_set))", "23319\n9995\n" ], [ "# Feature Vectors\nX_train = strat_train_set.drop(columns=['outcome'])\nX_test = strat_test_set.drop(columns=['outcome'])\n\n# Labels\ny_train = strat_train_set['outcome']\ny_test = strat_test_set['outcome']\n\nnumeric_train_df = X_train.select_dtypes(exclude=['object'])\nnumeric_test_df = X_test.select_dtypes(exclude=['object'])\n\n# to deal with sex\ncategorical_train_df = X_train.select_dtypes(['object'])\ncategorical_test_df = X_test.select_dtypes(['object'])", "_____no_output_____" ], [ "from sklearn.base import BaseEstimator, TransformerMixin\nclass DFSelector(BaseEstimator, TransformerMixin):\n def __init__(self, attribute_names):\n self.attribute_names = attribute_names\n def fit (self, X, y=None):\n return self\n def transform(self, X):\n return X[self.attribute_names].values", "_____no_output_____" ], [ "from sklearn.preprocessing import OneHotEncoder, StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\n\nnum_attributes = list(X_train.select_dtypes(exclude=['object']))\n# removed country so i only have a numerical pipeline\ncat_attributes = list(X_train.select_dtypes(['object']))\n\n\n\nnum_pipeline = Pipeline([\n ('select_numeric', DFSelector(num_attributes)),\n ('std_sclr', StandardScaler()),\n ])\n\ncat_pipeline = Pipeline([\n ('select_categoric', DFSelector(cat_attributes)),\n ('one_hot', OneHotEncoder()),\n ])\n\nfull_pipeline = ColumnTransformer([\n ('num', num_pipeline, num_attributes),\n ('cat', cat_pipeline, cat_attributes),\n ])\n\nX_train_scaled = full_pipeline.fit_transform(X_train)\nX_test_scaled = full_pipeline.fit_transform(X_test)\n\n# This is what o reilly does, but i dont think its what im after\n# it also reqwuires num_att and cat_att to be based on the entire svm_df\n# svm_df_prepared = full_pipeline.fit_transform(svm_df)", "_____no_output_____" ] ], [ [ "Label Scaling", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import LabelEncoder\n\nle = LabelEncoder()\ny_train_scaled = le.fit_transform(y_train)\ny_test_scaled = le.fit_transform(y_test)", "_____no_output_____" ], [ "from sklearn.metrics import accuracy_score, mean_squared_error, balanced_accuracy_score, jaccard_score, f1_score, confusion_matrix, plot_roc_curve\ndef performance_metrics(model, X_test, y_test, y_hat):\n print('Accuracy: ', accuracy_score(y_test, y_hat)*100, '%')\n print('Root Mean Squared Error: ', np.sqrt(mean_squared_error(y_test, y_hat)))\n print('Balanced Accuracy: ', balanced_accuracy_score(y_test, y_hat)*100, '%')\n print('Jaccard Score: ', jaccard_score(y_test, y_hat, average='weighted')*100, '%')\n print('F1 Score: ', f1_score(y_test, y_hat))\n\n cm = confusion_matrix(y_test, y_hat)\n print('True Negatives (Correctly Predicted Death): ', cm[0,0])\n print('False Negatives (Incorrectly Predicted as Death): ', cm[1,0])\n print('True Positives (Correctly Predicted as Alive): ', cm[1,1])\n print('False Positives (Incorrectly Predicted as Alive): ', cm[0,1])\n\n print('Sensitivty (Recall/True Positive Rate): ', cm[1,1] / (cm[1,1]+cm[1,0])) # TP/(TP+FN), proportion of actual positives branded as positives\n print('False Positive Rate: ', cm[0,1] / (cm[0,1]+cm[0,0])) # FP/(FP+TN), proportion of actual negatives branded as postives\n print('Specificity: ', cm[0,0] / (cm[0,0]+cm[0,1])) # TN/(TN+FP)\n print('Positive Predictive Value (Precision): ', cm[1,1] / (cm[1,1]+cm[0,1])) # TP/(TP+FP)\n print('Negative Predictive Value: ', cm[0,0] / (cm[0,0]+cm[1,0])) # TN/(TN+FN)\n\n plot_roc_curve(model, X_test, y_test)\n plt.show", "_____no_output_____" ] ], [ [ "## Support Vector Machine", "_____no_output_____" ], [ "Create a SVM classifier and perform 10-fold cross validation to get an idea of ifdeal parameters (no fitting to training set yet).", "_____no_output_____" ] ], [ [ "from sklearn.svm import SVC\nfrom sklearn.model_selection import cross_validate\n\nSVM_basemodel = SVC(random_state=42)\nscoring = ['accuracy', 'f1', 'precision', 'recall']\n\nscores = cross_validate(SVM_basemodel, X_train_scaled, y_train_scaled, cv = 5,\n scoring=scoring, return_estimator=True)\nsorted(scores.keys())", "_____no_output_____" ], [ "print('Average Accuracy:', scores['test_accuracy'].mean())\nprint('Average F1:', scores['test_f1'].mean())\nprint('Average Precision:', scores['test_precision'].mean())\nprint('Average Recall:', scores['test_recall'].mean())", "Average Accuracy: 0.9665080177551904\nAverage F1: 0.9828524147931358\nAverage Precision: 0.9682904452504643\nAverage Recall: 0.9978600089166296\n" ], [ "scores['estimator']", "_____no_output_____" ], [ "SVM_basemodel.fit(X_train_scaled, y_train_scaled)", "_____no_output_____" ] ], [ [ "Results of default base model with test set.", "_____no_output_____" ] ], [ [ "y_hat_SVM_base = SVM_basemodel.predict(X_test_scaled)", "_____no_output_____" ], [ "performance_metrics(SVM_basemodel, X_test_scaled, y_test_scaled, y_hat_SVM_base)", "Accuracy: 96.57828914457228 %\nRoot Mean Squared Error: 0.18497867053873304\nBalanced Accuracy: 57.89083286785947 %\nJaccard Score: 93.45359365156582 %\nF1 Score: 0.9824848919389533\nTrue Negatives (Correctly Predicted Death): 61\nFalse Negatives (Incorrectly Predicted as Death): 22\nTrue Positives (Correctly Predicted as Alive): 9592\nFalse Positives (Incorrectly Predicted as Alive): 320\nSensitivty (Recall/True Positive Rate): 0.9977116704805492\nFalse Positive Rate: 0.8398950131233596\nSpecificity: 0.16010498687664043\nPositive Predictive Value (Precision): 0.9677158999192897\nNegative Predictive Value: 0.7349397590361446\n" ] ], [ [ "Now use random search hyper tuning. Takes approximately 6 to 10 minutes.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import RandomizedSearchCV\nparameter_space = {\n 'C': [0.1, 1, 10, 100],\n 'gamma': [ 0.1, 1, 10],\n}\n\nSVM_tuned =SVC(random_state=42)\n\nSVM_randsearch = RandomizedSearchCV(estimator=SVM_tuned,\n param_distributions=parameter_space,\n scoring=scoring,\n verbose=1, n_jobs=-1,\n n_iter=1000, refit = 'accuracy') # set refit to false for multi key scoring\n\n\n\nSVM_rand_result = SVM_randsearch.fit(X_train_scaled, y_train_scaled)", "Fitting 5 folds for each of 12 candidates, totalling 60 fits\n" ], [ "results = SVM_rand_result.cv_results_\ndict(results).keys()", "_____no_output_____" ], [ "print('Accuracy: ', dict(results)['mean_test_accuracy'].max())\nprint('Precision: ', dict(results)['mean_test_precision'].max())\nprint('Recall: ', dict(results)['mean_test_recall'].max())\nprint('F1: ', dict(results)['mean_test_f1'].max())", "Accuracy: 0.9668939433789376\nPrecision: 0.9711893898298083\nRecall: 0.9994650022291574\nF1: 0.9830352587088766\n" ], [ "SVM_clf = SVM_rand_result.best_estimator_\nSVM_clf.fit(X_train_scaled, y_train_scaled)\ny_hat_SVM_tuned = SVM_clf.predict(X_test_scaled)", "_____no_output_____" ] ], [ [ "Results of final tuned model with tests et", "_____no_output_____" ] ], [ [ "performance_metrics(SVM_clf, X_test_scaled, y_test_scaled, y_hat_SVM_tuned)", "Accuracy: 96.58829414707354 %\nRoot Mean Squared Error: 0.18470803590874066\nBalanced Accuracy: 59.03032923880146 %\nJaccard Score: 93.53252376431833 %\nF1 Score: 0.9825208877953764\nTrue Negatives (Correctly Predicted Death): 70\nFalse Negatives (Incorrectly Predicted as Death): 30\nTrue Positives (Correctly Predicted as Alive): 9584\nFalse Positives (Incorrectly Predicted as Alive): 311\nSensitivty (Recall/True Positive Rate): 0.9968795506552943\nFalse Positive Rate: 0.8162729658792651\nSpecificity: 0.1837270341207349\nPositive Predictive Value (Precision): 0.9685699848408287\nNegative Predictive Value: 0.7\n" ] ], [ [ "---", "_____no_output_____" ], [ "# Random Forests", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_validate\nRF_basemodel = RandomForestClassifier(n_estimators=1000, random_state=42)\nscoring = ['accuracy', 'f1', 'precision', 'recall']\n\nscores = cross_validate(RF_basemodel, X_train_scaled, y_train_scaled, cv = 5,\n scoring=scoring, return_estimator=True)\n# print(f'{scores.mean()*100}% accuracy with a standard deviation of {scores.std()}')\nsorted(scores.keys())", "_____no_output_____" ] ], [ [ "metrics from validaiton set for default base model:", "_____no_output_____" ] ], [ [ "print('Average Accuracy:', scores['test_accuracy'].mean())\nprint('Average F1:', scores['test_f1'].mean())\nprint('Average Precision:', scores['test_precision'].mean())\nprint('Average Recall:', scores['test_recall'].mean())", "Average Accuracy: 0.9620481425800499\nAverage F1: 0.980412770791985\nAverage Precision: 0.9734551494451512\nAverage Recall: 0.9874721355327687\n" ], [ "scores['estimator']", "_____no_output_____" ], [ "RF_basemodel.fit(X_train_scaled, y_train_scaled)\ny_hat_RF_base = RF_basemodel.predict(X_test_scaled)", "_____no_output_____" ], [ "performance_metrics(RF_basemodel, X_test_scaled, y_test_scaled, y_hat_RF_base)", "Accuracy: 96.56828414207104 %\nRoot Mean Squared Error: 0.1852489097924456\nBalanced Accuracy: 60.280256209912594 %\nJaccard Score: 93.58148620774482 %\nF1 Score: 0.9823985220916508\nTrue Negatives (Correctly Predicted Death): 80\nFalse Negatives (Incorrectly Predicted as Death): 42\nTrue Positives (Correctly Predicted as Alive): 9572\nFalse Positives (Incorrectly Predicted as Alive): 301\nSensitivty (Recall/True Positive Rate): 0.9956313709174122\nFalse Positive Rate: 0.7900262467191601\nSpecificity: 0.2099737532808399\nPositive Predictive Value (Precision): 0.9695128127215639\nNegative Predictive Value: 0.6557377049180327\n" ] ], [ [ "Look at feature importances of base model.", "_____no_output_____" ] ], [ [ "importances = RF_basemodel.feature_importances_\nstd = np.std([\n tree.feature_importances_ for tree in RF_basemodel.estimators_], axis=0)\n\n\nforest_importances = pd.Series(importances, index=list(X_train.select_dtypes(exclude=['object'])))\n\nfig, ax = plt.subplots()\nforest_importances.plot.bar(yerr=std, ax=ax)\nax.set_ylabel(\"Mean decrease in impurity\")\nax.set_xticklabels(\n ax.get_xticklabels(),\n rotation=45,\n horizontalalignment='right'\n)\nfig.tight_layout()", "_____no_output_____" ] ], [ [ "Ranges for parameters may appear,narrow, trail and error was used to condfirm that the optimal values lie within this range.\nthis stiol takes a whilke, so need to cut down the numbrer of fits to try.", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import RandomizedSearchCV\nparameter_space = {\n 'max_depth': [100, 110],\n 'min_samples_leaf': [3, 4],\n 'min_samples_split': [6, 8, 10],\n 'criterion': ['gini', 'entropy']\n}\n\nRF_tuned = RandomForestClassifier(random_state=42)\n\nRF_randsearch = RandomizedSearchCV(estimator=RF_tuned,\n param_distributions=parameter_space,\n scoring=scoring,\n verbose=1, n_jobs=-1,\n n_iter=500, refit = 'accuracy') # set refit to false for multi key scoring\n\n\n\nRF_rand_result = RF_randsearch.fit(X_train_scaled, y_train_scaled)", "/usr/local/lib/python3.7/dist-packages/sklearn/model_selection/_search.py:281: UserWarning: The total space of parameters 24 is smaller than n_iter=500. Running 24 iterations. For exhaustive searches, use GridSearchCV.\n % (grid_size, self.n_iter, grid_size), UserWarning)\n[Parallel(n_jobs=-1)]: Using backend LokyBackend with 2 concurrent workers.\n" ], [ "results = RF_rand_result.cv_results_\ndict(results).keys()", "_____no_output_____" ], [ "print('Accuracy: ', dict(results)['mean_test_accuracy'].max())\nprint('Precision: ', dict(results)['mean_test_precision'].max())\nprint('Recall: ', dict(results)['mean_test_recall'].max())\nprint('F1: ', dict(results)['mean_test_f1'].max())", "Accuracy: 0.9671941332978239\nPrecision: 0.9724658837883566\nRecall: 0.9942041908158716\nF1: 0.9831362063481087\n" ], [ "RF_clf = RF_rand_result.best_estimator_\nRF_clf.fit(X_train_scaled, y_train_scaled)", "_____no_output_____" ], [ "y_hat_RF_tuned = RF_clf.predict(X_test_scaled)", "_____no_output_____" ], [ "performance_metrics(RF_clf, X_test_scaled, y_test_scaled, y_hat_RF_tuned)", "Accuracy: 96.67833916958479 %\nRoot Mean Squared Error: 0.1822542408399653\nBalanced Accuracy: 59.20316882586473 %\nJaccard Score: 93.6417697618546 %\nF1 Score: 0.9829883172781307\nTrue Negatives (Correctly Predicted Death): 71\nFalse Negatives (Incorrectly Predicted as Death): 22\nTrue Positives (Correctly Predicted as Alive): 9592\nFalse Positives (Incorrectly Predicted as Alive): 310\nSensitivty (Recall/True Positive Rate): 0.9977116704805492\nFalse Positive Rate: 0.8136482939632546\nSpecificity: 0.18635170603674542\nPositive Predictive Value (Precision): 0.9686931932942839\nNegative Predictive Value: 0.7634408602150538\n" ] ], [ [ "---", "_____no_output_____" ], [ "# Stochastic Gradient Descent", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import SGDClassifier", "_____no_output_____" ], [ "from sklearn.model_selection import cross_val_score, cross_validate\nscoring = ['accuracy', 'f1', 'precision', 'recall']\nSGD_basemodel = SGDClassifier(random_state=42)\n\n# scores = cross_val_score(SGD_basemodel, X_train_scaled, y_train_scaled, cv = 5)\n# print(f'{scores.mean()*100}% accuracy with a standard deviation of {scores.std()}')\n\nscores = cross_validate(SGD_basemodel, X_train_scaled, y_train_scaled,scoring=scoring)\nsorted(scores.keys())", "_____no_output_____" ], [ "print('Average Accuracy:', scores['test_accuracy'].mean())\nprint('Average F1:', scores['test_f1'].mean())\nprint('Average Precision:', scores['test_precision'].mean())\nprint('Average Recall:', scores['test_recall'].mean())", "Average Accuracy: 0.9632917930984\nAverage F1: 0.9812670065072855\nAverage Precision: 0.963679277897654\nAverage Recall: 0.9995095853767276\n" ], [ "SGD_basemodel.fit(X_train_scaled, y_train_scaled)\n# SGD_basemodel = scores.best_estimator_\ny_hat_SGD_scaled = SGD_basemodel.predict(X_test_scaled)", "_____no_output_____" ], [ "performance_metrics(SGD_basemodel, X_test_scaled, y_test_scaled, y_hat_SGD_scaled)", "Accuracy: 96.43821910955478 %\nRoot Mean Squared Error: 0.18872681024288052\nBalanced Accuracy: 53.40687274190581 %\nJaccard Score: 93.0125986673499 %\nF1 Score: 0.9818200388111531\nTrue Negatives (Correctly Predicted Death): 26\nFalse Negatives (Incorrectly Predicted as Death): 1\nTrue Positives (Correctly Predicted as Alive): 9613\nFalse Positives (Incorrectly Predicted as Alive): 355\nSensitivty (Recall/True Positive Rate): 0.9998959850218432\nFalse Positive Rate: 0.931758530183727\nSpecificity: 0.06824146981627296\nPositive Predictive Value (Precision): 0.9643860353130016\nNegative Predictive Value: 0.9629629629629629\n" ], [ "from sklearn.model_selection import RandomizedSearchCV\nparameter_space = {\n 'loss': ['hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'],\n 'penalty': ['l1', 'l2', 'elasticnet'],\n 'alpha': [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000],\n 'learning_rate': ['constant', 'optimal', 'invscaling', 'adaptive'],\n 'class_weight': [{1:0.5, 0:0.5}, {1:0.4, 0:0.6}, {1:0.6, 0:0.4}, {1:0.7, 0:0.3}],\n 'eta0': [1, 10, 100],\n}\n\nSGD_tuned = SGDClassifier(random_state=42)\n\nSGD_randsearch = RandomizedSearchCV(estimator=SGD_tuned,\n param_distributions=parameter_space,\n scoring=scoring,\n verbose=1, n_jobs=-1,\n n_iter=1000, refit = 'accuracy') # set refit to false for multi key scoring\n\nSGD_Xtrain = X_train.drop(columns=['sex'])\n\n\nSGD_rand_result = SGD_randsearch.fit(X_train_scaled, y_train_scaled)", "Fitting 5 folds for each of 1000 candidates, totalling 5000 fits\n" ], [ "results = SGD_rand_result.cv_results_", "_____no_output_____" ], [ "dict(results).keys()", "_____no_output_____" ], [ "print('Accuracy: ', dict(results)['mean_test_accuracy'].max())\nprint('Precision: ', dict(results)['mean_test_precision'].max())\nprint('Recall: ', dict(results)['mean_test_recall'].max())\nprint('F1: ', dict(results)['mean_test_f1'].max())", "Accuracy: 0.9647068230649737\nPrecision: 0.9784834286430109\nRecall: 1.0\nF1: 0.9819371065728723\n" ], [ "SGD_rand_result.best_params_", "_____no_output_____" ], [ "SGD_clf = SGD_rand_result.best_estimator_\n# SGD_clf = SGDClassifier(**SGD_rand_result.best_params_)", "_____no_output_____" ], [ "SGD_clf.fit(X_train_scaled, y_train_scaled)\ny_hat_SGD_tuned = SGD_clf.predict(X_test_scaled)", "_____no_output_____" ], [ "performance_metrics(SGD_clf, X_test_scaled, y_test_scaled, y_hat_SGD_tuned)", "Accuracy: 96.64832416208104 %\nRoot Mean Squared Error: 0.1830758268564957\nBalanced Accuracy: 58.30533665089243 %\nJaccard Score: 93.55483807515881 %\nF1 Score: 0.9828442669124801\nTrue Negatives (Correctly Predicted Death): 64\nFalse Negatives (Incorrectly Predicted as Death): 18\nTrue Positives (Correctly Predicted as Alive): 9596\nFalse Positives (Incorrectly Predicted as Alive): 317\nSensitivty (Recall/True Positive Rate): 0.9981277303931766\nFalse Positive Rate: 0.8320209973753281\nSpecificity: 0.1679790026246719\nPositive Predictive Value (Precision): 0.9680217895692524\nNegative Predictive Value: 0.7804878048780488\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4afcb81d9dffe281caae7293424f4d16c081eac1
31,171
ipynb
Jupyter Notebook
site/en/r2/tutorials/keras/basic_classification.ipynb
random-forests/docs
c3c4680115f10dd68766761c21e6c22b8bd39a90
[ "Apache-2.0" ]
1
2019-09-30T18:03:47.000Z
2019-09-30T18:03:47.000Z
site/en/r2/tutorials/keras/basic_classification.ipynb
random-forests/docs
c3c4680115f10dd68766761c21e6c22b8bd39a90
[ "Apache-2.0" ]
null
null
null
site/en/r2/tutorials/keras/basic_classification.ipynb
random-forests/docs
c3c4680115f10dd68766761c21e6c22b8bd39a90
[ "Apache-2.0" ]
null
null
null
31.108782
468
0.509576
[ [ [ "##### Copyright 2018 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_____" ], [ "#@title MIT License\n#\n# Copyright (c) 2017 François Chollet\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.", "_____no_output_____" ] ], [ [ "# Train your first neural network: basic classification", "_____no_output_____" ], [ "<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/tutorials/keras/basic_classification\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r2/tutorials/keras/basic_classification.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r2/tutorials/keras/basic_classification.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n</table>", "_____no_output_____" ], [ "This guide trains a neural network model to classify images of clothing, like sneakers and shirts. It's okay if you don't understand all the details, this is a fast-paced overview of a complete TensorFlow program with the details explained as we go.\n\nThis guide uses [tf.keras](https://www.tensorflow.org/guide/keras), a high-level API to build and train models in TensorFlow.", "_____no_output_____" ] ], [ [ "!pip install tf-nightly-2.0-preview", "_____no_output_____" ], [ "from __future__ import absolute_import, division, print_function\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nprint(tf.__version__)", "_____no_output_____" ] ], [ [ "## Import the Fashion MNIST dataset", "_____no_output_____" ], [ "This guide uses the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset which contains 70,000 grayscale images in 10 categories. The images show individual articles of clothing at low resolution (28 by 28 pixels), as seen here:\n\n<table>\n <tr><td>\n <img src=\"https://tensorflow.org/images/fashion-mnist-sprite.png\"\n alt=\"Fashion MNIST sprite\" width=\"600\">\n </td></tr>\n <tr><td align=\"center\">\n <b>Figure 1.</b> <a href=\"https://github.com/zalandoresearch/fashion-mnist\">Fashion-MNIST samples</a> (by Zalando, MIT License).<br/>&nbsp;\n </td></tr>\n</table>\n\nFashion MNIST is intended as a drop-in replacement for the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset—often used as the \"Hello, World\" of machine learning programs for computer vision. The MNIST dataset contains images of handwritten digits (0, 1, 2, etc) in an identical format to the articles of clothing we'll use here.\n\nThis guide uses Fashion MNIST for variety, and because it's a slightly more challenging problem than regular MNIST. Both datasets are relatively small and are used to verify that an algorithm works as expected. They're good starting points to test and debug code. \n\nWe will use 60,000 images to train the network and 10,000 images to evaluate how accurately the network learned to classify images. You can access the Fashion MNIST directly from TensorFlow, just import and load the data:", "_____no_output_____" ] ], [ [ "fashion_mnist = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()", "_____no_output_____" ] ], [ [ "Loading the dataset returns four NumPy arrays:\n\n* The `train_images` and `train_labels` arrays are the *training set*—the data the model uses to learn.\n* The model is tested against the *test set*, the `test_images`, and `test_labels` arrays.\n\nThe images are 28x28 NumPy arrays, with pixel values ranging between 0 and 255. The *labels* are an array of integers, ranging from 0 to 9. These correspond to the *class* of clothing the image represents:\n\n<table>\n <tr>\n <th>Label</th>\n <th>Class</th> \n </tr>\n <tr>\n <td>0</td>\n <td>T-shirt/top</td> \n </tr>\n <tr>\n <td>1</td>\n <td>Trouser</td> \n </tr>\n <tr>\n <td>2</td>\n <td>Pullover</td> \n </tr>\n <tr>\n <td>3</td>\n <td>Dress</td> \n </tr>\n <tr>\n <td>4</td>\n <td>Coat</td> \n </tr>\n <tr>\n <td>5</td>\n <td>Sandal</td> \n </tr>\n <tr>\n <td>6</td>\n <td>Shirt</td> \n </tr>\n <tr>\n <td>7</td>\n <td>Sneaker</td> \n </tr>\n <tr>\n <td>8</td>\n <td>Bag</td> \n </tr>\n <tr>\n <td>9</td>\n <td>Ankle boot</td> \n </tr>\n</table>\n\nEach image is mapped to a single label. Since the *class names* are not included with the dataset, store them here to use later when plotting the images:", "_____no_output_____" ] ], [ [ "class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', \n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']", "_____no_output_____" ] ], [ [ "## Explore the data\n\nLet's explore the format of the dataset before training the model. The following shows there are 60,000 images in the training set, with each image represented as 28 x 28 pixels:", "_____no_output_____" ] ], [ [ "train_images.shape", "_____no_output_____" ] ], [ [ "Likewise, there are 60,000 labels in the training set:", "_____no_output_____" ] ], [ [ "len(train_labels)", "_____no_output_____" ] ], [ [ "Each label is an integer between 0 and 9:", "_____no_output_____" ] ], [ [ "train_labels", "_____no_output_____" ] ], [ [ "There are 10,000 images in the test set. Again, each image is represented as 28 x 28 pixels:", "_____no_output_____" ] ], [ [ "test_images.shape", "_____no_output_____" ] ], [ [ "And the test set contains 10,000 images labels:", "_____no_output_____" ] ], [ [ "len(test_labels)", "_____no_output_____" ] ], [ [ "## Preprocess the data\n\nThe data must be preprocessed before training the network. If you inspect the first image in the training set, you will see that the pixel values fall in the range of 0 to 255:", "_____no_output_____" ] ], [ [ "plt.figure()\nplt.imshow(train_images[0])\nplt.colorbar()\nplt.grid(False)\nplt.show()", "_____no_output_____" ] ], [ [ "We scale these values to a range of 0 to 1 before feeding to the neural network model. For this, we divide the values by 255. It's important that the *training set* and the *testing set* are preprocessed in the same way:", "_____no_output_____" ] ], [ [ "train_images = train_images / 255.0\n\ntest_images = test_images / 255.0", "_____no_output_____" ] ], [ [ "Display the first 25 images from the *training set* and display the class name below each image. Verify that the data is in the correct format and we're ready to build and train the network.", "_____no_output_____" ] ], [ [ "plt.figure(figsize=(10,10))\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(train_images[i], cmap=plt.cm.binary)\n plt.xlabel(class_names[train_labels[i]])\nplt.show()", "_____no_output_____" ] ], [ [ "## Build the model\n\nBuilding the neural network requires configuring the layers of the model, then compiling the model.", "_____no_output_____" ], [ "### Setup the layers\n\nThe basic building block of a neural network is the *layer*. Layers extract representations from the data fed into them. And, hopefully, these representations are more meaningful for the problem at hand.\n\nMost of deep learning consists of chaining together simple layers. Most layers, like `tf.keras.layers.Dense`, have parameters that are learned during training.", "_____no_output_____" ] ], [ [ "model = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.Dense(10, activation='softmax')\n])", "_____no_output_____" ] ], [ [ "The first layer in this network, `tf.keras.layers.Flatten`, transforms the format of the images from a 2d-array (of 28 by 28 pixels), to a 1d-array of 28 * 28 = 784 pixels. Think of this layer as unstacking rows of pixels in the image and lining them up. This layer has no parameters to learn; it only reformats the data.\n\nAfter the pixels are flattened, the network consists of a sequence of two `tf.keras.layers.Dense` layers. These are densely-connected, or fully-connected, neural layers. The first `Dense` layer has 128 nodes (or neurons). The second (and last) layer is a 10-node *softmax* layer—this returns an array of 10 probability scores that sum to 1. Each node contains a score that indicates the probability that the current image belongs to one of the 10 classes.\n\n### Compile the model\n\nBefore the model is ready for training, it needs a few more settings. These are added during the model's *compile* step:\n\n* *Loss function* —This measures how accurate the model is during training. We want to minimize this function to \"steer\" the model in the right direction.\n* *Optimizer* —This is how the model is updated based on the data it sees and its loss function.\n* *Metrics* —Used to monitor the training and testing steps. The following example uses *accuracy*, the fraction of the images that are correctly classified.", "_____no_output_____" ] ], [ [ "model.compile(optimizer='adam', \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])", "_____no_output_____" ] ], [ [ "## Train the model\n\nTraining the neural network model requires the following steps:\n\n1. Feed the training data to the model—in this example, the `train_images` and `train_labels` arrays.\n2. The model learns to associate images and labels.\n3. We ask the model to make predictions about a test set—in this example, the `test_images` array. We verify that the predictions match the labels from the `test_labels` array. \n\nTo start training, call the `model.fit` method—the model is \"fit\" to the training data:", "_____no_output_____" ] ], [ [ "model.fit(train_images, train_labels, epochs=5)", "_____no_output_____" ] ], [ [ "As the model trains, the loss and accuracy metrics are displayed. This model reaches an accuracy of about 0.88 (or 88%) on the training data.", "_____no_output_____" ], [ "## Evaluate accuracy\n\nNext, compare how the model performs on the test dataset:", "_____no_output_____" ] ], [ [ "test_loss, test_acc = model.evaluate(test_images, test_labels)\n\nprint('\\nTest accuracy:', test_acc)", "_____no_output_____" ] ], [ [ "It turns out, the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy is an example of *overfitting*. Overfitting is when a machine learning model performs worse on new data than on their training data. ", "_____no_output_____" ], [ "## Make predictions\n\nWith the model trained, we can use it to make predictions about some images.", "_____no_output_____" ] ], [ [ "predictions = model.predict(test_images)", "_____no_output_____" ] ], [ [ "Here, the model has predicted the label for each image in the testing set. Let's take a look at the first prediction:", "_____no_output_____" ] ], [ [ "predictions[0]", "_____no_output_____" ] ], [ [ "A prediction is an array of 10 numbers. These describe the \"confidence\" of the model that the image corresponds to each of the 10 different articles of clothing. We can see which label has the highest confidence value:", "_____no_output_____" ] ], [ [ "np.argmax(predictions[0])", "_____no_output_____" ] ], [ [ "So the model is most confident that this image is an ankle boot, or `class_names[9]`. And we can check the test label to see this is correct:", "_____no_output_____" ] ], [ [ "test_labels[0]", "_____no_output_____" ] ], [ [ "We can graph this to look at the full set of 10 channels", "_____no_output_____" ] ], [ [ "def plot_image(i, predictions_array, true_label, img):\n predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n \n plt.imshow(img, cmap=plt.cm.binary)\n\n predicted_label = np.argmax(predictions_array)\n if predicted_label == true_label:\n color = 'blue'\n else:\n color = 'red'\n \n plt.xlabel(\"{} {:2.0f}% ({})\".format(class_names[predicted_label],\n 100*np.max(predictions_array),\n class_names[true_label]),\n color=color)\n\ndef plot_value_array(i, predictions_array, true_label):\n predictions_array, true_label = predictions_array[i], true_label[i]\n plt.grid(False)\n plt.xticks([])\n plt.yticks([])\n thisplot = plt.bar(range(10), predictions_array, color=\"#777777\")\n plt.ylim([0, 1]) \n predicted_label = np.argmax(predictions_array)\n \n thisplot[predicted_label].set_color('red')\n thisplot[true_label].set_color('blue')", "_____no_output_____" ] ], [ [ "Let's look at the 0th image, predictions, and prediction array. ", "_____no_output_____" ] ], [ [ "i = 0\nplt.figure(figsize=(6,3))\nplt.subplot(1,2,1)\nplot_image(i, predictions, test_labels, test_images)\nplt.subplot(1,2,2)\nplot_value_array(i, predictions, test_labels)", "_____no_output_____" ], [ "i = 12\nplt.figure(figsize=(6,3))\nplt.subplot(1,2,1)\nplot_image(i, predictions, test_labels, test_images)\nplt.subplot(1,2,2)\nplot_value_array(i, predictions, test_labels)", "_____no_output_____" ] ], [ [ "Let's plot several images with their predictions. Correct prediction labels are blue and incorrect prediction labels are red. The number gives the percent (out of 100) for the predicted label. Note that it can be wrong even when very confident. ", "_____no_output_____" ] ], [ [ "# Plot the first X test images, their predicted label, and the true label\n# Color correct predictions in blue, incorrect predictions in red\nnum_rows = 5\nnum_cols = 3\nnum_images = num_rows*num_cols\nplt.figure(figsize=(2*2*num_cols, 2*num_rows))\nfor i in range(num_images):\n plt.subplot(num_rows, 2*num_cols, 2*i+1)\n plot_image(i, predictions, test_labels, test_images)\n plt.subplot(num_rows, 2*num_cols, 2*i+2)\n plot_value_array(i, predictions, test_labels)\n", "_____no_output_____" ] ], [ [ "Finally, use the trained model to make a prediction about a single image. ", "_____no_output_____" ] ], [ [ "# Grab an image from the test dataset\nimg = test_images[0]\n\nprint(img.shape)", "_____no_output_____" ] ], [ [ "`tf.keras` models are optimized to make predictions on a *batch*, or collection, of examples at once. So even though we're using a single image, we need to add it to a list:", "_____no_output_____" ] ], [ [ "# Add the image to a batch where it's the only member.\nimg = (np.expand_dims(img,0))\n\nprint(img.shape)", "_____no_output_____" ] ], [ [ "Now predict the image:", "_____no_output_____" ] ], [ [ "predictions_single = model.predict(img)\n\nprint(predictions_single)", "_____no_output_____" ], [ "plot_value_array(0, predictions_single, test_labels)\n_ = plt.xticks(range(10), class_names, rotation=45)", "_____no_output_____" ] ], [ [ "`model.predict` returns a list of lists, one for each image in the batch of data. Grab the predictions for our (only) image in the batch:", "_____no_output_____" ] ], [ [ "np.argmax(predictions_single[0])", "_____no_output_____" ] ], [ [ "And, as before, the model predicts a label of 9.", "_____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", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4afcba2e36a0bb1db5c05b1309eda9a1c32a0216
4,276
ipynb
Jupyter Notebook
for/for2-strings-sol.ipynb
simoneb1x/softpython-en
4321fb033a10b57058e10c07f763d170b41a3082
[ "CC-BY-4.0" ]
null
null
null
for/for2-strings-sol.ipynb
simoneb1x/softpython-en
4321fb033a10b57058e10c07f763d170b41a3082
[ "CC-BY-4.0" ]
16
2020-10-24T15:16:59.000Z
2022-03-19T04:05:48.000Z
for/for2-strings-sol.ipynb
simoneb1x/softpython-en
4321fb033a10b57058e10c07f763d170b41a3082
[ "CC-BY-4.0" ]
1
2021-10-30T18:09:14.000Z
2021-10-30T18:09:14.000Z
23.36612
268
0.512161
[ [ [ "# Remember to execute this cell with Shift+Enter\n\nimport sys\nsys.path.append('../')\nimport jupman", "_____no_output_____" ] ], [ [ "# For loops 2 - iterating strings\n\n## [Download exercises zip](../_static/generated/for.zip) \n\n[Browse file online](https://github.com/DavidLeoni/softpython-en/tree/master/for)\n\nLet's see some exercise about strings.", "_____no_output_____" ], [ "## Exercise - Impertinence\n\nGiven the `sequence` of characters having a length multiple of 3, write some code which puts into variable `triplets` all the sub-sequences of three characters\n\nExample - given:\n\n```python\nsequence = \"IMPERTINENCE\" \n IMPERTINENTE\n \n```\nafter your code, it must result:\n\n```python\n>>> print(triplets)\n['IMP', 'ERT', 'INE', 'NCE']\n```", "_____no_output_____" ] ], [ [ "#jupman-purge-output\nsequence = \"IMPERTINENCE\" # ['IMP', 'ERT', 'INE', 'NCE']\n#sequence = \"CUTOUT\" # ['CUT', 'OUT']\n#sequence = \"O_o\" # ['O_o']\n\n# write here\ntriplets = []\nfor i in range(len(sequence)):\n if i % 3 == 0:\n triplets.append(sequence[i:i+3])\nprint(triplets)", "['IMP', 'ERT', 'INE', 'NCE']\n" ] ], [ [ "## Exercise - rosco\n\n✪✪ Given a string `word` and string `repetitions` containing only digits, write some code which puts in variable `result` a string containing all the characters of `word` repeated by the number of times reported in the corresponding position of `repetitions`.\n\nExample - given:\n\n```python\nword, repetitions = \"rosco\", \"14323\"\n```\n\nAfter your code it must result:\n\n```python\n>>> result\n'roooosssccooo'\n```", "_____no_output_____" ] ], [ [ "#jupman-purge-output\nword, repetitions = \"rosco\", \"14323\" # 'roooosssccooo'\nword, repetitions = \"chocolate\", \"144232312\" # 'chhhhooooccooollaaatee'\n\n# write here\nres = []\n\nfor i in range(len(word)):\n res.append(word[i]*int(repetitions[i]))\n \nresult = \"\".join(res)\nprint(result)", "chhhhooooccooollaaatee\n" ] ], [ [ "## Continue\n\nGo on with exercises about [for loops with lists](https://en.softpython.org/for/for3-lists-sol.html)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4afcbaa2c074c00824e08e119d2ec2a2ebb5df48
146,607
ipynb
Jupyter Notebook
06-DA_Pandas_introduction.ipynb
girijeshcse/NumpyPandas_course
63506c8e1229483512786323539fbcf853ae8495
[ "BSD-3-Clause" ]
33
2020-06-08T05:40:15.000Z
2021-11-24T15:59:59.000Z
06-DA_Pandas_introduction.ipynb
guiwitz/NumpyPandas_course
63506c8e1229483512786323539fbcf853ae8495
[ "BSD-3-Clause" ]
null
null
null
06-DA_Pandas_introduction.ipynb
guiwitz/NumpyPandas_course
63506c8e1229483512786323539fbcf853ae8495
[ "BSD-3-Clause" ]
11
2020-06-12T14:43:33.000Z
2021-10-06T18:25:26.000Z
191.39295
72,028
0.876077
[ [ [ "# 6. Pandas Introduction\n\nIn the previous chapters, we have learned how to handle Numpy arrays that can be used to efficiently perform numerical calculations. Those arrays are however homogeneous structures i.e. they can only contain one type of data. Also, even if we have a single type of data, the different rows or columns of an array do not have labels, making it difficult to track what they contain. For such cases, we need a structure closer to a table as can be found in Excel, and these structures are implemented by the package Pandas.\n\nBut why can't we simply use Excel then? While Excel is practical to browse through data, it is very cumbersome to use to combine, re-arrange and thoroughly analyze data: code is hidden and difficult to share, there's no version control, it's difficult to automate tasks, the manual clicking around leads to mistakes etc.\n\nIn the next chapters, you will learn how to handle tabular data with Pandas, a Python package widely used in the scientific and data science areas. You will learn how to create and import tables, how to combine them, modify them, do statistical analysis on them and finally how to use them to easily create complex visualizations.\n\nSo that you see where this leads, we start with a short example of how Pandas can be used in a project. We look here at data provided openly by the Swiss National Science Foundation about grants attributed since 1975.", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "## 6.1 Importing data\n\nBefore anything, we need access to the data that can be found [here](https://opendata.swiss/de/dataset/p3-export-projects-people-and-publications). We can either manually download them and then use the path to read the data or directly use the url. The latter has the advantage that if you have an evolving source of data, these will always be up to date:", "_____no_output_____" ] ], [ [ "# local import\nprojects = pd.read_csv('Data/P3_GrantExport.csv',sep = ';')\n\n# import from url\n#projects = pd.read_csv('http://p3.snf.ch/P3Export/P3_GrantExport.csv',sep = ';')", "_____no_output_____" ] ], [ [ "Then we can have a brief look at the table itself that Jupyter displays in a formated way and limit the view to the 5 first rows using ```head()```:", "_____no_output_____" ] ], [ [ "projects.head(5)", "_____no_output_____" ] ], [ [ "## 6.2 Exploring data\n\nPandas offers a variety of tools to compile information about data, and that compilation can be done very efficiently without the need for loops, conditionals etc.\n\nFor example we can quickly count how many times each University appear in that table. We just use the ```value_counts()``` method for that:", "_____no_output_____" ] ], [ [ "projects['University'].value_counts().head(10)", "_____no_output_____" ] ], [ [ "Then we can very easily plot the resulting information, either using directly Pandas or a more advanced library like Seaborn, plotnine or Altair.\n\nHere first with plain Pandas (using Matplotlib under the hood):", "_____no_output_____" ] ], [ [ "projects['University'].value_counts().head(10).plot(kind='bar')", "_____no_output_____" ] ], [ [ "## 6.3 Handling different data types\n\nUnlike Numpy arrays, Pandas can handle a variety of different data types in a dataframe. For example it is very efficient at dealing with dates. We see that our table contains e.g. a ```Start Date```. We can turn this string into an actual date:", "_____no_output_____" ] ], [ [ "projects['start'] = pd.to_datetime(projects['Start Date'])\nprojects['year'] = projects.start.apply(lambda x: x.year)", "_____no_output_____" ], [ "projects.loc[0].start", "_____no_output_____" ], [ "projects.loc[0].year", "_____no_output_____" ] ], [ [ "## 6.4 Data wrangling, aggregation and statistics\n\nPandas is very efficient at wrangling and aggregating data, i.e. grouping several elements of a table to calculate statistics on them. For example we first need here to convert the ```Approved Amount``` to a numeric value. Certain rows contain text (e.g. \"not applicable\") and we force the conversion:", "_____no_output_____" ] ], [ [ "projects['Approved Amount'] = pd.to_numeric(projects['Approved Amount'], errors = 'coerce')", "_____no_output_____" ] ], [ [ "Then we want to extract the type of filed without subfields e.g. \"Humanities\" instead of \"Humanities and Social Sciences;Theology & religion\". For that we can create a custom function and apply it to an entire column:", "_____no_output_____" ] ], [ [ "science_types = ['Humanities', 'Mathematics','Biology']\nprojects['Field'] = projects['Discipline Name Hierarchy'].apply(\n lambda el: next((y for y in [x for x in science_types if x in el] if y is not None),None) if not pd.isna(el) else el)\n ", "_____no_output_____" ] ], [ [ "Then we group the data by discipline and year, and calculate the mean of each group:", "_____no_output_____" ] ], [ [ "aggregated = projects.groupby(['Institution Country', 'year','Field'], as_index=False).mean()", "_____no_output_____" ] ], [ [ "Finally we can use Seaborn to plot the data by \"Field\" using just keywords to indicate what the axes and colours should mean (following some principles of the grammar of graphics):", "_____no_output_____" ] ], [ [ "sns.lineplot(data = aggregated, x = 'year', y='Approved Amount', hue='Field');", "_____no_output_____" ] ], [ [ "Note that here, axis labelling, colorouring, legend, interval of confidence have been done automatically based on the content of the dataframe.\n\nWe see a drastic augmentation around 2010: let's have a closer look. We can here again group data by year and funding type and calculate the total funding:", "_____no_output_____" ] ], [ [ "grouped = projects.groupby(['year','Funding Instrument Hierarchy']).agg(\n total_sum=pd.NamedAgg(column='Approved Amount', aggfunc='sum')).reset_index()", "_____no_output_____" ], [ "grouped", "_____no_output_____" ] ], [ [ "Now, for each year we keep only the 5 largest funding types to be able to plot them:", "_____no_output_____" ] ], [ [ "group_sorted = grouped.groupby('year',as_index=False).apply(lambda x: (x.groupby('Funding Instrument Hierarchy')\n .sum()\n .sort_values('total_sum', ascending=False))\n .head(5)).reset_index()", "_____no_output_____" ] ], [ [ "Finally, we only keep year in the 2000's:", "_____no_output_____" ] ], [ [ "instruments_by_year = group_sorted[(group_sorted.year > 2005) & (group_sorted.year < 2012)]", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nplt.figure(figsize=(10,10))\nsns.barplot(data=instruments_by_year,\n x='year', y='total_sum', hue='Funding Instrument Hierarchy')", "_____no_output_____" ] ], [ [ "We see that the main change, is the sudden increase in funding for national research programs.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4afcd2c7e3aaa9910832e70c70957e967c1d146d
1,208
ipynb
Jupyter Notebook
Week_1.ipynb
naquech/CourseraCapstone
31fa4beadacf7419af9200ca2bcc9de1f76dc2c7
[ "MIT" ]
null
null
null
Week_1.ipynb
naquech/CourseraCapstone
31fa4beadacf7419af9200ca2bcc9de1f76dc2c7
[ "MIT" ]
null
null
null
Week_1.ipynb
naquech/CourseraCapstone
31fa4beadacf7419af9200ca2bcc9de1f76dc2c7
[ "MIT" ]
null
null
null
17.257143
48
0.500828
[ [ [ "# Applied Data Science Capstone Project\n## IBM Data Science Certificate\n\n--------", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np", "_____no_output_____" ], [ "print('Hello Capstone project Course!')", "Hello Capstone project Course!\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ] ]
4afcec2956756897753c46713960655268e8d3e8
779,002
ipynb
Jupyter Notebook
flower_recognition_alternate.ipynb
avitripathi15/starter-hugo-academic
933358416116690bb42708e379b3dd33c04d2bfb
[ "MIT" ]
null
null
null
flower_recognition_alternate.ipynb
avitripathi15/starter-hugo-academic
933358416116690bb42708e379b3dd33c04d2bfb
[ "MIT" ]
null
null
null
flower_recognition_alternate.ipynb
avitripathi15/starter-hugo-academic
933358416116690bb42708e379b3dd33c04d2bfb
[ "MIT" ]
null
null
null
1,226.774803
674,469
0.954241
[ [ [ "<a href=\"https://colab.research.google.com/github/avitripathi15/starter-hugo-academic/blob/master/flower_recognition_alternate.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport PIL\nimport tensorflow as tf\n\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import datasets, layers, models\nimport pathlib", "_____no_output_____" ], [ "dataset_url = \"https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz\"\ndata_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)\ndata_dir = pathlib.Path(data_dir)\nimage_count = len(list(data_dir.glob('*/*.jpg')))\nprint(image_count)", "Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz\n228818944/228813984 [==============================] - 2s 0us/step\n228827136/228813984 [==============================] - 2s 0us/step\n3670\n" ], [ "batch_size = 32\nimg_height = 225\nimg_width = 225", "_____no_output_____" ], [ "train_ds = tf.keras.utils.image_dataset_from_directory(\n data_dir,\n validation_split=0.2,\n subset=\"training\",\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)", "Found 3670 files belonging to 5 classes.\nUsing 2936 files for training.\n" ], [ "val_ds = tf.keras.utils.image_dataset_from_directory(\n data_dir,\n validation_split=0.2,\n subset=\"validation\",\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)", "Found 3670 files belonging to 5 classes.\nUsing 734 files for validation.\n" ], [ "class_names = train_ds.class_names\nprint(class_names)", "['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']\n" ], [ "plt.figure(figsize=(10, 10))\nfor images, labels in train_ds.take(1):\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(images[i].numpy().astype(\"uint8\"))\n plt.title(class_names[labels[i]])\n plt.axis(\"off\")", "_____no_output_____" ], [ "AUTOTUNE = tf.data.AUTOTUNE\n\ntrain_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)\nval_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)", "_____no_output_____" ], [ "normalization_layer = layers.Rescaling(1./255)", "_____no_output_____" ], [ "normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))\nimage_batch, labels_batch = next(iter(normalized_ds))\nfirst_image = image_batch[0]\n# Notice the pixel values are now in `[0,1]`.\nprint(np.min(first_image), np.max(first_image)) ", "0.0 1.0\n" ], [ "data_augmentation = keras.Sequential(\n [\n layers.RandomFlip(\"horizontal\",\n input_shape=(img_height,\n img_width,\n 3)),\n layers.RandomRotation(0.1),\n layers.RandomZoom(0.2),\n ]\n)", "_____no_output_____" ], [ "num_classes = len(class_names)\n\nmodel = Sequential([\n data_augmentation,\n layers.Rescaling(1./255, input_shape=(img_height, img_width, 3)),\n layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=[64,64,3]),\n layers.MaxPooling2D(pool_size=2,strides=2),\n layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=[64,64,3]),\n layers.MaxPooling2D(pool_size=2,strides=2),\n layers.Conv2D(32, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(pool_size=2 , strides=2),\n layers.Conv2D(64, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(pool_size=2 , strides=2),\n layers.Dropout(0.5),\n layers.Flatten(),\n layers.Dense(128, activation='relu'),\n layers.Dense(128, activation='softmax')\n])", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])", "_____no_output_____" ], [ "epochs=15\nhistory = model.fit(\n train_ds,\n validation_data=val_ds,\n epochs=epochs\n)", "Epoch 1/15\n" ], [ "acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()", "_____no_output_____" ], [ "num_classes = len(class_names)\n\nmodel = Sequential([\n data_augmentation,\n layers.Rescaling(1./255, input_shape=(img_height, img_width, 3)),\n layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=[64,64,3]),\n layers.MaxPooling2D(pool_size=2,strides=2),\n layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=[64,64,3]),\n layers.MaxPooling2D(pool_size=2,strides=2),\n layers.Conv2D(32, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(pool_size=2 , strides=2),\n layers.Conv2D(32, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(pool_size=2 , strides=2),\n layers.Conv2D(64, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(pool_size=2 , strides=2),\n layers.Conv2D(64, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(pool_size=2 , strides=2),\n layers.Dropout(0.5),\n layers.Flatten(),\n layers.Dense(128, activation='relu'),\n layers.Dense(128, activation='softmax')\n])", "_____no_output_____" ], [ "epochs=15\nhistory = model.fit(\n train_ds,\n validation_data=val_ds,\n epochs=epochs\n)", "Epoch 1/15\n" ], [ "acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()", "_____no_output_____" ] ], [ [ "## **Checking the behaviour of the model by changing different hyperparameter and changing convolution layers**\n\n### **The maximum accuracy achived was 76.57%**", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4afcf27e247d9c63680429c8257387af300ac076
17,351
ipynb
Jupyter Notebook
lab9/movies.ipynb
voyager3/ML
fdd528e913106cfae4811252bb1c8fd2cd19fe80
[ "MIT" ]
null
null
null
lab9/movies.ipynb
voyager3/ML
fdd528e913106cfae4811252bb1c8fd2cd19fe80
[ "MIT" ]
2
2020-03-24T17:57:08.000Z
2021-08-23T20:29:19.000Z
lab9/movies.ipynb
hold-n/ML
fdd528e913106cfae4811252bb1c8fd2cd19fe80
[ "MIT" ]
null
null
null
86.323383
11,084
0.823641
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.io as scio\nfrom sklearn.linear_model import Ridge\n\n%load_ext autoreload\n%autoreload 2\nimport main", "_____no_output_____" ], [ "mat = scio.loadmat('ex9_movies.mat')\n\n# TODO: mean normalization: rows, columns and total\n# TODO: only calculate the mean for present values\nr = pd.DataFrame(mat['R'])\n# y = pd.DataFrame(mat['Y'])[r == 1]\ny = pd.DataFrame(mat['Y'])", "_____no_output_____" ], [ "# TODO: automatically select n\nn = 10\nx = np.random.random((y.shape[0], n))\ntheta = np.random.random((y.shape[1], n))\n\nalpha = 0.00008\ntolerance = 2\nreg_param = 1\n\n# TODO: try running PCA first\nprogress = []\nfor x, theta, cost in main.run_descent(alpha, tolerance, theta, x, y, r, reg_param):\n print(cost)\n progress.append(cost)\n \nplt.plot(progress)", "_____no_output_____" ], [ "plt.plot(progress)\nplt.show()", "_____no_output_____" ], [ "my_rating = np.zeros(y.shape[0])\n\nmy_rating[50] = 5 # star wars\nmy_rating[56] = 5 # pulp fiction\nmy_rating[64] = 5 # shawshank redemption\nmy_rating[65] = 3 # what's eating gilbert grape\nmy_rating[69] = 5 # forrest gump\nmy_rating[71] = 4 # lion king\nmy_rating[79] = 4 # the fugitive\nmy_rating[86] = 5 # remains of the day\nmy_rating[89] = 4 # blade runner\nmy_rating[94] = 3 # home alone\nmy_rating[96] = 5 # terminator 2\nmy_rating[98] = 5 # silence of the lambs\nmy_rating[127] = 5 # godfather\nmy_rating[135] = 4 # 2001 space odyssey\nmy_rating[151] = 4 # willie wonka\nmy_rating[172] = 5 # empire strikes back\nmy_rating[174] = 4 # raiders of the lost ark\nmy_rating[178] = 5 # 12 angry men\nmy_rating[181] = 5 # return of the jedi\nmy_rating[185] = 4 # psycho\nmy_rating[195] = 5 # terminator\nmy_rating[196] = 4 # dead poets society\nmy_rating[200] = 3 # shining\nmy_rating[202] = 5 # groundhog day\nmy_rating[483] = 4 # Casablanca (1942)\nmy_rating[755] = 3 # Jumanji (1995)\nmy_rating[902] = 5 # Big Lebowski, The (1998)\nmy_rating[1127] = 5 # Truman Show, The (1998)\nmy_rating[204] = 5 # Back to the Future (1985)\nmy_rating[209] = 3 # This Is Spinal Tap (1984)\nmy_rating[214] = 2 # Pink Floyd - The Wall (1982)\nmy_rating[216] = 4 # When Harry Met Sally... (1989)\nmy_rating[250] = 4 # Fifth Element, The (1997)\nmy_rating[257] = 4 # Men in Black (1997)\nmy_rating[302] = 5 # L.A. Confidential (1997)\nmy_rating[318] = 5 # Schindler's List (1993)\nmy_rating[340] = 4 # Boogie Nights (1997)\n\n# indexes in the file start with one, compensate\nmy_rating = np.roll(my_rating, -1, axis=0)\nmy_rating = pd.Series(my_rating)\nmy_actual_rating = my_rating[my_rating > 0]\nmy_movies = x.iloc[my_actual_rating]\n\nall_movies = pd.read_csv('movie_ids.txt', header=None, quotechar='\"').iloc[:, 1]", "_____no_output_____" ], [ "# we created linear regression in the 1st lab, no need to repeat the code here\nreg = Ridge(alpha=0.1).fit(my_movies, my_actual_rating)\nprediction = pd.Series(reg.predict(x))\nprediction = prediction.sort_values(ascending=False)\nfor i, score in prediction.iloc[:20].iteritems():\n print('{}: {}'.format(all_movies.iat[i], score))", "Highlander (1986): 5.728839083441782\nM*A*S*H (1970): 5.364936477106315\nApt Pupil (1998): 5.326645001803318\nShall We Dance? (1996): 5.313734419839206\nBody Snatcher, The (1945): 5.300216618589752\nButcher Boy, The (1998): 5.245175791808727\nSpeed (1994): 5.187545725743342\nDolores Claiborne (1994): 5.175382188084284\nEvent Horizon (1997): 5.154579429543501\nC'est arrivé près de chez vous (1992): 5.153113191062481\nSafe (1995): 5.150264506660337\nCook the Thief His Wife & Her Lover, The (1989): 5.143826750702315\nCourage Under Fire (1996): 5.125414147871106\nMother (1996): 5.112838982120777\nBig Blue, The (Grand bleu, Le) (1988): 5.103076212709746\nMary Shelley's Frankenstein (1994): 5.098805014149778\nGreat Day in Harlem, A (1994): 5.086731005607059\nSchindler's List (1993): 5.084809145604135\nOld Lady Who Walked in the Sea, The (Vieille qui marchait dans la mer, La) (1991): 5.079417315194116\nNightmare on Elm Street, A (1984): 5.053831570332282\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
4afcfb5bb75a62561a58ce8dd7745af5333ab1b9
284,386
ipynb
Jupyter Notebook
Facial_Emotion_Recognition_CNN_model.ipynb
itoyuhao/Real_Time_Facial_Expression_Recognition
7caa35fac9f7d0a13a3e8e85351d3a6a9afdeaee
[ "MIT" ]
null
null
null
Facial_Emotion_Recognition_CNN_model.ipynb
itoyuhao/Real_Time_Facial_Expression_Recognition
7caa35fac9f7d0a13a3e8e85351d3a6a9afdeaee
[ "MIT" ]
null
null
null
Facial_Emotion_Recognition_CNN_model.ipynb
itoyuhao/Real_Time_Facial_Expression_Recognition
7caa35fac9f7d0a13a3e8e85351d3a6a9afdeaee
[ "MIT" ]
null
null
null
284,386
284,386
0.84028
[ [ [ "# Facial Emotion Recognition (Model Training)\n\nThis dataset consists of 48*48 pixel grayscale face images.\nThe images are centered and occupy an equal amount of space.\nThe dataset consists of 7 categories:\n\n0. angry\n1. disgust (removed)\n2. fear\n3. happy\n4. sad\n5. surprise\n6. neutral\n\nTraining set: 28,709 samples\n\nPublic test set: 3,589 examples", "_____no_output_____" ] ], [ [ "# Import Libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport cv2\n\nfrom PIL import Image\nimport tensorflow as tf\nfrom IPython.display import Image \n\nfrom sklearn.model_selection import train_test_split\nfrom skimage.transform import resize\nfrom sklearn.metrics import accuracy_score\n\n\nfrom keras.applications.resnet import ResNet50\nfrom keras.applications.nasnet import NASNetLarge\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Activation\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping,ModelCheckpoint\nfrom tensorflow.keras.utils import plot_model\nfrom keras import regularizers\nimport keras.backend as K\n\nimport warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "## Explore dataset", "_____no_output_____" ] ], [ [ "# We need to import the file on google drive (authorization)\nfrom google.colab import drive\ndrive.mount('/content/drive') ", "Mounted at /content/drive\n" ], [ "# Count the images in the train file\ntrain = {}\ncount = 0\nfor folder in os.listdir('/content/drive/MyDrive/Colab Notebooks/FER_2013_images/train'):\n temp = []\n for files in os.listdir(f\"/content/drive/MyDrive/Colab Notebooks/FER_2013_images/train/{folder}\"):\n temp.append(files)\n count += len(temp)\n train[folder] = temp\n print(f\"{folder} has {len(temp)} images\")\nprint(f\"Total images in all folders are {count}\")", "sad has 5303 images\nfear has 4547 images\nhappy has 5555 images\nangry has 4443 images\nsurprise has 3580 images\nneutral has 5304 images\nTotal images in all folders are 28732\n" ], [ "# Count the images in the test file\ntest = {}\ncount = 0\nfor folder in os.listdir('/content/drive/MyDrive/Colab Notebooks/FER_2013_images/test'):\n temp = []\n for files in os.listdir(f\"/content/drive/MyDrive/Colab Notebooks/FER_2013_images/test/{folder}\"):\n temp.append(files)\n count += len(temp)\n test[folder] = temp\n print(f\"{folder} has {len(temp)} images\")\nprint(f\"Total images in all folders are {count}\")", "happy has 1774 images\nsad has 1247 images\nneutral has 1233 images\nsurprise has 831 images\nangry has 966 images\nfear has 1024 images\nTotal images in all folders are 7075\n" ], [ "# training dataframe with folder name as index\ntrain_df = pd.DataFrame.from_dict(train.values())\ntrain_df.index = train.keys()\ntrain_df", "_____no_output_____" ], [ "# list of all the emotions to classify in the output\nemotions = [k for k in train.keys()]\nemotions", "_____no_output_____" ], [ "base_dir = '/content/drive/MyDrive/Colab Notebooks/FER_2013_images/'", "_____no_output_____" ], [ "# lets see one image from each category from training data\nplt.figure(figsize = (20, 8))\nfor i in range(6):\n ax = plt.subplot(2,4, i+1)\n img = cv2.imread(f\"{base_dir}train/{emotions[i]}/{train_df.loc[emotions[i], i+7]}\")\n ax.imshow(img, cmap = 'gray')\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_title(emotions[i])", "_____no_output_____" ], [ "# To know the shape of image\none_img = cv2.imread('/content/drive/MyDrive/Colab Notebooks/FER_2013_images/train/surprise/Training_10013223.jpg')\none_img.shape", "_____no_output_____" ] ], [ [ "## Data Preprocessing\n\nUsing Keras \"ImageDataGenerator\" to augment images in real-time while our model is still training.\n\nThe ImageDataGenerator class has 3 methods `flow()`, `flow_from_directory()`, and `flow_from_dataframe()` to read the images from a big numpy array and folders containing images.\n\nHere, we use flow_from_directory() because it expects at least one directory under the given directory path.\n\n\n", "_____no_output_____" ] ], [ [ "# Data preprocessing(augmentation)\ntrain_dir = f\"{base_dir}/train\"\ntest_dir = f\"{base_dir}/test\"\n\ntrain_datagen = ImageDataGenerator(horizontal_flip = True,\n rotation_range= 10,\n zoom_range = 0.1, \n width_shift_range = 0.1,\n height_shift_range = 0.1,\n rescale = 1./255,\n fill_mode = 'nearest',\n validation_split = 0.2)\n\nvalid_datagen = ImageDataGenerator(rescale=1./255,\n validation_split=0.2)\n\ntest_datagen = ImageDataGenerator(rescale= 1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size=(48,48),\n batch_size=64,\n class_mode='categorical',\n color_mode='grayscale',\n subset = \"training\")\n\nvalid_generator = valid_datagen.flow_from_directory(train_dir,\n target_size=(48,48),\n class_mode='categorical',\n subset='validation',\n color_mode='grayscale',\n batch_size=64)\n\ntest_generator = test_datagen.flow_from_directory(\n test_dir,\n target_size=(48,48),\n batch_size=64,\n color_mode='grayscale',\n class_mode='categorical')", "Found 22988 images belonging to 6 classes.\nFound 5744 images belonging to 6 classes.\nFound 7075 images belonging to 6 classes.\n" ] ], [ [ "### CNN Model Building", "_____no_output_____" ] ], [ [ "model = None\n\n# Build model on the top of base model (transfer learning)\nmodel = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(3, 3), padding='same', activation='relu', input_shape=(48, 48, 1)))\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(2, 2))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same', kernel_regularizer=regularizers.l2(0.01)))\nmodel.add(Conv2D(256, kernel_size=(3, 3), activation='relu', kernel_regularizer=regularizers.l2(0.01)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dropout(0.5))\n \nmodel.add(Dense(6, activation='softmax'))\n\n\n# model Summary\nprint(f'Number of layers:', len(model.layers))\nmodel.summary()", "Number of layers: 14\nModel: \"sequential\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d (Conv2D) (None, 48, 48, 32) 320 \n_________________________________________________________________\nconv2d_1 (Conv2D) (None, 48, 48, 64) 18496 \n_________________________________________________________________\nbatch_normalization (BatchNo (None, 48, 48, 64) 256 \n_________________________________________________________________\nmax_pooling2d (MaxPooling2D) (None, 24, 24, 64) 0 \n_________________________________________________________________\ndropout (Dropout) (None, 24, 24, 64) 0 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 24, 24, 128) 73856 \n_________________________________________________________________\nconv2d_3 (Conv2D) (None, 22, 22, 256) 295168 \n_________________________________________________________________\nbatch_normalization_1 (Batch (None, 22, 22, 256) 1024 \n_________________________________________________________________\nmax_pooling2d_1 (MaxPooling2 (None, 11, 11, 256) 0 \n_________________________________________________________________\ndropout_1 (Dropout) (None, 11, 11, 256) 0 \n_________________________________________________________________\nflatten (Flatten) (None, 30976) 0 \n_________________________________________________________________\ndense (Dense) (None, 1024) 31720448 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 1024) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 6) 6150 \n=================================================================\nTotal params: 32,115,718\nTrainable params: 32,115,078\nNon-trainable params: 640\n_________________________________________________________________\n" ], [ "# function to calculate f1_score\ndef f1_score(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n recall = true_positives / (possible_positives + K.epsilon())\n f1_val = 2*(precision*recall)/(precision+recall+K.epsilon())\n return f1_val", "_____no_output_____" ], [ "# evaluation metrics\nfrom keras.metrics import AUC, BinaryAccuracy, Precision, Recall\nmetric = [BinaryAccuracy(name = 'accuracy'), \n Precision(name = 'precision'), \n Recall(name = 'recall'), \n AUC(name = 'AUC'),]", "_____no_output_____" ], [ "# callbacks\ncheckpoint = ModelCheckpoint('model.h5')\n\nearlystop = EarlyStopping(patience=20, verbose=1)\n# restore_best_weights=True)\n \nreduce_lr = ReduceLROnPlateau(monitor='val_loss', \n factor=0.5, \n patience=20, \n verbose=1,\n min_lr=1e-10)\n# min_delta=0.0001)\ncallbacks = [checkpoint,earlystop,reduce_lr]", "_____no_output_____" ], [ "# compile model (optimization)\nmodel.compile(optimizer= 'Adam', loss='categorical_crossentropy', metrics=metric)", "_____no_output_____" ] ], [ [ "The difference between `Keras.fit` and `Keras.fit_generator` functions used to train a deep learning neural network:\n\n`model.fit` is used when the entire training dataset can fit into the memory \n\n* `model.fit` is used when the entire training dataset can fit into the memory and no data augmentation is applied.\n* `model.fit_generator` is used when either we have a huge dataset to fit into our memory or when data augmentation needs to be applied.\n\n\n", "_____no_output_____" ] ], [ [ "# model fitting\nhistory = model.fit_generator(train_generator, validation_data=valid_generator,epochs=100,verbose = 1,callbacks=callbacks)", "Epoch 1/100\n360/360 [==============================] - 13722s 38s/step - loss: 12.0252 - accuracy: 0.7888 - precision: 0.1973 - recall: 0.0861 - AUC: 0.5304 - val_loss: 37.1911 - val_accuracy: 0.7176 - val_precision: 0.1526 - val_recall: 0.1525 - val_AUC: 0.4907\nEpoch 2/100\n360/360 [==============================] - 42s 117ms/step - loss: 2.3726 - accuracy: 0.8331 - precision: 0.2533 - recall: 7.6426e-04 - AUC: 0.5580 - val_loss: 4.0007 - val_accuracy: 0.7788 - val_precision: 0.2055 - val_recall: 0.1140 - val_AUC: 0.5325\nEpoch 3/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.9258 - accuracy: 0.8332 - precision: 0.3981 - recall: 0.0016 - AUC: 0.5583 - val_loss: 2.2842 - val_accuracy: 0.8161 - val_precision: 0.2510 - val_recall: 0.0522 - val_AUC: 0.5530\nEpoch 4/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.8206 - accuracy: 0.8332 - precision: 0.3598 - recall: 0.0017 - AUC: 0.5649 - val_loss: 1.8265 - val_accuracy: 0.8327 - val_precision: 0.2250 - val_recall: 0.0016 - val_AUC: 0.5579\nEpoch 5/100\n360/360 [==============================] - 41s 115ms/step - loss: 1.8023 - accuracy: 0.8333 - precision: 0.4299 - recall: 0.0021 - AUC: 0.5613 - val_loss: 1.7666 - val_accuracy: 0.8333 - val_precision: 0.0000e+00 - val_recall: 0.0000e+00 - val_AUC: 0.5907\nEpoch 6/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.7856 - accuracy: 0.8332 - precision: 0.4686 - recall: 0.0078 - AUC: 0.5821 - val_loss: 1.7698 - val_accuracy: 0.8328 - val_precision: 0.2424 - val_recall: 0.0014 - val_AUC: 0.6023\nEpoch 7/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.7697 - accuracy: 0.8337 - precision: 0.5433 - recall: 0.0152 - AUC: 0.5933 - val_loss: 1.7608 - val_accuracy: 0.8285 - val_precision: 0.4229 - val_recall: 0.0792 - val_AUC: 0.6523\nEpoch 8/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.7554 - accuracy: 0.8352 - precision: 0.6072 - recall: 0.0310 - AUC: 0.6120 - val_loss: 2.2346 - val_accuracy: 0.8061 - val_precision: 0.2711 - val_recall: 0.0966 - val_AUC: 0.5835\nEpoch 9/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.7171 - accuracy: 0.8363 - precision: 0.6155 - recall: 0.0466 - AUC: 0.6387 - val_loss: 1.7165 - val_accuracy: 0.8357 - val_precision: 0.5358 - val_recall: 0.1069 - val_AUC: 0.6580\nEpoch 10/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.6947 - accuracy: 0.8381 - precision: 0.6507 - recall: 0.0619 - AUC: 0.6587 - val_loss: 1.5839 - val_accuracy: 0.8451 - val_precision: 0.6930 - val_recall: 0.1266 - val_AUC: 0.7298\nEpoch 11/100\n360/360 [==============================] - 41s 115ms/step - loss: 1.6789 - accuracy: 0.8394 - precision: 0.6726 - recall: 0.0712 - AUC: 0.6750 - val_loss: 1.5347 - val_accuracy: 0.8497 - val_precision: 0.7417 - val_recall: 0.1509 - val_AUC: 0.7431\nEpoch 12/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.6767 - accuracy: 0.8400 - precision: 0.6790 - recall: 0.0756 - AUC: 0.6732 - val_loss: 1.5398 - val_accuracy: 0.8484 - val_precision: 0.7059 - val_recall: 0.1546 - val_AUC: 0.7422\nEpoch 13/100\n360/360 [==============================] - 42s 115ms/step - loss: 1.6354 - accuracy: 0.8422 - precision: 0.6998 - recall: 0.0931 - AUC: 0.6963 - val_loss: 1.5004 - val_accuracy: 0.8518 - val_precision: 0.7437 - val_recall: 0.1687 - val_AUC: 0.7615\nEpoch 14/100\n360/360 [==============================] - 41s 115ms/step - loss: 1.6327 - accuracy: 0.8423 - precision: 0.6993 - recall: 0.0948 - AUC: 0.7011 - val_loss: 1.4860 - val_accuracy: 0.8527 - val_precision: 0.7506 - val_recall: 0.1744 - val_AUC: 0.7670\nEpoch 15/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.6139 - accuracy: 0.8434 - precision: 0.7064 - recall: 0.1034 - AUC: 0.7103 - val_loss: 1.6119 - val_accuracy: 0.8417 - val_precision: 0.7264 - val_recall: 0.0804 - val_AUC: 0.7115\nEpoch 16/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.6086 - accuracy: 0.8438 - precision: 0.7119 - recall: 0.1051 - AUC: 0.7159 - val_loss: 1.4302 - val_accuracy: 0.8556 - val_precision: 0.7473 - val_recall: 0.2023 - val_AUC: 0.7911\nEpoch 17/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.5878 - accuracy: 0.8453 - precision: 0.7183 - recall: 0.1175 - AUC: 0.7243 - val_loss: 1.4943 - val_accuracy: 0.8502 - val_precision: 0.6508 - val_recall: 0.2183 - val_AUC: 0.7740\nEpoch 18/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.5656 - accuracy: 0.8463 - precision: 0.7107 - recall: 0.1321 - AUC: 0.7354 - val_loss: 1.4271 - val_accuracy: 0.8548 - val_precision: 0.7957 - val_recall: 0.1736 - val_AUC: 0.7969\nEpoch 19/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.5663 - accuracy: 0.8456 - precision: 0.7058 - recall: 0.1264 - AUC: 0.7366 - val_loss: 1.4244 - val_accuracy: 0.8545 - val_precision: 0.8427 - val_recall: 0.1558 - val_AUC: 0.7902\nEpoch 20/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.5439 - accuracy: 0.8470 - precision: 0.7137 - recall: 0.1369 - AUC: 0.7471 - val_loss: 1.4371 - val_accuracy: 0.8531 - val_precision: 0.7156 - val_recall: 0.1967 - val_AUC: 0.7861\nEpoch 21/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.5329 - accuracy: 0.8471 - precision: 0.7072 - recall: 0.1411 - AUC: 0.7511 - val_loss: 1.5483 - val_accuracy: 0.8478 - val_precision: 0.6886 - val_recall: 0.1583 - val_AUC: 0.7459\nEpoch 22/100\n360/360 [==============================] - 42s 115ms/step - loss: 1.5062 - accuracy: 0.8501 - precision: 0.7197 - recall: 0.1647 - AUC: 0.7644 - val_loss: 1.3566 - val_accuracy: 0.8590 - val_precision: 0.7521 - val_recall: 0.2293 - val_AUC: 0.8140\nEpoch 23/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.4938 - accuracy: 0.8495 - precision: 0.7062 - recall: 0.1659 - AUC: 0.7665 - val_loss: 1.4407 - val_accuracy: 0.8529 - val_precision: 0.7014 - val_recall: 0.2040 - val_AUC: 0.7853\nEpoch 24/100\n360/360 [==============================] - 41s 115ms/step - loss: 1.4933 - accuracy: 0.8492 - precision: 0.6937 - recall: 0.1705 - AUC: 0.7686 - val_loss: 1.3674 - val_accuracy: 0.8598 - val_precision: 0.7690 - val_recall: 0.2267 - val_AUC: 0.8104\nEpoch 25/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.4771 - accuracy: 0.8521 - precision: 0.7314 - recall: 0.1784 - AUC: 0.7725 - val_loss: 1.3306 - val_accuracy: 0.8619 - val_precision: 0.7610 - val_recall: 0.2500 - val_AUC: 0.8217\nEpoch 26/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.4685 - accuracy: 0.8518 - precision: 0.7115 - recall: 0.1868 - AUC: 0.7764 - val_loss: 1.3182 - val_accuracy: 0.8605 - val_precision: 0.6960 - val_recall: 0.2893 - val_AUC: 0.8285\nEpoch 27/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.4612 - accuracy: 0.8512 - precision: 0.7056 - recall: 0.1846 - AUC: 0.7808 - val_loss: 1.3013 - val_accuracy: 0.8608 - val_precision: 0.7473 - val_recall: 0.2491 - val_AUC: 0.8331\nEpoch 28/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.4376 - accuracy: 0.8526 - precision: 0.7071 - recall: 0.1971 - AUC: 0.7889 - val_loss: 1.3435 - val_accuracy: 0.8611 - val_precision: 0.7104 - val_recall: 0.2810 - val_AUC: 0.8193\nEpoch 29/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.4419 - accuracy: 0.8524 - precision: 0.7004 - recall: 0.1997 - AUC: 0.7890 - val_loss: 1.3626 - val_accuracy: 0.8558 - val_precision: 0.7243 - val_recall: 0.2181 - val_AUC: 0.8131\nEpoch 30/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.4407 - accuracy: 0.8523 - precision: 0.6986 - recall: 0.2003 - AUC: 0.7877 - val_loss: 1.2902 - val_accuracy: 0.8624 - val_precision: 0.7824 - val_recall: 0.2416 - val_AUC: 0.8357\nEpoch 31/100\n360/360 [==============================] - 43s 120ms/step - loss: 1.3983 - accuracy: 0.8562 - precision: 0.7176 - recall: 0.2259 - AUC: 0.8025 - val_loss: 1.3107 - val_accuracy: 0.8616 - val_precision: 0.7672 - val_recall: 0.2432 - val_AUC: 0.8279\nEpoch 32/100\n360/360 [==============================] - 43s 120ms/step - loss: 1.4082 - accuracy: 0.8552 - precision: 0.7085 - recall: 0.2232 - AUC: 0.8017 - val_loss: 1.3154 - val_accuracy: 0.8615 - val_precision: 0.7348 - val_recall: 0.2643 - val_AUC: 0.8295\nEpoch 33/100\n360/360 [==============================] - 43s 120ms/step - loss: 1.3964 - accuracy: 0.8561 - precision: 0.7153 - recall: 0.2271 - AUC: 0.8036 - val_loss: 1.3453 - val_accuracy: 0.8570 - val_precision: 0.8119 - val_recall: 0.1849 - val_AUC: 0.8227\nEpoch 34/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.3889 - accuracy: 0.8564 - precision: 0.7178 - recall: 0.2285 - AUC: 0.8068 - val_loss: 1.3284 - val_accuracy: 0.8601 - val_precision: 0.7460 - val_recall: 0.2439 - val_AUC: 0.8237\nEpoch 35/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.3847 - accuracy: 0.8564 - precision: 0.7180 - recall: 0.2277 - AUC: 0.8086 - val_loss: 1.3036 - val_accuracy: 0.8628 - val_precision: 0.6920 - val_recall: 0.3181 - val_AUC: 0.8337\nEpoch 36/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.3921 - accuracy: 0.8565 - precision: 0.7108 - recall: 0.2346 - AUC: 0.8076 - val_loss: 1.3163 - val_accuracy: 0.8619 - val_precision: 0.7644 - val_recall: 0.2474 - val_AUC: 0.8294\nEpoch 37/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.3583 - accuracy: 0.8577 - precision: 0.7140 - recall: 0.2441 - AUC: 0.8156 - val_loss: 1.2634 - val_accuracy: 0.8639 - val_precision: 0.7451 - val_recall: 0.2784 - val_AUC: 0.8453\nEpoch 38/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.3464 - accuracy: 0.8593 - precision: 0.7205 - recall: 0.2541 - AUC: 0.8205 - val_loss: 1.2653 - val_accuracy: 0.8640 - val_precision: 0.7374 - val_recall: 0.2855 - val_AUC: 0.8432\nEpoch 39/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.3737 - accuracy: 0.8576 - precision: 0.7146 - recall: 0.2428 - AUC: 0.8124 - val_loss: 1.2707 - val_accuracy: 0.8639 - val_precision: 0.7751 - val_recall: 0.2580 - val_AUC: 0.8421\nEpoch 40/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.3499 - accuracy: 0.8592 - precision: 0.7156 - recall: 0.2575 - AUC: 0.8205 - val_loss: 1.2661 - val_accuracy: 0.8646 - val_precision: 0.7239 - val_recall: 0.3031 - val_AUC: 0.8438\nEpoch 41/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.3342 - accuracy: 0.8602 - precision: 0.7212 - recall: 0.2626 - AUC: 0.8247 - val_loss: 1.2664 - val_accuracy: 0.8635 - val_precision: 0.7545 - val_recall: 0.2686 - val_AUC: 0.8432\nEpoch 42/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.3249 - accuracy: 0.8601 - precision: 0.7134 - recall: 0.2684 - AUC: 0.8275 - val_loss: 1.2519 - val_accuracy: 0.8653 - val_precision: 0.7546 - val_recall: 0.2838 - val_AUC: 0.8485\nEpoch 43/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.3243 - accuracy: 0.8606 - precision: 0.7167 - recall: 0.2708 - AUC: 0.8272 - val_loss: 1.2224 - val_accuracy: 0.8680 - val_precision: 0.7527 - val_recall: 0.3101 - val_AUC: 0.8568\nEpoch 44/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.3034 - accuracy: 0.8629 - precision: 0.7302 - recall: 0.2818 - AUC: 0.8336 - val_loss: 1.2320 - val_accuracy: 0.8690 - val_precision: 0.7415 - val_recall: 0.3282 - val_AUC: 0.8543\nEpoch 45/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.3118 - accuracy: 0.8621 - precision: 0.7233 - recall: 0.2798 - AUC: 0.8321 - val_loss: 1.2329 - val_accuracy: 0.8673 - val_precision: 0.7193 - val_recall: 0.3341 - val_AUC: 0.8529\nEpoch 46/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.3013 - accuracy: 0.8629 - precision: 0.7239 - recall: 0.2873 - AUC: 0.8341 - val_loss: 1.2287 - val_accuracy: 0.8674 - val_precision: 0.7359 - val_recall: 0.3188 - val_AUC: 0.8539\nEpoch 47/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2932 - accuracy: 0.8634 - precision: 0.7221 - recall: 0.2931 - AUC: 0.8362 - val_loss: 1.2200 - val_accuracy: 0.8681 - val_precision: 0.7764 - val_recall: 0.2927 - val_AUC: 0.8566\nEpoch 48/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.2925 - accuracy: 0.8645 - precision: 0.7351 - recall: 0.2927 - AUC: 0.8376 - val_loss: 1.2449 - val_accuracy: 0.8671 - val_precision: 0.7108 - val_recall: 0.3419 - val_AUC: 0.8497\nEpoch 49/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2830 - accuracy: 0.8637 - precision: 0.7205 - recall: 0.2973 - AUC: 0.8396 - val_loss: 1.2887 - val_accuracy: 0.8607 - val_precision: 0.7865 - val_recall: 0.2251 - val_AUC: 0.8408\nEpoch 50/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2834 - accuracy: 0.8639 - precision: 0.7275 - recall: 0.2936 - AUC: 0.8402 - val_loss: 1.2141 - val_accuracy: 0.8682 - val_precision: 0.7218 - val_recall: 0.3405 - val_AUC: 0.8584\nEpoch 51/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.2722 - accuracy: 0.8656 - precision: 0.7256 - recall: 0.3118 - AUC: 0.8428 - val_loss: 1.2527 - val_accuracy: 0.8666 - val_precision: 0.7158 - val_recall: 0.3315 - val_AUC: 0.8503\nEpoch 52/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.2601 - accuracy: 0.8663 - precision: 0.7345 - recall: 0.3095 - AUC: 0.8466 - val_loss: 1.2273 - val_accuracy: 0.8670 - val_precision: 0.7425 - val_recall: 0.3097 - val_AUC: 0.8557\nEpoch 53/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2766 - accuracy: 0.8653 - precision: 0.7296 - recall: 0.3048 - AUC: 0.8421 - val_loss: 1.2380 - val_accuracy: 0.8672 - val_precision: 0.7381 - val_recall: 0.3149 - val_AUC: 0.8528\nEpoch 54/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2753 - accuracy: 0.8645 - precision: 0.7211 - recall: 0.3046 - AUC: 0.8424 - val_loss: 1.2106 - val_accuracy: 0.8690 - val_precision: 0.7293 - val_recall: 0.3400 - val_AUC: 0.8599\nEpoch 55/100\n360/360 [==============================] - 43s 120ms/step - loss: 1.2660 - accuracy: 0.8650 - precision: 0.7254 - recall: 0.3057 - AUC: 0.8444 - val_loss: 1.2001 - val_accuracy: 0.8678 - val_precision: 0.7349 - val_recall: 0.3238 - val_AUC: 0.8628\nEpoch 56/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.2719 - accuracy: 0.8669 - precision: 0.7401 - recall: 0.3110 - AUC: 0.8437 - val_loss: 1.2124 - val_accuracy: 0.8688 - val_precision: 0.7600 - val_recall: 0.3115 - val_AUC: 0.8586\nEpoch 57/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2534 - accuracy: 0.8665 - precision: 0.7299 - recall: 0.3164 - AUC: 0.8483 - val_loss: 1.3562 - val_accuracy: 0.8596 - val_precision: 0.6497 - val_recall: 0.3419 - val_AUC: 0.8304\nEpoch 58/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.2545 - accuracy: 0.8662 - precision: 0.7294 - recall: 0.3140 - AUC: 0.8479 - val_loss: 1.2087 - val_accuracy: 0.8683 - val_precision: 0.7299 - val_recall: 0.3327 - val_AUC: 0.8600\nEpoch 59/100\n360/360 [==============================] - 43s 120ms/step - loss: 1.2504 - accuracy: 0.8679 - precision: 0.7343 - recall: 0.3247 - AUC: 0.8492 - val_loss: 1.2742 - val_accuracy: 0.8635 - val_precision: 0.6625 - val_recall: 0.3694 - val_AUC: 0.8479\nEpoch 60/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.2611 - accuracy: 0.8675 - precision: 0.7351 - recall: 0.3210 - AUC: 0.8471 - val_loss: 1.2541 - val_accuracy: 0.8664 - val_precision: 0.6986 - val_recall: 0.3487 - val_AUC: 0.8505\nEpoch 61/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.2393 - accuracy: 0.8682 - precision: 0.7326 - recall: 0.3298 - AUC: 0.8531 - val_loss: 1.2023 - val_accuracy: 0.8693 - val_precision: 0.7698 - val_recall: 0.3080 - val_AUC: 0.8634\nEpoch 62/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2385 - accuracy: 0.8681 - precision: 0.7329 - recall: 0.3284 - AUC: 0.8530 - val_loss: 1.1902 - val_accuracy: 0.8700 - val_precision: 0.7488 - val_recall: 0.3306 - val_AUC: 0.8660\nEpoch 63/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2307 - accuracy: 0.8699 - precision: 0.7382 - recall: 0.3398 - AUC: 0.8555 - val_loss: 1.2116 - val_accuracy: 0.8706 - val_precision: 0.7285 - val_recall: 0.3560 - val_AUC: 0.8600\nEpoch 64/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.2287 - accuracy: 0.8688 - precision: 0.7312 - recall: 0.3367 - AUC: 0.8549 - val_loss: 1.2554 - val_accuracy: 0.8679 - val_precision: 0.7466 - val_recall: 0.3139 - val_AUC: 0.8491\nEpoch 65/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2332 - accuracy: 0.8691 - precision: 0.7360 - recall: 0.3345 - AUC: 0.8539 - val_loss: 1.1709 - val_accuracy: 0.8721 - val_precision: 0.7694 - val_recall: 0.3322 - val_AUC: 0.8704\nEpoch 66/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.2373 - accuracy: 0.8685 - precision: 0.7329 - recall: 0.3325 - AUC: 0.8538 - val_loss: 1.2011 - val_accuracy: 0.8682 - val_precision: 0.7531 - val_recall: 0.3111 - val_AUC: 0.8626\nEpoch 67/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2220 - accuracy: 0.8702 - precision: 0.7423 - recall: 0.3387 - AUC: 0.8571 - val_loss: 1.2021 - val_accuracy: 0.8690 - val_precision: 0.7473 - val_recall: 0.3233 - val_AUC: 0.8626\nEpoch 68/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.2307 - accuracy: 0.8691 - precision: 0.7349 - recall: 0.3361 - AUC: 0.8549 - val_loss: 1.2199 - val_accuracy: 0.8688 - val_precision: 0.7045 - val_recall: 0.3670 - val_AUC: 0.8588\nEpoch 69/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2227 - accuracy: 0.8702 - precision: 0.7421 - recall: 0.3389 - AUC: 0.8566 - val_loss: 1.2271 - val_accuracy: 0.8675 - val_precision: 0.7605 - val_recall: 0.2996 - val_AUC: 0.8566\nEpoch 70/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.2107 - accuracy: 0.8706 - precision: 0.7409 - recall: 0.3439 - AUC: 0.8602 - val_loss: 1.1838 - val_accuracy: 0.8718 - val_precision: 0.7315 - val_recall: 0.3647 - val_AUC: 0.8666\nEpoch 71/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.2117 - accuracy: 0.8704 - precision: 0.7427 - recall: 0.3406 - AUC: 0.8591 - val_loss: 1.2337 - val_accuracy: 0.8689 - val_precision: 0.6899 - val_recall: 0.3877 - val_AUC: 0.8574\nEpoch 72/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.2227 - accuracy: 0.8694 - precision: 0.7280 - recall: 0.3454 - AUC: 0.8576 - val_loss: 1.2133 - val_accuracy: 0.8700 - val_precision: 0.7397 - val_recall: 0.3393 - val_AUC: 0.8588\nEpoch 73/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2185 - accuracy: 0.8702 - precision: 0.7373 - recall: 0.3432 - AUC: 0.8575 - val_loss: 1.1793 - val_accuracy: 0.8711 - val_precision: 0.7430 - val_recall: 0.3463 - val_AUC: 0.8680\nEpoch 74/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.2115 - accuracy: 0.8717 - precision: 0.7391 - recall: 0.3562 - AUC: 0.8604 - val_loss: 1.2219 - val_accuracy: 0.8686 - val_precision: 0.7563 - val_recall: 0.3118 - val_AUC: 0.8594\nEpoch 75/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.2039 - accuracy: 0.8718 - precision: 0.7458 - recall: 0.3502 - AUC: 0.8618 - val_loss: 1.2008 - val_accuracy: 0.8697 - val_precision: 0.7178 - val_recall: 0.3592 - val_AUC: 0.8636\nEpoch 76/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2149 - accuracy: 0.8685 - precision: 0.7265 - recall: 0.3384 - AUC: 0.8594 - val_loss: 1.1978 - val_accuracy: 0.8714 - val_precision: 0.7395 - val_recall: 0.3529 - val_AUC: 0.8645\nEpoch 77/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.1992 - accuracy: 0.8723 - precision: 0.7438 - recall: 0.3566 - AUC: 0.8632 - val_loss: 1.2412 - val_accuracy: 0.8667 - val_precision: 0.7247 - val_recall: 0.3231 - val_AUC: 0.8523\nEpoch 78/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.2087 - accuracy: 0.8718 - precision: 0.7387 - recall: 0.3568 - AUC: 0.8621 - val_loss: 1.1752 - val_accuracy: 0.8723 - val_precision: 0.7654 - val_recall: 0.3369 - val_AUC: 0.8698\nEpoch 79/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.1978 - accuracy: 0.8716 - precision: 0.7351 - recall: 0.3588 - AUC: 0.8638 - val_loss: 1.1777 - val_accuracy: 0.8726 - val_precision: 0.7400 - val_recall: 0.3632 - val_AUC: 0.8693\nEpoch 80/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1937 - accuracy: 0.8721 - precision: 0.7416 - recall: 0.3572 - AUC: 0.8650 - val_loss: 1.2243 - val_accuracy: 0.8681 - val_precision: 0.7387 - val_recall: 0.3229 - val_AUC: 0.8573\nEpoch 81/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.1942 - accuracy: 0.8726 - precision: 0.7424 - recall: 0.3606 - AUC: 0.8655 - val_loss: 1.1651 - val_accuracy: 0.8738 - val_precision: 0.7867 - val_recall: 0.3332 - val_AUC: 0.8722\nEpoch 82/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.1921 - accuracy: 0.8729 - precision: 0.7396 - recall: 0.3662 - AUC: 0.8649 - val_loss: 1.1604 - val_accuracy: 0.8752 - val_precision: 0.7567 - val_recall: 0.3703 - val_AUC: 0.8735\nEpoch 83/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.1908 - accuracy: 0.8719 - precision: 0.7406 - recall: 0.3564 - AUC: 0.8656 - val_loss: 1.1869 - val_accuracy: 0.8711 - val_precision: 0.7491 - val_recall: 0.3411 - val_AUC: 0.8655\nEpoch 84/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1711 - accuracy: 0.8743 - precision: 0.7431 - recall: 0.3759 - AUC: 0.8702 - val_loss: 1.2355 - val_accuracy: 0.8688 - val_precision: 0.6735 - val_recall: 0.4130 - val_AUC: 0.8612\nEpoch 85/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.1812 - accuracy: 0.8729 - precision: 0.7386 - recall: 0.3678 - AUC: 0.8690 - val_loss: 1.2936 - val_accuracy: 0.8632 - val_precision: 0.7005 - val_recall: 0.3135 - val_AUC: 0.8403\nEpoch 86/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1842 - accuracy: 0.8729 - precision: 0.7391 - recall: 0.3665 - AUC: 0.8670 - val_loss: 1.1835 - val_accuracy: 0.8735 - val_precision: 0.7390 - val_recall: 0.3727 - val_AUC: 0.8684\nEpoch 87/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1777 - accuracy: 0.8759 - precision: 0.7560 - recall: 0.3773 - AUC: 0.8688 - val_loss: 1.1639 - val_accuracy: 0.8743 - val_precision: 0.7369 - val_recall: 0.3823 - val_AUC: 0.8732\nEpoch 88/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1826 - accuracy: 0.8732 - precision: 0.7422 - recall: 0.3667 - AUC: 0.8675 - val_loss: 1.1796 - val_accuracy: 0.8727 - val_precision: 0.7182 - val_recall: 0.3888 - val_AUC: 0.8690\nEpoch 89/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.1781 - accuracy: 0.8736 - precision: 0.7462 - recall: 0.3661 - AUC: 0.8685 - val_loss: 1.2075 - val_accuracy: 0.8713 - val_precision: 0.7207 - val_recall: 0.3724 - val_AUC: 0.8630\nEpoch 90/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1816 - accuracy: 0.8750 - precision: 0.7479 - recall: 0.3775 - AUC: 0.8685 - val_loss: 1.2011 - val_accuracy: 0.8709 - val_precision: 0.7096 - val_recall: 0.3816 - val_AUC: 0.8623\nEpoch 91/100\n360/360 [==============================] - 43s 118ms/step - loss: 1.1788 - accuracy: 0.8739 - precision: 0.7449 - recall: 0.3705 - AUC: 0.8679 - val_loss: 1.1913 - val_accuracy: 0.8700 - val_precision: 0.7176 - val_recall: 0.3628 - val_AUC: 0.8652\nEpoch 92/100\n360/360 [==============================] - 42s 118ms/step - loss: 1.1741 - accuracy: 0.8739 - precision: 0.7454 - recall: 0.3695 - AUC: 0.8697 - val_loss: 1.1562 - val_accuracy: 0.8756 - val_precision: 0.7686 - val_recall: 0.3626 - val_AUC: 0.8745\nEpoch 93/100\n360/360 [==============================] - 43s 119ms/step - loss: 1.1814 - accuracy: 0.8721 - precision: 0.7350 - recall: 0.3639 - AUC: 0.8681 - val_loss: 1.2600 - val_accuracy: 0.8703 - val_precision: 0.7015 - val_recall: 0.3863 - val_AUC: 0.8539\nEpoch 94/100\n360/360 [==============================] - 42s 116ms/step - loss: 1.1513 - accuracy: 0.8763 - precision: 0.7493 - recall: 0.3875 - AUC: 0.8757 - val_loss: 1.1841 - val_accuracy: 0.8720 - val_precision: 0.7867 - val_recall: 0.3184 - val_AUC: 0.8688\nEpoch 95/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1642 - accuracy: 0.8753 - precision: 0.7476 - recall: 0.3804 - AUC: 0.8720 - val_loss: 1.2551 - val_accuracy: 0.8655 - val_precision: 0.7345 - val_recall: 0.3024 - val_AUC: 0.8504\nEpoch 96/100\n360/360 [==============================] - 42s 117ms/step - loss: 1.1696 - accuracy: 0.8743 - precision: 0.7447 - recall: 0.3741 - AUC: 0.8707 - val_loss: 1.2473 - val_accuracy: 0.8677 - val_precision: 0.6965 - val_recall: 0.3659 - val_AUC: 0.8531\nEpoch 97/100\n360/360 [==============================] - 41s 113ms/step - loss: 1.1576 - accuracy: 0.8776 - precision: 0.7641 - recall: 0.3842 - AUC: 0.8737 - val_loss: 1.1679 - val_accuracy: 0.8733 - val_precision: 0.7184 - val_recall: 0.3943 - val_AUC: 0.8718\nEpoch 98/100\n360/360 [==============================] - 41s 114ms/step - loss: 1.1568 - accuracy: 0.8750 - precision: 0.7458 - recall: 0.3794 - AUC: 0.8737 - val_loss: 1.1560 - val_accuracy: 0.8754 - val_precision: 0.7459 - val_recall: 0.3828 - val_AUC: 0.8748\nEpoch 99/100\n360/360 [==============================] - 41s 114ms/step - loss: 1.1661 - accuracy: 0.8747 - precision: 0.7470 - recall: 0.3753 - AUC: 0.8711 - val_loss: 1.1712 - val_accuracy: 0.8720 - val_precision: 0.7284 - val_recall: 0.3703 - val_AUC: 0.8706\nEpoch 100/100\n360/360 [==============================] - 41s 114ms/step - loss: 1.1815 - accuracy: 0.8726 - precision: 0.7393 - recall: 0.3636 - AUC: 0.8682 - val_loss: 1.2244 - val_accuracy: 0.8699 - val_precision: 0.6852 - val_recall: 0.4062 - val_AUC: 0.8618\n" ], [ "", "_____no_output_____" ] ], [ [ "### Save Model", "_____no_output_____" ] ], [ [ "model.save('model_optimal_singlechannel_addingdata_0626.h5')\nmodel.save_weights('model_weights_singlechannel_addingdata_0626.h5')", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "### Plotting", "_____no_output_____" ] ], [ [ "plt.figure(0)\nplt.plot(history.history['accuracy'], label= 'training accuracy')\nplt.plot(history.history['val_accuracy'], label= 'validation accuracy')\nplt.title('Accuracy')\nplt.xlabel('epochs')\nplt.ylabel('Accuracy')\nplt.legend()", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "plt.figure(0)\nplt.plot(history.history['loss'], label= 'training loss')\nplt.plot(history.history['val_loss'], label= 'validation loss')\nplt.title('Loss')\nplt.xlabel('epochs')\nplt.ylabel('Loss')\nplt.legend()", "_____no_output_____" ], [ "plt.figure(0)\nplt.plot(history.history['AUC'], label= 'training auc')\nplt.plot(history.history['val_AUC'], label= 'validation auc')\nplt.title('auc')\nplt.xlabel('epochs')\nplt.ylabel('auc')\nplt.legend()", "_____no_output_____" ], [ "plt.figure(0)\nplt.plot(history.history['precision'], label= 'train precision')\nplt.plot(history.history['val_precision'], label= 'validation precision')\nplt.title('precision')\nplt.xlabel('epochs')\nplt.ylabel('precision')\nplt.legend()", "_____no_output_____" ], [ "plt.figure(0)\nplt.plot(history.history['recall'], label= 'train recall')\nplt.plot(history.history['val_recall'], label= 'validation recall')\nplt.title('recall')\nplt.xlabel('epochs')\nplt.ylabel('recall')\nplt.legend()", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "### Testing Dataset Accuracy", "_____no_output_____" ] ], [ [ "model.evaluate(test_generator)", "111/111 [==============================] - 3320s 30s/step - loss: 1.1982 - accuracy: 0.8726 - precision: 0.6933 - recall: 0.4225 - AUC: 0.8685\n" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ] ], [ [ "### Confusion Matrix", "_____no_output_____" ] ], [ [ "y_pred = model.predict(train_generator)\ny_pred = np.argmax(y_pred, axis=1)\nclass_labels = test_generator.class_indices\nclass_labels = {v:k for k,v in class_labels.items()}\n\nfrom sklearn.metrics import classification_report, confusion_matrix\ncm_train = confusion_matrix(train_generator.classes, y_pred)\nprint('Confusion Matrix')\nprint(cm_train)\nprint('Classification Report')\ntarget_names = list(class_labels.values())\nprint(classification_report(train_generator.classes, y_pred, target_names=target_names))\n\nplt.figure(figsize=(8,8))\nplt.imshow(cm_train, interpolation='nearest')\nplt.colorbar()\ntick_mark = np.arange(len(target_names))\n_ = plt.xticks(tick_mark, target_names, rotation=90)\n_ = plt.yticks(tick_mark, target_names)", "Confusion Matrix\n[[ 228 450 729 992 656 500]\n [ 261 445 757 1032 635 508]\n [ 268 567 963 1280 762 604]\n [ 295 564 898 1186 769 532]\n [ 303 539 863 1151 819 568]\n [ 210 360 646 814 471 363]]\nClassification Report\n precision recall f1-score support\n\n angry 0.15 0.06 0.09 3555\n fear 0.15 0.12 0.14 3638\n happy 0.20 0.22 0.21 4444\n neutral 0.18 0.28 0.22 4244\n sad 0.20 0.19 0.20 4243\n surprise 0.12 0.13 0.12 2864\n\n accuracy 0.17 22988\n macro avg 0.17 0.17 0.16 22988\nweighted avg 0.17 0.17 0.17 22988\n\n" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "# Import the model (if re-connect)\nfrom tensorflow import keras\nmodel = keras.models.load_model('/content/drive/MyDrive/Colab Notebooks/Kevin/model_optimal.h5')", "_____no_output_____" ], [ "", "_____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", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4afcff83e83049e45845d60f596f7b9eae51793c
110,994
ipynb
Jupyter Notebook
Ch2/06_Snorkel.ipynb
avoutsas67/practical-nlp-code-1
cf3e159c7e523d7ba14788f6982290c8fc00317d
[ "MIT" ]
null
null
null
Ch2/06_Snorkel.ipynb
avoutsas67/practical-nlp-code-1
cf3e159c7e523d7ba14788f6982290c8fc00317d
[ "MIT" ]
null
null
null
Ch2/06_Snorkel.ipynb
avoutsas67/practical-nlp-code-1
cf3e159c7e523d7ba14788f6982290c8fc00317d
[ "MIT" ]
null
null
null
39.192797
9,290
0.553435
[ [ [ "This notebook has been adapted from the [spam example](https://github.com/snorkel-team/snorkel-tutorials/blob/master/spam/01_spam_tutorial.ipynb) of the [snorkel examples github](https://github.com/snorkel-team/snorkel-tutorials). Please visit the official snorkel tutorials [link](https://github.com/snorkel-team/snorkel-tutorials) for a more detailed and exhautive guide on how to use snorkel.<br>\nThis notebook demonstrates how to use snorkel for data labeling. Our goal here is to build a dataset which can be used to classify if a Youtube comment is Spam or Ham.\n\n\n## Installing Dependencies", "_____no_output_____" ] ], [ [ "# To install only the requirements of this notebook, uncomment the lines below and run this cell\n\n# ===========================\n\n# !pip install numpy==1.19.5\n# !pip install pandas==1.1.5\n# !pip install wget==3.2\n# !pip install matplotlib==3.2.2\n# !pip install utils==1.0.1\n# !pip install snorkel==0.9.6\n# !pip install scikit-learn==0.21.3\n# !pip install textblob==0.15.3\n# !pip install treedlib==0.1.3\n# !pip install numbskull==0.1.1\n# !pip install spacy==2.2.4\n\n# ===========================", "_____no_output_____" ], [ "# To install the requirements for the entire chapter, uncomment the lines below and run this cell\n\n# ===========================\n\n# try :\n# import google.colab\n# !curl https://raw.githubusercontent.com/practical-nlp/practical-nlp/master/Ch2/ch2-requirements.txt | xargs -n 1 -L 1 pip install\n# except ModuleNotFoundError :\n# !pip install -r \"ch2-requirements.txt\"\n\n# ===========================", "_____no_output_____" ], [ "# !pip install tensorflow==1.15\n# !pip install tensorboard==1.15\n!python -m spacy download en_core_web_sm", "Collecting en-core-web-sm==3.2.0\n Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.2.0/en_core_web_sm-3.2.0-py3-none-any.whl (13.9 MB)\n |████████████████████████████████| 13.9 MB 3.0 MB/s \n\u001b[?25hRequirement already satisfied: spacy<3.3.0,>=3.2.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from en-core-web-sm==3.2.0) (3.2.1)\nRequirement already satisfied: blis<0.8.0,>=0.4.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (0.7.5)\nRequirement already satisfied: pathy>=0.3.5 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (0.6.1)\nRequirement already satisfied: setuptools in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (59.0.1)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (2.0.6)\nRequirement already satisfied: requests<3.0.0,>=2.13.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (2.26.0)\nRequirement already satisfied: spacy-legacy<3.1.0,>=3.0.8 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (3.0.8)\nRequirement already satisfied: tqdm<5.0.0,>=4.38.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (4.62.3)\nRequirement already satisfied: srsly<3.0.0,>=2.4.1 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (2.4.2)\nRequirement already satisfied: thinc<8.1.0,>=8.0.12 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (8.0.13)\nRequirement already satisfied: spacy-loggers<2.0.0,>=1.0.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (1.0.1)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (3.0.6)\nRequirement already satisfied: jinja2 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (3.0.3)\nRequirement already satisfied: pydantic!=1.8,!=1.8.1,<1.9.0,>=1.7.4 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (1.8.2)\nRequirement already satisfied: wasabi<1.1.0,>=0.8.1 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (0.9.0)\nRequirement already satisfied: catalogue<2.1.0,>=2.0.6 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (2.0.6)\nRequirement already satisfied: numpy>=1.15.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (1.19.5)\nRequirement already satisfied: typer<0.5.0,>=0.3.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (0.4.0)\nRequirement already satisfied: langcodes<4.0.0,>=3.2.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (3.3.0)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (1.0.6)\nRequirement already satisfied: packaging>=20.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (21.3)\nRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from packaging>=20.0->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (3.0.6)\nRequirement already satisfied: smart-open<6.0.0,>=5.0.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from pathy>=0.3.5->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (5.2.1)\nRequirement already satisfied: typing-extensions>=3.7.4.3 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from pydantic!=1.8,!=1.8.1,<1.9.0,>=1.7.4->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (4.0.1)\nRequirement already satisfied: charset-normalizer~=2.0.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (2.0.10)\nRequirement already satisfied: idna<4,>=2.5 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (3.3)\nRequirement already satisfied: certifi>=2017.4.17 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (2021.10.8)\nRequirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from requests<3.0.0,>=2.13.0->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (1.26.7)\nRequirement already satisfied: click<9.0.0,>=7.1.1 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from typer<0.5.0,>=0.3.0->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (8.0.3)\nRequirement already satisfied: MarkupSafe>=2.0 in /Users/achilleas.voutsas/Development/books/practical-nlp-code/.venv/lib/python3.9/site-packages (from jinja2->spacy<3.3.0,>=3.2.0->en-core-web-sm==3.2.0) (2.0.1)\nInstalling collected packages: en-core-web-sm\nSuccessfully installed en-core-web-sm-3.2.0\n\u001b[38;5;2m✔ Download and installation successful\u001b[0m\nYou can now load the package via spacy.load('en_core_web_sm')\n" ], [ "import warnings\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "## Dataset\nLet's get the Youtube spam classification dataset from the UCI ML Repository archive. The link for the dataset can be found [here](http://archive.ics.uci.edu/ml/machine-learning-databases/00380/YouTube-Spam-Collection-v1.zip).", "_____no_output_____" ] ], [ [ "import os\nimport wget\n\nimport zipfile\nimport shutil\n\nfile_link = \"http://archive.ics.uci.edu/ml/machine-learning-databases/00380/YouTube-Spam-Collection-v1.zip\"\n\nos.makedirs(\"content\", exist_ok= True)\nif not os.path.exists(\"content/YouTube-Spam-Collection-v1.zip\"):\n wget.download(file_link, out=\"content/\")\nelse:\n print(\"File already exists\")\n\nwith zipfile.ZipFile(\"content/YouTube-Spam-Collection-v1.zip\", 'r') as zip_ref:\n zip_ref.extractall(\"content/\")\n\nshutil.rmtree(\"content/__MACOSX\")\nos.remove(\"content/YouTube-Spam-Collection-v1.zip\")\nos.listdir(\"content\")", "_____no_output_____" ] ], [ [ "Let's clone the necessary repos.", "_____no_output_____" ] ], [ [ "git_repo = \"snorkel-tutorials\"\nif (os.path.isdir(git_repo + '/.git')):\n print(f\"Git repo: {git_repo} already exists!\")\nelse:\n !git clone https://github.com/snorkel-team/snorkel-tutorials.git\n source = \"content/\"\n destination = git_repo + \"/spam/data/\"\n\n os.makedirs(destination, exist_ok= True)\n\n files = os.listdir(source)\n\n for file in files:\n new_path = shutil.move(f\"{source}/{file}\", destination)\n\n print(f\"Git repo: {git_repo} created!\")\n \nos.chdir(\"snorkel-tutorials/spam\")", "Git repo: snorkel-tutorials already exists!\n" ] ], [ [ "## Making the necessary imports", "_____no_output_____" ] ], [ [ "import re\nimport glob\n\nimport utils\n\nfrom snorkel.analysis import get_label_buckets\n\nfrom snorkel.labeling import labeling_function\nfrom snorkel.labeling import LFAnalysis\nfrom snorkel.labeling import PandasLFApplier\nfrom snorkel.labeling import LabelingFunction\nfrom snorkel.labeling.model import MajorityLabelVoter\nfrom snorkel.labeling.model import LabelModel\nfrom snorkel.labeling import filter_unlabeled_dataframe\nfrom snorkel.labeling.lf.nlp import nlp_labeling_function\n\nfrom snorkel.preprocess import preprocessor\nfrom snorkel.preprocess.nlp import SpacyPreprocessor\n\nfrom snorkel.utils import probs_to_preds\n\nfrom textblob import TextBlob\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib.pyplot as plt\n%matplotlib inline", "_____no_output_____" ], [ "def load_spam_dataset(load_train_labels: bool = False, split_dev_valid: bool = False):\n filenames = sorted(glob.glob(\"data/Youtube*.csv\"))\n dfs = []\n for i, filename in enumerate(filenames, start=1):\n df = pd.read_csv(filename)\n # Lowercase column names\n df.columns = map(str.lower, df.columns)\n # Remove comment_id field\n df = df.drop(\"comment_id\", axis=1)\n # Add field indicating source video\n df[\"video\"] = [i] * len(df)\n # Rename fields\n df = df.rename(columns={\"class\": \"label\", \"content\": \"text\"})\n # Shuffle order\n df = df.sample(frac=1, random_state=123).reset_index(drop=True)\n dfs.append(df)\n\n df_train = pd.concat(dfs[:4])\n df_dev = df_train.sample(100, random_state=123)\n\n if not load_train_labels:\n df_train[\"label\"] = np.ones(len(df_train[\"label\"])) * -1\n df_valid_test = dfs[4]\n df_valid, df_test = train_test_split(\n df_valid_test, test_size=250, random_state=123, stratify=df_valid_test.label\n )\n\n if split_dev_valid:\n return df_train, df_dev, df_valid, df_test\n else:\n return df_train, df_test", "_____no_output_____" ], [ "df_train, df_test = load_spam_dataset()\nprint(\"Train\")\ndisplay(df_train.head())\nprint('Test')\ndf_test.head()", "Train\n" ], [ "Y_test = df_test.label.values\nY_test[:5]", "_____no_output_____" ] ], [ [ "There are a few things to keep in mind with respect to the dataset:\n1. HAM represents a NON-SPAM comment.\n2. SPAM is a SPAM comment\n3. ABSTAIN is for neither of the above\n\nWe initialise their respective values below\n", "_____no_output_____" ] ], [ [ "ABSTAIN = -1\nHAM = 0\nSPAM = 1", "_____no_output_____" ] ], [ [ "We need to find some pattern in the data, so as to create rules for labeling the data.<br>\nHence, we randomly display some rows of the dataset so that we can try to find some pattern in the text. ", "_____no_output_____" ] ], [ [ "df_train[[\"author\", \"text\", \"video\"]].sample(20, random_state=2020)", "_____no_output_____" ] ], [ [ "An example for how a labeling function can be defined , anything that might match the pattern of a spam message can be used , here http is an example to show as many spam comments may contain links", "_____no_output_____" ] ], [ [ "@labeling_function()\ndef lf_contains_link(x):\n # Return a label of SPAM if \"http\" in comment text, otherwise ABSTAIN\n return SPAM if \"http\" in x.text.lower() else ABSTAIN", "_____no_output_____" ] ], [ [ "Defining labeling functions to check strings such as 'check', 'check out', 'http', 'my channel', 'subscribe'<br>\nTry to write your own labeling functions too.", "_____no_output_____" ] ], [ [ "@labeling_function()\ndef check(x):\n return SPAM if \"check\" in x.text.lower() else ABSTAIN\n\n@labeling_function()\ndef check_out(x):\n return SPAM if \"check out\" in x.text.lower() else ABSTAIN\n\n@labeling_function()\ndef my_channel(x):\n return SPAM if \"my channel\" in x.text.lower() else ABSTAIN\n\n@labeling_function()\ndef if_subscribe(x):\n return SPAM if \"subscribe\" in x.text.lower() else ABSTAIN", "_____no_output_____" ] ], [ [ "Using **LFApplier** to use our labelling fucntions with pandas dataframe object.\n\nthese labeling functions can also be used on columns other than 'text'", "_____no_output_____" ] ], [ [ "lfs = [check_out, check, lf_contains_link, my_channel, if_subscribe]\n\napplier = PandasLFApplier(lfs=lfs)\nL_train = applier.apply(df=df_train)", "100%|██████████| 1586/1586 [00:00<00:00, 11145.03it/s]\n" ], [ "L_train", "_____no_output_____" ] ], [ [ "_Coverage_ is the fraction of the dataset the labeling function labels.", "_____no_output_____" ] ], [ [ "coverage_check_out, coverage_check, coverage_link, coverage_my_channel, coverage_subscribe= (L_train != ABSTAIN).mean(axis=0)\nprint(f\"check_out coverage: {coverage_check_out * 100:.1f}%\")\nprint(f\"check coverage: {coverage_check * 100:.1f}%\")\nprint(f\"link coverage: {coverage_link * 100:.1f}%\")\nprint(f\"my_channel coverage: {coverage_my_channel * 100:.1f}%\")\nprint(f\"if_subscribe coverage: {coverage_subscribe * 100:.1f}%\")", "check_out coverage: 21.4%\ncheck coverage: 25.8%\nlink coverage: 11.9%\nmy_channel coverage: 7.0%\nif_subscribe coverage: 12.7%\n" ] ], [ [ "Before we procees further, let us understand a bit of jargon with respect to the summary of the _LFAnalysis_\n1. Polarity - set of unique labels that the labeling function outputs (excluding Abstains)\n\n2. Overlaps - where there is atleast one common entry for more than one labeling functions i.e the labeling fucntions agree upon the value to be returned\n\n3. Conflicts - where the labeling functions disagree upon the value to be returned", "_____no_output_____" ] ], [ [ "LFAnalysis(L=L_train, lfs=lfs).lf_summary()", "_____no_output_____" ] ], [ [ "Trying and checking the results by filtering out the matching rows and checking for false positives ", "_____no_output_____" ] ], [ [ "# display(df_train.iloc[L_train[:, 1] == SPAM].sample(10, random_state=2020))\n# display(df_train.iloc[L_train[:, 2] == SPAM].sample(10, random_state=2020))\ndf_train.iloc[L_train[:, 3] == SPAM].sample(10, random_state=2020)", "_____no_output_____" ] ], [ [ "Combining two labeling functions and checking the results ", "_____no_output_____" ] ], [ [ "#buckets = get_label_buckets(L_train[:, 0], L_train[:, 1])\n#buckets = get_label_buckets(L_train[:, 1], L_train[:, 2])\nbuckets = get_label_buckets(L_train[:, 0], L_train[:, 3])\n\ndf_train.iloc[buckets[(ABSTAIN, SPAM)]].sample(10, random_state=1)", "_____no_output_____" ] ], [ [ "**Regex Based Labeling Functions:** Using regular expressions to make the labeling functions more adaptive over differnt variations of the pattern string and repeating the the same process as above.<br>\n\nPlease feel free to find out patterns and write similar functions for 'http','subscribe', etc and if possible send a pull request.", "_____no_output_____" ] ], [ [ "#using regular expressions\n@labeling_function()\ndef regex_check_out(x):\n return SPAM if re.search(r\"check.*out\", x.text, flags=re.I) else ABSTAIN", "_____no_output_____" ], [ "lfs = [check_out, check, regex_check_out]\n\napplier = PandasLFApplier(lfs=lfs)\nL_train = applier.apply(df=df_train)", "100%|██████████| 1586/1586 [00:00<00:00, 19603.54it/s]\n" ], [ "LFAnalysis(L=L_train, lfs=lfs).lf_summary()", "_____no_output_____" ], [ "buckets = get_label_buckets(L_train[:, 1], L_train[:, 2])\ndf_train.iloc[buckets[(SPAM, ABSTAIN)]].sample(10, random_state=2020)", "_____no_output_____" ] ], [ [ "Let's use a 3rd party model, TextBlob in this case, to write a labeling function. Snorkel makes this very simple to implement.", "_____no_output_____" ] ], [ [ "@preprocessor(memoize=True)\ndef textblob_sentiment(x):\n scores = TextBlob(x.text)\n x.polarity = scores.sentiment.polarity\n x.subjectivity = scores.sentiment.subjectivity\n return x", "_____no_output_____" ], [ "@labeling_function(pre=[textblob_sentiment])\ndef textblob_polarity(x):\n return HAM if x.polarity > 0.9 else ABSTAIN\n\n@labeling_function(pre=[textblob_sentiment])\ndef textblob_subjectivity(x):\n return HAM if x.subjectivity >= 0.5 else ABSTAIN\n", "_____no_output_____" ], [ "lfs = [textblob_polarity, textblob_subjectivity]\n\napplier = PandasLFApplier(lfs)\nL_train = applier.apply(df_train)\n", "100%|██████████| 1586/1586 [00:02<00:00, 763.86it/s]\n" ], [ "LFAnalysis(L_train, lfs).lf_summary()", "_____no_output_____" ] ], [ [ "## Writing more labeling functions\n\nSingle labeling functions arent enough to test the entire databsase with accuracy as they do not have enough coverage, we usually need to combine differnt labeling functions(more rubost and accurate ones) to get this done.", "_____no_output_____" ], [ "**Keyword based labeling fucntions**: These are similar to the ones used befeore with the labeling_fucntion decorator. here we just make a few changes", "_____no_output_____" ] ], [ [ "def keyword_lookup(x, keywords, label):\n if any(word in x.text.lower() for word in keywords):\n return label\n return ABSTAIN\n\n\ndef make_keyword_lf(keywords, label=SPAM):\n return LabelingFunction(\n name=f\"keyword_{keywords[0]}\",\n f=keyword_lookup,\n resources=dict(keywords=keywords, label=label),\n )\n\n\n\"\"\"Spam comments talk about 'my channel', 'my video', etc.\"\"\"\nkeyword_my = make_keyword_lf(keywords=[\"my\"])\n\n\"\"\"Spam comments ask users to subscribe to their channels.\"\"\"\nkeyword_subscribe = make_keyword_lf(keywords=[\"subscribe\"])\n\n\"\"\"Spam comments post links to other channels.\"\"\"\nkeyword_link = make_keyword_lf(keywords=[\"http\"])\n\n\"\"\"Spam comments make requests rather than commenting.\"\"\"\nkeyword_please = make_keyword_lf(keywords=[\"please\", \"plz\"])\n\n\"\"\"Ham comments actually talk about the video's content.\"\"\"\nkeyword_song = make_keyword_lf(keywords=[\"song\"], label=HAM)\n", "_____no_output_____" ] ], [ [ "Modifying the above functions to use regualr expressions too would be an interesting exercise which we will leave to the reader.\n\nHaving other methods such as a Rule of Thumb or Heuristics(length of text) could help too. These are not extremely accurate but will get the job done to a certain extent.\n\nAn example is given below", "_____no_output_____" ] ], [ [ "@labeling_function()\ndef short_comment(x):\n \"\"\"Ham comments are often short, such as 'cool video!'\"\"\"\n return HAM if len(x.text.split()) < 5 else ABSTAIN", "_____no_output_____" ] ], [ [ "We can also use NLP preprocessors such as spaCy to enrich our data and provide us with more fields to work on which will make the labeling a bit easier . ", "_____no_output_____" ] ], [ [ "# The SpacyPreprocessor parses the text in text_field and\n# stores the new enriched representation in doc_field\nspacy = SpacyPreprocessor(text_field=\"text\", doc_field=\"doc\", memoize=True)\n\n@labeling_function(pre=[spacy])\ndef has_person(x):\n \"\"\"Ham comments mention specific people and are short.\"\"\"\n if len(x.doc) < 20 and any([ent.label_ == \"PERSON\" for ent in x.doc.ents]):\n return HAM\n else:\n return ABSTAIN", "_____no_output_____" ], [ "#snorkel has a pre built labeling function like decorator that uses spaCy as it is a very common nlp preprocessor\n\n@nlp_labeling_function()\ndef has_person_nlp(x):\n \"\"\"Ham comments mention specific people and are short.\"\"\"\n if len(x.doc) < 20 and any([ent.label_ == \"PERSON\" for ent in x.doc.ents]):\n return HAM\n else:\n return ABSTAIN\n", "_____no_output_____" ] ], [ [ "## Outputs\nLet's move onto learning how we can go about combining labeling function outputs with labeling models.\n\n", "_____no_output_____" ] ], [ [ "lfs = [\n keyword_my,\n keyword_subscribe,\n keyword_link,\n keyword_please,\n keyword_song,\n regex_check_out,\n short_comment,\n has_person_nlp,\n textblob_polarity,\n textblob_subjectivity,\n]\n", "_____no_output_____" ], [ "applier = PandasLFApplier(lfs=lfs)\nL_train = applier.apply(df=df_train)\nL_test = applier.apply(df=df_test)", "100%|██████████| 1586/1586 [00:13<00:00, 119.13it/s]\n100%|██████████| 250/250 [00:02<00:00, 103.08it/s]\n" ], [ "LFAnalysis(L=L_train, lfs=lfs).lf_summary()", "_____no_output_____" ] ], [ [ "We plot a histogram to get an idea about the coverages of the labeling functions", "_____no_output_____" ] ], [ [ "def plot_label_frequency(L):\n plt.hist((L != ABSTAIN).sum(axis=1), density=True, bins=range(L.shape[1]))\n plt.xlabel(\"Number of labels\")\n plt.ylabel(\"Fraction of dataset\")\n plt.show()\n\n\nplot_label_frequency(L_train)", "_____no_output_____" ] ], [ [ "We now convert the labels from our labeling functions to a single noise-aware probabilistic label per data. we do so by taking a majority vote on what the data should be labeled as .i.e if more labeling functions agree that the text/data is spam , then we label it as spam", "_____no_output_____" ] ], [ [ "majority_model = MajorityLabelVoter()\npreds_train = majority_model.predict(L=L_train)", "_____no_output_____" ], [ "preds_train", "_____no_output_____" ] ], [ [ "However there may be functions that are correlated and might give a false sense of majority , to handle this we use a differernt snorkel label model to comine inputs of the labeling functions.", "_____no_output_____" ] ], [ [ "label_model = LabelModel(cardinality=2, verbose=True)\nlabel_model.fit(L_train=L_train, n_epochs=500, log_freq=100, seed=123)", "INFO:root:Computing O...\nINFO:root:Estimating \\mu...\n 0%| | 0/500 [00:00<?, ?epoch/s]INFO:root:[0 epochs]: TRAIN:[loss=0.167]\n 17%|█▋ | 84/500 [00:00<00:00, 836.09epoch/s]INFO:root:[100 epochs]: TRAIN:[loss=0.011]\n 34%|███▎ | 168/500 [00:00<00:00, 728.65epoch/s]INFO:root:[200 epochs]: TRAIN:[loss=0.008]\n 50%|████▉ | 248/500 [00:00<00:00, 757.02epoch/s]INFO:root:[300 epochs]: TRAIN:[loss=0.008]\n 65%|██████▌ | 326/500 [00:00<00:00, 762.08epoch/s]INFO:root:[400 epochs]: TRAIN:[loss=0.008]\n100%|██████████| 500/500 [00:00<00:00, 806.70epoch/s]\nINFO:root:Finished Training\n" ], [ "majority_acc = majority_model.score(L=L_test, Y=Y_test, tie_break_policy=\"random\")[\"accuracy\"]\nprint(f\"{'Majority Vote Accuracy:':<25} {majority_acc * 100:.1f}%\")\n\nlabel_model_acc = label_model.score(L=L_test, Y=Y_test, tie_break_policy=\"random\")[\"accuracy\"]\nprint(f\"{'Label Model Accuracy:':<25} {label_model_acc * 100:.1f}%\")", "Majority Vote Accuracy: 84.0%\nLabel Model Accuracy: 86.4%\n" ] ], [ [ "We plot another graph to see the confidences that each data point is a spam", "_____no_output_____" ] ], [ [ "def plot_probabilities_histogram(Y):\n plt.hist(Y, bins=10)\n plt.xlabel(\"Probability of SPAM\")\n plt.ylabel(\"Number of data points\")\n plt.show()\n\nprobs_train = label_model.predict_proba(L=L_train)\nplot_probabilities_histogram(probs_train[:, SPAM])\n", "_____no_output_____" ] ], [ [ "There might be some data which do not get any label from the functions , we filter them out as follows", "_____no_output_____" ] ], [ [ "df_train_filtered, probs_train_filtered = filter_unlabeled_dataframe(\n X=df_train, y=probs_train, L=L_train\n)", "_____no_output_____" ] ], [ [ "## Training a classifier\nIn this section we use the probabilistic training labels we generated to train a classifier. for demonstration we use Scikit-Learn.<br>\n_Note:Do not worry if you do not understand what a classifier is. We cover all of this in Chapter 4. Please read Ch4 and look at the jupyter notebooks in Ch4._", "_____no_output_____" ] ], [ [ "vectorizer = CountVectorizer(ngram_range=(1, 5))\nX_train = vectorizer.fit_transform(df_train_filtered.text.tolist())\nX_test = vectorizer.transform(df_test.text.tolist())\n", "_____no_output_____" ], [ "preds_train_filtered = probs_to_preds(probs=probs_train_filtered)", "_____no_output_____" ], [ "sklearn_model = LogisticRegression(C=1e3, solver=\"liblinear\")\nsklearn_model.fit(X=X_train, y=preds_train_filtered)", "_____no_output_____" ], [ "print(f\"Test Accuracy: {sklearn_model.score(X=X_test, y=Y_test) * 100:.1f}%\")\n", "Test Accuracy: 93.6%\n" ] ], [ [ "We have just scratched the surface on what snorkel can do. We highly recommend going through their [github](https://github.com/snorkel-team/snorkel) and [tutorials](https://github.com/snorkel-team/snorkel-tutorials).", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
4afd1a851c4071612edc4aec3ae64268b792b68b
1,753
ipynb
Jupyter Notebook
课程汇集/其他课程/虚谷号GPIO范例/02.虚谷闪一闪.ipynb
xiezuoru/vvBoard-docs
4e13b4a6699cc937f2c61b60c8a6523b1f3557c6
[ "MIT" ]
13
2019-08-19T10:08:52.000Z
2021-08-08T03:41:20.000Z
课程汇集/其他课程/虚谷号GPIO范例/02.虚谷闪一闪.ipynb
xiezuoru/vvBoard-docs
4e13b4a6699cc937f2c61b60c8a6523b1f3557c6
[ "MIT" ]
null
null
null
课程汇集/其他课程/虚谷号GPIO范例/02.虚谷闪一闪.ipynb
xiezuoru/vvBoard-docs
4e13b4a6699cc937f2c61b60c8a6523b1f3557c6
[ "MIT" ]
8
2019-08-18T08:54:49.000Z
2021-08-17T07:59:13.000Z
21.641975
54
0.516258
[ [ [ "# 虚谷闪一闪\n\n让虚谷号自带的 LED(接在 13 号引脚,即 D13)闪烁,设置为亮1秒熄灭1秒\n\n采用数字输出的方式,使用xugu库的Pin类和时间模块进行,代码如下", "_____no_output_____" ] ], [ [ "import time # 导入 time 模块\nfrom xugu import Pin # 从 xugu 库中导入 Pin 类\nled = Pin(13, Pin.OUT) # 初始化 Pin 类\n# 等价的写法:led = Pin(“D13”, pin.OUT)\nwhile True:\n # #用循环实现持续地开灯关灯,到达闪烁的效果\n led.write_digital(1) # 点亮连接 13 号引脚的 LED 灯\n time.sleep(1) # 持续 1 秒\n led.write_digital(0) # 关闭 LED 灯\n time.sleep(1) # 持续 1 秒", "_____no_output_____" ] ], [ [ "让虚谷号自带的 LED(接在 13 号引脚,即 D13)闪烁,设置为亮2秒熄灭3秒\n\n使用xugu库的LED类和时间模块进行,代码如下", "_____no_output_____" ] ], [ [ "import time #导入time模块\nfrom xugu import LED #从xugu库中导入LED类\nled = LED(13) # 初始化LED类\n\nwhile True: # 用循环实现持续地开灯关灯,到达闪烁的效果 \n led.on() # 点亮连接13号引脚的LED灯\n time.sleep(2) # 持续2秒\n led.off() # 关闭LED灯\n time.sleep(3) # 持续3秒", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4afd1aff49918771d4634396b23e6ef396dad4a0
19,038
ipynb
Jupyter Notebook
src/datacleaning/Chapter 2/1_import_json.ipynb
vidyabhandary/DataScienceNotebooks
1a9a423ffe6bdcd803ed195da97a751e44567813
[ "MIT" ]
null
null
null
src/datacleaning/Chapter 2/1_import_json.ipynb
vidyabhandary/DataScienceNotebooks
1a9a423ffe6bdcd803ed195da97a751e44567813
[ "MIT" ]
null
null
null
src/datacleaning/Chapter 2/1_import_json.ipynb
vidyabhandary/DataScienceNotebooks
1a9a423ffe6bdcd803ed195da97a751e44567813
[ "MIT" ]
null
null
null
26.043776
2,108
0.523322
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Import-the-json-and-pprint-libraries\" data-toc-modified-id=\"Import-the-json-and-pprint-libraries-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Import the json and pprint libraries</a></span></li><li><span><a href=\"#Load-the-JSON-data-and-look-for-potential-issues\" data-toc-modified-id=\"Load-the-JSON-data-and-look-for-potential-issues-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Load the JSON data and look for potential issues</a></span></li><li><span><a href=\"#Check-for-differences-in-the-structure-of-the-dictionaries\" data-toc-modified-id=\"Check-for-differences-in-the-structure-of-the-dictionaries-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Check for differences in the structure of the dictionaries</a></span></li><li><span><a href=\"#Generate-counts-from-the-JSON-data\" data-toc-modified-id=\"Generate-counts-from-the-JSON-data-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Generate counts from the JSON data</a></span></li><li><span><a href=\"#Get-the-source-data-and-confirm-that-it-has-the-anticipated-length\" data-toc-modified-id=\"Get-the-source-data-and-confirm-that-it-has-the-anticipated-length-5\"><span class=\"toc-item-num\">5&nbsp;&nbsp;</span>Get the source data and confirm that it has the anticipated length</a></span></li><li><span><a href=\"#Fix-any-errors-in-the-values-in-the-dictionary\" data-toc-modified-id=\"Fix-any-errors-in-the-values-in-the-dictionary-6\"><span class=\"toc-item-num\">6&nbsp;&nbsp;</span>Fix any errors in the values in the dictionary</a></span></li><li><span><a href=\"#Create-a-pandas-DataFrame\" data-toc-modified-id=\"Create-a-pandas-DataFrame-7\"><span class=\"toc-item-num\">7&nbsp;&nbsp;</span>Create a pandas DataFrame</a></span></li><li><span><a href=\"#Confirm-that-we-are-getting-the-expected-values-for-source\" data-toc-modified-id=\"Confirm-that-we-are-getting-the-expected-values-for-source-8\"><span class=\"toc-item-num\">8&nbsp;&nbsp;</span>Confirm that we are getting the expected values for source</a></span></li></ul></div>", "_____no_output_____" ], [ "# Import the json and pprint libraries", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport json\nimport pprint\nfrom collections import Counter", "_____no_output_____" ], [ "import watermark\n\n%load_ext watermark\n%watermark -n -v -iv", "The watermark extension is already loaded. To reload it, use:\n %reload_ext watermark\nPython implementation: CPython\nPython version : 3.7.9\nIPython version : 7.20.0\n\nnumpy : 1.19.2\njson : 2.0.9\npandas : 1.2.1\nwatermark: 2.1.0\n\n" ] ], [ [ "# Load the JSON data and look for potential issues", "_____no_output_____" ] ], [ [ "with open('data/allcandidatenewssample.json') as f:\n candidatenews = json.load(f)", "_____no_output_____" ], [ "len(candidatenews)", "_____no_output_____" ], [ "pprint.pprint(candidatenews[0:2])", "[{'date': '2019-12-25 10:00:00',\n 'domain': 'www.nbcnews.com',\n 'panel_position': 1,\n 'query': 'Michael Bloomberg',\n 'source': 'NBC News',\n 'story_position': 6,\n 'time': '18 hours ago',\n 'title': 'Bloomberg cuts ties with company using prison inmates to make '\n 'campaign calls',\n 'url': 'https://www.nbcnews.com/politics/2020-election/bloomberg-cuts-ties-company-using-prison-inmates-make-campaign-calls-n1106971'},\n {'date': '2019-11-09 08:00:00',\n 'domain': 'www.townandcountrymag.com',\n 'panel_position': 1,\n 'query': 'Amy Klobuchar',\n 'source': 'Town & Country Magazine',\n 'story_position': 3,\n 'time': '18 hours ago',\n 'title': \"Democratic Candidates React to Michael Bloomberg's Potential Run\",\n 'url': 'https://www.townandcountrymag.com/society/politics/a29739854/michael-bloomberg-democratic-candidates-campaign-reactions/'}]\n" ], [ "pprint.pprint(candidatenews[0]['source'])", "'NBC News'\n" ] ], [ [ "# Check for differences in the structure of the dictionaries", "_____no_output_____" ] ], [ [ "Counter([len(item) for item in candidatenews])", "_____no_output_____" ], [ "pprint.pprint(next(item for item in candidatenews if len(item) < 9))", "{'date': '2019-09-11 18:00:00', 'reason': 'Not collected'}\n" ], [ "# checking the usage of next\npprint.pprint((item for item in candidatenews if len(item) < 9))", "<generator object <genexpr> at 0x0000024D4AC52948>\n" ], [ "pprint.pprint(next(item for item in candidatenews if len(item) > 9))", "{'category': 'Satire',\n 'date': '2019-08-21 04:00:00',\n 'domain': 'politics.theonion.com',\n 'panel_position': 1,\n 'query': 'John Hickenlooper',\n 'source': 'Politics | The Onion',\n 'story_position': 8,\n 'time': '4 days ago',\n 'title': '‘And Then There Were 23,’ Says Wayne Messam Crossing Out '\n 'Hickenlooper Photo \\n'\n 'In Elaborate Grid Of Rivals',\n 'url': 'https://politics.theonion.com/and-then-there-were-23-says-wayne-messam-crossing-ou-1837311060'}\n" ], [ "pprint.pprint([item for item in candidatenews if len(item) == 2][0:10])", "[{'date': '2019-09-11 18:00:00', 'reason': 'Not collected'},\n {'date': '2019-07-24 00:00:00', 'reason': 'No Top stories'},\n {'date': '2019-08-19 20:00:00', 'reason': 'Not collected'},\n {'date': '2019-09-13 16:00:00', 'reason': 'Not collected'},\n {'date': '2019-10-16 20:00:00', 'reason': 'No Top stories'},\n {'date': '2019-10-17 18:00:00', 'reason': 'Not collected'},\n {'date': '2019-08-02 14:00:00', 'reason': 'Not collected'},\n {'date': '2019-05-27 12:00:00', 'reason': 'Not collected'},\n {'date': '2019-12-03 12:00:00', 'reason': 'No Top stories'},\n {'date': '2019-01-03 00:00:00', 'reason': 'No Top stories'}]\n" ], [ "candidatenews = [item for item in candidatenews if len(item) > 2]", "_____no_output_____" ], [ "len(candidatenews)", "_____no_output_____" ] ], [ [ "# Generate counts from the JSON data", "_____no_output_____" ] ], [ [ "politico = [item for item in candidatenews if item['source'] == \"Politico\"]", "_____no_output_____" ], [ "len(politico)", "_____no_output_____" ], [ "pprint.pprint(politico[0:2])", "[{'date': '2019-05-18 18:00:00',\n 'domain': 'www.politico.com',\n 'panel_position': 1,\n 'query': 'Marianne Williamson',\n 'source': 'Politico',\n 'story_position': 7,\n 'time': '1 week ago',\n 'title': 'Marianne Williamson reaches donor threshold for Dem debates',\n 'url': 'https://www.politico.com/story/2019/05/09/marianne-williamson-2020-election-1315133'},\n {'date': '2018-12-27 06:00:00',\n 'domain': 'www.politico.com',\n 'panel_position': 1,\n 'query': 'Julian Castro',\n 'source': 'Politico',\n 'story_position': 1,\n 'time': '1 hour ago',\n 'title': \"O'Rourke and Castro on collision course in Texas\",\n 'url': 'https://www.politico.com/story/2018/12/27/orourke-julian-castro-collision-texas-election-1073720'}]\n" ] ], [ [ "# Get the source data and confirm that it has the anticipated length", "_____no_output_____" ] ], [ [ "sources = [item.get('source') for item in candidatenews]", "_____no_output_____" ], [ "type(sources)", "_____no_output_____" ], [ "len(sources)", "_____no_output_____" ], [ "sources[0:5]", "_____no_output_____" ], [ "pprint.pprint(Counter(sources).most_common(10))", "[('Fox News', 3530),\n ('CNN.com', 2750),\n ('Politico', 2732),\n ('TheHill', 2383),\n ('The New York Times', 1804),\n ('Washington Post', 1770),\n ('Washington Examiner', 1655),\n ('The Hill', 1342),\n ('New York Post', 1275),\n ('Vox', 941)]\n" ] ], [ [ "# Fix any errors in the values in the dictionary", "_____no_output_____" ] ], [ [ "for newsdict in candidatenews:\n newsdict.update((k, 'The Hill') for k, v in newsdict.items()\n if k == 'source' and v == 'TheHill')", "_____no_output_____" ], [ "# Usage of item.get('source') instead of item['source']. \n# This is handy when there might be missing keys in a dictionary. get returns None when the key\n# is missing, but we can use an optional second argument to specify a value to return.\n\nsources = [item.get('source') for item in candidatenews]", "_____no_output_____" ], [ "pprint.pprint(Counter(sources).most_common(10))", "[('The Hill', 3725),\n ('Fox News', 3530),\n ('CNN.com', 2750),\n ('Politico', 2732),\n ('The New York Times', 1804),\n ('Washington Post', 1770),\n ('Washington Examiner', 1655),\n ('New York Post', 1275),\n ('Vox', 941),\n ('Breitbart', 799)]\n" ] ], [ [ "# Create a pandas DataFrame", "_____no_output_____" ] ], [ [ "candidatenewsdf = pd.DataFrame(candidatenews)", "_____no_output_____" ], [ "candidatenewsdf.dtypes", "_____no_output_____" ] ], [ [ "# Confirm that we are getting the expected values for source", "_____no_output_____" ] ], [ [ "candidatenewsdf.rename(columns={'date': 'storydate'}, inplace=True)", "_____no_output_____" ], [ "candidatenewsdf['storydate'] = candidatenewsdf['storydate'].astype(\n 'datetime64[ns]')", "_____no_output_____" ], [ "candidatenewsdf.shape", "_____no_output_____" ], [ "candidatenewsdf['source'].value_counts(sort=True).head(10)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4afd2430cfd12748a7b30f77b9e8fb2984855acf
4,732
ipynb
Jupyter Notebook
examples/tutorial/00_Setup.ipynb
ablythed/holoviz
ddfbfc504ade73e24aeb66560d9d3aa6f578956b
[ "BSD-3-Clause" ]
207
2019-11-14T08:41:44.000Z
2022-03-31T11:26:18.000Z
examples/tutorial/00_Setup.ipynb
ablythed/holoviz
ddfbfc504ade73e24aeb66560d9d3aa6f578956b
[ "BSD-3-Clause" ]
74
2019-11-21T16:39:45.000Z
2022-02-15T16:46:51.000Z
examples/tutorial/00_Setup.ipynb
ablythed/holoviz
ddfbfc504ade73e24aeb66560d9d3aa6f578956b
[ "BSD-3-Clause" ]
36
2020-01-17T08:01:53.000Z
2022-03-11T01:33:47.000Z
30.928105
405
0.60503
[ [ [ "<style>div.container { width: 100% }</style>\n<img style=\"float:left; vertical-align:text-bottom;\" height=\"65\" width=\"172\" src=\"../assets/holoviz-logo-unstacked.svg\" />\n<div style=\"float:right; vertical-align:text-bottom;\"><h2>Tutorial 0. Setup</h2></div>", "_____no_output_____" ], [ "This first step to the tutorial will make sure your system is set up to do all the remaining sections, with all software installed and all data downloaded as needed. The [index](index.ipynb) provided some links you might want to examine before you start.", "_____no_output_____" ], [ "## Getting set up\n\nPlease consult [holoviz.org](http://holoviz.org/installation.html) for the full instructions on installing the software used in these tutorials. Here is the condensed version of those instructions, assuming you have already downloaded and installed [Anaconda](https://www.anaconda.com/download) or [Miniconda](https://conda.io/miniconda.html) and have opened a command prompt in a Conda environment:", "_____no_output_____" ], [ "```\nconda install anaconda-project\nanaconda-project download pyviz/holoviz_tutorial\ncd holoviz_tutorial # You may need to delete this directory if you've run the command above before\nanaconda-project run jupyter notebook\n```", "_____no_output_____" ], [ "If you prefer JupyterLab to the default (classic) notebook interface, you can replace \"notebook\" with \"lab\".", "_____no_output_____" ], [ "Once your chosen environment is running, navigate to `tutorial/00_Setup.ipynb` (i.e. this notebook) and run the following cell to test the key imports needed for this tutorial. If it completes without errors your environment should be ready to go:", "_____no_output_____" ] ], [ [ "import datashader as ds, bokeh, holoviews as hv # noqa\nfrom distutils.version import LooseVersion\n\nmin_versions = dict(ds='0.13.0', bokeh='2.3.2', hv='1.14.4')\n\nfor lib, ver in min_versions.items():\n v = globals()[lib].__version__\n if LooseVersion(v) < LooseVersion(ver):\n print(\"Error: expected {}={}, got {}\".format(lib,ver,v))", "_____no_output_____" ] ], [ [ "And you should see the HoloViews, Bokeh, and Matplotlib logos after running the following cell:", "_____no_output_____" ] ], [ [ "hv.extension('bokeh', 'matplotlib')", "_____no_output_____" ] ], [ [ "## Downloading sample data", "_____no_output_____" ], [ "Lastly, let's make sure the datasets needed are available. First, check that the large earthquake dataset was downloaded correctly during the `anaconda-project run` command:", "_____no_output_____" ] ], [ [ "import os\nfrom pyct import cmd\n\nif not os.path.isfile('../data/earthquakes-projected.parq'):\n cmd.fetch_data(name='holoviz', path='..') # Alternative way to fetch the data", "_____no_output_____" ] ], [ [ "Make sure that you have the SNAPPY dependency required to read these data:", "_____no_output_____" ] ], [ [ "try:\n import pandas as pd\n columns = ['depth', 'id', 'latitude', 'longitude', 'mag', 'place', 'time', 'type']\n data = pd.read_parquet('../data/earthquakes-projected.parq', columns=columns, engine='fastparquet')\n data.head()\nexcept RuntimeError as e:\n print('The data cannot be read: %s' % e)", "_____no_output_____" ] ], [ [ "If you don't see any error messages above, you should be good to go! Now that you are set up, you can continue with the [rest of the tutorial sections](01_Overview.ipynb). ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4afd251b3441dea7067ff92caf247595a31ddb70
91,830
ipynb
Jupyter Notebook
code/exploratory/CFF_explorer.ipynb
ErgoCitizenScientists/ERGo
6d826554607d9bc7b7a631d8ca8e20ee94924fa0
[ "MIT" ]
null
null
null
code/exploratory/CFF_explorer.ipynb
ErgoCitizenScientists/ERGo
6d826554607d9bc7b7a631d8ca8e20ee94924fa0
[ "MIT" ]
null
null
null
code/exploratory/CFF_explorer.ipynb
ErgoCitizenScientists/ERGo
6d826554607d9bc7b7a631d8ca8e20ee94924fa0
[ "MIT" ]
null
null
null
91,830
91,830
0.713155
[ [ [ "import os, sys, subprocess\n# Colab setup ------------------\nif \"google.colab\" in sys.modules:\n \n # Mount drive\n from google.colab import drive\n print('Select your Caltech Google Account')\n drive.mount('/content/drive/')", "Select your Caltech Google Account\nMounted at /content/drive/\n" ], [ "import numpy as np\nimport pandas as pd\n\nfrom scipy.signal import filtfilt, butter\n\nimport holoviews as hv\nimport panel as pn\n# import holoviews.operation.datashader\nimport bokeh\nfrom holoviews import opts\nhv.extension('bokeh', 'matplotlib')", "_____no_output_____" ], [ "!pip install -e drive/MyDrive/My\\ Science\\ Practice/13\\ Dissemination\\ Publication\\ Outreach/ERGo/erg", "Obtaining file:///content/drive/MyDrive/My%20Science%20Practice/13%20Dissemination%20Publication%20Outreach/ERGo/erg\nRequirement already satisfied: numpy in /usr/local/lib/python3.7/dist-packages (from erg==0.0.1) (1.19.5)\nRequirement already satisfied: pandas in /usr/local/lib/python3.7/dist-packages (from erg==0.0.1) (1.1.5)\nRequirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from erg==0.0.1) (1.4.1)\nRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from erg==0.0.1) (3.2.2)\nRequirement already satisfied: holoviews in /usr/local/lib/python3.7/dist-packages (from erg==0.0.1) (1.14.4)\nRequirement already satisfied: bokeh>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from erg==0.0.1) (2.3.2)\nRequirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.7/dist-packages (from pandas->erg==0.0.1) (2018.9)\nRequirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas->erg==0.0.1) (2.8.1)\nRequirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->erg==0.0.1) (0.10.0)\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->erg==0.0.1) (2.4.7)\nRequirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->erg==0.0.1) (1.3.1)\nRequirement already satisfied: pyviz-comms>=0.7.4 in /usr/local/lib/python3.7/dist-packages (from holoviews->erg==0.0.1) (2.0.2)\nRequirement already satisfied: panel>=0.8.0 in /usr/local/lib/python3.7/dist-packages (from holoviews->erg==0.0.1) (0.11.3)\nRequirement already satisfied: colorcet in /usr/local/lib/python3.7/dist-packages (from holoviews->erg==0.0.1) (2.0.6)\nRequirement already satisfied: param<2.0,>=1.9.3 in /usr/local/lib/python3.7/dist-packages (from holoviews->erg==0.0.1) (1.10.1)\nRequirement already satisfied: tornado>=5.1 in /usr/local/lib/python3.7/dist-packages (from bokeh>=1.4.0->erg==0.0.1) (5.1.1)\nRequirement already satisfied: packaging>=16.8 in /usr/local/lib/python3.7/dist-packages (from bokeh>=1.4.0->erg==0.0.1) (20.9)\nRequirement already satisfied: Jinja2>=2.9 in /usr/local/lib/python3.7/dist-packages (from bokeh>=1.4.0->erg==0.0.1) (2.11.3)\nRequirement already satisfied: pillow>=7.1.0 in /usr/local/lib/python3.7/dist-packages (from bokeh>=1.4.0->erg==0.0.1) (7.1.2)\nRequirement already satisfied: typing-extensions>=3.7.4 in /usr/local/lib/python3.7/dist-packages (from bokeh>=1.4.0->erg==0.0.1) (3.7.4.3)\nRequirement already satisfied: PyYAML>=3.10 in /usr/local/lib/python3.7/dist-packages (from bokeh>=1.4.0->erg==0.0.1) (3.13)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (from python-dateutil>=2.7.3->pandas->erg==0.0.1) (1.15.0)\nRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from panel>=0.8.0->holoviews->erg==0.0.1) (2.23.0)\nRequirement already satisfied: tqdm in /usr/local/lib/python3.7/dist-packages (from panel>=0.8.0->holoviews->erg==0.0.1) (4.41.1)\nRequirement already satisfied: markdown in /usr/local/lib/python3.7/dist-packages (from panel>=0.8.0->holoviews->erg==0.0.1) (3.3.4)\nRequirement already satisfied: pyct>=0.4.4 in /usr/local/lib/python3.7/dist-packages (from panel>=0.8.0->holoviews->erg==0.0.1) (0.4.8)\nRequirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/dist-packages (from Jinja2>=2.9->bokeh>=1.4.0->erg==0.0.1) (2.0.1)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->panel>=0.8.0->holoviews->erg==0.0.1) (2021.5.30)\nRequirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->panel>=0.8.0->holoviews->erg==0.0.1) (3.0.4)\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->panel>=0.8.0->holoviews->erg==0.0.1) (1.24.3)\nRequirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->panel>=0.8.0->holoviews->erg==0.0.1) (2.10)\nRequirement already satisfied: importlib-metadata; python_version < \"3.8\" in /usr/local/lib/python3.7/dist-packages (from markdown->panel>=0.8.0->holoviews->erg==0.0.1) (4.5.0)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata; python_version < \"3.8\"->markdown->panel>=0.8.0->holoviews->erg==0.0.1) (3.4.1)\nInstalling collected packages: erg\n Running setup.py develop for erg\nSuccessfully installed erg\n" ], [ "import drive/MyDrive/My\\ Science\\ Practice/13\\ Dissemination\\ Publication\\ Outreach/ERGo/erg", "_____no_output_____" ], [ "ergram = ERGio.ERG(r'../../data/BYB_Recording_2020-12-23_13.47.39.wav')", "_____no_output_____" ] ], [ [ "### Data validation: confirming that the shifted times are sawtoothed and the normal times look like a slippery staircase", "_____no_output_____" ] ], [ [ "%%opts Curve {+axiswise}\n\nhv.Curve(\n ergram.df['shifted time (s)'].values, \n label='shifted'\n) + hv.Curve(\n ergram.df['time (s)'].values,\n label='normal'\n)", "_____no_output_____" ] ], [ [ "### Visualize TTL pulses for each frequency\n\nFor a specific frequency, this is where all of that frequency occurred for each color.", "_____no_output_____" ] ], [ [ "color_dict = {\n 'IR':'deeppink',\n 'R':'firebrick',\n 'G':'green',\n 'B':'blue',\n 'UV':'violet'\n}", "_____no_output_____" ], [ "frequency_picker = pn.widgets.Select(\n name=\"Frequency (Hz)\",\n options=sorted(list(ergram.df['theoretical frequency'].unique())),\n value=8,\n width=100\n)\n\[email protected](frequency=frequency_picker.param.value)\ndef plot_stimuli_select_frequency(frequency):\n return hv.NdOverlay(\n {\n color: hv.Curve(\n data=ergram.df[\n (ergram.df.color==color) \n & (ergram.df['theoretical frequency']==frequency)\n ],\n kdims=['time (s)'],\n vdims=[\n 'TTL'\n ],\n ).opts(\n color=color_dict[color],\n width=600,\n height=200\n ) for color in list(color_dict.keys())\n },\n kdims='Color'\n ).opts(\n legend_position='right'\n )\n\n\n\ncolor_picker = pn.widgets.Select(\n name=\"Color\",\n options=sorted(list(ergram.df.color.unique())),\n value='R',\n width=100\n)\n\[email protected](color=color_picker.param.value)\ndef plot_stimuli_select_color(color):\n return hv.NdOverlay(\n {\n frequency: hv.Curve(\n data=ergram.df[\n (ergram.df.color==color) \n & (ergram.df['theoretical frequency']==frequency)\n ],\n kdims=['time (s)'],\n vdims=['TTL'],\n ).opts(\n color=color_dict[color],\n width=600,\n height=200\n ) for frequency in list(ergram.df['theoretical frequency'].unique())\n },\n kdims='Color'\n ).opts(\n legend_position='right'\n )\n\npn.Column(frequency_picker, plot_stimuli_select_frequency, color_picker, plot_stimuli_select_color)\n", "_____no_output_____" ] ], [ [ "### Visualize responses to light", "_____no_output_____" ] ], [ [ "\n# Make a selector for the color to display\ncolor_selector = pn.widgets.Select(\n name=\"Color\",\n options=list(color_dict.keys()),\n value=\"R\",\n width=100\n)\n\n# Plot the colors\[email protected](color=color_selector.param.value)\ndef plot_responses(color):\n return hv.Curve(\n data=ergram.df[ergram.df['color']==color],\n kdims=['shifted time (s)'],\n vdims=[\n ('channel 1', 'Voltage'),\n ('theoretical frequency', 'frequency (Hz)')\n ]\n ).groupby(\n ['theoretical frequency']\n ).layout(\n 'theoretical frequency'\n ).opts(\n opts.Curve(\n line_width=2,\n color=color_dict[color],\n xaxis=None, yaxis=None\n )\n ).cols(5)\n\npn.Column(color_selector, plot_responses)", "_____no_output_____" ] ], [ [ "So this is kind of interesting. Toward the end of the end of stimulation, especially with prolonged periods of stimulation (e.g., at high frequencies or low frequencies), you get some movement artifact. I saw the cockroaches really seem to not like that- they would squirm a lot. Another observation which I think is even more important, at around the halfway point, you see some short upward notch.", "_____no_output_____" ] ], [ [ "def RMS(arr):\n # mean-center\n arr -= np.mean(arr)\n \n # Square\n squared = arr ** 2\n \n # Mean\n mean_squared = np.mean(squared)\n \n # Root\n root_mean_squared = np.sqrt(mean_squared)\n \n return root_mean_squared\n ", "_____no_output_____" ], [ "RMS_df = ergram.df.groupby(\n ['trial', 'color', 'theoretical frequency']\n).agg(\n lambda x: RMS(x['channel 1'])\n).reset_index()", "_____no_output_____" ], [ "RMS_df['power'] = RMS_df[0]", "_____no_output_____" ] ], [ [ "TODO: make color a numerical thing so you can make it the x-axid", "_____no_output_____" ] ], [ [ "hv.Curve(\n data=RMS_df,\n kdims='theoretical frequency', # consider making this actual frequency\n vdims=['power','color'],\n).groupby(\n 'color'\n).overlay('color')", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4afd2bd9fbe889bf94a48d3bcb51e17bc0aea368
23,055
ipynb
Jupyter Notebook
week_02/seminar1_student.ipynb
dukanov/speech_course
3298d186f952647ffcf487edf318e3b9cbf863b4
[ "MIT" ]
83
2021-02-15T16:22:29.000Z
2022-03-31T08:45:39.000Z
week_02/seminar1_student.ipynb
dukanov/speech_course
3298d186f952647ffcf487edf318e3b9cbf863b4
[ "MIT" ]
10
2021-02-22T10:58:17.000Z
2022-03-20T09:45:56.000Z
week_02/seminar1_student.ipynb
dukanov/speech_course
3298d186f952647ffcf487edf318e3b9cbf863b4
[ "MIT" ]
34
2021-02-15T16:42:25.000Z
2022-03-20T09:45:16.000Z
41.465827
567
0.610323
[ [ [ "### Seminar: Spectrogram Madness\n\n![img](https://github.com/yandexdataschool/speech_course/raw/main/week_02/stft-scheme.jpg)\n\n#### Today you're finally gonna deal with speech! We'll walk you through all the main steps of speech processing pipeline and you'll get to do voice-warping. It's gonna be fun! ....and creepy. Very creepy.", "_____no_output_____" ] ], [ [ "from IPython.display import display, Audio\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\nimport librosa\n\ndisplay(Audio(\"sample1.wav\"))\ndisplay(Audio(\"sample2.wav\"))\ndisplay(Audio(\"welcome.wav\"))", "_____no_output_____" ], [ "amplitudes, sample_rate = librosa.core.load(\"sample1.wav\")\n\ndisplay(Audio(amplitudes, rate=sample_rate))\nprint(sample_rate)\n\nprint(\"Length: {} seconds at sample rate {}\".format(amplitudes.shape[0] / sample_rate, sample_rate))\nplt.figure(figsize=[16, 4])\nplt.title(\"First 10^4 out of {} amplitudes\".format(len(amplitudes)))\nplt.plot(amplitudes[:10000]);", "_____no_output_____" ] ], [ [ "### Task 1: Mel-Spectrogram (5 points)\n\nAs you can see, amplitudes follow a periodic patterns with different frequencies. However, it is very difficult to process these amplitudes directly because there's so many of them! A typical WAV file contains 22050 amplitudes per second, which is already way above a typical sequence length for other NLP applications. Hence, we need to compress this information to something manageable. \n\nA typical solution is to use __spectrogram:__ instead of saving thousands of amplitudes, we can perform Fourier transformation to find which periodics are prevalent at each point in time. More formally, a spectrogram applies [Short-Time Fourier Transform (STFT)](https://en.wikipedia.org/wiki/Short-time_Fourier_transform) to small overlapping windows of the amplitude time-series:\n\n\n<img src=\"https://www.researchgate.net/profile/Phillip_Lobel/publication/267827408/figure/fig2/AS:295457826852866@1447454043380/Spectrograms-and-Oscillograms-This-is-an-oscillogram-and-spectrogram-of-the-boatwhistle.png\" width=\"480px\">\n\nHowever, this spectrogram may have extraordinarily large numbers that can break down neural networks. Therefore the standard approach is to convert spectrogram into a __mel-spectrogram__ by changing frequencies to [Mel-frequency spectrum(https://en.wikipedia.org/wiki/Mel-frequency_cepstrum)].\n\nHence, the algorithm to compute spectrogram of amplitudes $y$ becomes:\n1. Compute Short-Time Fourier Transform (STFT): apply fourier transform to overlapping windows\n2. Build a spectrogram: $S_{ij} = abs(STFT(y)_{ij}^2)$\n3. Convert spectrogram to a Mel basis", "_____no_output_____" ] ], [ [ "# Some helpers:\n# 1. slice time-series into overlapping windows\ndef slice_into_frames(amplitudes, window_length, hop_length):\n return librosa.core.spectrum.util.frame(\n np.pad(amplitudes, int(window_length // 2), mode='reflect'),\n frame_length=window_length, hop_length=hop_length)\n # output shape: [window_length, num_windows]\n\ndummy_amps = amplitudes[2048: 6144]\ndummy_frames = slice_into_frames(dummy_amps, 2048, 512)\nprint(amplitudes.shape)\n\nplt.figure(figsize=[16, 4])\nplt.subplot(121, title='Whole audio sequence', ylim=[-3, 3])\nplt.plot(dummy_amps)\n\nplt.subplot(122, title='Overlapping frames', yticks=[])\nfor i, frame in enumerate(dummy_frames.T):\n plt.plot(frame + 10 - i);", "_____no_output_____" ], [ "# 2. Weights for window transform. Before performing FFT you can scale amplitudes by a set of weights\n# The weights we're gonna use are large in the middle of the window and small on the sides\ndummy_window_length = 3000\ndummy_weights_window = librosa.core.spectrum.get_window('hann', dummy_window_length, fftbins=True)\nplt.plot(dummy_weights_window); plt.plot([1500, 1500], [0, 1.1], label='window center'); plt.legend()", "_____no_output_____" ], [ "# 3. Fast Fourier Transform in Numpy. Note: this function can process several inputs at once (mind the axis!)\ndummy_fft = np.fft.rfft(dummy_amps[:3000, None] * dummy_weights_window[:, None], axis=0) # complex[sequence_length, num_sequences]\nplt.plot(np.real(dummy_fft)[:, 0])\nprint(dummy_fft.shape)", "_____no_output_____" ] ], [ [ "Okay, now it's time to combine everything into a __S__hort-__T__ime __F__ourier __T__ransform", "_____no_output_____" ] ], [ [ "def get_STFT(amplitudes, window_length, hop_length):\n \"\"\" Compute short-time Fourier Transform \"\"\"\n # slice amplitudes into overlapping frames [window_length, num_frames]\n frames = slice_into_frames(amplitudes, window_length, hop_length)\n \n # get weights for fourier transform, float[window_length]\n weights_window = <YOUR CODE>\n \n \n # apply fourier transfrorm to frames scaled by weights\n stft = <YOUR CODE>\n return stft", "_____no_output_____" ], [ "stft = get_STFT(amplitudes, window_length=2048, hop_length=512)\nplt.plot(abs(stft)[0])", "_____no_output_____" ], [ "def get_spectrogram(amplitudes, sample_rate=22050, n_mels=128,\n window_length=2048, hop_length=512, fmin=1, fmax=8192):\n \"\"\"\n Implement mel-spectrogram as described above.\n :param amplitudes: float [num_amplitudes], time-series of sound amplitude, same as above\n :param sample rate: num amplitudes per second\n :param n_mels: spectrogram channels\n :param window_length: length of a patch to which you apply FFT\n :param hop_length: interval between consecutive windows\n :param f_min: minimal frequency\n :param f_max: maximal frequency\n :returns: mel-spetrogram [n_mels, duration]\n \"\"\"\n # Step I: compute Short-Time Fourier Transform\n stft = <YOUR CODE>\n assert stft.shape == (window_length // 2 + 1, len(amplitudes) // hop_length + 1)\n \n # Step II: convert stft to a spectrogram\n spectrogram = <YOUR CODE>\n \n return spectrogram", "_____no_output_____" ] ], [ [ "#### The Mel Basis\n\nThe Mel-scale is a perceptual scale which represents how sensitive humans are to various sounds. We will use it to compress and transform our spectrograms.", "_____no_output_____" ] ], [ [ "mel_basis = librosa.filters.mel(22050, n_fft=2048,\n n_mels=128, fmin=1, fmax=8192)\nplt.figure(figsize=[16, 10])\nplt.title(\"Mel Basis\"); plt.xlabel(\"Frequence\"); plt.ylabel(\"Mel-Basis\")\nplt.imshow(np.log(mel_basis),origin='lower', cmap=plt.cm.hot,interpolation='nearest', aspect='auto')\nplt.colorbar(use_gridspec=True)\n\n# Can \nmat= np.matmul(mel_basis.T, mel_basis)\n\nplt.figure(figsize=[16, 10])\nplt.title(\"recovered frequence Basis\"); plt.xlabel(\"Frequence\"); plt.ylabel(\"Frequency\")\nplt.imshow(np.log(mat),origin='lower', cmap=plt.cm.hot,interpolation='nearest', aspect='auto')\nplt.colorbar(use_gridspec=True)\n", "_____no_output_____" ], [ "def get_melspectrogram(amplitudes, sample_rate=22050, n_mels=128,\n window_length=2048, hop_length=512, fmin=1, fmax=8192):\n spectrogram = get_spectrogram(amplitudes, sample_rate=sample_rate, n_mels=n_mels,\n window_length=window_length, hop_length=hop_length, fmin=fmin, fmax=fmax)\n \n # Step III: convert spectrogram into Mel basis (multiplying by transformation matrix)\n mel_basis = librosa.filters.mel(sample_rate, n_fft=window_length,\n n_mels=n_mels, fmin=fmin, fmax=fmax)\n # -- matrix [n_mels, window_length / 2 + 1]\n \n mel_spectrogram = <YOUR_CODE>\n assert mel_spectrogram.shape == (n_mels, len(amplitudes) // hop_length + 1)\n \n return mel_spectrogram", "_____no_output_____" ], [ "amplitudes1, s1 = librosa.core.load(\"./sample1.wav\")\namplitudes2, s2 = librosa.core.load(\"./sample2.wav\")\nprint(s1)\nref1 = librosa.feature.melspectrogram(amplitudes1, sr=sample_rate, n_mels=128, fmin=1, fmax=8192)\nref2 = librosa.feature.melspectrogram(amplitudes2, sr=sample_rate, n_mels=128, fmin=1, fmax=8192)\nassert np.allclose(get_melspectrogram(amplitudes1), ref1, rtol=1e-4, atol=1e-4)\nassert np.allclose(get_melspectrogram(amplitudes2), ref2, rtol=1e-4, atol=1e-4)", "_____no_output_____" ], [ "plt.figure(figsize=[16, 4])\nplt.subplot(1, 2, 1)\nplt.title(\"That's no moon - it's a space station!\"); plt.xlabel(\"Time\"); plt.ylabel(\"Frequency\")\nplt.imshow(np.log10(get_melspectrogram(amplitudes1)),origin='lower', vmin=-10, vmax=5, cmap=plt.cm.hot)\nplt.colorbar(use_gridspec=True)\n\nplt.subplot(1, 2, 2)\nplt.title(\"Help me, Obi Wan Kenobi. You're my only hope.\"); plt.xlabel(\"Time\"); plt.ylabel(\"Frequency\")\nplt.imshow(np.log10(get_melspectrogram(amplitudes2)),origin='lower', vmin=-10, vmax=5, cmap=plt.cm.hot);\nplt.colorbar(use_gridspec=True)\n\n# note that the second spectrogram has higher mean frequency corresponding to the difference in gender", "_____no_output_____" ] ], [ [ "### Task 2 - Griffin-Lim Algorithm - 5 Points\n\n\nIn this task you are going to reconstruct the original audio signal from a spectrogram using the __Griffin-Lim Algorithm (GLA)__ . The Griffin-Lim Algorithm is a phase reconstruction method based on the redundancy of the short-time Fourier transform. It promotes the consistency of a spectrogram by iterating two projections, where a spectrogram is said to be consistent when its inter-bin dependency owing to the redundancy of STFT is retained. GLA is based only on the consistency and does not take any prior knowledge about the target signal into account.\n\n\nThis algorithm expects to recover a __complex-valued spectrogram__, which is consistent and maintains the given amplitude $\\mathbf{A}$, by the following alternative projection procedure. Initialize a random \"reconstruced\" signal $\\mathbf{x}$, and obtain it's STFT\n$$\\mathbf{X} = \\text{STFT}(\\mathbf{x})$$\n\nThen we __discard__ the magnitude of $\\mathbf{X}$ and keep only a random phase $\\mathbf{\\phi}$. Using the phase and the given magnitude $\\mathbf{A}$ we construct a new complex value spectrogram $ \\mathbf{\\tilde X}$ using the euler equation\n\n$$\\mathbf{\\tilde X} = \\mathbf{A}\\cdot e^{j\\mathbf{\\phi}}$$\n\nThen we reconstruct the signal $\\mathbf{\\tilde x}$ using an __inverse STFT__:\n\n$$\\mathbf{\\tilde x} = \\text{iSTFT}(\\mathbf{\\tilde X})$$\n\nWe update our value of the signal reconstruction:\n\n$$ \\mathbf{x} = \\mathbf{\\tilde x} $$\n\nFinally, we interate this procedure multiple times and return the final $$\\mathbf{x}$$.", "_____no_output_____" ] ], [ [ "# STEP 1: Reconstruct your Spectrogram from the Mel-Spectrogram\ndef inv_mel_spectrogram(mel_spectrogram, sample_rate=22050, n_mels=128,\n window_length=2048, hop_length=512, fmin=1, fmax=8192):\n \n mel_basis = librosa.filters.mel(sample_rate, n_fft=window_length,\n n_mels=n_mels, fmin=fmin, fmax=fmax)\n \n inv_mel_basis = <INSERT YOUR CODE>\n spectrogram = <INSERT YOUT CODE>\n \n \n return spectrogram", "_____no_output_____" ], [ "amplitudes, sample_rate = librosa.core.load(\"welcome.wav\")\ndisplay(Audio(amplitudes, rate=sample_rate))\n\n\ntrue_spec = get_spectrogram(amplitudes)\nmel_spec = get_melspectrogram(amplitudes, window_length=2048, hop_length=512)\n\n#!!! Here you can modify your Mel-Spectrogram. Let your twisted imagination fly wild here !!!\n\n#mel_spec[40:50,:]=0 # Zero out some freqs\n\n# mel_spec[10:124,:] = mel_spec[0:114,:] # #Pitch-up \n# mel_spec[0:10,:]=0 \n\n# mel_spec[0:114,:] = mel_spec[10:124,:] # #Pitch-down \n# mel_spec[114:124,:]=0\n\n#mel_spec[:,:] = mel_spec[:,::-1] #Time reverse\n\n#mel_spec[64:,:] = mel_spec[:64,:] # Trippy Shit\n\n#mel_spec[:,:] = mel_spec[::-1,:] # Aliens are here\n\n#mel_spec[64:,:] = mel_spec[:64,:] # Trippy Shit\n\n#mel_spec[:,:] = mel_spec[::-1,::-1] # Say hello to your friendly neighborhood Chaos God\n\n#!!! END MADNESS !!!\n\n\n#Convert Back to Spec\nspec = inv_mel_spectrogram(mel_spec, window_length=2048, hop_length=512)\n\nscale_1 = 1.0 / np.amax(mel_spec)\n\nscale_1 = 1.0 / np.amax(true_spec)\nscale_2 = 1.0 / np.amax(spec)\n\nplt.figure(figsize=[16, 4])\nplt.subplot(1, 2, 1)\nplt.title(\"Welcome...!\"); plt.xlabel(\"Time\"); plt.ylabel(\"Frequency\")\nplt.imshow((true_spec*scale_1)**0.125,origin='lower',interpolation='nearest', cmap=plt.cm.hot, aspect='auto')\nplt.colorbar(use_gridspec=True)\n\nplt.subplot(1, 2, 2)\nplt.title(\"Xkdfsas...!\"); plt.xlabel(\"Time\"); plt.ylabel(\"Frequency\")\nplt.imshow((spec*scale_2)**0.125,origin='lower',interpolation='nearest', cmap=plt.cm.hot, aspect='auto')\nplt.colorbar(use_gridspec=True)\n\n\nplt.figure(figsize=[16, 10])\nplt.title(\"Xkdfsas...!\"); plt.xlabel(\"Time\"); plt.ylabel(\"Frequency\")\nplt.imshow((mel_spec**0.125),origin='lower',interpolation='nearest', cmap=plt.cm.hot, aspect='auto')\nplt.colorbar(use_gridspec=True)", "_____no_output_____" ], [ "# Lets examine how to take an inverse FFT\ndummy_window_length = 3000\ndummy_weights_window = librosa.core.spectrum.get_window('hann', dummy_window_length, fftbins=True)\n\ndummy_fft = np.fft.rfft(dummy_amps[:3000, None] * dummy_weights_window[:, None], axis=0) # complex[sequence_length, num_sequences]\nprint(dummy_fft.shape)\nrec_dummy_amps = dummy_weights_window*np.real(np.fft.irfft(dummy_fft[:,0]))\nplt.plot(dummy_amps[:3000])\nplt.plot(rec_dummy_amps[:3000])\nplt.legend(['Original', 'Reconstructed'])", "_____no_output_____" ], [ "# Step II: Reconstruct amplitude samples from STFT\ndef get_iSTFT(spectrogram, window_length, hop_length):\n \"\"\" Compute inverse short-time Fourier Transform \"\"\"\n \n # get weights for fourier transform, float[window_length]\n window = librosa.core.spectrum.get_window('hann', window_length, fftbins=True)\n \n time_slices = spectrogram.shape[1]\n len_samples = int(time_slices*hop_length+window_length)\n \n x = np.zeros(len_samples)\n # apply inverse fourier transfrorm to frames scaled by weights and save into x\n amplitudes = <YOUR CODE>\n \n # Trim the array to correct length from both sides\n x = <YOUR_CODE>\n return x", "_____no_output_____" ], [ "# Step III: Implement the Griffin-Lim Algorithm\ndef griffin_lim(power_spectrogram, window_size, hop_length, iterations, seed=1, verbose=True):\n \"\"\"Reconstruct an audio signal from a magnitude spectrogram.\n Given a power spectrogram as input, reconstruct\n the audio signal and return it using the Griffin-Lim algorithm from the paper:\n \"Signal estimation from modified short-time fourier transform\" by Griffin and Lim,\n in IEEE transactions on Acoustics, Speech, and Signal Processing. Vol ASSP-32, No. 2, April 1984.\n Args:\n power_spectrogram (2-dim Numpy array): The power spectrogram. The rows correspond to the time slices\n and the columns correspond to frequency bins.\n window_size (int): The FFT size, which should be a power of 2.\n hop_length (int): The hope size in samples.\n iterations (int): Number of iterations for the Griffin-Lim algorithm. Typically a few hundred\n is sufficient.\n Returns:\n The reconstructed time domain signal as a 1-dim Numpy array.\n \"\"\"\n \n time_slices = power_spectrogram.shape[1]\n len_samples = int(time_slices*hop_length-hop_length)\n \n # Obtain STFT magnitude from Spectrogram\n\n magnitude_spectrogram = <YOUR CODE>\n \n # Initialize the reconstructed signal to noise.\n np.random.seed(seed)\n x_reconstruct = np.random.randn(len_samples)\n \n for n in range(iterations):\n # Get the SFTF of a random signal\n reconstruction_spectrogram = <YOUR_CODE>\n \n # Obtain the angle part of random STFT. Hint: unit np.angle\n reconstruction_angle = <YOUR_CODE>\n \n # Discard magnitude part of the reconstruction and use the supplied magnitude spectrogram instead.\n proposal_spectrogram = <YOUR_CODE>\n assert proposal_spectrogram.dtype == np.complex\n \n \n # Save previous construction\n prev_x = x_reconstruct\n \n # Reconstruct signal\n x_reconstruct = <YOUR CODE>\n \n # Measure RMSE\n diff = np.sqrt(sum((x_reconstruct - prev_x)**2)/x_reconstruct.size)\n if verbose:\n # HINT: This should decrease over multiple iterations. If its not, your code doesn't work right!\n # Use this to debug your code!\n print('Reconstruction iteration: {}/{} RMSE: {} '.format(n, iterations, diff))\n return x_reconstruct", "_____no_output_____" ], [ "rec_amplitudes1 = griffin_lim(true_spec, 2048, 512, 1, verbose=False)\ndisplay(Audio(rec_amplitudes1, rate=sample_rate))\nrec_amplitudes2 = griffin_lim(true_spec, 2048, 512, 50, verbose=False)\ndisplay(Audio(rec_amplitudes2, rate=sample_rate))\n\nrec_amplitudes3 = griffin_lim(spec, 2048, 512, 1, verbose=False)\ndisplay(Audio(rec_amplitudes3, rate=sample_rate))\nrec_amplitudes4 = griffin_lim(spec, 2048, 512, 50, verbose=False)\ndisplay(Audio(rec_amplitudes4, rate=sample_rate))", "_____no_output_____" ], [ "# THIS IS AN EXAMPLE OF WHAT YOU ARE SUPPORT TO GET\n# Remember to apply sqrt to spectrogram to get magnitude, note power here.\n\n# Let's try this on a real spectrogram\nref_amplitudes1 = librosa.griffinlim(np.sqrt(true_spec), n_iter=1, hop_length=512, win_length=2048)\ndisplay(Audio(ref_amplitudes1, rate=sample_rate))\nref_amplitudes2 = librosa.griffinlim(np.sqrt(true_spec), n_iter=50, hop_length=512, win_length=2048)\ndisplay(Audio(ref_amplitudes2, rate=sample_rate))\n\n# Not let's try this on a reconstructed spectrogram\nref_amplitudes3 = librosa.griffinlim(np.sqrt(spec), n_iter=1, hop_length=512, win_length=2048)\ndisplay(Audio(ref_amplitudes3, rate=sample_rate))\nref_amplitudes4 = librosa.griffinlim(np.sqrt(spec), n_iter=50, hop_length=512, win_length=2048)\ndisplay(Audio(ref_amplitudes4, rate=sample_rate))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]